text:
Q: Why "~undefined" is -1 in JavaScript? According to this post, run the following codes
> ~function () { console.log('foo');}()
  foo
  -1

As we all know, the return value of the above anonymous function is undefined. Why ~undefined is -1? I couldn't find any similar question.

A: every thing that cannot be represented in bits in JS for example "undefined, NaN" is treated a 0 or 0000000000000b for the ~ operator since it converts the operand into an signed integer see @felixkling answer for more details on this and since the operation ~ is BITwise not or 1s complement which flips the bits so the statement results in 111111111111b as a sequence of 1 and when dealing in numbers on binary level the MSB(most significant bit) is treated as a sign so when converting all the 0s to 1s it results in decimal value of -1 try ~0 for instance. and use this code to get the binary representation of a number (-3 >>> 0).toString(2))

A: ~ is bitwise NOT. It uses ToInt32 to convert the argument to a number. ToInt32 is defined as:

*

*Let number be ToNumber(argument).

*ReturnIfAbrupt(number).

*If number is NaN, +0, −0, +∞, or −∞, return +0.
  ...

In turn, ToNumber(undefined) returns NaN, so according to step 3, ToInt32 returns 0.
And ~0 is -1.

A: Apparently the bit representation of undefined is all 0s. This can be seen if by the following: undefined | 0 which evaluates to 0. Because of this we know that undefined's bit representation is all zeros.
If we now filp all bits (wich is exactly what ~ does) we get all 1s which is the representation of -1.
All this works because of javascript's type cohersion


text:
Q: Best way to handle session management in spring mvc filters or interceptors Requirement:
Before every action meaning every controller method i.e handler I have to check if session is valid or not .
   If session is valid check for user login details availability in session else those details should be set in session.
  If session is not valid it should be redirected to login page.
Can one let me know which suits my requirement.

A: You can also configure a custom interceptor in your dispatcher servlet,
<mvc:interceptors>
    <bean class="com.CusInterceptor"/>
</mvc:interceptors>

And extend the class HandlerInterceptorAdapter and override the preHandle() method to intercept all requests.
public class CusInterceptorextends HandlerInterceptorAdapter {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

    // verify user session here and process it for further operations
    }

A: Use Spring Security for that. It will store a security context object in the session, holding all the credentials and so on. The security filter chain will make sure, that this object sill is valid, or redirect the user to a login page, for example.

A: Agree with @Stefan on that one. go with Spring Security (we are using the same for session authentication/validations in our mvc app).
But please remember that Ajax calls need a little tweaking before you can get them to redirect to login page.. otherwise you just get an error page response which you may or may not be parsing/handling at the JS (client) level

redpajama_set_name: RedPajamaStackExchange


text:
Q: Display one row in UICollectionView - Swift I'm trying to figure out how to limit a UICollectionView to display a horizontal scrollable list in a single row.
Any Ideas?

A: I just used something that is working for me:

*

*Set the Scroll direction to Horizontal.

*Set the size of your Cells using sizeForItemAt indexPath method.

*Set a constraint to your CollectionView making its height equal to (or a bit greater than) the Cell's height which you specified above.

The logic behind it:
When the height of CollectionView is equal to the height of it's items and it is set to horizontal scroll, then it can only show them in one row. I said "or a bit greater than cell's height" because if you set the height of your CollectionView twice bigger than cell's height then it can fit 2 rows of cells and it will show them in 2 rows instead of one.


text:
Q: Why a linearly independent set of vectors must not contain the zero vector? Why is it necessary for a linearly independent set of vectors to not contain the zero vector? I am looking with the definition perspective i.e. why do we define linear independence in this way?

A: A big part of what makes the definition of "linearly independent" so useful is that it gives a robust notion of "basis" and "dimension": a basis is a linearly independent set which spans the entire vector space, and any two bases for a vector space have the same number of elements, which we call the dimension of the space.  Any two vector spaces of the same dimension are isomorphic.  These basic facts are fantastically powerful, and (when paired with the fact that any linearly independent set can be extended to a basis) are arguably the main reason that linear algebra is such a central part of mathematics.
If you allow the zero vector to be in a linearly independent set, all of this breaks down.  You could take any basis and add the zero vector to it, so a vector space can have bases of different sizes.  Furthermore, it would no longer be true that the size of a basis determines the vector space up to isomorphism (for instance, if $K$ is your scalar field, then both $K$ and $K^2$ have a basis of size $2$, namely $\{0,1\}$ and $\{(0,1),(1,0)\}$).
In a certain sense, allowing the zero vector to be in a linearly independent set is much like considering the integer $1$ to be prime: the purpose of primes is to be able to factor other numbers into them, but if you allow $1$ to be prime these factorizations are no longer unique, because you can add in as many copies of $1$ as you like.  Similarly, any vector space can be "factored" into a basis (or more abstractly, split as a direct sum of simple vector spaces), but the number of terms in this factorization would not be unique if zero could be a basis element.

A: Consider a set of vectors A1,A2, ... ,An
Let A1 be the null vector, i.e. A1= 0
Now consider the linear combination:
Y=x1 A1+x2 A2+....+xn An , where x1, x2,  ..., xn are scalars.
By definition, for the vectors to be linearly independent, Y=0 if and only if x1=x2=...=xn=0.
However, let x1 not be equal to zero and x2=x3=....=xn=0
Then Y=x1 A1=0
Hence they can't be linearly independent!
Have a look at this video:


text:
Q: How to find maximum value in each row and convert it to specific value I have a matrix like this:
0.1  0.2  0.5
0.3  0.7  0.4

I know that I can use max function to find the maximum value in each row. How do I use the indices returned from max to create a new matrix like this:
0  0  1
0  1  0

A: result = bsxfun(@eq, A, max(A,[],2));

A: Code
%%// Given matrix
A= [0.1  0.2  0.5;0.3  0.7  0.4]

%%// Get the column indices of max values across each row into y1
[~,y1] = max(A,[],2);

