Probability of Collision [binary vector]

Question: Given a collection of nonzero distinct binary vectors $x_1,..., x_m \in {0,1}^n$. To make look up faster, we hash them to vectors of length $p<n$ by means of a lienar mapping $x_i \rightarrow Ax_i$ where $A$ is a $p\times n$ matrix with 0-1 entries, and all computations are performed modulo 2.
Suppose the entries of the matrix are picked uniformly at random (each independent coin toss)...
1- If we were to pick any $1 \leq i < j \leq m $ what is the prob. that $x_i$ and $x_j$ hash to the same vector and we have a collision?

My attempt: I think that this is similar to the birthday problem from
  https://preshing.com/20110504/hash-collision-probabilities/ but I'm really unsure that we are bringing in an exponential 'e'. I'd guess from that link that the probability of collision = 1 - prob(no collision). So P(collision )= $1- e^{-p*(p-1)/2m}$ =$1- e^{-2*(2-1)/2m}$ = $1- e^{-1/m}$. Is that correct or completely the wrong? ... or would you leave the answer in terms of p (I think we only pick one i and j so we can simplify here?

2- Prove that if $p \geq 2log_2 m$, then with probability atleast $\frac{1}{2}$ there are no collisions among the $x_i$.

My attempt: I'd say I need the answer to above (which is why I was concerned) .... but we would need $\frac{1}{2} =$ P(No Collision) =$e^{-p*(p-1)/2m}$ ... but this is not simplifying to $log_2$ and instead would mean $2mln(\frac{1}{2})= -p^{2}-p$. which is wrong b/c I will have that ln follow around ...
Comment: sorry for you 1- why are you doing a birthday problem type argument? when you  are just asking about a particular x_i being hashed to a particular x_j or am I reading this incorrectly?
Comment: I thought birthday problem can tell you what prob. the x_i and x_j would collide... I'm guessing this is not the case (why not?)
Comment: I think your wording is wierd pick any $1 \leq i < j \leq m $  that means you fix a particular i,j  and ask if they collide which is not the same thing as there is a collision for some x_i,x_j
Comment: Whoops updated the problem to say $x_i$ and $x_j$ hash to the same vector , so then your answer makes sense :) of how to ge to $(2^p)^2 + 2^p$ let me just ask why are we comparing to the $ \geq 2^p$ is that the p(collision)?
Answer: I think you should have 2^p in place of p in your formula then you get the correct answer
Since you are mapping into {0,1}^p each x_i gets sent to a random entry of {0,1}^p uniformly at random  so it's the birthday problem with 2^p birthdays and m persons so by your estimate
$\frac{1}{2} =$ P(No Collision) =$e^{-(2^p)*(2^p-1)/2m}$
$2mln(\frac{1}{2})= -(2^p)^{2}+(2^p)   $.
which is closer
I think it's best if you use the theorem that you get probability about 0.5 if you have that the square root of the number of possible birthdays is equal to the number of people (once both are large enough)
Comment: Can I get the reason behind $\geq 2^p$ (originally problem statement says  P(no collision)$\geq \frac{1}{2}$  not the $2^p$?
Comment: sorry thats a typo
Answer: Hints: Note that $Ax_i=Ax_j$ if and only if $A(x_i-x_j)=0$. By assumption $x_i-x_j\neq 0$ for $i\neq j$. So you can reduce your problem to determining the probability $Az=0$ for any $z\neq 0$. Can you show that each component of $Az$ is uniformly random in $\{0,1\}$, and that the components are independent?
If you can, this will imply the probability $Ax_i=Ax_j$ is $1/2^p$. By linearity of expectation, this means the expected number of collisions among all the $x_i$ is ${m \choose 2} 2^{-p}\leq \frac{m^2}{2\cdot 2^p}$. What happens when you plug in $p=2\log_2 m$? Why does this imply what you want about the probability of a collision?
Comment: Wow this looks like were getting at the answer. I just need a bit more help, how did you go from 1/2^p to (m 2) 2^-p <= m^2/(2*2^p) ... you mentioned linearity of expectation, can you help me out here.How can the expected value of 1/2^p become that inequality... After plugging in the p=2log_m in that inequality it gets to (m choose 2 ) is <= to 1/32  ... I'm guessing were supposed to end to m >= 1/2?


XML Schema - xs:string - multiple occurrences

Question: How should be formatted a given XML file to validate against the following schema?
...
<xs:element name="myElement">
 <xs:complexType>
<xs:all>
  <xs:element minOccurs="0" maxOccurs="3" name="myStringNode" type="xs:string"/>
</xs:all>
</xs:complexType>
</xs:element>
...

Indeed, the constraints above describe that MyElement->stringNode must contain a string, which may occur multiple times. But what does that mean in case of multiple strings (3 or more)?

Should be the enclosed strings separated by spaces, commas, ... or
nothing?
Has maxOccurs a real meaning?
Should this XML validate/invalidate against the schema above?
<myElement>
<myStringNode>str1 str2 str3 str4 str5</myStringNode>
</myElement>
Answer: yes it validates your example because "str1 str2 ..." is seen as a single string. If you want multiple myStringNode you just have to use multiple tags like :
<myElement>
     <myStringNode> here is your string </myStringNode>
     <myStringNode> here is your other string </myStringNode>
</myElement>

And maxOccurs specifies the number of element <myStringNode> you can add in an element <myElement>.


If I leave a companion in F:NV can I get him back later?

Question: I've been running with Boone for a while and, while he's a good marksman, he's kind of a nuisance. The Legion are the only group I'm in bad blood with and he just likes to run into them headfirst, often throwing all attempts to a stealth approach to the dirt.
If I let a companion go for somebody else:

Can I "get" him back later?
Where will he be?
Are there other complications?
Answer: Dismissing a companion is typically a temporary thing that you can do whenever you want and as often as you want.  You can go solo or change your mind about your companions as many times as you wish.  However, there are some caveats.
If your companions don't like the things you're doing (ie, they're "good" and you're doing "evil" things, or they're NCR-friendly and you're helping the Legion) they may give you a warning, and if you continue, they may leave permanently.  In some cases you can avoid these conversations by not ever speaking to them.  However, this will prevent you from dismissing them, as talking to them would cause them to leave permanently.
When dismissed, companions will return to their homes, or to the Presidential Suite of the Lucky 38 if you've got access to that via the main storyline missions.  Note that their homes are not always where you found them originally - Raul, for instance, doesn't live where he is found by the Courier.  There will usually be a notification about where they are headed when you dismiss them.
DLC companions are a special case - they cannot leave their DLCs to return to the Mojave with you.  Likewise, you can't take the main game companions into DLC.
Answer: First of all, yes, you can get him back later.
When dismissing a companion, they will head back to their home location - by default this is usually around where you first hired them.
You can re-hire them there by talking to them again and asking them to join you for another fancy adventure.
In order to dismiss a companion, choose "Talk To" on the companion wheel, then just follow the appropriate conversation options ("time to part ways", etc). You can also use a Companion dismissal terminal.
This being a Bethesda and Obsidian game, there are obviously also some bugs with companions that may or may not affect you and the ability to actually dismiss and rehire.
Comment: Related: [Where do companions go when dismissed in Fallout: New Vegas?](http://gaming.stackexchange.com/questions/78093/)
Comment: Related: [What are some options for finding my lost companion Veronica, besides a manual search?](http://gaming.stackexchange.com/questions/10225/)


Good technique to trim 2mm or 1/16inch off 2x4 (without a drop saw)

Question: Simple noob question: cutting 2x4's to length, need to make a tight fit (no two the exact same length) so often need to trim 1mm to 4mm (say 1/16 to 1/8th inch) off the end.
Without a dropsaw or skillsaw, what's a good way to do this?  (lengths cut with handsaw) Never used a plane - is it a good tool for this job / do they cut across the grain?
Currently using a random orbital w/ 40 grit. Does the job but there has to be a better way.
Cheers.
Answer: A block plane will do the job - end grain is their forte. Needs to be sharp, like you may never have seen sharp, if you have not used planes before.You'll also want to set the one you are shortening up against a scrap piece so that the plane does not tear-out as it leaves the edge of the board. Just let it stick out a millimeter or two beyond the supporting scrap.
Comment: +1 and as the gap tends toward 1/8 or more, a Japanese style pull saw, thin kerf, fine teeth, does pretty good on slim cuts.
Answer: A miter box and a hand saw (or more properly a backsaw) should work (search on google for images)
This will also get you the ability to do accurate angle cuts.
Comment: If you're light on tools, you can use a bit of scrap wood to hold the saw along the line you want to cut: lay the scrap alongside or under your 2x4 but protruding by an inch or so  - enough to reliably hold the saw blade. Clamp it and mark your cut across both pieces. Start cutting the scrap wood and it will hold the saw blade true to your thin cut line, even if bits of your wood break off. I


How to implement Picasso image loading library in android?

Question: I am new to android I have tried Glide library with YouTube tutorial, but I want to use Picasso library.
Code I am using currently:
Glide.with(this).load(currentUser.getPhotoUrl()).into(navUserPhoto);

Comment: Learn about Picasso library in the documentation
Comment: Hello Welcome to stackoverflow please read this [how-to-ask](https://stackoverflow.com/help/how-to-ask)
Comment: Picasso.with(getBaseContext()).load(model.getImage()).placeholder(R.drawable.placeholder).into(viewHolder.imageView);
Comment: For more details try project link: https://github.com/square/picasso, For implementation try this : https://www.journaldev.com/13759/android-picasso-tutorial
Answer:
Import picasso library to your project:

implementation 'com.squareup.picasso:picasso:2.71828'

Use picasso instead of Glide:

Picasso.get().load(currentUser.getPhotoUrl()).into(navUserPhoto);

Go through picasso documentation if you require extra modifications.
Answer: //install this one in to the build.gradile(Module)
//in dependencies
//After sync the project
implementation 'com.squareup.picasso:picasso:2.71828'


Does the set containing all sets contain itself?

Question: A set containing all sets by definition contains itself. Is that even possible, for a set besides the empty set?
Comment: And by the way, the empty set does not contain itself. It doesn't contain anything.
Comment: Googling the title of your topic gives me [this](https://en.wikipedia.org/wiki/Russell%27s_paradox)
Comment: Within the axioms of ZF there is not set containing all sets due to the axiom of regularity.
Answer: In most modern set theories the collection of all sets is not a set itself. Namely, if $X$ is a set, then there is a set $Y$ such that $Y\notin X$.
Set theories like Zermelo-Fraenkel prove this by showing that if $X$ is a set, then $\{x\in X\mid x\notin x\}$ is a subset of $X$ which cannot be an element of $X$. However, they also prove this using the axiom of regularity which implies that $X\notin X$ for every set $X$, and as you notice the set of all sets must be an element of itself.
However, in the set theory New Foundations there is a universal set. And yes, it is an element of itself. In this set theory, if $X$ is a set, then $\{x\in X\mid x\notin x\}$ does not define a set, so it is not an element of $X$ (it does not exist in the universe).
And while we're clearing things up, the empty set does not contain itself. It is empty, namely $\forall x(x\notin\varnothing)$, and if $\varnothing\in\varnothing$, then $\varnothing$ wouldn't be empty.
Answer: In ZF or ZFC there is no such thing as the set of all sets. There is a class of all sets, but it is a "proper" class, which simply means that it isn't a set. It also means that it is not an element of itself.
Within ZF or ZFC you might additionally ask whether any set (not just the universal set) is an element of itself. In ZF or ZFC there is a separate axiom called the axiom of regularity which forbids this entirely. (Note that you should be careful about the word "contains"; sometimes it appears to mean $\supseteq$ while other times it appears to mean $\ni$. You do have $\emptyset \supseteq \emptyset$ but you don't have $\emptyset \ni \emptyset$. "Is an element of" and "is a subset of" remove this ambiguity.)
In some other set theories there is a universal set. For instance this occurs in NF and NFU. In this case of course the universal set must be an element of itself, because it is also a set.
In any set theory containing a universal set (call it $U$), one must be careful because $S=\{ x : x \not \in x \}$ is paradoxically defined: regardless of what the set theory says, the question "is $S \in S$?" cannot be resolved. In ZF and ZFC, the paradox is resolved by requiring that all comprehensions are over a domain which is already a set: so you would need $\{ x \in U : x \not \in x \}$ but there is no $U$. In NF and NFU, the workaround is forbidding comprehension using a certain class of predicates, including $x \not \in x$.
Answer: As David Ullrich notes, the empty set does not contain itself--it does not contain anything. I suspect, perhaps, that you are confusing $\in$ with $\subseteq$ (you may find this helpful if that is, indeed, the case). Then, note that $A\subseteq A$ for all sets $A$, even when $A=\varnothing$.
On a different note, you may enjoy the following exercise that addresses Russell's paradox, what Zubzub refers to in the first comment (this particular exercise appears in A Transition to Advanced Mathematics):

A logical difficulty arises from the idea, which at first appears natural, of calling any collection of objects a set. A set $B$ is ordinary if $B\not\in B$. For example, if $B$ is the set of all chairs, then $B\not\in B$, for $B$ is not a chair. It is only in the case of very unusual collections that we are tempted to say that a set is a member of itself. (The collection of all abstract ideas certainly is an abstract idea.) Let $X=\{x : \text{$x$ is an ordinary set}\}$. Is $X\in X$? Is $X\not\in X$? What should we say about the collection of all ordinary sets?

After reflecting on that, consider the following:

 Suppose that $X$ is a set. If $X\in X$, then $X$ is not an ordinary set, so $X\not\in X$. On the other hand, if $X\not\in X$, then $X$ is an ordinary set, so $X\in X$. Both $X\in X$ and $X\not\in X$ lead to a contradiction. We conclude that the collection of ordinary sets is not a set.


Binary XML file line #19: Error inflating class only on Android 3.2

Question: I am developing an app that uses fragments with the support library. The app is working and is published, but i get this error report(Only with 3.2 OS versions):
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.naviter.seeyou/com.naviter.seeyou.MenuDisplayActivity}: android.view.InflateException: Binary XML file line #19: Error inflating class
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1815)
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1831)
android.app.ActivityThread.access$500(ActivityThread.java:122)
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1024)
android.os.Handler.dispatchMessage(Handler.java:99)
android.os.Looper.loop(Looper.java:132)
android.app.ActivityThread.main(ActivityThread.java:4123)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:491)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:849)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:607)
dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #19: Error inflating class
android.view.LayoutInflater.createView(LayoutInflater.java:596)
com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
android.view.LayoutInflater.onCreateView(LayoutInflater.java:644)
android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:669)
android.view.LayoutInflater.rInflate(LayoutInflater.java:724)
android.view.LayoutInflater.rInflate(LayoutInflater.java:727)
android.view.LayoutInflater.inflate(LayoutInflater.java:479)
android.view.LayoutInflater.inflate(LayoutInflater.java:391)
com.naviter.seeyou.DisplayFragment.onCreateView(DisplayFragment.java:57)

The Exception is thrown at the last line in the onCreateView method:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState){
    if (container == null)
        return null;
    getActivity().setTitle(R.string.Display);
    return inflater.inflate(R.layout.settings_display, container, false); //here
}

and this is the xml file:

<ListView
    android:id="@+id/listViewDisplay"
    android:layout_width="match_parent"
    android:layout_height="0dip"
    android:layout_weight="1" >

</ListView>

<LinearLayout
    android:id="@+id/rlAsDialog"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <Button
        android:id="@+id/buttonDisplayOk"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="@string/Ok" />

    <Button
        android:id="@+id/buttonDisplayCancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="@string/Cancel" />

</LinearLayout>
</LinearLayout>

I repeat, that the app is runnig well, i got this exception only on few devices with Android 3.2 OS. And i'm importing fragment from:

android.support.v4.app.Fragment;

Any suggestions?
Thanks.
Comment: what do you have on line 19 in your xml?
Answer: There's nothing immediately apparent. I have seen crashes that report that as the primary stack trace with a "caused by" out of memory exception while it's trying to create a bitmap from a resource for the view it's inflating. Perhaps that's what's happening.
Answer: I thing i solved the issue.
I was accidentally extending the class with:

DialogFragment

instead of:

Fragment

And then using a custom layout for DialogFragment. Obviously this causes problems only on Android 3.2
I also find another problem later. In the Manifest i was using the theme Theme.DeviceDefault wich was added in android api level 14 and android 3.2 obviously can't live with this. Then i implemented a theme selector wich chooses the theme depending on the device API level.


How do I change the colors of the Ambiance & Radiance themes?

Question: I am using Ubuntu 11.10 and i wanted to change colors in Ambiance/Radiance themes, by default it has orange and i wanted to change it to Blue,
I tried using gnome-color-chooser, but it didn't work?
any other ideas?
Answer: What you have do is copy radiance as backup and change setting.ini file in themes
by using.
gksu gedit /usr/share/themes/Radiance/gtk-3/settings.ini

Edit:
nselected_bg_color:#f07746

So it says:
nselected_bg_color:#7FADFD

And do the same with gtk-2, using:
gksu gedit /usr/share/themes/Radiance/gtk-2/gtkrc

Otherwise gtk-2 applications like chrome etc will have old orange color
and you are done. Reload the theme using gnome-tweak-tool.
Every GNOME-3 theme works with unity-3d perfectly but with 2D it has fallback window control problem when maximized (means in global panel it has fallback window controls which are ugly as hell, even the themes have unity folder in them and they work fine with 3D)
The colour used above [#7FADFD] is just one example of any number of hex colours that can be employed. Refer to here for other hex colour codes.
Answer: If you are looking to locally change the orange. (selected_bg_color) then in 11.10 & 12.04 you can simply set in gsettings or dconf-editor
Example  - setting to D3B37D
gsettings set org.gnome.desktop.interface gtk-color-scheme "selected_bg_color:#D3B37D"

You can string other overrides in this fashion, example adding a selected_fg_color of 3c3b37
gsettings set org.gnome.desktop.interface gtk-color-scheme "selected_bg_color:#D3B37D;selected_fg_color:#3c3b37"

screen shows where to add visually in dconf-editor, reflects the above command

Comment: graphical utility on screenshot is dconf-editor, not gconf-editor, although very similar, distribution of configurations isn't the same, and mistake made me install gconf-editor for no use at all :(
Answer: There are plenty of Light themes recolorations available on GNOME-Look.
Here's a partial list of some GTK+3 ones I found:

Humanity Icons Colors Version (You'll probably want to recolor your icons to match the rest of your theme)
Ambiance & Radiance Colors Version
Ambiance DS Blue (Tweaks the theme a bit more to change gradients and window buttons, but it also has a dark sidebar if that interests you)

If you use 11.04 or older, you'll want to look for GTK+2 themes instead, but there are even more of those if you search for them.
Answer: If you don't want to change your whole theme, and rather modify the ecxisting ones you can use a nice gui tool called gtk-theme-config.
In order to install it, open a terminal and give the following commands one by one:
sudo add-apt-repository ppa:shimmerproject/ppa
sudo apt-get update
sudo apt-get install gtk-theme-config


KMP prefix construction with NASM

Question: I'm trying to implement the following C code in NASM and then link it to a C program&run from there.
The code I'm trying to implement:
   void preKmp(char *x, int m, int kmpNext[]) {
   int i, j;

   i = 0;
   j = kmpNext[0] = -1;
   while (i < m) {
      while (j > -1 && x[i] != x[j])
         j = kmpNext[j];
      i++;
      j++;
      if (x[i] == x[j])
         kmpNext[i] = kmpNext[j];
      else
         kmpNext[i] = j;
   }
}

My attempt in NASM with my comments:
;nasm -f elf32 table.asm -o table.o

segment .bss
kmpNext resd 256

segment .text
global table

table:
    push ebp          ;save the old base pointer value
    mov  ebp,esp      ;base pointer <- stack pointer

    mov eax,[ebp+8]     ;function argument, eax = search_string
    mov ecx, 0          ;i = 0
    mov edx, -1         ;j = -1
    mov [kmpNext], edx  ;kmpNext[0] = -1
oWhile:
    cmp byte [eax + ecx*4], 0  ;end of array control
    je finished
iWhile:
    cmp edx, -1
    jle pass
    mov edi,[eax + ecx*4] ;edi = x[i]
    mov esi,[eax + edx*4] ;esi = x[j]
    cmp edi, esi
    je pass
    mov edx, [kmpNext +edx*4] ;j = kmpNext[j]
pass:
    inc ecx
    inc edx
    mov edi,[eax + ecx*4] ;edi = x[i]
    mov esi,[eax + edx*4] ;esi = x[j]
    cmp edi, esi
    jne store
    mov edi, [kmpNext + edx*4]  ;edi = kmpNext[j]
    mov [kmpNext + ecx*4], edi  ;kmpNext[i] = edi
store:
    mov [kmpNext + ecx*4], edx  ;kmpNext[i] = j
    jmp oWhile
finished:
    mov eax, kmpNext;

    pop ebp
    ret

My C code in which I call the NASM function:
#include <stdio.h>
#include <string.h>

int* table(char *str);

int main(void)
{
    char str[256];
    int i, n, *pre;

    printf("Enter string: ");
    scanf("%s" , str) ;
    n = strlen(str);
    pre = table(str);
    for (i = 0; i < n; i++){
      printf("%d ", pre[i]);

    }
    printf("\n");
    return 0;
}

Everything compiles and run OK but the output is wrong. For example,
for 'cocacola' I should get: -1 -1 0 -1 0 1 -1 -1
where I get: -1 0 0 0 0 0 0 0
Can someone point out my mistake in the NASM code ?
I suspect that the problem is with this line:
mov esi, [eax + ecx*4]
When I run a debugger, I don't see a change in contents of esi.
Comment: It is **you** seeking help and it is a rule of this site. Otherwise you should use google to find an answer to your question! "Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a [mcve]."
Comment: So why do you think every one knows what "KMP" means and you do not need to provide a clear description? Use a debugger.
Comment: It's irrevelant and everyone has google. I'm just trying to implement the function I provided on the top.
Comment: Everything is clear in my question. Stop whining. Provide an answer if you want to be helpful to other users. I'm just inexperienced with debugging an assembly. This is the reason why I can't be more precise.
Comment: With that attitude you better try on Facebook. People here help voluntarily. EOM
Comment: I'm not arguing or anything. What's lacking in my question ? Please do tell me and I'll do my best to patch it up.
Comment: Your C-function gives me for 'cocacola': -1 0 -1 1 -1 0 2 0. My implementation of the original KMP gives -1 0 0 1 0 1 2 0. What's going on?
Comment: Ok that might be wrong too.
Comment: In the NASM code I don't see the jumps back to `oWhile` and `iWhile`. So the while loops are computed only one time.
Comment: I noticed and fixed that but it still doesn't work.
Answer: 1) The main error is, that str is an array of bytes (8 bits), but you treat it as an array of integers (32 bits).
2) There are two while loops. Both of them need a jump-back for repetition.
3) store is the else-case. It must not run, if the the if-case fits. In this case is appropriate a jump to oWhile.
This is the corrected function:
table:
    push ebp          ;save the old base pointer value
    mov  ebp,esp      ;base pointer <- stack pointer

    push edi          ; callee saved
    push ebx

    mov eax,[ebp+8]     ;function argument, eax = search_string
    mov ecx, 0          ;i = 0
    mov edx, -1         ;j = -1
    mov [kmpNext], edx  ;kmpNext[0] = -1