%%// Create a zero matix of size same as A and set the values corresponding
%%// to y1 along each row as 1
A1 = zeros(size(A));
A1(sub2ind(size(A1),1:numel(y1),y1'))=1

Output
A =

    0.1000    0.2000    0.5000
    0.3000    0.7000    0.4000

A1 =

     0     0     1
     0     1     0


text:
Q: Differential equation system with x(s), y (s) and z(s) Where $s$ is the curvilinear abscissa A curve $\gamma$ is parametrized by the parametric equations $x(t), y(t)$ and $z(t)$ where $t$ is the parametrization parameter (not a normal parametrization).
$x(t), y(t)$ and $z(t)$ are unkown. What we do know is their differentials with respect to the curvilinear abscissa $s$ :
$\frac{dx}{ds} = \frac {B_x}{B}$
$\frac{dy}{ds} = \frac {B_y}{B}$
$\frac{dz}{ds} = \frac {B_z}{B}$
Where :  $ds = \sqrt{ dx^2 + dy^2 + dz^2 }$ is the curvilinear abscissa.
and $B_x, B_y, B_z$ are functions of $x(t), y(t)$ and $z(t)$.
and $B = \sqrt{B_x^2 + B_y^2 + B_z^2}$
On other hand, the curvilinear abscissa caracteristic regarding a parametrization is :
$s(t)= \int_{t_0}^{t} \left\| \gamma ^\prime (u) \right\| \, \mathrm{d}u $
I want to solve the differential equation system $\frac{dx}{ds}$, $\frac{dy}{ds}$, $\frac{dz}{ds}$
The problem is that $x(t), y(t)$ and $z(t)$ are functions of the parameter $t$, but the differential equation system is function of the curvilinear abscissa $s$.
So, I used the relation $s(t)= \int_{t_0}^{t} \left\| \gamma ^\prime (u) \right\| \, \mathrm{d}u $, to calculate $s(t)$ :
$\frac {dx}{du} = \frac {dx}{ds}\frac {ds}{du}$
$s(t)= \int_{t_0}^{t} \sqrt {\left(\frac {dx}{du}\right)^2 + \left(\frac {dy}{du}\right)^2 + \left(\frac {dz}{du}\right)^2} \, \mathrm{d}u $
$s(t)= \int_{t_0}^{t} \sqrt {\left(\frac {dx}{ds}\right)^2 + \left(\frac {dy}{ds}\right)^2 + \left(\frac {dz}{ds}\right)^2} \frac {ds}{du} \, \mathrm{d}u $
$s(t)= \int_{t_0}^{t} \sqrt {\left(\frac {B_x}{B}\right)^2 + \left(\frac {B_y}{B}\right)^2 + \left(\frac {B_z}{B}\right)^2} \, \mathrm{d}s $
$s(t)= \int_{t_0}^{t} \sqrt {\frac {B_x^2 + B_y^2 + B_z^2}{B^2}} \, \mathrm{d}s $
$s(t)= \int_{t_0}^{t} 1 \, \mathrm{d}s = [s]_{t_0}^{t} = t - t_0$
So, with $s(t) = t - t_0 \Rightarrow ds = dt$, can I write :
$\frac{dx}{ds} = \frac {dx}{dt}$
$\frac{dy}{ds} = \frac {dy}{dt}$
$\frac{dz}{ds} = \frac {dz}{dt}$
Can I solve the differential equation system $\frac{dx}{dt}$, $\frac{dy}{dt}$, $\frac{dz}{dt}$ instead?
Do I have to replace $x(t)$ by $x(s)$ or something like that? Something is not right what do you think?
My knowledge about the curvilinear abscissa $s$ is limited. Please if you have any idea help!
Thank you all
S.


text:
Q: Django request object and function declaration I'm fairly new to Django and one of the things that I am unclear about is how the request object gets included.
For example, in the views.py file in any given app I can declare:
def my_func(request):
   do_something(request)
   ...

and at this point Django includes the request object. So my questiin is can I include the request object in any other file that I create and Django will do the right thing and automatically include the object?

A:
can I include the request object in any other file that I create and Django will do the right thing and automatically include the object?

No, my_func() is a view and receives a request object by definition:

A view function, or view for short, is simply a Python function that takes a Web request and returns a Web response.

You cannot expect an arbitrary function anywhere in the project to receive request automagically.

A: There is no magic involved. The view works because it is linked to an url through your url.py file.
If you want you can delcare views in other files, for example viewsmail.py. As long as you link the function to an url in the url file, the funciton will be called with the right request object, regardless of where the function is located.


text:
Q: Decrement a field and delete entire object if field's value reaches to 0 in mongoose I am trying to create a Chat room mechanism and for this I am using nodejs,mongodb and mangoose.
I want to delete entire row if  "count" field reaches to "0".
So far I have this function which increase and decreases the count field successfully, but want to delete the object when count =0. How can I achieve this using below method.
function addOrRemoveFromRoom(mRoom, userCount) {
        ModelRooms.findByIdAndUpdate(mRoom.id, {
            $inc: { count: userCount },
            $addToSet: {
                "users": {
                    $each: [mUser],
                }
            }
        }, { returnOriginal: false }, function (err, doc) {
            if (err) {
                logger.error("Error occured", err);
            }
            else {
                logger.info("Success", mRoom.roomName);
            }
        });
    }

This is my schema
let roomsSchema = new mongoose.Schema({
    roomName: String,
    count: {
        type: Number,
        min: 0
    },
    createdAt: {
        type: Date,
        default: Date.now
    },
    users: [
        {
            userId: String,
            created: {
                type: Date,
                default: Date.now
            }
        }
    ]
});

How can i delete entire object if count field reaches to 0 (Zero)

A: You can try using "findAndModify"
https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/


text:
Q: How to get a param from URL Laravel 8
Hello!
I have some form like this
<form id="perpage" action="{{ route('partners.index.perpage') }}" method="get">

<label for="rows">Rows per page</label>

<select name="rows" id="rows" onchange="this.form.submit()">
    <option value="10">10</option>
    <option value="25">25</option>
    <option value="50">50</option>
</select>

Then the form is submited the URL gets string like this:
127.0.0.1:8000/partners/perpage?rows=25

127.0.0.1:8000/partners/perpage?rows=50

Route::get('partners/perpage/{rows}', 'App\Http\Controllers\PartnerController@indexPerpage')
    ->name('partners.index.perpage');

public function indexPerpage($rows)
{
    ddd('Hello');

    $total = User::find(Auth::id())->partners()->count();
    $partners = User::find(Auth::id())->partners()->simplePaginate($rows);
}

This function don`t calling in this case.
Thanks a lot!

A: You don't need to include the rows in the route. There is a ways to do that, first you should remove the {rows} from the route:
Route::get('partners/perpage', 'App\Http\Controllers\PartnerController@indexPerpage')
    ->name('partners.index.perpage');

Then change the indexPerpage method:
public function indexPerpage()
{
    $rows = request('rows');

    $total = User::find(Auth::id())->partners()->count();
    $partners = User::find(Auth::id())->partners()->simplePaginate($rows);
}


text:
Q: opencv python- not able to write videos I tried as given in the to tutorial, but I am not able to open the video. I guess there is some problem with the fourcc thing in OpenCV-Python. My code was as follows:
import numpy as np
import cv2

cap = cv2.VideoCapture(0)
#fourCc = cv.VideoWriter_fourcc(*'XVID')
fourCc = cv2.VideoWriter_fourcc('X','V','I','D')
out = cv2.VideoWriter('output.avi',fourCc,20.0,(640,480))

while(cap.isOpened()):
    ret, frame = cap.read()
    if ret==True:
        frame = cv2.flip(frame,0)
        out.write(frame)
        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

cap.release()
out.release()
cv2.destroyAllWindows()

It does create a file named output.avi (of non-zero size), but I am not able to play it, even using VLC.
NOTE: The same thing in C++ is working fine


text:
Q: Add a specific color to each tile and a legend in geom_tile I want to add two things to the following figure:

*

*add a legend (zp or df$legend) (which is similar to each block) to the geom_tile figure

*assign a specific color to each tile (which repeats for every block) instead of scale_fill_continuous but keep the "white" color for NA values.

    library(ggplot2)
    library(RColorBrewer)

    xp <- c('Disease_1','Disease_2','Disease_3','Disease_4')
    yp <- c('B Cell','T Cell')
    zp <- c('feature1','feature2','feature3','feature4','feature5','feature6','feature7','feature8')
    xp1 <- xp[1:2]
    df <- list(x=1:2,y=1:4,xp1,yp)
    df <- expand.grid(df)
    df$z <- c(1.804344554,1.158037086,1.686173307,0.500280283,1.710806067,0.857513435,0.66474755,1.164780941,1.769090931,2.058400169,3.114233859,1.436684123,1.770306398,0.995507604,2.538556363,2.264486118,1.424789875,1.816608927,2.773082903,1.197434618,0.829416784,1.622892741,2.035117094,1.650363345,1.927235048,1.546477438,2.308773122,1.041881013,1.216029616,0.478353441,0.834348006,1.240448774)
    df$legend <- rep(c('feature1','feature2','feature3','feature4','feature5','feature6','feature7','feature8'))

    cols <- rev(brewer.pal(11, 'RdYlBu'))
    p <- ggplot(df)
    p <- p + geom_tile(aes(x, y, fill = ifelse(z > 1, z, NA)),
                       colour = "black", width=0.85, height=0.85, size=1) +
      scale_fill_continuous(name = "z Scale", na.value = 'white') +
      labs() +
      facet_grid(Var3~Var4) +
      theme(strip.background =element_blank(), #remove bg color of facet_grid texts
            strip.text.x = element_text(size=12, color="black", face="bold"),
            strip.text.y = element_text(size=10, color="black", face="bold"))
    print(p)
    p + coord_fixed() +
      theme(
        axis.title = element_blank(),
        axis.text=element_blank(),
        axis.ticks=element_blank(),
        plot.background=element_blank(),
        panel.border=element_blank(),
        panel.background = element_blank())

Thanks in advance.


text:
Q: .htaccess redirect from subfolder to root keeping paths I'm migrating a site so I need to redirect all content from a www.oldurl.com/subfolder to the www.newurl.com and keep all the links, for example:
www.oldurl.com/subfolder/subfolder2

needs to redirect to
www.newurl.com/subfolder2

AND
www.oldurl.com/subfolder/subfolder3/link.html

needs to redirect to
www.newurl.com/subfolder3/link.html

my .htacess looks like this:
RewriteEngine on
RewriteRule ^subfolder/(.*)$ /$1 [R=301,L]

It is redirecting all www.oldurl.com/subfolder to www.newurl.com/ but does not follow the old paths it just sends all request to home page

A: For new conditions new .htaccess
RewriteEngine on
RewriteRule ^subfolder/(.*)$ http://www.newurl.com/$1 [R=301,L]


text:
Q: I got java.lang.IllegalStateException: No activity error when I update androidX libraries I got this error while I am going to show a dialog box
Error:-

This error coming when I update below androidx's Libraries
1. implementation 'androidx.appcompat:appcompat:1.1.0-rc01
2. implementation 'com.google.android.material:material:1.1.0-alpha09'
----- This is my Confirm Dialog ----
public class ConfirmDialog extends BaseDialogFragment {

public static ConfirmDialog newInstance() {
    return new ConfirmDialog();
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);      // Error Comes

}

@Override
protected Dialog createDialog(Context activityContext) {

    AlertDialog.Builder builder;
        builder = new AlertDialog.Builder(activityContext, android.R.style.Theme_Material_Light_Dialog_Alert);

    AlertDialog alertDialog = builder.create();
    alertDialog.setCanceledOnTouchOutside(false);
    return alertDialog;
}

@Override
public void onClick(DialogInterface dialog, int which) {
    super.onDialogClick(dialog, which, which);
}
}

----- This is my BaseDialog ----
public abstract class BaseDialogFragment extends DialogFragment implements DialogInterface.OnClickListener {

protected OnDialogClickListener onClickListener;

protected BaseDialogFragment() {
}

protected BaseDialogFragment(OnDialogClickListener onClickListener) {
    this.onClickListener = onClickListener;
}

public static void show(BaseDialogFragment dialogFragment, Context context) {
    dialogFragment.onCreate(null);
    Dialog dialog = dialogFragment.createDialog(context);
    dialog.show();
}

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    return createDialog(getActivity());
}

protected abstract Dialog createDialog(Context activityContext);

public void setOnClickListener(OnDialogClickListener onClickListener) {
    this.onClickListener = onClickListener;
}

public void removeOnClickListener() {
    this.onClickListener = null;
}

public void onDialogClick(DialogInterface dialog, int which, Object o) {
    if (this.onClickListener != null) {
        this.onClickListener.onDialogClick(dialog, which, o);
    }
}
}

---  And Last, This is when I call my Confirmdialog  ---
ConfirmDialog confirmDialog = ConfirmDialog.newInstance();
        confirmDialog.setOnClickListener(new OnDialogClickListener() {
        @Override
        public void onDialogClick(DialogInterface dialog, int which, Object o) {

            }
        });

 ConfirmDialog.show(confirmDialog, activity); // When I call this

A: You can try:
ConfirmDialog.show(confirmDialog, activity);
instead
ConfirmDialog.show(confirmDialog, this);
Pass context or instance of the activity

A: Dialog Fragment should handle click events inside, not in activity/fragment where you are initializing it.
And for comunication between dialog fragment and activity create interface implemented by activity.
For example
interface DialogFragmentResultListener {
    fun onDialogResultReceived(requestCode: Int, isPositive: Boolean)
}

and pass result from DialogFragment like this:
   if (activity is DialogFragmentResultListener) {
                        ......
   }

A: You Can Try like this method -
BaseDialogFragment -
 abstract class BaseDialogFragment : DialogFragment(), View.OnClickListener, BaseView {

override fun onClick(v: View?) {
}

abstract fun initObjects()

abstract fun registerListeners()

abstract fun initWidgets()

protected fun setFullScreen() {
    val width = ViewGroup.LayoutParams.MATCH_PARENT
    val height = ViewGroup.LayoutParams.MATCH_PARENT
    dialog?.window?.setLayout(width, height)
}

override fun onNetworkFailure(errorCode: Int, errorMessage: String?) {
    (activity!! as BaseActivity).onNetworkFailure(errorCode, errorMessage)
}

override fun onResponseFailure(error: CloudError?) {
    (activity!! as BaseActivity).onResponseFailure(error)

}

override fun showLoader(msg: String?) {
    (activity!! as BaseActivity).showLoader(msg)

}

override fun showLoader(msg: String?, isCancellable: Boolean?) {
    (activity!! as BaseActivity).showLoader(msg, isCancellable)

}

override fun dismissLoader() {
    (activity!! as BaseActivity).dismissLoader()
}

}
Create your confirm Dialog like this -
public class AddEmailDialogFragment extends BaseDialogFragment implements View.OnClickListener {
public static final String TAG = AddEmailDialogFragment.class.getSimpleName();
private Button btnSubmit;
private EditText etEmail;

private GetEmailCallback getEmailCallBack;

public static AddEmailDialogFragment newInstance() {
    return new AddEmailDialogFragment();
}

public void setListener(GetEmailCallback listener) {
    getEmailCallBack = listener;
}

@Nullable
@Override
public View onCreateView(@NotNull LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_askemail, container, false);

}

@Override
public void onViewCreated(@NotNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    initObjects();
    initWidgets();
    registerListeners();
}

@Override
public void initObjects() {

}

@Override
public void registerListeners() {
    btnSubmit.setOnClickListener(this);

}

@Override
public void initWidgets() {
    View view = getView();
    btnSubmit = view.findViewById(R.id.btn_submit);
    etEmail = view.findViewById(R.id.et_email);

}

@Override
public void onClick(View view) {
    if (view.getId() == R.id.btn_submit) {
        saveEmail();
    }
}

private boolean isValidEmail(String target) {
    return (!TextUtils.isEmpty(target) && Patterns.EMAIL_ADDRESS.matcher(target).matches());
}

private void saveEmail() {
    if (isValidEmail(etEmail.getText().toString()))
        getEmailCallBack.gotEMail(etEmail.getText().toString());
    else
        etEmail.setError(getString(R.string.err_invalidEmail));
}

}
And call the dialog fragment using this-
    val activity = activity
        if (null != activity) {
            addEmailDialogFragment = AddEmailDialogFragment.newInstance()
            addEmailDialogFragment!!.show(getActivity()!!.supportFragmentManager, AddEmailDialogFragment.TAG)
            addEmailDialogFragment!!.isCancelable = false
            addEmailDialogFragment!!.setListener(this)
        }

A: I got this issue after updating the version of androidx appcompat dependency.
For Temporary I have resolved this issue by the below solution.
Use
implementation 'androidx.appcompat:appcompat:1.0.2'

instead of
implementation 'androidx.appcompat:appcompat:1.1.0'


text:
Q: Is this proof of the $\lim_{(x,y)\to (0,0))} \frac{x^6y}{x^8+y^4}$ correct? Let $\varepsilon>0$ be arbitrary. Note that $||(x,y)-(0,0)||<\delta \implies \sqrt{x^2+y^2}<\delta$, which in turn yields $|x|<\delta$ and $|y|<\delta$.
Now, let $\delta=\varepsilon$ and assume that $||(x,y)-(0,0)||<\delta$. From what we just proved, $|x|<\varepsilon$ and $|y|<\varepsilon$. Finally, we have:
$$\bigg|\frac{x^6y}{x^8+y^4}\bigg|=\frac{|x|^6|y|}{|x|^8+|y|^4}<\frac{\varepsilon^7}{\varepsilon^8+\varepsilon^4}<\frac{\varepsilon^7}{\varepsilon^4}<\varepsilon^3$$
Since $\varepsilon^3\to 0$ as $\varepsilon\to0$, the limit is $0$.

A: No, this is not correct. Your first equality does not hold, nor do your later inequalities (remember that if $a < b$ then $\frac1a > \frac1b$).
To explore this further, consider what happens if you approach the origin:
a) along the curve $y = x^2$
b) along the curve $y = 0$

A: actually  the above limit does not exist because if we approach the origin  (0,0) along the curve y =mx^2 (upward parabola)  the limit depends upon m  so taking different values of m we get different limit

A: NO. $(|x|^6|y|<e^7$ and $|x|^8+|y|^4<e^8+e^4)$ does NOT imply that $\frac {|x|^6|y|}{|x|^8+|y|^4}<\frac {e^7}{e^8+e^4}$ for the same reason that $(2<3$ and $1<8)$ does not imply that $\frac {2}{1}<\frac {3}{8}.$
There is no limit. If $0\ne y=x^2$ then $\frac {x^6y}{x^8+y^4}=\frac {1}{2}$ but if $x=0\ne y$ then $\frac {x^6y}{x^8+y^4}=0.$


text:
Q: React Native components are behaving strangely, showing inverted shadows/different colors to background I've started up a new expo react-native project after a few month hiatus, and there seems to be some issue with colouring of the background components.
The code:
import {
  StyleSheet,
  Text,
  View,
  StatusBar,
  SafeAreaView,
  TextInput,
  TouchableOpacity,
  Dimensions,
} from "react-native";

export default function App() {
  return (
    <View>
      <Text>hahahh</Text>
      <TextInput
        style={{ width: Dimensions.get("screen").width * 0.8, borderWidth: 1 }}
      />
      <TouchableOpacity
        style={{ width: 340, backgroundColor: "red", height: 500 }}
      ></TouchableOpacity>
      <TextInput
        style={{
          width: Dimensions.get("screen").width * 0.8,
          borderWidth: 1,
          alignSelf: "center",
          top: 100,
        }}
      />
    </View>
  );
}

I don't quite know how to explain it, but the color width-wise of widgets is some shade of grey, with an inverted shadow. It's really bizarre I can't see this on my monitor using a virtual device, but viewing the screenshot on my phone, it's quite clear there's a color difference.

The arrows point to the areas the color changes take place
Extract from package.json:
"expo": "~45.0.0",
"expo-status-bar": "~1.3.0",
"react": "17.0.2",
"react-dom": "17.0.2",
"react-native": "0.68.2",
"react-native-web": "0.17.7",


text:
Q: WebKit or Gecko with .NET In my searching I've found WebKit.NET, but I'm not sure that's what I'm aiming for. To be clear, I'm aiming to use a rendering engine like Gecko or Webkit with .NET. I'm hoping to use it within a service or website back-end to allow the rendering engine complete the rendering of the webpage and let JavaScript do its thing, and then return the end result of the DOM to the caller. Are there any other .NET implementations?

A: IF you want a "windowless" rendering engine then try http://awesomium.com/ .
It is based on Chrome/WebKit and supports among other things the scenario you describe.
There is a free license, a "Pro" license and a source code license...


text:
Q: Integration problem with full derivative I am trying to find out what type of integration is used to solve this problem and what are the rules behind it. I am sorry, if this question is quite basic, but I do not study Mathematics.
The homework problem and its answer
The translation of the text: Test, if this differential form is a full differential. Calculate the finite change dv integrating this differential form from the start of coordinates to the point (a,b) along two tajectories: (0,0)->(a,0)->(a.b) and (0,0)->(0,b)->(a,b).
I would be extremely thankful for any kind of help!
Best regards,
Austėja


text:
Q: Using user's token to make requests to Twitter API in Rails I'm using Omniauth to get credentials from Twitter for a specific User.  Part of the OmniAuth object that I get is like this:
credentials=#
<Hashie::Mash secret="XXXX" token="XXXX">
extra=#<Hashie::Mash access_token=#<OAuth::AccessToken:xxxx @token="xxxx", @secret="xxxxx", ..

Right now I'm storing the credentials[token] and the UID for that specific User.  At some point I want to fetch the Twitter API using the auth for that specific User to avoid getting the 150 max requests for a specific IP.  Right now I'm just doing this:
twitter_user_name = Twitter.user(user_id).screen_name

So, how can I do to make those requests using the Twitter gem using the auth provided by OmniAuth instead of doing requests from my own IP (unauthenticated calls and therefore limited)

A: After playing with the gem, I've figured how to do it:
You want to create a new API object for a specific User, so you want to do this:
client = Twitter::Client.new(:oauth_token => 'XXXXX', :oauth_token_secret => 'XXXX')

And use this client to do the requests.


text:
Q: How to mimic built-in .NET serialization idioms? I have a library (written in C#) for which I need to read/write representations of my objects to disk (or to any Stream) in a particular binary format (to ensure compatibility with C/Java library implementations). The format requires a fair amount of bit-packing and some DEFLATE'd bytestreams. I would like my library, however, to be as idiomatic .NET as possible, however, and so would like to provide an API as close as possible to the normal binary serialization process. I'm aware of the ability to implement the IFormatter interface, but being that I really am unable to reuse any part of the built-in serialization stack, is it worth doing this, or will it just bring unnecessary overhead. In other words:
Implement IFormatter and co.
OR
Just provide "Serialize"/"Deserialize" methods that act on a Stream?

A good point brought up below about needing the serialization semantics for any case involving Remoting. In a case where using MarshalByRef objects is feasible, I'm pretty sure that this won't be an issue, so leaving that aside are there any benefits or drawbacks to using the ISerializable/IFormatter versus a custom stack (or, is my understanding remoting incorrectly)?

A: I have always gone with the latter.  There isn't much use in reusing the serialization framework if all you're doing is writing a file to a specific framework.  The only place I've run into any issues with using a custom serialization framework is when remoting, you have to make your objects serializable.
This may not help you since you have to write to a specific format, but protobuf and sqlite are good tools for doing custom serialization.

A: I'd do the former.  There's not much to the interface, and so if you're mimicking the structure anyway adding an ": IFormatter" and the other code necessary to get full compatibility won't take much.

A: Writing your own serialization code is error prone and time consuming.
As a thought - have you considered existing open-source portable formats, for example "protocol buffers"? This is a high density binary serialization format that underpins much of Google's data transfer etc. Versions are available in a wide range of languages - including Java/C++ etc (in the core Google distribution), and a vast range of others.
In particular, for .NET-idiomatic usage, protobuf-net looks a lot like XmlSerializer or DataContractSerializer (indeed, it can even work purely with xml/wcf attributes if it includes an order on each element) - or can use the specific protobuf-net attributes:
[ProtoContract]
class Person {
    [ProtoMember(1)]
    public string Name {get;set;}
}

If you want to guarantee portability to other implementations, the recommendation is to start "contract first", with a ".proto" file - in this case, something like:
message person {
    required string name = 1;
}

This .proto file can then be used to generate any language-specific variant; so with protobuf-net you'd run it through "protogen" (included in protobuf-net; and a VS2008 add-on is in progress); or for Java/C++ etc you'd run it through "protoc" (included in Google's protobuf). "protogen" in protobuf-net can currently emit C# and VB, but it is pretty easy to add another language if you want to use F# etc - it just involves writing (or migrating) an xslt.
There is also another .NET version that is a more direct port of the Java version; as such it is less .NET idiomatic. This is dotnet-protobufs.


text:
Q: How to draw a loop with an arrow at the end I'm trying to draw a loop arrow beginning and ending at a point, but the arrow head is missing. Here's the code:
\begin{tikzpicture}

\node [circle,fill=black,inner sep=0,minimum size=4,label=below:\Large$P$] (P) at (0,0) {};

\draw (P) to [->,-stealth,thick,out=300,in=30,looseness=20] (P);

\end{tikzpicture}

What is shown is a loop but without the arrowhead. How to fix this so it shows the arrow head?

A: Do you want something like this ?
\documentclass[12pt]{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\node [circle, draw] (P) at (0,0) {$P$};
\draw[->,>= stealth]  (P) edge [out=120,in=60,distance=15mm]   (P);
\end{tikzpicture}
\end{document}

Closer to your original post you may also use :
\begin{tikzpicture}
\node [circle, draw, fill=black, label=below:$P$] (P) at (0,0) {};
\draw[->,>= stealth]  (P) edge [out=120,in=60,distance=15mm]   (P);
\end{tikzpicture}

to obtain

A:
 \begin{tikzpicture}\tikzstyle{loop right} = [thick,->,>=stealth,
    out=60,in=-60,looseness=20]

    \node [circle,fill=black,inner sep=0,minimum size=4pt,label=
    {[yshift=-3pt]below:\Large$P$}] (P) at (0,0) {};

    \path (P) edge [loop right] (P);

 \end{tikzpicture}


text:
Q: Регулярное выражение с исключением Доброго времени суток! Нужна помощь в написании регулярного выражения. В базе есть таблица chars с полями id, title, val, в которой хранятся значения val, например:

*

*|Хром матовый|Золото|

*|Антик|Хром|

*Квадратный

*Круглый

(Символ "|" не означает, что я пытался таблицу рисовать, этот символ относится к строке, которая хранится в поле val.)
Проблема в следующем: мне необходимо по запросу получить title, часть условия в запросе первоначально была такая:

WHERE val LIKE '%$value%'

Но в таком случае, если $value='Хром', то подходят записи с val равном как |Антик|Хром| (что правильно), так и |Хром матовый|Золото| (что неправильно).
Заменил LIKE на RLIKE, написал такое выражение:
$rlike='('.$value.'[^[:space:]])';
WHERE val RLIKE '$rlike'

Получилось, что при $value='Хром' всё идеально, т.к. поля с таким значением содержат несколько так сказать наборов переменных (разделены "|"), но когда, например, $value='Круглый', он ничего не находит. (
Помогите написать правильную регулярку!
A: Так?
where '|'+val+'|' rlike '|$value|'

А можете рассказать, зачем вам такая структура данных, с которой вы работать не можете/не умеете?
Обновление
Все просто. Ваша структура находится не в первой нормальной форме. И недостатки проектирования вы пытаетесь оправдать каким-то регулярками. Очевидно правильный вариант - декомпозиция, после которой написать запрос не составит никакого труда. И вопрос бы вы не задавали, разумеется.

Да, естественно код в ответе работать не будет, т.к. формат регулярных выражений для mysql свой. Это был псевдокод.

Вот вам фидл с работающим запросом.
where CONCAT('|',val,'|') rlike '.*[[.vertical-line.]]$value[[.vertical-line.]].*';


text:
Q: AlwaysOn Geo Dispersed Automatic Failover I'm looking to implement a "not quite" hub and spoke type architecture using AlwaysOn and wondered how the cluster quorum might play into this scenario if a remote site can't connect to the hub where we setup a file share witness or the other nodes in the underlying cluster. If the remote location was the primary for the AG and had a local secondary and also a remote secondary (Corp), would the AG automatically failover to the remote secondary even though there may not be an issue inside the remote location?
For example: The hub we will call corporate and the remote locations we will call stores, all on the same AD domain. I put all twelve stores (two servers each, a primary and a local secondary) and the corporate server (will be a central secondary to each of the remote primary servers) into the cluster together (not using Failover Clustering, just the backbone of AlwaysOn) and setup a file share witness. Now let's say that store 1 looses WAN connectivity back to corporate for a few hours. Since neither of the servers (primary or local secondary) can connect to any other store (node) and the file share witness can't be reached, will the Availability Group automatically failover if I have it set for Automatic Failover and Database Level Health Detection? Or will it understand that it has gotten separated from the cluster and simply do nothing?
I realize this is a bit of a complex use case when it comes to AlwaysOn, but thought I'd see if anyone had knowledge of how this scenario might work.

A: There is a max of 8 secondary replicas for AlwaysOn in SQL 2016, I do not believe there is a change for that in 2017

Always On Availability Groups on 2016 supports up to eight secondary replicas including one primary replica and two synchronous-commit secondary replicas (no Enhancement on this compared to SQL 2014). Also use SQL Server 2016 Always On Availability Groups to provide high availability for SQL Server databases hosted in Azure, etc. Source

In any case adding a local secondary would not add value from a SQL failover scenario.  Only the instance with votes for quorum can be primary, of these there can only be three potential primaries

Another enhancement is an increase in the number of Automatic Failover partners which means you can have two more failover partners apart from the primary. In a three node scenario, if one node fails still we can have high availability with other two nodes. Source

Automatic failover requires synchronous-commit, Spreading synchronous-commit over geographic distance can have an impact on performance.
If you have a 3 node cluster (file share and other quorum considerations excepted ...), any node that can not talk to the at least one of the other two will be down. If all three loose connection, there will be no auto failover (all three will be down). If any two can talk, one of those two will be primary.
Any of the replicas that can communicate with the current primary can have asynchronous copies that are current.   So if corporate goes down, one of your two stores will be primary, and you could have several stores with asynchronous read only copies.
Given your scenario you probably want the primary at corporate, and your two synchronous-commit automatic failover partners at the stores that provide the fastest and most dependable connections to corporate.


text:
Q: Rendering points and polygons with Mapnik I've tried to render a few maps in Mapnik and I have a little problem. I want to render a map that contains two layers: point and polygon. I've used this script:
import mapnik
rule = mapnik.Rule()
rule.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color("darkgreen")))
rule.symbols.append(mapnik.PointSymbolizer())
style = mapnik.Style()
style.rules.append(rule)
layer = mapnik.Layer("mapLayer")
layer.datasource = mapnik.Shapefile(file="polska.shp")
layer.styles.append("mapStyle")
map = mapnik.Map(640, 480)
map.background = mapnik.Color("white")
map.append_style("mapStyle", style)
map.layers.append(layer)
map.zoom_all()
mapnik.render_to_file(map, "map.png", "png")

There is only one shapefile to render, but that is my problem. When I'm adding the 4th line rule.symbols.append(mapnik.PointSymbolizer()), I always get rendered polygons with additional points (centroids of each object I guess):

Why are there black points? Is there any possibility to render two layers (polygons and points) at the same time, without these centroids? What am I doing wrong?

A: I realise this is a hella-old question, but maybe someone else faces a similar problem and is scratching their heads over it.
The issue appears to be that your shapefile contains 2 layers, but you only add one mapnik layer; mapnik isnot going to be able to style two independent sets of data if it only has one layer.
Then you feed it the whole shapefile as the layer's datasource - I think mapnik.Shapefile() assumes that the shapefile only has one layer (so maybe it just yanks out the first layer?).
If there are two layers in your shapefile, and you can't access them independently using mapnik.Shapefile(), then each could be loaded into a separate layer by using mapnik.Ogr().
Assume polska.shp has two layers:

*

*a polygon layer called "polylayername" and

*a points layer called "ptlayername".

The following will give two mapnik layers from the data...
poly_lyr = mapnik.layer('polygons')
poly_lyr.datasource= mapnik.Ogr(file="polska.shp",layer="*polylayername*")
pt_lyr = mapnik.layer('points')
pt_lyr.datasource= mapnik.Ogr(file="polska.shp",layer="*ptlayername*")

Then go on with the styling as usual: each layer can be styled separately.
If the shapefile doesn't have two layers, you're kinda boned. But it should be possible to split out the points data (in QGIS, or using mapnik.Ogr() with layer_by_sql, 'querying' the points out by their aspatial characteristics).

A: You should create a separate style for the points.
s = mapnik.Style()
r = mapnik.Rule()
point_sym = mapnik.PointSymbolizer()
point_sym.filename = './symbols/airport.png'
r.symbols.append(point_sym) # add the PointSymbolizer to the rule object
s.rules.append(r)
m.append_style('airport point', s)

Now instead of black dots the points will be the image found at './symbols/airport.png'. In order to move the points you would have to add a different layer with a data source containing the Point geometries. If you want to add points dynamically in your script check out mapnik.MemoryDatasource
I have to assume that the reason your points are centered is because your shape file contains both polygons and points. You could add the proper points to your shape file so that mapnik would render them automatically. If I didn't answer your question please post your shape file and we can get to the bottom of it.


text:
Q: Why equals function not working? when i compile the code below it shows that the (string) username and myList.get(0) are equal to but the equals function returning false why same also happen for password .
btnLogIn.addActionListener(new ActionListener()
 {
   public void actionPerformed(ActionEvent e) {

    String Username=(String) textField.getText();   //fatch the user name from text field
    String Password=(String) textField_1.getText();  //fatch password frof text field
    databaseconnection connect = new databaseconnection(); // databaseconnection class object to connect to data base
    ArrayList myList = connect.search(Username,Password);  //serch the username and password in data base
            System.out.println((String)myList.get(0));  //for testing
            System.out.println((String)myList.get(1));  //for testing
            System.out.println(Username);               //for testing
            System.out.println(Password);               //for testing
            System.out.println(Username.equals(myList.get(0)));  //for testing
            System.out.println(Password.equals((String)myList.get(1)));   //for testing
            if(Username.equals(myList.get(0))&&Password.equals((String)myList.get(1))){
            System.out.println("Hello"+Username);
            }
        }
    });

this is my databaseconnection class
   import java.sql.*;
   import java.util.ArrayList;

 public class databaseconnection{
Statement stmt  ;
ResultSet rs ;
Connection conn;
ArrayList<String> temp = new ArrayList<String>();

public void getconnection(){

try{

    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

    Connection conn = DriverManager.getConnection("jdbc:odbc:Database1","","");

    stmt = conn.createStatement();

}
catch(Exception e){
    System.out.println("connection error");
}
}
public ArrayList  search(String Username,String Password){

    getconnection();
    try{
    rs = stmt.executeQuery("select username,password from login where username = \'"+Username+"\'");
    if(rs.next()){
    String tempString=rs.getString("username");
    temp.add(tempString);
    tempString= rs.getString("password");
    temp.add(tempString);
    }
    }
    catch(Exception e){
    System.out.println("search error");
    }
    return temp;
  }

  }

A: I rewrote your code as:
String Username = "user";
String Password = "pass";

List<String> myList = new ArrayList<>();
myList.add("user");
myList.add("pass");

System.out.println(Username);
System.out.println(Password);
System.out.println(myList.get(0));
System.out.println(myList.get(1));
System.out.println(Username.equals(myList.get(0)));
System.out.println(Password.equals(myList.get(1)));

if (Username.equals(myList.get(0)) && Password.equals(myList.get(1))) {
    System.out.println("Hello, " + Username);
}

And now it works. Note the <String> after the List declaration. That's called generics and says that only Strings can be put into the list. It also removes any need of explicit casting which is error-prone and should be done only in cases when you are sure that you can do it safely.
If you changed your code according to this and still didn't get the right results, make sure the values from your connection are right and don't contain any sort of invisible characters.

Also, in Java, variable names are usually in lowerCamelCase. Class names should be in UpperCamelCase. See Java naming conventions.
Don't forget to close your connections! Java 7 automatic resource management helps you with that. In a general case, you also should handle any connection errors.
And it's a good idea to name your variables by what they do. Therefore, your code should look more like this:
public void actionPerformed(ActionEvent e) {
    String username = "user";
    String password = "pass";

    List<String> dtbSearchResults;
    try (DatabaseConnection connection = new DatabaseConnection()) {
        dtbSearchResults = connection.search(username, password);
    } catch (SomeExceptionYouReallyShouldHandle e) {
        // seriously, handle it here
    }

    System.out.println(username);
    System.out.println(password);
    System.out.println(dtbSearchResults.get(0));
    System.out.println(dtbSearchResults.get(1));
    System.out.println(username.equals(dtbSearchResults.get(0)));
    System.out.println(password.equals(dtbSearchResults.get(1)));

    if (username.equals(dtbSearchResults.get(0)) && password.equals(dtbSearchResults.get(1))) {
        System.out.println("Hello, " + username);
    }
}

It's still not perfect, because the search() method should return an instance of type UserCredentials or an instance of List<UserCredentials> based on what it should exactly do. UserCredentials would then look like this:
public class UserCredentials {

    private final String username;
    private final String password;

    public UserCredentials(String username, String password) {
        // maybe some validity checks
        this.username = username;
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

}

With this class implemented, your code would look like this (assuming search() should return only one result):
public void actionPerformed(ActionEvent e) {
    String username = "user";
    String password = "pass";

    UserCredentials user;
    try (DatabaseConnection connection = new DatabaseConnection()) {
        user = connection.search(username, password);
    } catch (SomeExceptionYouReallyShouldHandle e) {
        // seriously, handle it here
    }

    System.out.println(username);
    System.out.println(password);
    System.out.println(user.getUsername());
    System.out.println(user.getPassword());
    System.out.println(username.equals(user.getUsername()));
    System.out.println(password.equals(user.getPassword()));

    if (username.equals(user.getUsername())
            && password.equals(user.getPassword())) {
        System.out.println("Hello, " + username);
    }
}

Please ask any additional questions if you have any.

A: Define myList as type ArrayList<String>


text:
Q: Why is pygrapviz(neato) overlapping my clusters? I am trying to draw a graph from the following dot file. The neato algo is overlapping the nodes while the dot one puts the clusters side by side when I want them to be like in a top down order.
This was added here because StackOv says I did not add enough detais
graph  {
    graph [mindist=0.5,
        overlap=False,
        ranksep=1
    ];
    node [fontsize=11];
    edge [fontsize=9,
        len=4
    ];
    subgraph cluster_avvc {
        graph [label=AVVC,
            rank="same; 1"
        ];
        avvcsw1      [data="<__main__.N9KSwitch object at 0x02E24490>"];
        avvcsw2      [data="<__main__.N9KSwitch object at 0x02E248D0>"];
    }
    subgraph cluster_spines {
        graph [label=Spines,
            rank="same; 2"
        ];
        sp1      [data="<__main__.N9KSwitch object at 0x02E15D50>"];
        sp2      [data="<__main__.N9KSwitch object at 0x02E156B0>"];
    }
    subgraph cluster_bl {
        graph [label="Border Leafs",
            rank="same; 3"
        ];
        bl1      [data="<__main__.N9KSwitch object at 0x02E15F10>"];
        bl2      [data="<__main__.N9KSwitch object at 0x02E153B0>"];
    }
    avvcsw1 -- sp1 [key=0,
    color=blue,
    headlabel="Eth1/52",
    interfaces="{'sp1': 'Eth1/52', 'avvcsw1': 'Eth2/1'}",
    taillabel="Eth2/1"];
    avvcsw1 -- extLB [key=0,
    color=blue,
    headlabel="E1/2",
    interfaces="{'avvcsw1': 'Eth1/34', 'extLB': 'E1/2'}",
    taillabel="Eth1/34"];
    avvcsw1 -- extLB [key=1,
    color=blue,
    headlabel="E1/1",
    interfaces="{'avvcsw1': 'Eth1/33', 'extLB': 'E1/1'}",
    taillabel="Eth1/33"];
    avvcsw2 -- sp2 [key=0,
    color=blue,
    headlabel="Eth1/36",
    interfaces="{'sp2': 'Eth1/36', 'avvcsw2': 'Eth2/1'}",
    taillabel="Eth2/1"];
    avvcsw2 -- intFW [key=0,
    color=blue,
    headlabel="Gi0/0/1",
    interfaces="{'avvcsw2': 'Eth1/33', 'intFW': 'Gi0/0/1'}",
    taillabel="Eth1/33"];
    avvcsw2 -- intFW [key=1,
    color=blue,
    headlabel="Gi0/0/0",
    interfaces="{'avvcsw2': 'Eth1/34', 'intFW': 'Gi0/0/0'}",
    taillabel="Eth1/34"];
    avvcsw2 -- extFW [key=0,
    color=blue,
    headlabel="Gi0/0/0",
    interfaces="{'avvcsw2': 'Eth1/36', 'extFW': 'Gi0/0/0'}",
    taillabel="Eth1/36"];
    avvcsw2 -- extFW [key=1,
    color=blue,
    headlabel="Gi0/0/1",
    interfaces="{'avvcsw2': 'Eth1/35', 'extFW': 'Gi0/0/1'}",
    taillabel="Eth1/35"];
    avvcsw2 -- fgFW [key=0,
    color=blue,
    headlabel="??",
    interfaces="{'avvcsw2': 'Eth1/32', 'fgFW': '??'}",
    taillabel="Eth1/32"];
    avvcsw2 -- esxSvr [key=0,
    color=blue,
    headlabel=vmnic5,
    interfaces="{'avvcsw2': 'Eth1/31', 'esxSvr': 'vmnic5'}",
    taillabel="Eth1/31"];
    bl1 -- sp1 [key=0,
    color=blue,
    headlabel="Eth1/49",
    interfaces="{'sp1': 'Eth1/49', 'bl1': 'Eth2/1'}",
    taillabel="Eth2/1"];
    bl1 -- sp2 [key=0,
    color=blue,
    headlabel="Eth1/1",
    interfaces="{'sp2': 'Eth1/1', 'bl1': 'Eth2/2'}",
    taillabel="Eth2/2"];
    bl1 -- intLB [key=0,
    color=blue,
    headlabel=1.1,
    interfaces="{'bl1': 'Eth1/32', 'intLB': '1.1'}",
    taillabel="Eth1/32"];
    bl2 -- sp1 [key=0,
    color=blue,
    headlabel="Eth1/50",
    interfaces="{'sp1': 'Eth1/50', 'bl2': 'Eth2/1'}",
    taillabel="Eth2/1"];
    bl2 -- sp2 [key=0,
    color=blue,
    headlabel="Eth1/1",
    interfaces="{'sp2': 'Eth1/1', 'bl2': 'Eth2/2'}",
    taillabel="Eth2/2"];
    bl2 -- esxSvr [key=0,
    color=blue,
    headlabel=vmnic2,
    interfaces="{'bl2': 'Eth1/28', 'esxSvr': 'vmnic2'}",
    taillabel="Eth1/28"];
    bl2 -- intLB [key=0,
    color=blue,
    headlabel=1.2,
    interfaces="{'bl2': 'Eth1/32', 'intLB': '1.2'}",
    taillabel="Eth1/32"];
}

Edit: I updated the dot file with the complete config so you can try it yourself


text:
Q: Why is this code printing a random character inbetween the input and output lines? I'm trying to write a program (in C) where the input is reversed and printed in reverse line by line. For the most part, the code actually does just that. The trouble is that for some (most) of my input, I will get a random character or an extra newline in between my input and my output in the console.
For example, I start the program, type "testing" into the console, and get "gnitseT" back after hitting enter. This has happened successfully and is what I expect. It looks like this:

Testing
gnitseT

But then when I type "Hello" into the console, it looks like this:

Hello
g                (unexpected)
olleH

Or if I type "running" into the console, instead of getting an unexpected "g" in between my input and output lines, I get an extra newline.

Running
newline here
extra newline here (unexpected)
gninnuR

#include <stdio.h>

void reverse(int length, char s[])
{
    int i;

    for (i = length; i >= 0; i--)
    {
        printf("%c", s[i]);
    }
    printf("\n");

}

int main(void)
{
    char smain[2000];
    int c;
    int i;

    i = 0;
    while ((c = getchar()) != EOF)
    {
        smain[i] = c;
        i++;
        if (c == '\n')
        {
            reverse(i, smain);
            i = 0;
        }
    }

    return 0;
}

The expected behavior is for the program to output into the console the reversed input after the enter key is pressed.
Sometimes, especially at the very beginning of the program, it will work perfectly.
Then, it starts giving me a random character in between my input and output, or it starts giving me an extra newline.
I would like to have it so that it just prints the input in reverse order without any unexpected odd characters showing up in between the input and the output.
Thanks for any help.

A: Your immediate problem is you are reading and attempting to print one character past the end of the characters stored in your array with
for (i = length; i >= 0; i--) {
    printf("%c", s[i]);
}

Why? You add length characters to smain in main(). In C, arrays are zero-based. The characters in your string are from 0 -> length-1 (the nul-character in a string is located at s[length], but here you never add a nul-terminating character, so the value at that index is simply indeterminate). If the element has not been initialized (which it will not be on your first word or any subsequent word equal to or longer than your longest word entered at that time) Undefined Behavior results since you are attempting to read and print an indeterminate value from an uninitialized element in array. How your terminal will output the indeterminate is undefined -- and may well result in a G being printed.
To correct the problem, loop for (i = length - 1; i >= 0; i++) or very simply:
while (length--)
    printf ("%c", s[length]);

putchar ('\n');     /* don't printf a single-character */

(note: don't call the variadic printf function to output a single-character, that is what putchar() is for)
Putting it altogether and fixing your logic so you don't add and print the '\n' as part of every word you are reversing, you could do:
#include <stdio.h>

#define MAXC 2048   /* if you need a constant, #define one (or more) */

void reverse(int length, char s[])
{
    while (length--)
        printf ("%c", s[length]);

    putchar ('\n');     /* don't printf a single-character */
}

int main (void) {

    char smain[MAXC];
    int c, i = 0;

    while ((c = getchar()) != EOF) {
        if (c == '\n') {
            reverse(i, smain);
            i = 0;
        }
        else
            smain[i++] = c;
    }
    if (i)  /* protect against file with no POSIX end-of-file */
        reverse (i, smain);

    return 0;
}

(note: the if {...} else {...} logic to prevent adding the '\n')
Example Use/Output
$ printf "Hello\nGoodbye\n" | ./bin/prnrevlines
olleH
eybdooG

Which will work just as well without the POSIX eof, e.g.
$ printf "Hello\nGoodbye" | ./bin/prnrevlines
olleH
eybdooG

A: on line 29
++i;

this means "i" now have length+1 so, you have been out of the string, you can change the program to :
#include <stdio.h>

void reverse(int length, char s[])
{
    int i;

    for (i = length; i >= 0; i--)
    {
        printf("%c", s[i]);
    }
    printf("\n");

}

int main(void)
{
    char smain[2000];
    int c;
    int i;

    i = 0;
    while ((c = getchar()) != EOF)
    {
        smain[i] = c;
        if (c == '\n')
        {
            reverse(i, smain);
            i = 0;
        }
        else i++;
    }

    return 0;
}


text:
Q: trigonometric range of given function I came up with this sum in my exam its like what is the range where $$\frac{\tan(x)}{\tan(3x)}$$ is never defined . I made all terms in $tan(x)$ and then was going to differentiate but that approach in a competitive exam seems useless . Any good hints, solution !!

A: Let $\displaystyle f(x) = \frac{\tan x}{\tan 3x} = \frac{\tan x\cdot (1-3\tan^2 x)}{3\tan x-\tan^3 x} = \frac{1-3\tan^2 x}{3-\tan^2 x}$
Now Put $\tan x=t\;,$ We get $$\displaystyle y=f(t) = \frac{1-3t^2}{3-t^2}$$
So $$y(3-t^2) = (1-3t^2)\Rightarrow 3y-t^2y = 1-3t^2$$
So $$(3y-1)=t^2(y-3)\Rightarrow t^2= \frac{3y-1}{y-3}$$
Now Using $$t^2\geq 0$$

A: $$\tan 3x = \frac{3\tan x-\tan^3x}{1-3\tan^2x}$$
$$\frac{\tan x}{\tan 3x} = \dots = 3 - \frac8{3-\tan^2x}$$
$$\tan^2x\ge0$$
$$3-\tan^2x\le3$$
$$3-\tan^2x<0 ~~~\text{or}~~~0< 3-\tan^2x\le3$$
$$\frac1{3-\tan^2x}\le 0~~~\text{or}~~~\frac1{3-\tan^2x}\ge \frac13$$
$$\frac8{3-\tan^2x}\le 0~~~\text{or}~~~\frac8{3-\tan^2x}\ge \frac83$$
$$-\frac8{3-\tan^2x}\ge 0~~~\text{or}~~~-\frac8{3-\tan^2x}\le -\frac83$$
$$3-\frac8{3-\tan^2x}\ge 3~~~\text{or}~~~3-\frac8{3-\tan^2x}\le \frac13$$
$$\frac{\tan x}{\tan 3x}\ge 3~~~\text{or}~~~\frac{\tan x}{\tan 3x}\le \frac13$$
Hence:
$$R_{\frac{\tan x}{\tan 3x}} = (-\infty,\frac13]\cup(3,+\infty)$$


text:
Q: Storing a byte array into MySQL binary column with JdbcTemplate I have a MySQL table (simplified):
CREATE TABLE `tokens` (
    `token` BINARY(16) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

And I try to insert a row like this:
JdbcTemplate jdbcTemplate; // org.springframework.jdbc.core.JdbcTemplate
...
String sql = "INSERT INTO `tokens` (`token`) VALUES (?)";
String token = "123e4567e89b12d3a456426655440000"; // UUID
jdbcTemplate.update(sql, new Object[]{token.getBytes()});

But I get this exception:
Data truncation: Data too long for column 'token' at row 1

What do I do wrong? Thanks.
Edit: see my answer, I missed the hexadecimal conversion (token is an UUID).

A: Here is the solution to store the token (which is an UUID):
jdbcTemplate.update(sql, new Object[]{DatatypeConverter.parseHexBinary(token)});

Let us know if there are other ways...


text:
Q: Microsoft Dynamics CRM or SQL Server? In my organisation we write many custom mobile solutions for many different clients. We have started utilizing Microsoft Dynamics CRM 2011 in some of our test products however almost all of the work we are using it for is done with custom entities and the solutions are utilizing it as a back-end database. From my impressions so far, using CRM in this way is counter-intuitive and slow.
From your experience, would there be any benefit I am not seeing by using CRM instead of a normal SQL Server? I have only seen very basic stuff on the CRM front-end but am not sure how the custom entities become useful in CRM?

A: I write a lot of code for CRM and you are right, it isn't quick. It's benefits aren't for the developer though, they are for the end user. Through workflow and customisation they can create their own system to their own needs and can use the in-built entities to help manage their businesses.
That said, if you are not putting CRM in front of the customer (or using it internally for its true purpose) and are just using it as a database for your application, then this is not a good approach. You'd be better off talking directly to SQL Server.

A: Microsoft (and many partners) leverage Dynamics CRM as a platform for rapid and extensible development.  There is a term we use: xRM that implies you can build many different applications types faster than traditional custom development.
I have used Dynamics CRM in situations simply because of it amazingly granular security capabilities (and built a custom UI for most of the users).  Building a row-level security mechanism with the capabilities found in OOB Dynamics CRM 2011 would be a daunting task in itself...I often tell my new CRM developers, "when you are building your CRM, make sure you include: user data imports, row-level security, solution file deployments, simple form customization, custom views, etc."
With CRM 2011, you start with all of that and have a product with well designed extension points (plugins, workflows, web resources, JScript API, OData, SOAP).  All without writing, testing, debugging a single line of code.  The other thing I tell developers: coding is expensive, so don't write code :)


text:
Q: Clear browser cache for load renamed file I have some images in a folder that I rename (like 1000.jpg 2000.jpg...) with PHP script and when PHP return to html the images don't have been reloaded in the right order, instead of what's happened in directory. How can i clear browser cache from file and image without using Chrome standard function in PHP or javascript?
something like this
header("Expires: Tue, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

or like
location.reload(true)

doesn't work

A: You can try something like this:
<img src="1000.jpg?<?php echo(time());?>">


text:
Q: JSLint: Expected an identifier and instead saw 'class' (a reserved word) JSLint tells me "Expected an identifier and instead saw 'class' (a reserved word)"
$("<a/>", {
  class: "fr" // Error appears here
}).attr("data-name", f)

NOTE: The code runs find without any errors I'm just wondering....
What can I do to get rid of this lint from appearing while still having my function run without errors?
Full code for function...
var showFiles = function() {
  listFiles.forEach(function(f) {
    $("[data-action=filetree]").append(
      $("<div/>").append(
        $("<a/>", {
          text: f
        }).attr("data-name", f)
        .attr("data-nme", f)
        .attr("data-location", "file://" + __dirname + "/content/project/" + f),

        $("<a/>", {
          class: "fr"
        }).attr("data-name", f)
        .html("<i class=\"fa fa-times\"></i>")
        .attr("data-delete", "file://" + __dirname + "/content/project/" + f)
      )
    );
  });
};
showFiles();

A: You can also disable JSLint at the file scope or at the single-line scope by using a directive in the comments. This section from the JSLint documentation seems to point to the rule that is applying. You should be able to disable it by writing something like.
/*jshint es5: false */

Hopefully this helps, and it may be more preferable than quoting your object property names.


text:
Q: Template Mode in api.ai is not working with Google Assistant I have on Dialogflow agent and I want to sync it with google assistant.
For user says section, I want to use Template mode. It works fine in api.ai, but when I click on option 'See how it works in Google Assistant', it throws error like 'Request contains an invalid argument.
Query pattern contains invalid characters in custom intent '999154f0-830a-480b-bdc9-2e9e89f45cdd': $SchemaOrg_Color:color $SchemaOrg_Text:query $quantifier:quantifier @sys.unit-currency:unit-currency $Filters:Filters'
After checking each and every annotations, I came to know that @sys.unit-currency:unit-currency is creating issue. Its working with api.ai agent but not with google assistant.
I've attached screenshot of intent. What's need to be corrected? I went through many blogs, but not able to find any help regarding this.


text:
Q: Linked List Help, Singly Linked (Multiple Structures) (C Programming) I need some help with Linked Lists.
I have figured out how to do individual linked list, but I am struggling when trying to implement multiple struct's and lists.
My last program was all used with Structs but now I must implement linked list's.
It says to use "External Pointers" in the functions to use in traversing through the various lists.
This is homework for one of my classes, I am not asking for you all to do it for me, but I am asking to help point me in the right direction.
The structs are as follows:
            struct stockItem
            {
              char stockName[60];
              char stockType[60];
              int itemNumber;
              float actualCost;
              float markUp;
              int totalCurrentInventory;
              int monthlyRestock;
              float price; //stores actual cost + markup

            };

            struct roomData
            {
              float widthFeet, widthInch;
              float lengthFeet, lengthInch;
              char roomName[100];
              int roomNumberOfType;
              char roomType[6]; //char of room type
              int roomStock[100][2]; //for storing each room stock types
              int roomHasStock; //if the room has a stock avaliable
              int roomStockCount; //how many stocks the room has
              float area;  // sq ft
              float rentalRate;
              float profitsPerRoom;
              float netProfit;
              float grossProfit;
              char stockLine[200];
            };

            struct staffData
            {
                char firstName[100];
                char lastName[100];
                char fullName[100];
                int employeeNumber;
                char typeOfEmployee[10];
                char payType[10];
                float hourlyWage;
                float salary;
                int hours;
                char address[150];
                char city[150];
                char state[10];
                int zip;
                char phone[30];
                float yearlyTotalPay;

                struct hireDate //holds staff hire date
                {
                  int month;
                  int day;
                  int year;
                }hireDate;

                struct birthDate //holds staff birth date
                {
                  int month;
                  int day;
                  int year;
                }birthDate;
            };

A: typedef struct YourStructNode_ {

   struct YourStructNode_ * next;
   struct YourStructNode_ * prev;

   YourStruct data;

} T_YourStructList;

Replace "YourStruct" by the name of your structs to make a doubly linked list.
Even if you make more than once T_XXXX_List with this pattern you should manipulate the list with the same function since the two first fields of T_Node is always the same.
Write add, insert, remove functions to manipulate this structure.

A: Is your linked list supposed to utilize the structs that you have developed? This way you have a linked list where each node contains an instance of all of those structs you listed.
struct node {
  struct node *left;
  struct node *right;
  roomData room;
  stockItem stock;
  staffData staff;
  hireDate hire;
  birthDate birth;
};


text:
Q: Query builder like Drupal's Database API? I'm looking to branch out of plain mysql and mysqli and try to use something way better for database access thats not a DAO layer (adds too much complexity here).
When I did some Drupal development I had to use its Database API. It was really nice most of the time, allowing you to build queries and have it escape everything for you. PDO and mysqli prepared statements don't come close to the niceness and cleanliness of the Drupal Database API. And I still can't figure out how to, for example, use a prepared statement in mysqli to insert an unknown size of rows without building the query yourself, defeating the purpose of prepared statements. Its just getting in my way
Example from actual code of Drupal API
$query = db_select('tcsync_queue', 'q')
    ->condition('q.id', $post["tcsync_lastrecord"], '>')
    ->fields('q', array('id', 'uid', 'type', 'name', 'data'))
    ->execute();

foreach ($query as $item) {
    $updateitem = array(
        "id" => $item->id,
        "uid" => $item->uid,
        "type" => $item->type,
        "name" => strtoupper($item->name),
        "data" => $item->data);
    ....
}

Is there a query builder that accomplishes some close to Drupal's query builder?

A: I think you'd like the Doctrine 2's DBAL.
I'll throw some saple code for you:
    $locationIds = array(1,2,3,4,5,6,7);

    $locationTreeDepthQb = $conn->createQueryBuilder();
    $locationTreeDepthQb->select("COUNT(*) as count")
        ->from('location_tree_data', 'd')
        ->where("d.tree_depth >= 2")
        ->andWhere("d.tree_id IN (?)");
    $stmt = $conn->executeQuery($locationTreeDepthQb->getSQL(), array($locationIds), array(Connection::PARAM_INT_ARRAY));
    $res = $stmt->fetch();

Please note how easy is to pass an array for a "IN" SQL statement in this query builder.
Documentation can be found here:
http://www.doctrine-project.org/docs/dbal/2.2/en/

A: CodeIgniter does this really well:
e.g.
Select:
$this->db->select('title')->from('mytable')->where('id', $id)->limit(10, 20);
$query = $this->db->get();

Insert:
$this->db->set('title',$title)->insert('mytable');

Update:
$this->db->where('id', $id)->set('title',$title)->update('mytable');

See: http://codeigniter.com/user_guide/database/active_record.html

A: You might be looking for the NotORMHomepage PHP library. It's quite lightweight (which I think is what you ask for) and a stand-alone component so you don't have the burden with integration so much.
It works with PDO as the connection object:
include "NotORM.php";
$pdo = new PDO("mysql:dbname=software");
$db = new NotORM($pdo);

so it supports any database that is available in PDO.
You can then just run queries in an easy fashion, this is an example for a database with an application table:
foreach ($db->application() as $application) { // get all applications
    echo "$application[title]\n"; // print application title
}

When it comes to where and limits, it works like this:
$applications = $db->application()
    ->select("id, title")
    ->where("web LIKE ?", "http://%")
    ->order("title")
    ->limit(10)
;
foreach ($applications as $id => $application) {
    echo "$application[title]\n";
}

It does things well, which is not the case with similar looking code, for example the sql code in codeigniter.

A: https://github.com/kenaniah/insight/blob/master/classes/query.php can be modified to stand on its own.


text:
Q: Hitting enter does not invoke javascript function in HTML form I have a simple form with one input field. It works fine when I use the submit but hitting enter in the text field reloads the page with the form variable in the URL.
I looked through the many solutions available online (except for JQuery since it seems like overkill for something this simple) and haven't been able to get 'enter' to work. Any help would be great
<form name="myform" action="" method="GET" > Enter text:

  <input type="text" name="queryinput" onkeyup="if(isEnterPressed(event)){initialize(this.form.queryinput.value);}">

  <input type="button" name="Search" value="Search" onClick="initialize(this.form.queryinput.value);">
  <input type="submit" value="Reset" onclick="reset();" />
</form>

function isEnterPressed(e){
  var keycode=null;
  if (e!=null){
    if (window.event!=undefined)
      if (window.event.keyCode) keycode = window.event.keyCode;
      else if (window.event.charCode) keycode = window.event.charCode;
    }else{
            keycode = e.keyCode;
    }
  }
return (keycode == 13);}

Edit 1: Version using onsubmit instead of the keycode listeners:
<form name="myform" action="" onsubmit="return initialize(this.form.queryinput.value)"  method="GET"> Enter text:

<input type="text" name="queryinput">
<input type="submit" value="submit" >
<input type="button" value="Reset" onclick="clearAllPoints();"/>
</form>

Using onSubmit causes the click button to behave the same as hitting enter but neither version works.

A: Try using the onSubmit event for the form rather than the onClick event for the input element.  It seems that onClick is firing only when it's physically clicked by a mouse (which makes sense, I've just never encountered it like this I guess).  The onSubmit event, however, should fire regardless of how the form is submitted.

A: If you set your field outside of the form, it will not auto-submit the form when you press enter.  Then you can have your button copy the text inside the input field to a hidden field inside the actual form and then submit it.
--edit, added code--
Enter text:

<input type="text" id="myinputfield">
<form name="myform" id="myform" action="" method="GET">
  <input type="hidden" name="queryinput" id="queryinput">
  <input type="button" value="Submittal button" onclick="doSubmitForm();" />
</form>


text:
Q: How To migrate windows service in Azure service fabric I want to migrate typical windows service which is written in .net to Azure using Service fabric.
To implement this , I am creating one service fabric application containing one micro service as guest executable which uses .exe of windows service and deploying application package to service fabric cluster.
After deploying service fabric application on cluster I want windows service should install & start automatically on all nodes however at any time application is running on any single node. I want windows service should run on only one node at a time.
Please kindly help to implement this.

A: You can certainly run your service as a guest executable. Making sure it only runs on one node can be done by setting the instance count to 1 in the manifest, like so:
  <Parameters>
    <Parameter Name="GuestService_InstanceCount" DefaultValue="-1" />
  </Parameters>
  ...
  <DefaultServices>
    <Service Name="GuestService">
      <StatelessService ServiceTypeName="GuestServiceType"
                        InstanceCount="[GuestService_InstanceCount]">
        <SingletonPartition />
      </StatelessService>
    </Service>
  </DefaultServices>

Or, you could actually migrate it, not just re-host it in the SF environment...
If your Windows Service is written in .NET and the you wan't to benefit from Service Fabric then the job of migrating the code from a Windows Service to a Reliable Service in Service Fabric should not be to big.
Example for a basic service:
If you start by creating a Stateless Service in a Service Fabric application you end up with a service implementation that looks like (comments removed):
internal sealed class MigratedService : StatelessService
{
    public MigratedService(StatelessServiceContext context)
        : base(context)
    { }

    protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
    {
        return new ServiceInstanceListener[0];
    }

    protected override async Task RunAsync(CancellationToken cancellationToken)
    {
        // TODO: Replace the following sample code with your own logic
        //       or remove this RunAsync override if it's not needed in your service.
        long iterations = 0;
        while (true)
        {
            cancellationToken.ThrowIfCancellationRequested();
            ServiceEventSource.Current.ServiceMessage(this.Context, "Working-{0}", ++iterations);
            await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
        }
    }

The RunAsync method starts running as soon as the Service is up and running on a node in the cluster. It will continue to run until the cluster, for some reason, decides to stop the service, or move it to another node.
In your Windows Service code you should have a method that is run on start. This is usually where you set up a Timer or similar to start doing something on a continuous basis:
protected override void OnStart(string[] args)
{
  System.Timers.Timer timer = new System.Timers.Timer();
  timer.Interval = 60000; // 60 seconds
  timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer);
  timer.Start();
}

public void OnTimer(object sender, System.Timers.ElapsedEventArgs args)
{
    ...
    DoServiceStuff();
    Console.WriteLine("Windows Service says hello");
}

Now grab that code in OnTimer and put it in your RunAsync method (and any other code you need):
protected override async Task RunAsync(CancellationToken cancellationToken)
{
    while (true)
    {
        cancellationToken.ThrowIfCancellationRequested();
        DoServiceStuff();
        ServiceEventSource.Current.ServiceMessage(this.Context,
            "Reliable Service says hello");
        await Task.Delay(TimeSpan.FromSeconds(60), cancellationToken);
    }
}

Note the Task.Delay(...), it should be set to the same interval as your Windows Service had for it's Timer.
Now, if you have logging in your Windows Service and you use ETW, then that should work out of the box for you. You simply need to set up some way of looking at those logs from Azure now, for instance using Log Analytics (https://learn.microsoft.com/en-us/azure/log-analytics/log-analytics-service-fabric).
Other things you might have to migrate is if you run specific code on shut down, on continue, and if you have any parameters sent to the service on startup (for instance connection strings to databases). Those need to be converted to configuration settings for the service, look at SO 33928204 for a starting point for that.

A: The idea behind service fabric is so that it manages your services, from deployment and running. Once you've deployed your service/application to the service fabric instance it will be just like running a windows service (kinda) so you wont need to install your windows service. If you're using something like TopShelf you can just run the exe and everything will run totally fine within service fabric.


text:
Q: How to merge a jpg with a gif without lossing the animation of gif file? I am trying to merge a splash screen image which is in jpg format with an ajaxloader which is in gif format.
I tried the following command using ImageMagik:
convert -delay 50 splashimage.jpg ajaxloader.gif final.gif
This command does merge the gif file with the jpg image but the loader appear at the top-left corner.
I was wondering if there is an option available to place it at a specfic (x,y) point on the jpg image?
If anybody has had done a similar thing or has an idea as to how a similar thing can be achieved, please guide me through.
Thanks.

A: Why would you want to do this? You'd be turning a nice 24bit JPG into a crappy quality single frame on an 8bit gif. You could just use some CSS tricks to overlay the loader .gif on top of the .jpg on a webpage, which would not sacrifice any image quality to achieve the same effect.

A: I solved the problem by designing individual frames of images with the desired location of my text and merged them using Imagemagik.


text:
Q: How do i repeat data in Microsoft excel in relative with variable? Hi I have a List of names and a variable, i need an excel formula or Add-on or an automated method to repeat the names based on the number in the variable.
I need a formula to automate Output column,
eg:

A: Probably as clean as I can make it. There is a For loop and Do Until loop to give you options.
Sub repeat()
    ' define varible types
    Dim i, n As Integer
    Dim wb As Workbook: Set wb = Workbooks(ThisWorkbook.Name)
    Dim ws As Worksheet: Set ws = wb.Worksheets("Sheet1")
    Dim LastRow As Long

    ' initialize variables
    n = 1
    i = 1

    ' do loop until empty cell is found in column 1 (A)
    Do Until IsEmpty(ws.Cells(i, 1))
        ' second loop to define number of iterations
        For n = 1 To ws.Cells(i, 2)
            ' find last row to keep adding to the bottom of the list
            LastRow = ws.Cells(ws.Rows.Count, "C").End(xlUp).Row
            ' populate list
            ws.Cells(LastRow + 1, 3) = ws.Cells(i, 1)
        Next
        i = i + 1
    Loop

End Sub

A: I thought this was a great puzzle to do without VBA.
Solved it by making index column, repeat column and iteration column...Then do some vlookup and hlookup stuff. Should be noted that Vlookup needs to be a sorted list to work.
Here is a link to my example where I tried to show you.


text:
Q: Comments show path Here is what I have in my comments controller:
def show
  @comment = Comment.find(params[:id])
end

private

def find_commentable
  params[:commentable_type].constantize.find(params[:commentable_id])
end

In my users controller:
  def show
    @user = User.find_by_username(params[:id])
    @comments =  @user.comments.find(:all, :order => "id desc", :limit => 20)
  end

In my user show:
<% @comments.each do |comment| %>
<%= truncate(comment.body, length: 100) %>
<%= link_to "Expand comment", post_comments_path(comment) %>
<% end %>

When clicking on the link I get this error:
undefined method `constantize' for nil:NilClass

These are the highlighted lines:
def find_commentable
  params[:commentable_type].constantize.find(params[:commentable_id])
end

The url I am taken to is:
/15/comments

When I need to be going to:
/2/comments/15

2 being the post id and 15 being the comment id. How do I get this working?
The comments path:
post_comment GET    /:post_id/comments/:id(.:format)      comments#show

 @commentable = find_commentable
  @comment = @commentable.comments.build(params[:comment])

A: Your problem is here:
<%= link_to "Expand comment", post_comments_path(comment) %>

Look at your rake routes and see what the actual parameters it's using.  You can pass them like so:
post_comments_path(post_id: post_id, id: comment_id)

Or another way is simply use the order
post_comments_path(post_id, comment_id)

Then in your controller you should actually use these id's:
@post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])

Since you only want the comment and you have its id, you can ignore the post id and just do this in your controller:
@comment = Comment.find(params[:id])

And then call it like this:
post_comment_path(id: comment.id, post_id: 0)


text:
Q: meaning of pool number in default name of thread in ScheduledExecutorService I am using ScheduledExecutorService to maintain a thread pool of core size 10

ScheduledExecutorService visiblityThreadPool =
  Executors.newScheduledThreadPool(10);

Now in the log I see thredName as pool-39-thread-3 .
I am ok with thread number 3 assuming that thread number can vary from 1 to 10 but how come the pool number in the name in 39 ?
What does 39 indicates here ? Please put some light on it.

A: That string is the name prefix for Thread objects initialized from a java.util.concurrent.Executors$DefaultThreadFactory.
The source code of this class looks like
/**
 * The default thread factory
 */
static class DefaultThreadFactory implements ThreadFactory {
    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    DefaultThreadFactory() {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() :
                              Thread.currentThread().getThreadGroup();
        namePrefix = "pool-" +
                      poolNumber.getAndIncrement() +
                     "-thread-";
    }

    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r,
                              namePrefix + threadNumber.getAndIncrement(),
                              0);
        if (t.isDaemon())
            t.setDaemon(false);
        if (t.getPriority() != Thread.NORM_PRIORITY)
            t.setPriority(Thread.NORM_PRIORITY);
        return t;
    }
}