oWhile:
    cmp byte [eax + ecx], 0  ;end of array control
    je finished

iWhile:
    cmp edx, -1
    jle pass

    mov bl,[eax + ecx] ; bl = x[i]
    mov bh,[eax + edx] ; bh = x[j]
    cmp bl, bh

    je pass
    mov edx, [kmpNext +edx*4] ;j = kmpNext[j]
    jmp iWhile

pass:
    inc ecx
    inc edx

    mov bl,[eax + ecx] ; bl = x[i]
    mov bh,[eax + edx] ; bh = x[j]
    cmp bl, bh

    jne store
    mov edi, [kmpNext + edx*4]  ;edi = kmpNext[j]
    mov [kmpNext + ecx*4], edi  ;kmpNext[i] = edi

    jmp oWhile

store:
    mov [kmpNext + ecx*4], edx  ;kmpNext[i] = j
    jmp oWhile

finished:
    mov eax, kmpNext;

    pop ebx
    pop edi
    pop ebp
    ret

Comment: Still missing some parts I think. For example, aaaa should return -1,0,1,2 rite ?
Comment: @SpiderRico: It does what the C-function does. I'm still convinced that your algorithm is wrong. But that was not the question.
Comment: Ah you're rite! The original algorithm I posted is wrong. I'll work from your code anyway. Thanks
Comment: Or perhaps just a different imp. It's from there ->  http://www-igm.univ-mlv.fr/~lecroq/string/node8.html
Comment: @SpiderRico: It seems that there are different algrithms that produce different tables. My personal implementation of [this algorithm](https://de.wikipedia.org/wiki/Knuth-Morris-Pratt-Algorithmus#Pr.C3.A4fix-Analyse_2) produces indeed -1,0,1,2 .
Answer: oWhile:
    cmp byte [eax + ecx*4], 0

This is not equivalent to while (i < m). It should be:
oWhile:
    cmp ecx,[ebp+12]
    jge finished

You should not mov eax, [kmpNext] before return; it is a void function (though no harm - the compiler will ignore the return value).
Also, you may need to save edi and esi and possibly other registers as otherwise the caller can get confused. Check your C compiler's manual about it.
Comment: That didn't fix it. Problem seems to be related with comparison.
Comment: What exactly does eax contains in my code ? Is it a reference to the string I supplied ? Error seems to be related with it.
Comment: Check `cmp bl, bh': why load/compare the `l` part of the register if `kmpNext` are integers? You should load the full register. Your question: `eax` contains a pointer. You use it corectly.

KMP prefix construction with NASM


Get the document with the max value of a field in MongoDB

Question: I'm using aggregation framework to get the max value of a field from a collection across a set of documents, like this
db.getCollection('Collection').aggregate([
   {$match: {"product": {$in: ["product-a"]}}},
   {$group: {_id: null, maxPrice: {$max: "$price"}}}
])

But what if I want to get the ID of the document that matches this criteria? How can I do that in the next stage of the pipeline?
Answer: You can put all the fields in $max operator like this... It will give you the document for the max field which is used at first in the $max  object. Just I have used price here.
db.getCollection("Collection").aggregate([
  { "$match": { "product": { "$in": ["product-a"] } } },
  { "$group": {
    "_id": null,
    "maxPrice": {
      "$max": {
        "price": "$price",
        "_id": "$_id"
      }
    }
  }}
])

Comment: Thank you so much! I don't know why I didn't thought you can project multiple fields in $max operator
Comment: Will it pick the document with the greatest `_id` in case `price` values are equal?
Comment: @GregoryPakosz then you should put `_id` first.
Comment: If I put `_id` first, then it will pick the document with the greatest `_id` right? What I was wondering is: is `_id` used at all in the comparison. I would say yes, and wanted to confirm is price is the same for two documents, then the document with the greater `_id` wins


Unable to use "locate" command to find a file created in my home directory

Question: I'm new to linux. And I'm just exploring terminal.

I created a file touch Desktop/vvv.
Now I updated the database using sudo updatedb.
The command locate vvv doesn't shows any result.
While it just works fine with find / -name vvv .

I have found that is that locate doesn't seem to search in my home directory, as it shows results from usr, var, slib, opt, etc. directories.

Why I'm saying this is because when I try to locate some random file like complete which is in Download directory (which is not quite a unique name), it will show results from other directories but not Download.
Update:
To demonstrate this, I've copied this from terminal:
aditya@ubuntu16:~$ cd /usr/

aditya@ubuntu16:/usr$ ls

bin  games  include  lib  local  locale  sbin  share  src

aditya@ubuntu16:/usr$ sudo touch aaaa

[sudo] password for aditya:

aditya@ubuntu16:/usr$ ls

aaaa  bin  games  include  lib  local  locale  sbin  share  src

aditya@ubuntu16:/usr$ sudo updatedb

aditya@ubuntu16:/usr$ locate aaaa

/usr/aaaa

/var/cache/fontconfig/0bd3dc0958fa2205aaaa8ebb13e2872b-le64.cache-6

aditya@ubuntu16:/usr$ cd ../home/aditya/Desktop/

aditya@ubuntu16:~/Desktop$ touch aaaa

aditya@ubuntu16:~/Desktop$ updatedb

updatedb: can not open a temporary file for `/var/lib/mlocate/mlocate.db'

aditya@ubuntu16:~/Desktop$ sudo updatedb

sudo: unable to resolve host ubuntu16

aditya@ubuntu16:~/Desktop$ locate aaa

/usr/aaaa

/usr/share/app-install/desktop/jaaa:jaaa-alsa.desktop

/var/cache/fontconfig/0bd3dc0958fa2205aaaa8ebb13e2872b-le64.cache-6

/var/cache/fontconfig/bab58bb527bb656aaa9f116d68a48d89-le64.cache-6

aditya@ubuntu16:~/Desktop$

Comment: [this may help you](https://unix.stackexchange.com/a/151707)
Comment: Could you please post text files, dialogue messages, and program output listings as text, not as images? To achieve the latter two you can either 1) select, copy & paste the dialogue text or terminal content or 2) [save the program output to a file](//askubuntu.com/q/420981/175814) and use that. Longer listings (the editor will tell you what's too long) should be uploaded to a [pastie service](https://paste.ubuntu.com/) and linked to in the question. Thanks.
Answer: By default find searches for your defined pattern within the all files and subdirectories you specified in the real time, so even after search has been started you can create a new file somewhere and if find didn't search that place yet it will find that file for you.
on the other hand, as you know locate uses a cached database to speed up this process, however it only caches some specific directories, you can use /etc/updatedb.conf file to define some directories to be excluded from being cached.
updating the data with sudo on a machine with multiple users is a security risk cause we will end up to a database which contains all users data and everyone can search for it.
For me sudo updatedb works fine, so check /etc/updatedb.conf to see if anything has been excluded in your machine.
If you want to create a database only for your user you can use:
updatedb -l 0  --output=/home/username/.mydb.db

then to search within it use:
locate -d ~/.mydb.db search-pattern

And use aliases to make it more convenience:
alias lupdatedb="updatedb -l 0  --output=/home/username/.mydb.db"
alias llocate="locate -d ~/.mydb.db"

Comment: I checked `/etc/updatedb.conf` , here's what it shows: PRUNE_BIND_MOUNTS="yes"
# PRUNENAMES=".git .bzr .hg .svn"
PRUNEPATHS="/tmp /var/spool /media /home/.ecryptfs /var/lib/schroot"
PRUNEFS="NFS nfs nfs4 rpc_pipefs afs binfmt_misc proc smbfs autofs iso9660 ncpfs coda devpts ftpfs devfs mfs shfs sysfs cifs lustre tmpfs usbfs udf fuse.glusterfs fuse.sshfs curlftpfs ecryptfs fusesmb devtmpfs"
Comment: I'm the only user of my laptop, but still  I tried it ( `updatedb -l 0  --output=/home/username/.mydb.db` )... here also unable to locate....
Answer: updatedb scans your whole filesystem, and as such, is a quite expensive operation. It is not meant to be run after every file creation, rather once a day or so to give you a rough idea about the system files.
As you can see it by running via sudo, it does not create or update a per user database, it creates or updates a common global one containing a manifest of your entire system. Your system has (or potentially might have) multiple users, each of them having read access to the database.
Hence, for privacy concerns, by default updatedb does not scan directories that are not readable by every user. It would be a privacy risk if you didn't grant read access to your home directory to others (as it is by default in most distributions), yet other users could get a list of your files via updatedb/locate.
For locating files under your home directory, or anywhere where reflecting recent changes is necessary, you should consider using find or other utilities that scan the filesystem just when you need it.
Comment: Actually I'm the only user of my laptop. Except me only guest account is there, but I guess, everyone have that account.
Comment: Thanks for sharing your concern (about multiple user), I hope my laptop isn't hacked!???
Comment: There's no way the `updatedb` program could know that you're the only user and you intend to keep it this way in the future. It would be stupid if it behaved differently based on whether at the moment of running you're the only user. I said your system _might potentially have_ multiple users (Linux is a multi-user operating system, you know), and `updatedb` is prepared for its implications.


Does uniform convergence of a sequence of functions imply uniform convergence of a subsequence?

Question: I know that if a sequence of real numbers converges then all subsequences converge and all convergent subsequences converge to the same limit. But does this apply to sequences of functions and do the subsequences converge uniformly?
Answer: If $f_{k_n}$ is a subsequence of $f_n$ then for every $x$, $f_{k_n}(x)$ is a subsequence of $f_n(x)$, so $f_{k_n}(x)\to f(x)$ since a subsequence of a convergent sequence also converges to the same limit, so that $f_{k_n} \to f$ as well.
$f_n \to f$ uniformly means $\forall \epsilon>0~\exists N ~ \forall x ~\forall n>N ~|f_n(x)-f(x)|<\epsilon$.
The convergence of $f_{k_n}$ is also uniform since $\forall \epsilon>0~\exists N ~ \forall x ~\forall n>N ~ |f_{k_n}(x)-f(x)|<\epsilon$, because by $f_n\to f$ uniformly we know there's such $N$ so that whenever $n > N$ we have $|f_n(x)-f(x)|<\epsilon$, and we know that $k_n$ is an increasing sequence of natural numbers so that $k_n \geq n$ so that $n>N$ implies $k_n > N$.


Sum function in a sql query

Question: I have the below query:
SELECT
     cc.chain_desc as chain_desc
    ,cc.chain_id as chain_id
    ,COUNT(distinct t.trans_id) as TranCount
FROM TRANSACTION AS t
LEFT OUTER JOIN location AS l
ON t.location_id = l.location_id
LEFT OUTER JOIN trans_line AS tl
ON t.trans_id = tl.trans_id
LEFT OUTER JOIN contract as c
ON t.contract_id = c.contract_id
LEFT OUTER JOIN chain_desc as cc
ON l.chain_id = cc.chain_id
WHERE
t.loc_country = 'U'
AND c.issuer_id IN (156966,166203)
AND t.trans_date >= '2016-10-01 00:00'
and t.trans_date < '2016-10-31 00:00'
AND tl.cat NOT IN ('DEF','DEFD','DEFC')
GROUP BY cc.chain_desc, cc.chain_id
ORDER BY cc.chain_desc, cc.chain_id

The above query when executed, gives me the below result:

I need a sum of the final column "trancount" which will be 490. I have tried changing the query as below:
SELECT
     cc.chain_desc as chain_desc
    ,cc.chain_id as chain_id
    ,COUNT(distinct t.trans_id) as TranCount
    ,SUM(distinct t.trans_id)as TransSum
FROM TRANSACTION AS t
LEFT OUTER JOIN location AS l
ON t.location_id = l.location_id
LEFT OUTER JOIN trans_line AS tl
ON t.trans_id = tl.trans_id
LEFT OUTER JOIN contract as c
ON t.contract_id = c.contract_id
LEFT OUTER JOIN chain_desc as cc
ON l.chain_id = cc.chain_id
WHERE
t.loc_country = 'U'
AND c.issuer_id IN (156966,166203)
AND t.trans_date >= '2016-10-01 00:00'
and t.trans_date < '2016-10-31 00:00'
AND tl.cat NOT IN ('DEF','DEFD','DEFC')
GROUP BY cc.chain_desc, cc.chain_id
ORDER BY cc.chain_desc, cc.chain_id

But I didnt get the expected result. What is the right way to do a summation of the transcount column?.
Comment: If you are using Informix why did you tag either mysql OR sql-server???
Comment: `Group by grouping sets` (SQL Server) or `With Rollup` (mySQL)
Comment: Yeah - which RDBMS?
Comment: Using Informix.
Answer: == EDITED VERSION ==
Try (in SQL Server):
SELECT
     chain_desc
    ,chain_id
    ,TranCount
    ,SUM(TranCount) OVER (PARTITION BY 1) as TransSum
    (
        SELECT
             cc.chain_desc as chain_desc
            ,cc.chain_id as chain_id
            ,COUNT(distinct t.trans_id) as TranCount
        FROM TRANSACTION AS t
        LEFT OUTER JOIN location AS l
        ON t.location_id = l.location_id
        LEFT OUTER JOIN trans_line AS tl
        ON t.trans_id = tl.trans_id
        LEFT OUTER JOIN contract as c
        ON t.contract_id = c.contract_id
        LEFT OUTER JOIN chain_desc as cc
        ON l.chain_id = cc.chain_id
        WHERE
        t.loc_country = 'U'
        AND c.issuer_id IN (156966,166203)
        AND t.trans_date >= '2016-10-01 00:00'
        and t.trans_date < '2016-10-31 00:00'
        AND tl.cat NOT IN ('DEF','DEFD','DEFC')
        GROUP BY cc.chain_desc, cc.chain_id
    ) as a
    ORDER BY chain_desc, chain_id

and remove the GROUP BY
Comment: On doing the above, Im getting multiple rows as below:

chain_desc chain_id trancount transum
  66 490
  66 490
  66 490
  66 490
LOVES 2 212 490
LOVES 2 212 490
LOVES 2 212 490
LOVES 2 212 490
LOVES 2 212 490
LOVES 2 212 490
Comment: you could also try to mess around with distinct
Comment: Getting this error when I try the query:

ERROR com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax;  near '(PARTITION BY 1) as TransSum
Comment: Ah, you are using MySQL - Sorry, i thought you are using SqlServer (Microsoft)
Answer: SELECT
     cc.chain_desc as chain_desc
    ,cc.chain_id as chain_id
    ,COUNT(distinct t.trans_id) as TranCount
FROM TRANSACTION AS t
LEFT OUTER JOIN location AS l
ON t.location_id = l.location_id
LEFT OUTER JOIN trans_line AS tl
ON t.trans_id = tl.trans_id
LEFT OUTER JOIN contract as c
ON t.contract_id = c.contract_id
LEFT OUTER JOIN chain_desc as cc
ON l.chain_id = cc.chain_id
WHERE
t.loc_country = 'U'
AND c.issuer_id IN (156966,166203)
AND t.trans_date >= '2016-10-01 00:00'
and t.trans_date < '2016-10-31 00:00'
AND tl.cat NOT IN ('DEF','DEFD','DEFC')
GROUP BY GROUPING SETS ((cc.chain_desc, cc.chain_id), ())
ORDER BY cc.chain_desc, cc.chain_id

Group by grouping sets allows you to do multiple levels of aggregation those values not aggregated will Reuther NULL
or perhpas you need with rollup if MySQL...
SELECT
     cc.chain_desc as chain_desc
    ,cc.chain_id as chain_id
    ,COUNT(distinct t.trans_id) as TranCount
FROM TRANSACTION AS t
LEFT OUTER JOIN location AS l
ON t.location_id = l.location_id
LEFT OUTER JOIN trans_line AS tl
ON t.trans_id = tl.trans_id
LEFT OUTER JOIN contract as c
ON t.contract_id = c.contract_id
LEFT OUTER JOIN chain_desc as cc
ON l.chain_id = cc.chain_id
WHERE
t.loc_country = 'U'
AND c.issuer_id IN (156966,166203)
AND t.trans_date >= '2016-10-01 00:00'
and t.trans_date < '2016-10-31 00:00'
AND tl.cat NOT IN ('DEF','DEFD','DEFC')
GROUP BY cc.chain_desc, cc.chain_id with Rollup
ORDER BY cc.chain_desc, cc.chain_id

Sum function in a sql query


How to change DNS IP addresses in C#

Question: In order to programmatically change my adapter (NetworkInterface) DNS IP addresses in my WPF application, I followed this question : Change DNS in windows using c# answer and add it as follow :
    ///
    /// Method to set the DNS IP addresses of a given <see cref="NetworkInterface"/>
    /// Note : using "Win32_NetworkAdapterConfiguration" library, so only on Windows OS
    ///
    /// <param name="ni">The <see cref="NetworkInterface"/> adapter to modify its DNS IP addresses along given <paramref name="addresses"/></param>
    /// <param name="addresses">The IP addresses to store in <paramref name="ni"/> adapter as its new DNS IP addresses</param>
    public static void SetDNS(this NetworkInterface ni, string[] addresses)
    {
        if (ni == null) return;

        ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
        ManagementObjectCollection objMOC = objMC.GetInstances();
        foreach (ManagementObject objMO in objMOC)
        {
            if ((bool)objMO["IPEnabled"])
            {
                if (objMO["Caption"].ToString().Contains(ni.Description))
                {
                    ManagementBaseObject objdns = objMO.GetMethodParameters("SetDNSServerSearchOrder");
                    if (objdns != null)
                    {
                        objdns["DNSServerSearchOrder"] = addresses;
                        objMO.InvokeMethod("SetDNSServerSearchOrder", objdns, null);
                    }
                }
            }
        }
    }

Entering debug mode show that it correctly call this function, looping through ManagementObjectCollection, ending one of the items to correctly match my 2 if statement, and finally call
objdns["DNSServerSearchOrder"] = addresses;
                            objMO.InvokeMethod("SetDNSServerSearchOrder", objdns, null);

see : https://i.stack.imgur.com/hxqhS.jpg
But my DNS IP addresses aren't changed when I check with an ipconfig /all CLI !
How to effectively change my DNS addresses in windows directly via C#, and not via calling a cmd.exe process behind.
Thank you.
Comment: `InvokeMethod()` returns a value. Add: `var outPar = objMO.InvokeMethod("SetDNSServerSearchOrder", objdns, null); uint result = (uint)outPar.GetPropertyValue("ReturnValue");`, see what that is. Compare with the [SetDNSServerSearchOrder()](https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/setdnsserversearchorder-method-in-class-win32-networkadapterconfiguration) return values.
Comment: BTW, you have 3 disposable objects you really need to dispose, since you're using System.Management.
Comment: @Jimi, thank you to point me in the way to further understanding the issue : The result code is 91, so according to your link : "Access Denied" issue.
Thank you too for the dispose, i guessed that creating a `new ManagementClass` would create a managed object that GC would take care of, but your comment seems I was wrong.
Comment: When an object exposes a `Dispose()` method, you need to call it, or declare the object with a `using` statement. Then the GC can do its job. -- BTW, `outPar` is also disposable :)
Comment: Now I have another error code : 70 (Invalid IP), what I'm trying to pass here is a `string[4]`  of 4 IP addresses for my DNS : the 2 first are IPv6 ones and the 2 last are IPv4 ones. Eg : https://imgur.com/a/Ospnozu
I guess this `SetDNS()` only work for IPv4 addresses ?
Comment: Yes, IPv6 is not supported here, neither reading or writing. Note that it's just adding those values to the `Registry` + `WM_SETTINGSCHANGED`.  The reg values are in `HKLM\SYSTEM\CurrentControlSet\services\TCPIP6\Parameters\Interfaces\{Interface GUID}\NameServer`. Of course you can execute `netsh` silently.
Answer: So here is what I ending with to change my system DNS addresses.
Thanks to @jimi for helping me in my way to better understanding this.
So after all I'm using netsh silently to set new DNS addresses, as pointed out by @jimi, because IPv6 isn't supported by the original solution I tried (via WMI)
So far (didn't throughfully tested it) it work !
Here is what I did :
    ///
    /// Start a <see cref="Process"/>
    ///
    /// <param name="processName">The <see cref="ProcessStartInfo.FileName"/> (usually name of the exe / command to start)</param>
    /// <param name="args">The <see cref="ProcessStartInfo.Arguments"/> (the argument of the command)</param>
    /// <param name="verb">The <see cref="ProcessStartInfo.Verb"/>. Use "runas" to start the process with admin priviledge (default is null)</param>
    /// <param name="useShell">The <see cref="ProcessStartInfo.UseShellExecute"/>. Does the process run silently or not (silent by default)</param>
    /// <param name="redirectErros">The <see cref="ProcessStartInfo.RedirectStandardError"/>. Do we redirect standard error ? (true by default)</param>
    /// <param name="redirectOutput">The <see cref="ProcessStartInfo.RedirectStandardOutput"/>. Do we redirect standard output ? (true by default)</param>
    /// <param name="noWindow">The <see cref="ProcessStartInfo.CreateNoWindow"/>. Do we prevent the creation of CMD window to run silently ? (silent by default)</param>
    /// <returns>True if <paramref name="processName"/> isn't null and process execution succeeded. False if <paramref name="processName"/> is null or empty.
    /// Throw an <see cref="Exception"/> if execution failed</returns>
    public static bool StartProcess(string processName, string args, string verb = null, bool useShell = false, bool redirectErros = true, bool redirectOutput = true, bool noWindow = true)
    {
        if (string.IsNullOrWhiteSpace(processName))
            return false;
        ProcessStartInfo psi = new ProcessStartInfo();
        psi.FileName = processName;
        psi.Arguments = args;
        psi.UseShellExecute = useShell;
        psi.RedirectStandardOutput = redirectOutput;
        psi.RedirectStandardError = redirectErros;
        psi.CreateNoWindow = noWindow;
        if (verb != null)
            psi.Verb = verb;
        Process proc = Process.Start(psi);
        proc.WaitForExit();
        string errors = proc.StandardError.ReadToEnd();
        string output = proc.StandardOutput.ReadToEnd();
        if (proc.ExitCode != 0)
            throw new Exception(processName + " exit code: " + proc.ExitCode.ToString() + " " + (!string.IsNullOrEmpty(errors) ? " " + errors : "") + " " + (!string.IsNullOrEmpty(output) ? " " + output : ""));
        return true;
    }

    ///
    /// Convinient method to start a "netsh" process as admin to set a new DNS IP address calling <see cref="StartProcess(string, string, string, bool, bool, bool)"/>
    ///
    /// <param name="interfaceName">The name of the interface to set its new <paramref name="address"/> IP ddress</param>
    /// <param name="address">The new IP address to set of the <paramref name="interfaceName"/> DNS</param>
    /// <param name="isPrimary">Is this new DNS IP address is a primary one ?</param>
    /// <returns><see cref="StartProcess(string, string, string, bool, bool, bool)"/> return value,
    /// or false if <paramref name="address"/> isn't a correct IP address</returns>
    public static bool netshSetNewDNS(string interfaceName, string address, bool isPrimary)
    {
        var ipVer = IPversion(address, RGXVX);
        if (!(ipVer[0] || ipVer[1]))
            return false;
        return netshSetNewDNS(interfaceName, address, isPrimary, ipVer[0]);
    }

    ///
    /// Convinient method to start a "netsh" process as admin to set a new DNS IP address calling <see cref="netshSetNewDNS(string, string, bool)"/>
    ///
    /// <param name="interfaceName">The name of the interface to set its new <paramref name="address"/> IP ddress</param>
    /// <param name="address">The new IP address to set of the <paramref name="interfaceName"/> DNS</param>
    /// <param name="isPrimary">Is this new DNS IP address is a primary one ?</param>
    /// <param name="isIPv6">Does <paramref name="address"/> is IPv6 ?</param>
    /// <returns><see cref="netshSetNewDNS(string, string, bool)"/> return value</returns>
    public static bool netshSetNewDNS(string interfaceName, string address, bool isPrimary, bool isIPv6)
    {
        string arg = string.Format("interface {0} {1} dnsservers \"{2}\"{3} {4} {5}", isIPv6 ? "ipv6" : "ipv4", isPrimary ? "set" : "add", interfaceName, isPrimary ? " static" : "", address, isPrimary ? "primary" : "index=2");
        return StartProcess("netsh", arg, "runas");
    }

    ///
    /// Method to set the DNS IP addresses of a given <see cref="NetworkInterface"/>
    /// note : we use netsh silently.
    /// see : https://www.tenforums.com/tutorials/77444-change-ipv4-ipv6-dns-server-address-windows.html
    ///
    /// <param name="ni">The <see cref="NetworkInterface"/> adapter to modify its DNS IP addresses along given <paramref name="addresses"/></param>
    /// <param name="ipv4">The IPv4 addresses to store in <paramref name="ni"/> adapter as its new DNS IP addresses</param>
    /// <param name="ipv6">The IPv6 addresses to store in <paramref name="ni"/> adapter as its new DNS IP addresses</param>
    public static void SetDNS(this NetworkInterface ni, string[] ipv4, string[] ipv6)
    {
        if (!(ipv4.Any(add => IsIP(add, RGXV4)) || ipv6.Any(add => IsIP(add, RGXV6))))
        {
            Debug.WriteLine("None of the suplied addresses are IPv4/6.\nCan not update DNS IP addresses.");
            return;
        }
        // delete current IPv4 DNS
        StartProcess("netsh", "interface ipv4 delete dnsservers \"" + ni.Name + "\" all", "runas");
        // delete current IPv6 DNS
        StartProcess("netsh", "interface ipv6 delete dnsservers \"" + ni.Name + "\" all", "runas");
        string address;
        //set new IPv4 DNS addresses
        if (ipv4 != null && ipv4.Length>0)
        {
            //primary
            address = ipv4[0];
            try
            { bool res = netshSetNewDNS(ni.Name, address, true, false); }
            catch(Exception e)
            { Debug.WriteLine(e.Message); }
            if (ipv4.Length>1)
            {
                //secondary
                address = ipv4[1];
                try
                { bool res = netshSetNewDNS(ni.Name, address, false, false); }
                catch (Exception e)
                { Debug.WriteLine(e.Message); }
            }
        }

        //set new IPv6 DNS addresses
        if (ipv6 != null && ipv6.Length > 0)
        {

            //primary
            address = ipv6[0];
            try
            { bool res = netshSetNewDNS(ni.Name, address, true, true); }
            catch (Exception e)
            { Debug.WriteLine(e.Message); }

            if (ipv6.Length > 1)
            {
                //secondary
                address = ipv6[1];
                try
                { bool res = netshSetNewDNS(ni.Name, address, false, true); }
                catch (Exception e)
                { Debug.WriteLine(e.Message); }
            }
        }
    }

I have though 1 "minor" issue : setting ipv6 (+ipv4 ?) addresses suffer performance issue.
Whereas with only new (2) ipv4 IP addresses it is almost immediate (1 second max), with  2 ipv6 + 2 ipv4 setting, it take up to 10 seconds before actually (correctly) changing my DNS IP addresses.
Debugging show that it freeze on proc.WaitForExit(); of StartProcess(...) function called on the secondary IPv4 DNS address setting (in SetDNS(...) bool res = netshSetNewDNS(ni.Name, address, false, false);)!
It is strange it always freeze here because when I call with only 2 new IPv4 DNS addresses setting it doesn't freeze this time ...

How to change DNS IP addresses in C#


Aggregate by paymentamount

Question: I have data like this:
emailaddress    customer_acquisation_date  customer_order_date  payment_amount
email@example.com     01/05/2013 6:24 AM         01/05/2013 5:10 AM           $ 20.67
email@example.com     01/05/2013 6:24 AM         02/07/2013 7:21 PM           $ 25.56
firstname.lastname@example.com     01/05/2013 6:24 AM         07/10/2013 8:00 AM           $100.00
email@example.com     01/05/2013 6:24 AM         08/12/2013 9:35 AM           $30.00

I am trying to sum(payment amount) by emailaddress where i want final output as:
emailaddress    customer_acquisation_date  customer_order_date  payment_amount
email@example.com     01/05/2013 6:24 AM         01/05/2013            $ 177
                                            02/07/2013
                                            07/10/2013
                                            08/12/2013

code I am writing
z <- aggregate(x$emailaddress~x$paymentamount,data=x,FUN=sum)

Error I am getting
Error in Summary.factor(c(211594L, 291939L, 79240L, 208971L, 369325L,  :
  'sum' not meaningful for factors

What is right way of doing this. Any help is appreciated
Answer: The aggregate function first takes a value to aggregate on, then the grouping argument. As mentioned, you also need to remove the dollar sign to be able to convert the column to numeric format.
# Remove the dollar sign
x$payment_amount = as.numeric( gsub('[$]', '', x$payment_amount ))

# Write it in the right order .. aggregate(x, by, FUN .. )
z <- aggregate( payment_amount ~ emailaddress, data = x, FUN = sum )

Edit: Adding a data.table solution, keeping the other columns as well.
 library(data.table)
 setDT(x) # Convert the data.frame to data.table
 z = x[, payment_total := sum(payment_amount), by = emailaddress]
 setDF(z) # Convert the result to data.frame

Comment: Nice - much faster data.table solution +1
Answer: Instead of removing the $ sign, the following extracts the numeric value directly. This has the benefit of not needing to specify what to actually remove (e.g. different currency signs, or "10.00 USD"). I've also added merge to get exactly OP's desired output (not really, but better IMHO):
library(magrittr)
library(dplyr)

x$payment_amount %<>% {regmatches(., gregexpr("[[:digit:]]+[.][[:digit:]]+", .))} %>%
  as.numeric()

aggre = aggregate(payment_amount ~ emailaddress, data = df, FUN = sum)

select(x, -payment_amount) %>%
  merge(aggre, by = "emailaddress") %>%
  rename(tot_payment_amount = payment_amount)

Result:
  emailaddress customer_acquisation_date customer_order_date tot_payment_amount
1 email@example.com        01/05/2013 6:24 AM  01/05/2013 5:10 AM             176.23
2 email@example.com        01/05/2013 6:24 AM  02/07/2013 7:21 PM             176.23
3 firstname.lastname@example.com        01/05/2013 6:24 AM  07/10/2013 8:00 AM             176.23
4 firstname.lastname@example.com        01/05/2013 6:24 AM  08/12/2013 9:35 AM             176.23

Note:
I used the magrittr package mainly for it's convenient two-way pipe operator %<>%. This feeds the LHS (x$payment_amount) to the .'s on the RHS and sets the LHS equal to the output of RHS. {} around regmatches is required to feed x$payment_amount into a function within a function (i.e. text= argument of gregexpr that is inside regmatches). For those who find %<>% to be confusing, here is how to do the same without %<>%:
x$payment_amount =
  with(x, regmatches(payment_amount, gregexpr("[[:digit:]]+[.][[:digit:]]+", payment_amount))) %>%
  as.numeric()

Answer: We could not add character or factor together. We need to convert the factor to character, remove $, and then convert to numeric.
library(dplyr)
library(stringr)

x2 <- x %>%
  mutate(payment_amount = as.character(payment_amount)) %>%
  mutate(payment_amount = str_replace(payment_amount, fixed("$"), "")) %>%
  mutate(payment_amount = as.numeric(payment_amount)) %>%
  group_by(emailaddress) %>%
  summarise(payment_amount = sum(payment_amount))

x2
# A tibble: 1 x 2
  emailaddress payment_amount
        <fctr>          <dbl>
1 firstname.lastname@example.com         176.23

Data
x <- read.table(text = "emailaddress    customer_acquisation_date  customer_order_date  payment_amount
email@example.com     '01/05/2013 6:24 AM'         '01/05/2013 5:10 AM'           '$ 20.67'
                email@example.com     '01/05/2013 6:24 AM'         '02/07/2013 7:21 PM'           '$ 25.56'
                firstname.lastname@example.com     '01/05/2013 6:24 AM'         '07/10/2013 8:00 AM'           '$100.00'
                firstname.lastname@example.com     '01/05/2013 6:24 AM'         '08/12/2013 9:35 AM'           '$30.00'",
                header = TRUE)

Comment: Thanku for solution but it is giving me error Error in x %>% mutate(paymentamount = as.character(paymentamount)) %>%  :
  could not find function "%>%"
Comment: @sim you need to load the `dplyr` package with `library(dplyr)`
Comment: Did you load the `dplyr` package by `library(dplyr)`?
Comment: @ycw..yes I loaded the dplyr..now got that error resolved but getting new one..Error in mutate(paymentamount = as.character(paymentamount)) :
  object 'paymentamount' not found
Comment: It is a typo. it should be `payment_amount`.
Comment: @ycw..but i dont have payment_amount in my data..the column name is paymentamount?
Comment: I created the data frame based on the example you gave. You specified it to be `payment_amount`, not me.
Answer: I would suggest using readr, dplyr, and lubridate:
library(tidyverse)
library(lubridate)

data_string <- trimws('
email        , datetime           , payment
firstname.lastname@example.com , 01/05/2013 5:10 AM , $20.67
firstname.lastname@example.com , 02/07/2013 7:21 PM , $25.56
email@example.com , 07/10/2013 8:00 AM , $100.00
firstname.lastname@example.com , 08/12/2013 9:35 AM , $30.00
')

orders <- read_csv(data_string, col_types = cols(
    email = col_character(),
    datetime = col_datetime(format = "%m/%d/%Y %I:%M %p"),
    payment = col_number()
))
orders

## # A tibble: 4 x 3
##          email            datetime payment
##          <chr>              <dttm>   <dbl>
## 1 firstname.lastname@example.com 2013-01-05 05:10:00   20.67
## 2 email@example.com 2013-02-07 19:21:00   25.56
## 3 email@example.com 2013-07-10 08:00:00  100.00
## 4 firstname.lastname@example.com 2013-08-12 09:35:00   30.00

customers <- orders %>%
    group_by(email) %>%
    summarise(
        total_payment = sum(payment),
        acquisition_date = min(datetime),
        order_dates = list(date(datetime))
    )
customers

## # A tibble: 1 x 4
##          email total_payment    acquisition_date order_dates
##          <chr>         <dbl>              <dttm>      <list>
## 1 firstname.lastname@example.com        176.23 2013-01-05 05:10:00  <date [4]>

customers$order_dates

## [[1]]
## [1] "2013-01-05" "2013-02-07" "2013-07-10" "2013-08-12"

Aggregate by paymentamount


whois-rb gem produces error: "Whois::ServerNotFound"

Question: I'm totally lost here. I was trying to set up the whois gem according to the documentation at https://whoisrb.org/. Unfortunately I'm always getting an error when trying to perform a whois, locally on my machine.
Error message:

Unable to find a WHOIS server for `;; answer received from 192.168.178.1 (75 bytes) ;; ;; security level : unchecked ;; ->>header<<- opcode: query, status: noerror, id: 51102 ;; flags: qr rd ra cd; query: 1, answer: 1, authority: 0, additional: 1 opt pseudo-record : payloadsize 512, xrcode 0, version 0, flags 32768 ;; question section (1 record) ;; google-public-dns-b.google.com.    in  a ;; answer section (1 record) google-public-dns-b.google.com.  84453   in  a   184.108.40.206 '

Don't get confused, I'm using the dnsruby gem as well.. The corresponding code in my model:
def set_isp
    res = Resolver.new
    a_record = res.query(self.domain_name)
    whois = Whois::Client.new
    rec = whois.lookup(a_record)
    self.isp = rec.name
end

Thanks a lot in advance!
Answer: According to the error, the issue is that you are passing the result of
a_record = res.query(self.domain_name)

straight to
whois.lookup

but the content of the a_record is not a domain name. Instead, it's a full DNS response:
;; answer received from 192.168.178.1 (75 bytes)
;;
;; security level : unchecked
;; ->>header<<- opcode: query, status: noerror, id: 51102
...

Please make sure the input is a valid domain name (or IP address).
Answer: I am not sure where did you go wrong I just try to create a sample apple using the gem whoisrb all I had to do is Add the whois gem to the Gemfile.
#Gemfile
gem 'whois', '~> 3.0'

Now you can open the console and type in
$ client = Whois::Client.new
$ response = client.lookup("google.com")

I created a example git project that will show you how its put together in the controller. I could and should it to a model method
https://github.com/mzaragoza/sample-whoisrb


Verify hidden text presence using Selenium IDE

Question: Creating some test cases for a web page using Selenium IDE,I've found this situation: inside a DIV tag (hidden by a CSS) there is a very long text. I'd like to find a solution to automatically check if a very short portion of this text is matching with a string defined by a regular expression (for example: *check*this*).
The original idea is using verifyTextPresent command with glob:*check*this*, but it seems this idea doesn't like because the element is hidden.
I'm thinking also to use a "SEO" trick to change an hidden DIV by CSS to an hidden (or almost) text with a different solution like putting it in a textarea with dimension 1x1 or 0x0...
Any hint to move forward?
Thank you!
Answer: storeVisible ( locator, variableName )

Determines if the specified element is visible. An element can be rendered invisible by setting the CSS "visibility" property to "hidden", or the "display" property to "none", either for the element itself or one if its ancestors. This method will fail if the element is not present.
Arguments:
    locator - an element locator
    variableName - the name of a variable in which the result is to be stored.

Returns:
true if the specified element is visible, false otherwise

Related Assertions, automatically generated:
    assertVisible ( locator )
    assertNotVisible ( locator )
    verifyVisible (locator )
    verifyNotVisible ( locator )
    waitForVisible ( locator )
    waitForNotVisible ( locator )

Comment: @ironFritz, check the answer and let me know it will help you or not
Comment: thank you for your reply, but I was looking for something different. Let me try to explain better: I've some text included inside hidden tags, and I would like to grab that text. For Example:  TEXT TO BE GRABBED , I'd like to store in a variable "TEXT TO BE GRABBED". Thank you
Comment: @IronFritz  Verifyvisible | xpath of your tag | TEXT TO BE GRABBED

try verifyvisible command check CSS and find hidden tag but you have to defined xpath of element.
if this answer help you then please accept my answer


Upload PDF, Doc, Video using Volley MultiPart

Question: I am using Volley Android Multipart VolleyMultipartRequest request class to upload various types of mime types. i.e, Image,Video,Audio,Document,PDF. Current i am using this method for uploading Image which is working fine.
        @Override
        protected Map<String, DataPart> getByteData() {
            Map<String, DataPart> params = new HashMap<>();
            params.put("Key", new DataPart("Filename", byte[], "image/jpeg"));
            return params;
        }

It is working absolutely fine but for image , what if i want to use this request for all mime types what should i put the last parameter for Video and PDF. For example for image "image/jpeg" being sent what will be for audio , video and pdf or doc, Any help will be much appropriated.
Comment: Possible duplicate of [this](https://stackoverflow.com/questions/8589645/how-to-determine-mime-type-of-file-in-android)
Comment: try this https://stackoverflow.com/questions/16797468/how-to-send-a-multipart-form-data-post-in-android-with-volley/
Comment: @Sandeep Randhawa I am more interested in a solution to my problem than to see you profile.
Comment: @AliAkram I didn't get you. But your basic problem was to get the mime-type for your file and I gave you solution already present in [here](https://stackoverflow.com/questions/8589645/how-to-determine-mime-type-of-file-in-android)
Answer: You can use below function to find out mimetype of file from the file path,Just pass the file path to this function and it will return te mime type of your file
public static String getMimeTypefromfilepath(String path) {
    String mimetype = null;
    String extension = MimeTypeMap.getFileExtensionFromUrl(path);
    if (extension != null) {
        mimetype = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    }
    return mimetype;
}


Searching for executable files

Question: Is there a way to search and delete all executables files within folder if there is no extension?
e.g  Let's suppose I have 4 files with .ubu extension and the following bash does the job I'm asking for:
rm *.ubu

e.g_2 Now let's suppose I have 4 but there is no extension at all, something like:
test test_2 test_3 (chmod +x on them)
How do I delete those files?
Answer: If we're talking about files with executable bit set, then find command has -executable test, and a -delete action.
find /DIR/EC/TORY -type f -executable -delete

or
find /DIR/EC/TORY -type f -executable -exec rm -f {} \;

should do the trick.
To specifically delete all executable files in your home directory (not in sub-directories) and ask you whether you want to delete each file you can do something like
find ~ -type f -executable -maxdepth 0 -exec rm -i {} \;

from man find:

   -exec command ;
          Execute  command;  true  if 0 status is returned.  All following
          arguments to find are taken to be arguments to the command until
          an  argument  consisting of `;' is encountered.  The string `{}'
          is replaced by the current file name being processed  everywhere
          it occurs in the arguments to the command, not just in arguments
          where it is alone, as in some versions of find.  Both  of  these
          constructions might need to be escaped (with a `\') or quoted to
          protect them from expansion by the shell.  See the EXAMPLES sec‐
          tion for examples of the use of the -exec option.  The specified
          command is run once for each matched file.  The command is  exe‐
          cuted  in  the starting directory.   There are unavoidable secu‐
          rity problems surrounding use of the -exec  action;  you  should
          use the -execdir option instead.

   -exec command {} +
          This  variant  of the -exec action runs the specified command on
          the selected files, but the command line is built  by  appending
          each  selected file name at the end; the total number of invoca‐
          tions of the command will  be  much  less  than  the  number  of
          matched  files.   The command line is built in much the same way
          that xargs builds its command lines.  Only one instance of  `{}'
          is  allowed  within the command.  The command is executed in the
          starting directory.

Comment: I have 2 files / executables in my home directory, call them what you want but don't append an extension, how can I delete these files using a simple bash command  ?
Comment: Thank you Sergey, can you explain a little the second command ?
    rm -rf {} \;
what does this mean ?
Comment: If you only have 2 files and you know their names, why don't you just do `rm test test_2 test_3`? Or delete them in Nautilus? I thought the question was "how do I generally delete any executable files in a directory"
Comment: @pyn: the second command is "find anything of type *file* with executable bit set in directory /DIR/EC/TORY and below and for each file found execute `rm -f` command passing it the full path to the file."
Comment: 2 files was just an example, you are right with the question.

If I understood well {} means the full path to that directory ? Thank you for your patience and understanding (I know, my english is awfull ).
Comment: @pyn: also note that in the second command I used `rm -f`, not `rm -rf` (where `-r` stands for "recursive" and `-f` is "force"). Since we only look for files, the effect would be the same, but using `-r` with `-f` is a bit scary because it can delete whole directories with their contents without any prompt. At any rate, it is advisable to test the command first by running it without `-exec rm -f {} \;` part - it will just print the names of the files it found to the terminal.
Comment: I understand the risk of using rm -rf but the part I dont fully understand is: {} \ ; ( I suppose semicolon means end of the line like in programming ).
Comment: @pyn: I've updated my answer
Comment: I see, so the {} means the name of the file(s) found by the find.
Answer: To find files (or directories!) without a dot, use the extended file matching pattern
!(*.*)

You need shopt -s extglob -- I think that option is on by default in interactive shells.
To delete executable files in bash
shopt -s extglob nullglob
for file in !(*.*); do
    [[ -f $file && -x $file ]] && echo rm "$file"
    # -f -> true if it's a file
    # -x -> true if it's executable
done

Answer: A binary file will have the executable bit marked.
So you can write a simple bash script which checks if the executable bit is set, and if so delete the file.

Searching for executable files


How do you arrive at a information architecture from a mental model?

Question: We have created a mental model for a large website redesign project. We are in the process of mapping content and functionality to task towers.
While I understand how it gives an indication of what behaviours are supported, I'm not sure how the mental model can be used to inform the site's information architecture. The UX lead seems to believe the model will?
Comment: information architecture
Comment: When you say site architecture, do you mean database/service layer structure or information architecture?
Answer: The mental model attempts to define a map of the user cognitive processes. Depending on how it's done it can help define what is the user looking for, what kind of decisions is she taking etc.
In my experience mental models serve more as a framework to refer to as one explores different possibilities. The mental model itself does not deliver specific design choices.
For navigation you still need to do exercises like card sorting, or do task flow diagrams etc. Once you have done those, the understanding of the mental model would help you evaluate the results and make better decisions.
Answer: In my experience, once you know which tasks your user must complete, you can then define your task flows.
With task flows you can figure out which pages you need on your site. You also figure out what goes on each page & how everything is grouped together on the page.
Then you can start to define how the various pages are linked together, which informs your interaction areas & navigation areas. From there, you create your wireframes.
Answer: I think a lot of it depends on how you developed and verified this mental model.  If you derived it and tested it with users, it will give the user a framework with which to understand and predict your system instead of requiring the user to wrap their head around your system, on your system's terms.  This can be especially true if your system's information architecture is based off technical requirements or business rules.
A mental model is a cognitive construct of how a system works.  It may or may not be accurate but it can be useful if it helps a users interact with the system successfully.  A good mental model is one that seems natural to users and gives them enough of an understanding of the system to be able to predict how it will work.  They are usually simplified or abstracted versions of the actual system model.
A more common term for a mental model is a "working understanding".  Someone might not know exactly how their home heating and cooling system works, but he might have enough of a working understanding to be able to set it and maybe even troubleshoot minor issues.
Comment: "A mental model is a cognitive construct of how a system works. It may or may not be accurate but it can be useful if it helps a users interact with the system successfully"
Nicely put.
Answer: I'm not too experienced with this but here goes. Also, my understanding is going from a mental model ( business models ) to website architecture ( database model ). But a have a tickling feeling that I'm wrong about that.
First, unless the UX guy has some experience working in the middle tier/back end, I think you should take their advice with a grain of salt. Depending on how the service layer is build, it can very highly reflect the database with 1-1 relationship of model to table or it might not.
My usual process is

What are the things that can exist without any other things? These become their own table/entity.
Which entities have relationships with each other and how do I build those relationships into the database? ( try to normalize the data as much as possible while keeping related attributes together )
Use it and see where it breaks and fix it


Two toolbars in master-detail view

Question: We're creating a new version of an application that is based on a master-detail view of data. So basically there is a list of records at the top and detail information about selected record at the bottom.
Unfortunately there can be another list in the detailed view. A user is able to create/edit/delete or to use some other actions on records in both lists. So the current version of the app has two toolbars, one for each list. Here is a quick sketch of current app:

We can't get rid of these "detail" lists, we have to keep the same functionality. We want to get rid of those two toolbars, because we find them confusing for a user. We have some ideas like inline controls or some toolbar that slides from one list to another depending on focus but nothing seems to be ideal solution.
Did anyone encounter such a problem?? Does anyone have any suggestions?
Answer: Do you have the need to have the master section constantly visible when editing/working with the details list? Think of progressive disclosure: first select item from master, then open/slide in a new page with the details, now with enough space to present the details in detail.
So the master list would be only one step/click away (back) and you are able to make better use of screen space. It should bring in more clarification on the action buttons, because the buttons are only visible in the correct context. So nobody can confuse the "new" from the first row with the "new" from the details actions. (Think of scent of information, I'm looking for deletion, and the first thing which seems to me which brings me to my goal could be the very first occurance of this button).
Hope this helps
Comment: Unfortunately we have to keep the master section visible.
Answer: Distinguish Selected from Current
You need to separate content marked for action from content marked as the master record. That is, you need to functionally and visually distinguish selected content from the current record. The current record is the master record for the detail list. There is always exactly 1 current record for a given master list. Selected content is what the user has explicitly highlighted for action. It may be master record or a detail record. It may be multiple records in a list, assuming you support multiple selection (you should). It may not be a record at all, but a field in a record or a portion of a field (e.g., highlight text in a text box), assuming you support edit-in-place (you should). Maybe it's even multiple fields. There may be nothing selected at all (e.g., when the user is typing in a text field).
No matter what is selected, how many are selected, or even if nothing is selected, there is still always exactly one current record per master list. There has to be –you are always showing the detail list, so you always have to show what it belongs to. This is why selected and current need to be functionally and visually separate, even though it represents an additional complication for your users. The selected record often is the current record, but it doesn't have to be.
The Menu Acts on the Selected
Not trivially, separating selected from current also solves your problem. You have one menu and it operates on the selected content (which is the definition of selected content). The current record is irrelevant. For example, the user can use the same Copy menu item to copy one or more master records, or one or more detail records, or one or more characters from a text box, and one or more fields. All that matters is what's selected.
(BTW, for commands on the view of the list as a whole, e.g. filtering,  I recommend you do have a separate menu for each list. This is because the menu items often also show the settings of the view, e.g., what is being filtered, and the user should be able to see these all the time).
UI for Current and Selected
Visually, you can indicate the selected content by highlighting (e.g., reverse-video or shading), and indicate the current record with a marker in the left margin.

You may also try including a dotted box around the current record, consistent with how the list boxes indicate the item with focus during keyboard use (especially if you do not have edit-in-place, in which case, the current record is the item with focus in the master list).
Functionally, the user sets the current record by clicking anywhere on a master record (e.g., clicking a checkbox in the record, or clicking in a text box to edit it). The master record is the record the user most recently clicked on in the master list. By default, it's the first record in the list. If you do not have edit-in-place, the selected record(s) is/are the record(s) the user most recently click on from either list. If you have edit in place, you need to functionally distinguish selecting an entire record from setting focus or selecting within a record (e.g., to copy text from a text box). I recommend an "object control" in the left margin to handle actions on an entire record.
Comment: One menu for both lists sounds good. There is just one problem: there can be different actions for records in master and records in detail. In that case the menu will change - some actions will disappear, another actions will appear - when user changes selected records - as you said it can be record(s) from master or record(s) from detail. I'm afraid it can confuse the user.
Comment: Normally, you disable, not hide, menu items that do not apply to the current selection (e.g., in Firefox, Cut, Paste, and Delete are enabled for selections in URL text box, but disabled for selections of the web page). This keeps the menu items in the same relative location to avoid confusion. Usually, users can understand why a menu item is enabled or disabled (e.g., you can't change a web page). In your case, with only two lists, you can make it clearer by appending the class of the applicable records to the menu item caption (e.g., "Audit Pass" not simply "Audit").

Two toolbars in master-detail view


How to prove $A+I_n$ reversibility

Question: Let $n$-order square matrix $A$ satisfy $A^m=A$,where $m$ is a positive even number.prove that $A+I_n$ reversibility.I want to use
$$(I_n+A)(I-A+A^2-\cdots+(-1)^{m-1}A^{m-1})=I_n+(-1)^mA^m.$$
But it felt like something was wrong.
Answer: This is only true if your coefficient field has characteristic $\neq 2$, which I will assume from now on.
Suppose that $A + I_n$ is not invertible. This means that it has non-trivial kernel, and hence there exists a nonzero vector $v$ such that $(A+I_n)v = 0$, or $Av = -v$.
Applying $A$ repeatedly, we see that $A^mv = (-1)^mv = v$ since $m$ is even.
However, we also have $A^m v = Av = -v$. We now have $2v = 0$, which leads to $v = 0$, a contradiction.

It is easy to see that the condition of characteristic $\neq 2$ is necessary for the question, as shown by the example $A = I_n$ over a field of characteristic $2$.
Comment: Thank you,the teacher's suggestion is to make up the factor method.what should I think...
Comment: Unfortunately I don't know what's the intended solution in the teacher's mind...

How to prove $A+I_n$ reversibility


Unable to run gem command: match init

Question: I am trying to run a gem called match. https://codesigning.guide/
match init

When this runs the following is returned:
-bash: /usr/local/bin/match: /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby: bad interpreter: No such file or directory

I have seen other related posts but those do not resolve my issue: CocoaPods not working in macOS High Sierra
It seems something somewhere is pointing toward Ruby 2.0, but that is not the current version in use.
ruby -v
ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-darwin17]

rvm -v
rvm 1.27.0 (latest) by Wayne E. Seguin <firstname.lastname@example.com>, Michal Papis <firstname.lastname@example.com> [https://rvm.io/]

If I got to the path: /System/Library/Frameworks/Ruby.framework/Versions/ -- this has a folder 2.3 and Current.
I am not familiar with gems/ruby/rvm so unsure where to check.
Answer: It looks like match is installed system-wide on your computer (perhaps done previously, before you installed RVM). The shell is picking it up from /usr/local/bin instead of from your RVM installation.
Not sure why the path of RVM is not before /usr/local/bin, but a quick fix is to rename the file match in /usr/local/bin to something else, and then try again:
sudo mv /usr/local/bin/match /usr/local/bin/match_old
hash -r

Now your shell should pick up match from your RVM installation instead (provided you've installed that gem under RVM).
Comment: thank you! I would have never worked that out. I did have to gem install match after as well.

Unable to run gem command: match init


C++11 atomic library std::compare_and_exchange semantics

Question: If sequenceNumber is atomic<int> (seq_no is just an int),
Why does
sequenceNumber.compare_exchange_strong(sequenceNumber, seq_no );

not compile ?
I had a comparison operation with the atomic variable sequenceNumber before the compare_exchange_strong operation and wanted to check if the value of sequenceNumber had been changed by the other thread by the time I actually came to update it in my thread.
Something like this:
if ( seq_no > sequenceNumber )
      sequenceNumber.compare_exchange_strong(sequenceNumber, seq_no);

I fixed it by:
int current_sequence_number = sequenceNumber.load();
if ( seq_no > current_sequence_number )
    sequenceNumber.compare_exchange_strong(current_sequence_number, seq_no );

But I am wondering why the compiler does not allow me to use an atomic<int> in place of the first argument, i.e. the "expected" parameter in the function call -
bool compare_exchange_strong( T& expected, T desired,
                              std::memory_order order =
                                  std::memory_order_seq_cst );

What was the motivation behind disallowing an atomic variable in place of the expected argument especially when seq_no > sequenceNumber seems to be allowed ?
By the way, is using seq_no > sequenceNumber also wrong ? (even though it compiles) Should I go for seq_no > sequenceNumber.load() in that case as well ?
Comment: What is `sequenceNumber`? In what way, if at all, is it related to `sequence_number`?
Comment: @IgorTandetnik Those were typos. I fixed them. I am really, really sorry for them. Will you please take a look at the question again ?
Comment: `atcmic` provides a conversion `operator T()` which does the same thing as `load()`. This is why you can use an instance of `atomic` wherever a value of `T` is required. `seq_no > sequence_number` is equivalent to `seq_no > sequence_number.load()`
Comment: Ok, but why does the `operator T()` not work for `compare_exchange_strong` ?
Comment: `operator T()` gives you an rvalue of type `T`. `compare_exchange_strong` expects an lvalue - a non-const reference. `atomic` cannot be converted to `T&`. If it allowed a direct access to underlying storage, you could modify it bypassing its "atomic-ness". For an atomic, every load and store matters, as they affect synchronization with other threads.
Comment: Got it. Thanks a lot. Why don't you add an answer ?!
Answer: atomic<T>::compare_exchange_strong takes T& as its first parameter. atomic<T> is not convertible to T& (even though it is convertible to an rvalue of type T; such a conversion just calls load()).
If atomic<T> were convertible to T&, it would effectively give unrestricted access to underlying raw storage, and allow users to modify it at will, bypassing any synchronization mechanisms. Which would thoroughly defeat the point of having an atomic in the first place.


check for identical rows in different numpy arrays

Question: how do I get a row-wise comparison between two arrays, in the result of  a row-wise  true/false array?
Given datas:
a = np.array([[1,0],[2,0],[3,1],[4,2]])
b = np.array([[1,0],[2,0],[4,2]])

Result  step 1:
c = np.array([True, True,False,True])

Result final:
a = a[c]

So how  do I get   the  array c  ????
P.S.: In this example the arrays a and b  are sorted, please give also information if in your solution it is important that the arrays are sorted
Answer: Here's a vectorised solution:
res = (a[:, None] == b).all(-1).any(-1)

print(res)

array([ True,  True, False,  True])

Note that a[:, None] == b compares each row of a with b element-wise. We then use all + any to deduce if there are any rows which are all True for each sub-array:
print(a[:, None] == b)

[[[ True  True]
  [False  True]
  [False False]]

 [[False  True]
  [ True  True]
  [False False]]

 [[False False]
  [False False]
  [False False]]

 [[False False]
  [False False]
  [ True  True]]]

Comment: this looks  good                                                             a = np.array([[1,0],[2,0],[4,2],[3,1],[3,0]])
b = np.array([[1,0],[2,0],[3,1]])
c = (a[:, None] == b).all(-1).any(-1)                          result   [ True  True False  True False]
Comment: Similar to here https://stackoverflow.com/questions/53631460/using-numpy-isin-element-wise-between-2d-and-1d-arrays
Answer: you can use numpy with apply_along_axis (kind of iteration on specific axis while axis=0 iterate on every cell, axis=1 iterate on every row, axis=2 on matrix and so on
import numpy as np
a = np.array([[1,0],[2,0],[3,1],[4,2]])
b = np.array([[1,0],[2,0],[4,2]])
c = np.apply_along_axis(lambda x,y: x in y, 1, a, b)

Comment: This doesn't actually use **`np.isin`**, bit confused why you mentioned it, as I don't think it's particularly useful here.
Comment: seems  not to work in order to check for identical rows: a = np.array([[1,0],[2,0],[4,2],[3,1],[3,0]])
b = np.array([[1,0],[2,0],[3,1]])
c = np.apply_along_axis(lambda x,y: x in y, 1, a, b) result is  [ True  True False  True  True]    the last one should be false
Answer: Approach #1
We could use a view based vectorized solution -
# https://stackoverflow.com/a/45313353/ @Divakar
def view1D(a, b): # a, b are arrays
    a = np.ascontiguousarray(a)
    b = np.ascontiguousarray(b)
    void_dt = np.dtype((np.void, a.dtype.itemsize * a.shape[1]))
    return a.view(void_dt).ravel(),  b.view(void_dt).ravel()

A,B = view1D(a,b)
out = np.isin(A,B)

Sample run -
In [8]: a
Out[8]:
array([[1, 0],
       [2, 0],
       [3, 1],
       [4, 2]])

In [9]: b
Out[9]:
array([[1, 0],
       [2, 0],
       [4, 2]])

In [10]: A,B = view1D(a,b)

In [11]: np.isin(A,B)
Out[11]: array([ True,  True, False,  True])

Approach #2
Alternatively for the case when all rows in b are in a and rows are lexicographically sorted, using the same views, but with searchsorted -
out = np.zeros(len(A), dtype=bool)
out[np.searchsorted(A,B)] = 1

If the rows are not necessarily lexicographically sorted -
sidx = A.argsort()
out[sidx[np.searchsorted(A,B,sorter=sidx)]] = 1

Answer: You can do it as a list comp via:
c = np.array([row in b for row in a])

though this approach will be slower than a pure numpy approach (if it exists).
Answer: You can use scipy's cdist which has a few advantages:
from scipy.spatial.distance import cdist

a = np.array([[1,0],[2,0],[3,1],[4,2]])
b = np.array([[1,0],[2,0],[4,2]])

c = cdist(a, b)==0
print(c.any(axis=1))

[ True  True False  True]

print(a[c.any(axis=1)])

[[1 0]
 [2 0]
 [4 2]]

Also, cdist allows passing of a function pointer. So you can specify your own distance functions, to do whatever comparison you need:
c = cdist(a, b, lambda u, v: (u==v).all())
print(c)

[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 0.]
 [0. 0. 1.]]

And now you can find which index matches. Which will also indicate if there are multiple matches.
# Array with multiple instances
a2 = np.array([[1,0],[2,0],[3,1],[4,2],[3,1],[4,2]])

c2 = cdist(a2, b, lambda u, v: (u==v).all())
print(c2)

idx = np.where(c2==1)
print(idx)

print(idx[0][idx[1]==2])

[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 0.]
 [0. 0. 1.]
 [0. 0. 0.]
 [0. 0. 1.]]
(array([0, 1, 3, 5], dtype=int64), array([0, 1, 2, 2], dtype=int64))
[3 5]

Comment: Interesting approach. I wonder how it fares in terms of performance
Answer: a = np.array([[1,0],[2,0],[3,1],[4,2]])
b = np.array([[1,0],[2,0],[4,2]])

i = 0
j = 0
result = []

We can take advantage of the fact that they are sorted and do this in O(n) time. Using two pointers we just move ahead the pointer that has gotten behind:
while i < len(a) and j < len(b):
    if tuple(a[i])== tuple(b[j]):
        result.append(True)
        i += 1
        j += 1 # get rid of this depending on how you want to handle duplicates
    elif tuple(a[i]) > tuple(b[j]):
        j += 1
    else:
        result.append(False)
        i += 1

Pad with False if it ends early.
if len(result) < len(a):
    result.extend([False] * (len(a) - len(result)))

print(result) # [True, True, False, True]

This answer is adapted from Better way to find matches in two sorted lists than using for loops? (Java)
Answer: The recommended answer is good, but will struggle when dealing with arrays with a large number of rows. An alternative is:
baseval = np.max([a.max(), b.max()]) + 1
a[:,1] = a[:,1] * baseval
b[:,1] = b[:,1] * baseval
c = np.isin(np.sum(a, axis=1), np.sum(b, axis=1))

This uses the maximum value contained in either array plus 1 as a numeric base and treats the columns as baseval^0 and baseval^1 values. This ensures that the sum of the columns are unique for each possible pair of values. If the order of the columns is not important then both input arrays can be sorted column-wise using np.sort(a,axis=1) beforehand.
This can be extended to arrays with more columns using:
baseval = np.max([a.max(), b.max()]) + 1
n_cols = a.shape[1]
a = a * baseval ** np.array(range(n_cols))
b = b * baseval ** np.array(range(n_cols))
c = np.isin(np.sum(a, axis=1), np.sum(b, axis=1))

Overflow can occur when baseval ** (n_cols+1) > 9223372036854775807 if using int64. This can be avoided by setting the numpy arrays to use python integers using dtype=object.
Comment: You need ** not * I think.


How to adjust strike that's too small for metal jam?

Question: I am installing new Schlage lock set. Problem is the included Schlage strike is much smaller/shorter than the drilled out rectangle space in the metal door jam. Only one screw hole matches other hole is about 1/2 inch too short. How do I adjust?
Comment: Your new door knob should work fine with the old strike plate.
Comment: @Alaskaman Geez! It did. Thx!
Comment: Talking about the strike plate or the latch assembly? ... put the old plate back.
Answer: Strike plates are rarely proprietary to the door knob itself. Most are the same size, some slightly different in size or screw hole placement but the catch of the door knob should fit in the catch hole  of all of them if they are lined up right.
Since you have metal door jamb it is not easy to modify your jamb.
Try using the old strike plate, it should work just fine.
Credit to Mazura for thinking of it first.
Comment: I don't throw anything away (doesn't everybody have three buckets of lock parts? ;) and I usually don't pull the plate off if I can avoid it; too many times pieces of trim caked on with paint have come off with it, even if you use a knife to cut around it.
Answer: You may have use a longer screw for the hole that is not lining-up. I'm assuming it's over the opening on the jamb for the latch. If so, you can drill a hole into the door jamb to allow a longer screw to screw into the wall stud. You may need to back-up the pate if it doesn't have part of the jamb to support it when screwed down.
You may be able to replace the original strike plate with a Dead bolt strike plate. These are usually longer than standard door plate. There may be a problem in that there is no curved lip and the latch opening is slightly wider.

How to adjust strike that’s too small for metal jam?


How can I write an if block using lambda?

Question: Could you please tell me how can I write this expression using lambda/ Java 8 ?
String str = "Hello";
String x = "1";

if(str.equals("Hello") || str.equals("Helloo") ||
         str.equals("Hellooo") || str.equals("Hellooo...")) {
   if(x != null) {
       // do something
   } else {
       // do something else
   }
}

Comment: Any reason you want to use a lambda expression for this?
Comment: Have you tried anything yet? Where exactly are you stuck?
Comment: In general, I need to use everywhere I can lambda expression, this is the requirement,  and I am quite new on this...
Answer: You can use a Set to store all your salutations, and then use filter and ifPresent to make your condition:
Stream.of("Hello", "Helloo", "Hellooo", "Hellooo...")
        .filter(str::equals)
        .findAny()
        .ifPresent(c -> {
            if (x != null) {
                // do something
            } else {
                // do something else
            }
        });

But in your case, I would like to use:
if (str.matches("Hell[o]{1,4}(\\.{4})?")) {
    if (x != null) {
        // do something
    } else {
        // do something else
    }
}

About the regex, you can improve it based on your inputs, I made a quick one to show you the other solution.
Comment: You could inline that by using `Stream.of("Hello", "Helloo", "Hellooo", "Hellooo...")`
Comment: Note, if you are using Java 8, you can pass the list to a `HashSet` e.g. `new HashSet<>(Arrays.asList("Hello", "Helloo", "Hellooo", "Hellooo..."))`
Comment: I agree @Andreas, Set.of is used from Java10, so its better to use `Stream.of("Hello", "Helloo", "Hellooo", "Hellooo...")`
Comment: @Mr.Polywhirl or much better the proposition of Andreas `Stream.of("Hello", "Helloo", "Hellooo", "Hellooo...")`
Comment: @YCF_L The `Set.of` method was introduced in Java 9, I was just noting compatability, but `Stream.of` will work! -- Alternatively, for Java 8 :- `Stream.of("Hello", "Helloo", "Hellooo", "Hellooo...").collect(Collectors.toSet())`
Comment: @YCF_L I fixed it, I meant `Set.of` :p
Comment: @Mr.Polywhirl I read the doc, and Stream.of is introduced in Java 8 https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#of-T...- :D