The number following the pool- is therefore generated from an AtomicInteger stored in a static field. Each DefaultThreadFactory instance gets an "id" of sorts, representing how many others instances where initialized before it (+1).
Since most ExecutorService factory methods in Executors make use of this DefaultThreadFactory, you can also assume that this number represents how many thread pools were created through the ExecutorService.


text:
Q: Erasing from std vector with size_type index results in compiler error? // second try: correct but potentially slow
vector<Student_info> extract_fails(vector<Student_info>& students)
{
    vector<Student_info> fail;
    vector<Student_info>::size_type i = 0;

    // invariant:elements [0, i) of students represent passing grades
    while (i != students.size())
    {
        if (fgrade(students[i]))
        {
            fail.push_back(students[i]};
            students.erase(students.begin() + i);
        } else
            ++i;
    }
    return fail;
}

The code above comes from the book "Accelerated C++" and will calculate user marks. Based on a failing or passing grade, the result is put into a fail vector for students that fail. students is the vector that contains student who will pass
All is fine and well, however when I change the following line from
students.erase(students.begin() + i);

to
students.erase(i);

I get the following compiler error:

error: no matching function for call to 'std::vector, std::allocator>::erase(size_t&)'

Even though I think they are functionally the same. Could anyone explain what causes this?

A: The "no matching function for call" basically says it all. There is no such erase function which takes a "size_t" as an argument. And that is the whole reason for the perhaps seemingly strange students.erase(students.begin() + i); in the first place.

A: You should you iterator to move through the vector. So you can call iterator = students.erase(it), and it will give you the correct iterator to continue without problem.
Something like this
for( vector<Student_info>::itreator it; = students.begin(), it != students.end(); it++)
{
    if(fgrade(*it))
    {
        fail.push_back(*it);
        it = students.erase(it);
    }
}


text:
Q: How to Stop MVC Page Refresh After Ajax Call url Change when Keyboard Enter Pressed When i Write text in Text box and Press Enter then My page refresh and URL Change i am Upload Page Snap and You can see in Image .
Here is my JQgrid code when i enter text in textbox then data show in jQgrid .
How to Stop page refresh when i enter textbox value and press keyboard Enter button .
Here is my code of HTML AND Jquery i want to stop page refresh when enter value in text box and Press Enter then my page Regresh and page link has change
Here is Page link http://localhost:11736/Home/Index?

jQuery(document).ready(function($) {

  jQuery("#searchAll").change(function() {
    var $grid = $("#searchGrid");

    $grid.jqGrid({
      url: '@Url.Action("Search_All")',
      datatype: 'json',
      postData: {
        mSearch: function() {
          return $("#searchAll").val();
        }
      },
      jsonReader: {
        id: 'MemberShipID'
      },
      colModel: [{
          name: 'MemberShipID',
          index: 'MemberShipID',
          label: 'MemberShip ID',
          width: 20
        },
        {
          name: 'MembershipName',
          index: 'MembershipName',
          label: 'Membership Name',
          width: 30
        },
        {
          name: 'address',
          index: 'address',
          label: 'address',
          width: 50
        },
        {
          name: 'address1',
          index: 'address1',
          label: 'address1',
          width: 50
        },
        {
          name: 'FileID',
          index: 'FileID',
          label: 'File ID',
          width: 20
        },
        {
          name: 'SectorName',
          index: 'SectorName',
          label: 'SectorName',
          width: 20
        },
        {
          name: 'PhaseName',
          index: 'PhaseName',
          label: 'PhaseName',
          width: 20
        },
        {
          name: 'PlotCategory',
          index: 'PlotCategory',
          label: 'PlotCategory',
          width: 20
        },
        {
          name: 'RPersonName',
          index: 'RPersonName',
          label: 'RPersonName',
          width: 20
        },
        {
          name: 'CityName',
          index: 'CityName',
          label: 'City',
          width: 10
        },
        {
          name: 'CountryName',
          index: 'CountryName',
          label: 'Country',
          width: 10
        }
      ],
      additionalProperties: [],
      loadonce: true,
      navOptions: {
        reloadGridOptions: {
          fromServer: true
        }
      },

      formEditing: {

        closeOnEscape: true,
        closeAfterEdit: true,
        savekey: [true, 13],
        reloadGridOptions: {

          fromServer: true
        }
      },
      viewrecords: true,
      height: 300,
      width: 1200,
      rowNum: 100,
      autoheight: true,
      rowList: [10, 20, 30, 50, 100, 500],
      pager: "#jqGridPager",
      rownumbers: true

    });

  });

});

<form class="app-search">
  <input type="text" class="form-control" id="searchAll" placeholder="Search for...">
</form>

A: As far as I understand, your problem is the default submit behavior of form tag that raise submit event when Enter key is pressed.
To prevent that event you can use the following code
jQuery(document).ready(function(){
    jQuery("form.app-search").submit(function(e){
        e.preventDefault();
    });
})

Where jQuery("form.app-search") is a jquery selector that look for form tags having class app-search, even you can write a very specific Id(# selector).
Try FIDDLE
Hope this works for you.

A: $(document).keypress(function(e)
  { if(e.keyCode === 13) // 13 is ASCII-code for keyboard ENTER key
  { e.preventDefault(); return false; } });


text:
Q: How to select a subset of Avro files from Azure Data Lake Gen2 by data content I have lots of Avro files in an Azure Data Lake Gen2 storage sent by an Event Hub service with capture enabled. These Avro files contain data from different sensors and engines. The structure of the directory is organized in folders with the following path format (typical of Azure Blobs):
namespace/eventhub/partition/year/month/day/hour/minute/file.avro
I need to access to some of these files, in order to get data to 1) pre-process and 2) train or re-train a machine learning model. I'd like to know what procedure could I follow to download or mount just the files containing data of a particular engine and/or sensor, given that not data from all of them are present in all Avro files. Let's assume I'm interested just in files containing data from:
Engine = engine_ID_4012
Sensor = sensor_engine_4012_ID_0114

I'm aware that Spark offers some advantages working with Avro files, so I could consider to carry out this task using Databricks. Otherwise the option is Azure Machine Learning service, but maybe there are other possiblities, for instance a combination. The goal is to speed up the data ingestion process, avoiding to read files with no needed data.
Thanks.

A: Thanks for reaching out. In azure machine learning, you can:
1. create a datastore to connect to your storage service (ADLS Gen2 in your case)
sample code: https://learn.microsoft.com/en-us/azure/machine-learning/how-to-access-data#azure-data-lake-storage-generation-2

2. create a filedataset from the adlsgen2 pointing to your avro files.
sample code: https://learn.microsoft.com/en-us/azure/machine-learning/how-to-create-register-datasets#create-a-filedataset

3. learn about how to download or mount those files on your compute in ML experiments:
https://learn.microsoft.com/en-us/azure/machine-learning/how-to-train-with-datasets


text:
Q: Query to display specific columns using a Set operator I am trying to use a Set operator to show country names(Table A col.) without a city(Table B col.) and cities(B) without a country(A). I have also tried to write this query using LEFT JOINS, which I show below and I included Table C(Regions) because I am not sure whether to use that primary key in a LEFT JOIN.
Table A (Countries):
Column_name   |   Column_id
              |
COUNTRY_ID    |     1
COUNTRY_NAME  |     2
REGION_ID     |     3

Table B (Locations):
Column_name   |   Column_id
              |
LOCATION_ID   |     1
   CITY       |     4
COUNTRY_ID    |     6

Table C(Regions):
Column_name   |   Column_id
              |
 REGION_ID    |     1

I have tried the following:
SELECT c.country_name, l.city
FROM Countries c
LEFT JOIN Locations l ON c.country_id = l.country_id

UNION

SELECT c2.country_name, l2.city
FROM Countries c2
LEFT JOIN Locations l2 ON c2.country_id = l2.country_id;

The SQL statement above returned all Table A values, and Table A values that do not contain Table B values (Countries that do not have Cities).
I also tried this statement below and got the exact same result:
SELECT c.country_name, l.city
FROM Countries c
LEFT JOIN Locations l ON c.country_id = l.country_id
LEFT JOIN Regions r ON r.region_id = c.region_id;

The one thing it is missing is Table A values not found in Table B (Countries not found in Cities.)

A: There are a lot of options to get your desired result. One way is to use LEFT JOIN to get the countries without city and RIGHT JOIN to get the cities without country:
SELECT c.country_name, l.city
FROM countries c
LEFT JOIN locations l ON c.country_id = l.country_id
WHERE l.city IS NULL
UNION ALL
SELECT c.country_name, l.city
FROM countries c
RIGHT JOIN locations l ON c.country_id = l.country_id
WHERE c.country_name IS NULL;

Another possibility is to use two LEFT JOIN, but starting from the opposite table, like this:
SELECT c.country_name, l.city
FROM countries c
LEFT JOIN locations l ON c.country_id = l.country_id
WHERE l.city IS NULL
UNION ALL
SELECT c.country_name, l.city
FROM locations l
LEFT JOIN countries c ON c.country_id = l.country_id
WHERE c.country_name IS NULL;

If you don't like using JOIN at all, you can do this using NOT IN:
SELECT c.country_name, NULL city
FROM countries c
WHERE country_id NOT IN (SELECT country_id FROM locations)
UNION ALL
SELECT NULL country_name, l.city
FROM locations l
WHERE country_id NOT IN (SELECT country_id FROM countries);

Or if you prefer NOT EXISTS, this will work, too:
SELECT c.country_name, NULL city
FROM countries c
WHERE NOT EXISTS (SELECT 1 FROM locations WHERE country_id = c.country_id)
UNION ALL
SELECT NULL country_name, l.city
FROM locations l
WHERE NOT EXISTS (SELECT 1 FROM countries WHERE country_id = l.country_id);

I created an example that shows all these queries will produce the identic outcome: db<>fiddle
Add ORDER BY c.country_name and ORDER BY l.city to the queries in case you want the result set to be sorted by them.
A last, but important note: As you see, I used UNION ALL instead of UNION because I don't see a reason why to use UNION in your use case. UNION ALL is much faster, so I recommend to use that unless there is a really convincing reason to do not use it. The only advantage of UNION is that it does not show duplicate rows, but I think they are very unlikely in your situation, so it should not be required.

A: The simplest illustration of using a set operator to find countries without cities would be:
select country_id from countries
minus
select country_id from locations

COUNTRY_ID
----------
         1
         4

As you need the country name, you just need to look it up:
select country_name from countries
minus
select c.country_name from locations l
       join countries c on c.country_id = l.country_id;

COUNTRY_NAME
-----------------
England
Italy

Cities without a country (or with an invalid country code) is simpler as a left join and filter:
select l.city, l.country_id
from   locations l
       left join countries c on c.country_id = l.country_id
where  c.country_id is null

CITY
-----------------
Berlin
Tokyo

If the requirement really is to do this using set operators, you would (conceptually) look for cities whose country_id is in the set of (location countries minus city countries):
select l.location_id, l.city, l.country_id
from   locations l
where  l.country_id in
       ( select country_id from locations
         minus
         select country_id from countries )

However this wouldn't give you locations whose country_id was null.


text:
Q: Can you use a USB to expand the Xbox's storage? I have an Xbox 360 4GB, and I just bought GTA V, but it needs 8GB.  Can I use a USB or hard drive to use its storage so I don't need to buy a new Xbox?

A: You can expand your storage space.
The stick must be formatted to the xbox file system and can be then only used on the xbox, also the maximum possible size is 32GB. To format the usb stick:

*

*Plug in stick

*Press th Guide button and go to Settings tab and select System settings

*Select storage

*Select USB storage

*Click configure now

*Move the reserved storage slider you your wanted level, preferably use the
wholestick. Note that 512Mb of your stick is used for xbox system files so
it cannot be used to save game data. (So for gta you should get a 16GB stick,
8GB isn't enough.

*All done, you can now save your GTA to the stick

Guide adapted from xbox support

A: You can use a 32GB USB stick by just plugging it in and then going to the storage options in the system preference area and formatting it for use with the Xbox. Be warned that after doing this, you can't use it on regular PC's without reformatting it.
Any larger than 32GB and it only allows you to use 32GB for games, and the rest will be allocated to video/image files (or not recognized, I forget).
Furthermore, you don't need to buy a new Xbox if you want to get more storage space. You can just purchase a 320GB hard drive and plug it in on the top (there's either a panel that you can remove if its a slim or the hard drive is connected on top if you own the older white Xboxs). Be warned that if you choose to do this, you will most probably need to do a content transfer which will require an additional cable.

A: You can.
But you must format this USB to use it for the XBox. So you can use it only for the XBox.
And the maximum space of the USB is 32GB! So do not use bigger USB's.