text:
Q: How to get object already in store with all its subfield? I'm trying to get an object with all its attribute from Apollo store
Use case detailed
First query server side:
Person {
 id # id=1
 field_A
 field_B
}

Second query client side:
Person {
 id # id=1
 field_C
}

After these queries Apollo store look like that:
Person: {
 id # id=1
 field_A
 field_B
 field_C
}

Is it possible to get the Person with id=1 and all its attributes without writing a query specifying all fields ? Or readQuery the previous queries and merge the 2 Persons manually ?
Thanks

A: You will need to write the query and you have two options to get this data from your store:
First:
Use the withApollo HOC to get access to your client and then use readQuery passing the query that have all the fields you need.
Second:
Use the query component with the query that have all the fields you need and pass cache-only as the fetch policy. More info here: https://www.apollographql.com/docs/react/api/react-apollo.html#graphql-config-options-fetchPolicy


text:
Q: can't handle a redirect
I've been trying to redirect a page but with no success.
My purpose is to redirect example.com/me/name to example.com/me?n=name
I've tried with add_rewrite_rule, write conditions in .htaccess, but nothing worked.
Any clue?

Edit:
The full htaccess code is this:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

<IfModule mod_deflate.c>
  # Compress HTML, CSS, JavaScript, Text, XML and fonts
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/rss+xml
  AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
  AddOutputFilterByType DEFLATE application/x-font
  AddOutputFilterByType DEFLATE application/x-font-opentype
  AddOutputFilterByType DEFLATE application/x-font-otf
  AddOutputFilterByType DEFLATE application/x-font-truetype
  AddOutputFilterByType DEFLATE application/x-font-ttf
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE font/opentype
  AddOutputFilterByType DEFLATE font/otf
  AddOutputFilterByType DEFLATE font/ttf
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE image/x-icon
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE text/xml

  # Remove browser bugs (only needed for really old browsers)
  BrowserMatch ^Mozilla/4 gzip-only-text/html
  BrowserMatch ^Mozilla/4\.0[678] no-gzip
  BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
  Header append Vary User-Agent
</IfModule>

## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 2 days"
</IfModule>
## EXPIRES CACHING ##

Edit 2:
The code for redirect I was trying to use is this:
#RewriteRule (http://example.com/me/*) http://example.com/me?n=$1

Edit 3:
The "name" in the code does not stay the same, it is variable depending on person. It can be Ash, George, Mike, whatever.

A: use This Plugin
Or Write this code on top of htacces file:
Redirect 301 /oldfile.htm http://example.net/newfile.htm

A: Can you please try the following? Also make sure your Rewrite Module is "uncommented" from apache.conf and/or php.ini depending on your configuration.
#permanently redirect from example.com/me/name domain to example.com/me?n=name
RewriteEngine on
Options +FollowSymLinks
RewriteCond %{HTTP_HOST} ^www\.example/me\.com$ [NC]
RewriteRule ^(.*)$ www.example.com/?n=name/$1 [R=301,L]

A: I agree with @Kinal Nagarkar that there is a simple plugin for this. My personal Favorite is Redirection. It not only allows direct URL redirects, but also REGEX and give you a counter to monitor how often it is used. (There are also some other features that I don't personally use, but I'm sure are useful).
Either way, there are at least two plugins that you could use that are pretty light weight and don't require you to reinvent the wheel for a single redirect.
While changing your .htaccess might operate faster, please consider usability as another important factor too.

redpajama_set_name: RedPajamaStackExchange


text:
Q: I am having trouble following the trace function in Prolog. I am new to Prolog and computer programming in general. I have been going through the exercises in Learn Prolog Now! and have been getting along alright but occasionally, when I do run into difficulty, I attempt to use the trace function to follow the program line for line and see how it is working or what is going wrong but I can't make heads or tails of what is being listed by trace. I'll give an example...
One of the exercises was to fill out a crossword grid with a predicate crossword/6. These are all the facts and rules in the answer:
 word(abalone,a,b,a,l,o,n,e).
 word(abandon,a,b,a,n,d,o,n).
 word(enhance,e,n,h,a,n,c,e).
 word(anagram,a,n,a,g,r,a,m).
 word(connect,c,o,n,n,e,c,t).
 word(elegant,e,l,e,g,a,n,t).

crossword(V1,V2,V3,H1,H2,H3):-
word(H1,_,H12V12,_,H14V22,_,H16V32,_),
word(H2,_,H22V14,_,H24V24,_,H26V34,_),
word(H3,_,H32V16,_,H34V26,_,H36V36,_),

word(V1,_,H12V12,_,H22V14,_,H32V16,_),
word(V2,_,H14V22,_,H24V24,_,H34V26,_),
word(V3,_,H16V32,_,H26V34,_,H36V36,_).

This works just fine. But I wanted to know how it worked, I wanted to see how the computer works its way through the rules step by step. So I used trace on the query crossword(V1,V2,V3,H1,H2,H3). What follows are just the first ten line or so of what is produced.
[trace]  ?- crossword(V1,V2,V3,H1,H2,H3).
  Call: (8) crossword(_5238, _5240, _5242, _5244, _5246, _5248) ? creep
  Call: (9) word(_5244, _5658, _5660, _5662, _5664, _5666, _5668, _5670) ? creep
  Exit: (9) word(abalone, a, b, a, l, o, n, e) ? creep
  Call: (9) word(_5246, _5658, _5660, _5662, _5664, _5666, _5668, _5670) ? creep
  Exit: (9) word(abalone, a, b, a, l, o, n, e) ? creep
  Call: (9) word(_5248, _5658, _5660, _5662, _5664, _5666, _5668, _5670) ? creep
  Exit: (9) word(abalone, a, b, a, l, o, n, e) ? creep
  Call: (9) word(_5238, _5658, b, _5662, b, _5666, b, _5670) ? creep
  Fail: (9) word(_5238, _5658, b, _5662, b, _5666, b, _5670) ? creep
  Redo: (9) word(_5248, _5658, _5660, _5662, _5664, _5666, _5668, _5670) ? creep
  Exit: (9) word(abandon, a, b, a, n, d, o, n) ? creep
  Call: (9) word(_5238, _5658, b, _5662, b, _5666, b, _5670) ? creep
  Fail: (9) word(_5238, _5658, b, _5662, b, _5666, b, _5670) ? creep

I know that the first line is just a restatement of the query but with the variables changed into arbitrary numbers. Then it goes to the first goal of the rule, and again, the variables are simply instantiated as arbitrary numbers.  This goal sends the program to the first fact in the database, namely word(abalone,a,b,a,l,o,n,e).
Now is where I start to get confused. Why is the next line after that, the first goal again, but with the first variable changed from _5244 to _5246? Then I get an Exit: word(abalone,a,b,a,l,o,n,e) - by the way, I'm not sure what Call: and Exit: mean exactly either - followed again by the same line but with the first variable changed from _5246 to _5248. What is going on here? Why are all the other variables constant and just the first one is changing?
A little further down I get even more baffled. With the line Call: (9) word(_5238, _5658, b, _5662, b, _5666, b, _5670) ? creep, where are the b's coming from and why are there three of them? I figured the first one is there because it is the second letter of abalone, thus filling that spot in the crossword, but why are the next two b's there? Shouldn't they be 'l' and 'n'?
I realize that this is probably very simple to someone who understands Prolog well but I have no idea what is going on. And that is a problem because the trace function is probably the single most useful tool in learning Prolog. If I can't use it and understand it then I won't be able to check how things work along the way as I learn. If anyone is able to just clear this up for me and maybe suggest a way for me to get better at reading and understanding trace I would really appreciate it.

A: If you are using SWI-Prolog, I recommend gtrace(type "gtrace." and call predicate)
_5238 means a Variable .
when you call word/6 , Variables are patternmatched to first candidate and a choice point is generated.
in this case, assume 6(number of word/8 definitions) "or" sentenses are generated.
if pattenmatch is failed,prolog tryes next candidate.
if pattenmatch is success,prolog goes to next line(and next choice points are generated)
if all choices are failed, prolog goes back to previous choice point and try next candidates at the point(backtrack)
notice choice points are generated at each word/8 calling individually.
at all choice points, prolog remembers which candidate now testing.
and notice when backtrack occured , all variables at the choice point are become free(prolog variables are not permitted to be changed. either a value or free)


text:
Q: python for loop in matrix to assign values I was creating a program that will create a grid and the program will
deside its position by a matrix array you assign at the input.
code:
def onbekende_naam(hoogtes):
    print(hoogtes)
    i = 0
    j = 0
    pos1 = set()

    for hoogtes_subs in hoogtes:
        j = 0
        for hoogtes in hoogtes:
            print("i = " + str(i))
            print("j = " + str(j))
            pos1.add((i, j))
            print pos1
            j += 1
        i += 1
        #pos1.add((i, j))

    return pos1

#verwerking
print (onbekende_naam(hoogtes))

input:
4 4
1 2 3 4
5 6 7 8
9 1 2 3
4 5 6 7
12 1

output:
[['1', '2', '3', '4'], ['5', '6', '7', '8'], ['9', '1', '2', '3'], ['4', '5', '6', '7']]
i = 0
j = 0
set([(0, 0)])
i = 0
j = 1
set([(0, 1), (0, 0)])
i = 0
j = 2
set([(0, 1), (0, 0), (0, 2)])
i = 0
j = 3
set([(0, 1), (0, 3), (0, 0), (0, 2)])
i = 1
j = 0
set([(0, 1), (0, 3), (0, 0), (0, 2), (1, 0)])
i = 1
j = 1
set([(0, 1), (0, 0), (0, 2), (1, 0), (0, 3), (1, 1)])
i = 1
j = 2
set([(0, 1), (1, 2), (0, 0), (0, 2), (1, 0), (0, 3), (1, 1)])
i = 1
j = 3
set([(0, 1), (1, 2), (0, 0), (0, 2), (1, 3), (1, 0), (0, 3), (1, 1)])
i = 2
j = 0
set([(0, 1), (1, 2), (0, 0), (0, 2), (2, 0), (1, 3), (1, 0), (0, 3), (1, 1)])
i = 3
j = 0
set([(0, 1), (1, 2), (0, 0), (3, 0), (0, 2), (2, 0), (1, 3), (1, 0), (0, 3), (1, 1)])
set([(0, 1), (1, 2), (0, 0), (3, 0), (0, 2), (2, 0), (1, 3), (1, 0), (0, 3), (1, 1)])

as you can see it stops incrementing j when the i value is bigger than 2
I'm fairly new at this so thanks for helping

A: It looks like you use the same name in your second for loop. Can you try if changing this works?
def onbekende_naam(hoogtes):
    print(hoogtes)
    i = 0
    j = 0
    pos1 = set()

    for hoogtes_subs in hoogtes:
        j = 0
        for another_name_hoogtes in hoogtes:
            print("i = " + str(i))
            print("j = " + str(j))
            pos1.add((i, j))
            print pos1
            j += 1
        i += 1
        #pos1.add((i, j))

    return pos1

#verwerking
print (onbekende_naam(hoogtes))

Also: when I run your original code I get the following error:

TypeError: 'int' object is not iterable

Why didn't you get this error?


text:
Q: Programmatically open app in split screen How do I open another app in a split screen in the android N (SDK 24)?
In the documentation I found this:

Launch New Activities in Multi-Window Mode
When you launch a new activity, you can hint to the system that the new activity should be displayed adjacent to the current one, if possible. To do this, use the flag Intent.FLAG_ACTIVITY_LAUNCH_TO_ADJACENT. Passing this flag requests the following behaviour:
If the device is in split-screen mode, the system attempts to create the new activity next to the activity that launched it, so the two activities share the screen. The system is not guaranteed to be able to do this, but it makes the activities adjacent if possible.
If the device is not in split-screen mode, this flag has no effect.
If a device is in freeform mode and you are launching a new activity, you can specify the new activity's dimensions and screen location by calling ActivityOptions.setLaunchBounds(). This method has no effect if the device is not in multi-window mode.

so when I tried this out, the Intent.FLAG_ACTIVITY_LAUNCH_TO_ADJACENT flag does not exist. I installed

*

*Android 6.x (N) SDK 24 revision 1

*Android N Preview SDK N revision 3

*Android 6.0 (Marshmallow) SDK 23 revision 3

this is my gradle:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.0"

    defaultConfig {
        applicationId "PACKAGENAME"
        minSdkVersion 16
        targetSdkVersion 24
        versionCode 2
        versionName "2.4.1"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.0.0'
    compile 'com.android.support:design:24.0.0'
    compile 'org.jsoup:jsoup:1.8.3'
    compile 'com.android.support:support-v4:24.0.0'
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'com.squareup.okhttp3:okhttp:3.2.0'
}

A: Hi Starting from android 7.0 you can go to Freeform multiwindow mode. Turn on developer options in your device and use following adb commands :
adb shell settings put global enable_freeform_support  1
adb shell settings put global force_resizable_activities  1

After you can use the following function to launch different activities in split screen programmatically:
private void goToSplitMode() {
        PackageManager manager = getPackageManager();
        Intent i = manager.getLaunchIntentForPackage("com.google.android.apps.maps");

        i.addFlags(Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT |
                Intent.FLAG_ACTIVITY_NEW_TASK |
                Intent.FLAG_ACTIVITY_MULTIPLE_TASK);

        DisplayMetrics displayMetrics = new DisplayMetrics();
        Rect mBounds = new Rect(300, 0, getScreenWidth(this), getScreenHeight(this));
         mOptions = getActivityOptions(MainActivity.this);
        mOptions = mOptions.setLaunchBounds(mBounds);

        startActivity(i, mOptions.toBundle());

        i = new Intent(this, SplitMainActivity.class);
        mBounds = new Rect(0, 0, 300, getScreenHeight(this));
        mOptions = getActivityOptions(MainActivity.this);
        mOptions = mOptions.setLaunchBounds(mBounds);

        i.addFlags(Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT |
                Intent.FLAG_ACTIVITY_NEW_TASK |
                Intent.FLAG_ACTIVITY_MULTIPLE_TASK);

        startActivity(i, mOptions.toBundle());
    }

    public static ActivityOptions getActivityOptions(Context context) {
        ActivityOptions options = ActivityOptions.makeBasic();
        int freeform_stackId = 5;
        try {
            Method method = ActivityOptions.class.getMethod("setLaunchWindowingMode", int.class);
            method.invoke(options, freeform_stackId);
        } catch (Exception e) { /* Gracefully fail */
            }

        return options;
    }

public static int getScreenWidth(@NonNull Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            WindowMetrics windowMetrics = activity.getWindowManager().getCurrentWindowMetrics();
            Insets insets = windowMetrics.getWindowInsets()
                    .getInsetsIgnoringVisibility(WindowInsets.Type.systemBars());
            return windowMetrics.getBounds().width() - insets.left - insets.right;
        } else {
            DisplayMetrics displayMetrics = new DisplayMetrics();
            activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
            return displayMetrics.widthPixels;
        }
    }

    public static int getScreenHeight(@NonNull Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            WindowMetrics windowMetrics = activity.getWindowManager().getCurrentWindowMetrics();
            Insets insets = windowMetrics.getWindowInsets()
                    .getInsetsIgnoringVisibility(WindowInsets.Type.systemBars());
            return windowMetrics.getBounds().height() - insets.top - insets.bottom;
        } else {
            DisplayMetrics displayMetrics = new DisplayMetrics();
            activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
            return displayMetrics.heightPixels;
        }
    }

A: First of all app should be targeted to SDK 24+ version. If it targeted to lower than 24 SDK then split screen mode would not work.
Then carefully read here and here

If the device is in split-screen mode, the system attempts to create
  the new activity next to the activity that launched it, so the two
  activities share the screen. The system is not guaranteed to be able
  to do this, but it makes the activities adjacent if possible.
This flag is only used in split-screen multi-window mode. The new
  activity will be displayed adjacent to the one launching it. This can
  only be used in conjunction with FLAG_ACTIVITY_NEW_TASK. Also, setting
  FLAG_ACTIVITY_MULTIPLE_TASK is required if you want a new instance of
  an existing activity to be created.

It means that you can't start split screen mode programmatically. You can just try to launch activity in another part of screen if you are already in split screen mode.


text:
Q: Making simplified MakeBoxes What is the simplest way to make an analog of MakeBoxes which will reproduce only on aspect of its behavior: converting correct expressions involving only symbols without FormatValues to BoxForms:
Trace[MakeBoxes[graphics[disk[]], StandardForm], TraceInternal -> True]

This function should be recursive as MakeBoxes is. What is really confusing is how to convert disk[] to RowBox[{"disk", "[", "]"}] avoiding parsing of string representation of the original expression.
P.S. This question comes from the previous question.

A: I don't think you can avoid parsing or string conversion in one way or another - at the end you need strings, and you start with symbols. Either you somehow  reuse MakeBoxes, or you have to deal with strings. Dragging my code around: the following simple box-making function is based on the Mathematica parser posted here (my second post there, at the bottom of the page):
Clear[toBoxes];
toBoxes[expr_] :=
  First[parse[tokenize[ToString@FullForm[expr]]] //. {
    head_String[elem_] :>    RowBox[{head, "[", elem, "]"}],
    head_String[elems___] :>  RowBox[{head, "[", RowBox[Riffle[{elems}, ","]], "]"}]}]

If you don't want to parse but don't mind ToString, then a slight variation of the above will do:
toBoxesAlt[expr_] :=
  expr /. s_Symbol :> ToString[s] //. {
     head_String[elem_] :> RowBox[{head, "[", elem, "]"}],
     head_String[elems___] :>  RowBox[{head, "[", RowBox[Riffle[{elems}, ","]], "]"}]}

Note that this last function does not involve any parsing.Then, we need:
Clear[MakeBoxesStopAlt];
MakeBoxesStopAlt /: MakeBoxes[MakeBoxesStopAlt[expr_], form_] :=  toBoxes[expr]

For example:
In[327]:= MakeBoxesStopAlt[Graphics[Disk[]]]

Out[327]= Graphics[Disk[List[0, 0]]]

You may want to re-implement the parser if my implementation looks too complicated, although mine is rather efficient.
EDIT
Here is a very simplistic and probably slow approach to parsing: the function tokenize is the same as before, and I will repost it here for convenience:
tokenize[code_String] :=
 Module[{n = 0, tokenrules},
   tokenrules = {"[" :> {"Open", ++n}, "]" :> {"Close", n--},
     Whitespace | "" ~~ "," ~~ Whitespace | ""};
   DeleteCases[StringSplit[code, tokenrules], "", Infinity]];

Here is the parsing function:
parseSimple[tokenized_] :=
  First[tokenized //. {left___,
     Shortest[
       PatternSequence[h_, {"Open", n_}, elems___, {"Close", n_}]], right___} :>
       {left, h[elems], right}];

You may use it in place of parse, and these two functions then form a self-contained solution for the parser.
The same comment as for my answer to your previous question is in order: if you want to handle /disallow expression evaluation, add appropriate attributes and Unevaluated wrappers where needed.
EDIT2
Here is a version of makeBoxes that does not involve parsing, does not leak evaluation and does handle nested heads correctly (at least for some simple tests):
Clear[handleElems];
handleElems[] := Sequence[];
handleElems[el_] := el;
handleElems[els__] := RowBox[Riffle[{els}, ","]];

ClearAll[makeBoxes];
SetAttributes[makeBoxes, HoldAllComplete];
makeBoxes[ex_] :=
 Block[{makeBoxes},
   SetAttributes[makeBoxes, HoldAllComplete];
   makeBoxes[expr_ /;!FreeQ[Unevaluated[expr],
        s_ /; AtomQ[Unevaluated[s]] && ! StringQ[Unevaluated[s]]]] :=
     makeBoxes[#] &@(Unevaluated[expr] /.
          s_ /; AtomQ[Unevaluated[s] && ! StringQ[Unevaluated[s]]] :>
                  ToString[Unevaluated[s]]);

   makeBoxes[a_ /; AtomQ[Unevaluated[a]]] := a;

   makeBoxes[expr_] /; MatchQ[expr, h_String[___]] :=
        expr //. {
           (h : ("Rule" | "RuleDelayed"))[l_, r_] :>
                 RowBox[{l, h /. {
                           "Rule" -> "\[Rule]",
                           "RuleDelayed" -> "\[RuleDelayed]"
                         }, r}],
           "List"[elems___] :> RowBox[{"{", handleElems[elems], "}"}],
           head_String[elems___] :> RowBox[{head, "[", handleElems[elems], "]"}]
        };

   makeBoxes[expr_] :=
       RowBox[{makeBoxes[#] &@Head[expr], "[",
           handleElems @@ (makeBoxes @@@ expr), "]"}];

   makeBoxes @@ (HoldComplete[ex] /. s_String :>
       With[{eval = StringJoin["\"", s, "\""]}, eval /; True])
];

Example of use:
In[228]:= a=1;b=2;c = 3;

In[229]:= makeBoxes[a:>b]
Out[229]= RowBox[{a,:>,b}]

In[230]:= makeBoxes[a->b]
Out[230]= RowBox[{a,->,b}]

In[231]:= makeBoxes[{a,{b,c}}]
Out[231]= RowBox[{{,RowBox[{a,,,RowBox[{{,RowBox[{b,,,c}],}}]}],}}]

In[232]:= makeBoxes[a[b][c]]
Out[232]= RowBox[{RowBox[{a,[,b,]}],[,c,]}]

In[233]:= makeBoxes[a[b[e[],f[]],c[g[],h[]]][x,y]]

Out[233]= RowBox[{RowBox[{a,[,RowBox[{RowBox[{b,[,RowBox[{RowBox[{e,
   [,]}],,,RowBox[{f,[,]}]}],]}],,,RowBox[{c,[,RowBox[{RowBox[{g,[,]}],,,
    RowBox[{h,[,]}]}],]}]}],]}],[,RowBox[{x,,,y}],]}]

In all cases tested, the output is the same as that of MakeBoxes.

A: Here is my implementation of simplified MakeBoxes without conversion of the original expression to string:
ClearAll[SimpleMakeBoxes, SimpleMakeBoxesRules];
SetAttributes[SimpleMakeBoxes, HoldAll];
SimpleMakeBoxesRules = {h_Symbol[] :> RowBox[{ToString@h, "[", "]"}],
   h_Symbol[expr_] :>
    RowBox[{ToString@h, "[", Unevaluated[expr] /. SimpleMakeBoxesRules, "]"}],
   h_Symbol[expr__] :>
    RowBox[{ToString@h, "[",
      RowBox[Riffle[
        List @@ Replace[Hold[expr],
          x_ :> (Unevaluated[x] /. SimpleMakeBoxesRules), {1}], ","]], "]"}],
   a:(_Real | _Integer | _String) :> ToString[FullForm@a]};
SimpleMakeBoxes[expr_] :=
 Unevaluated[expr] /.
   SimpleMakeBoxesRules //. {RowBox[{"List", "[", elems___, "]"}] :>
    RowBox[{"{", elems, "}"}],
   RowBox[{"Rule", "[", RowBox[{lhs_, ",", rhs_}], "]"}] :>
    RowBox[{lhs, "\[Rule]", rhs}],
   RowBox[{"RuleDelayed", "[", RowBox[{lhs_, ",", rhs_}], "]"}] :>
    RowBox[{lhs, "\[RuleDelayed]", rhs}]}

Usage example:
In[7]:= SimpleMakeBoxes@Graphics[Disk[]]
RawBoxes@%
Out[7]= RowBox[{Graphics,[,RowBox[{Disk,[,]}],]}]
Out[8]= Graphics[Disk[]]


text:
Q: Combine/concatenate multiple MP4 files, making each file into a chapter I am looking to use handbrake to combine 43 short mp4 files into one larger file. However, I want to ensure that the start of each file is recognized as a chapter. I'd be using vlc to play the file.

A:
What format are your video files in ? If they're DVD MPEG-2 then Handbrake can convert them to MP4/M4V or MKV, both of which support chapter markers.
If you already have MP4 files I believe you can use Subler to add chapters or something like Metadata Hootenanny.

Basically it is saying your MP4's needs to have the Chapters created before using handbrake.  You may try Subler to add chapters.  I have never tried Subler so I wouldn't be able to give you any specifics.
http://forum.videohelp.com/threads/311503-Video-format-with-chapter-markers


text:
Q: Wix installer: How to ask user to provide a file path needed by application configuration I am developing a Chrome extension for my company. The extension uses Chrome native messaging, so I am using Wix to create an installer for the host application (Just copy the binary and write a specific registry).
The native host application needs a configuration file, because the host application is performing crypto operations and in order to do that, the user needs to provide his pkcs12 keystore with signing certificates.
My first thought was to create the configuration file during installation. User would provide a path to his keystore file, the installer would write that path into the config file and copy it into the installation directory next to the host binary. I was searching the internet for hours just to find out it is not possible to select a file using Wix, only a directory.
My question is, is this actually true and there is really no way of doing this, and if so, what would you suggest? It's not very user-friendly to ask users to copy their keystore into a particular location. My second idea was to just put a text field and tell the user to fill in the path to their keystore file, but that isn't user-friendly either.
Thank you for all your suggestions


text:
Q: File size in human readable format Given the size of a file in bytes, I want to format it with IEC (binary) prefixes to 3 significant figures with trailing zeros, e.g. 1883954 becomes 1.80M.
Floating-point arithmetic isn't supported in bash, so I used awk instead. The problem is I don't how to keep the trailing zeros. Current solution:
if [ $size -ge 1048576 ]
then
    size=$(awk 'BEGIN {printf "%.3g",'$size'/1048576}')M
elif [ $size -ge 1024 ]
then
    size=$(awk 'BEGIN {printf "%.3g",'$size'/1024}')K
fi

(The files aren't that big so I don't have to consider bigger units.)
Edit: There's another problem with this. See Adrian Frühwirth's comment below.

A: GNU Coreutils contains an apparently rather unknown little tool called numfmt for numeric conversion, that does what you need:
$ numfmt --to=iec-i --suffix=B --format="%.3f" 4953205820
4.614GiB

I think that suits your needs well, and isn't as large or hackish as the other answers.
If you want a more powerful solution, look at my other answer.

A: Instead of using ls and awk to get the file size, use stat -c %s filename.ext. It outputs only the number, with nothing else (at least on version 8.21). I can't use numfmt because it's an older version which doesn't appear to use the printf syntax with decimal precision. I instead use the script below. I use the last line to test if the script is being sourced. If it's not, I can call it directly on the command line.
#!/bin/bash

function getFriendlyFileSize() {
    OUT='/dev/null'
    [ "$#" == 0 ] && echo 'No number given' && return 1
    [ ! $(echo $1 | egrep -i '\-?[0-9]+') ] && echo 'Garbage data' && return 1

    if [ "$1" == '' -o "$1" -lt 0 ] 2>$OUT
    then
            echo '0 B'
            return 1
    else
            FSIZE=$1
    fi

    [ "$2" == '' ] && DECPTS=1 || DECPTS=$2

    KB=1024
    MB=1048576
    GB=1073741824
    TB=1099511627776
    PB=1125899906842624
    EB=1152921504606846976
    LM=9223372036854775807 # bash comparison limit = 2^63-1 (signed int?)

    [ "$FSIZE" -le 0 ] 2>$OUT && echo "0 B" && return
    [ "$FSIZE" -lt $KB ] 2>$OUT && echo "$FSIZE B" && return
    [ "$FSIZE" -lt $MB ] 2>$OUT && echo "$(echo "scale=$DECPTS;$FSIZE/$KB"|bc) KB" && return
    [ "$FSIZE" -lt $GB ] 2>$OUT && echo "$(echo "scale=$DECPTS;$FSIZE/$MB"|bc) MB" && return
    [ "$FSIZE" -lt $TB ] 2>$OUT && echo "$(echo "scale=$DECPTS;$FSIZE/$GB"|bc) GB" && return
    [ "$FSIZE" -lt $PB ] 2>$OUT && echo "$(echo "scale=$DECPTS;$FSIZE/$TB"|bc) TB" && return
    [ "$FSIZE" -lt $EB ] 2>$OUT && echo "$(echo "scale=$DECPTS;$FSIZE/$PB"|bc) PB" && return
    [ "$FSIZE" -le $LM ] 2>$OUT && echo "$(echo "scale=$DECPTS;$FSIZE/$EB"|bc) EB" && return
    [ "$?" -ne '0' ] 2>$OUT && echo "Bad input" && return 1
}

[[ $_ == $0 ]] && getFriendlyFileSize $1 $2

A: I know that it's a little late. But may someone find it useful.
The answer is, simply, to use %.2f instead of %.3g in your script. (src)

Test:
#!/bin/bash

size=1883954

if [ $size -ge 1048576 ]
then
    size=$(awk 'BEGIN {printf "%.2f",'$size'/1048576}')M
elif [ $size -ge 1024 ]
then
    size=$(awk 'BEGIN {printf "%.2f",'$size'/1024}')K
fi

echo $size

The Output:
1.80M

A: If you don't mind using bc then the following will help do floating point operations. scale can changed as per your needs depending on many digits you want to print.
size=1883954

if [ $size -ge 1048576 ]
then
    size=$(echo "scale=2;$size/1048576"| bc)M
elif [ $size -ge 1024 ]
then
    size=$(echo "scale=2;$size/1024" | bc)K
fi

echo $size

A: Is there any reason you are not using
ls -lh

command ? If you are on a Linux system which has been released in the last few years, you have this functionality.

A: ls -lah /path/to/your/file | awk -F " " {'print $5'}

A: If you happen to have Qalculate! installed (which is awesome by the way),
there's an easy trick:
human_readable="$( qalc -t set "precision $precision" "${in_bytes}B" )"

Example:
$ qalc -t -set "precision 3" 5264334820B
5.26 GB

It's a very very powerful tool to have in shell scripting, as it can even simplify formulas, solve for unknowns, and many many more things.
$ qalc -t "e^(i*x)=-1"
x = 3.1415927

If you want a simpler, less heavy-weight solution, look at my other answer.


text:
Q: What are the numbers in the upper right corner? In Call-Of-Duty Black-OPS and Modern-Warfare-2, there are 2 series of numbers in the upper right corner.
I thought they could be be an IP but one of these numbers is 0 in MW2.
I thought they could be the version, but the first number is 50 in BO.
I don't know if these numbers exist in other version of COD.
What do they mean?

A: It is the current production version of the each game.  It started to display the current version number with Call of Duty 4: Modern Warfare.

A: On Black Ops, this begins at 50.0.0.0, but then when it connects to the Playstation Network to go into multiplayer, this updates to the newest version (currently 53.x.x.x). These updates seem to be downloaded quietly and quickly.

A: Well I am not positive but I think it means the number of servers being used at once. But again I am not positive this is the right answer. ;-)


text:
Q: Validate whether its a human submitting a form and not a DOS :-0 How do you ensure that whoever is submitting a form is doing it and its not some DOS attack?
I was hoping there was an easy way to generate some kind of image or squiggle that the user has to enter prior to submitting a web form
Technology Stack
MVC with C#

A: http://en.wikipedia.org/wiki/Capcha
Try using Capcha possibly?

A: I'm assuming you mean that you want to check that it's not a bot (rather than DOS which is something else). For that, take a look at reCAPTCHA.

A: here is a short tutorial on generating a capcha.  a search on google reveals many more.


text:
Q: How to convert ruby array to support PostgreSQL array in ruby I have a following ruby array, need to convert array to support PostgresSQL array.
The array I have
ruby_array = ["9771", "9773", "9778", "9800", "9806"]

I need to convert this to following format
postgresSQL_array = {"9771", "9773", "9778", "9800", "9806"}

by using ruby

A: If you simply need to create a string in that format, you can stringify the Ruby array, removing the first and last characters and inserting it between curly braces.
irb(main):001:0> ruby_array = ["9771", "9773", "9778", "9800", "9806"]
=> ["9771", "9773", "9778", "9800", "9806"]
irb(main):002:0> postgresSQL_array = "{#{ruby_array.to_s[1...-1]}}"
=> "{\"9771\", \"9773\", \"9778\", \"9800\", \"9806\"}"
irb(main):003:0> puts postgresSQL_array
{"9771", "9773", "9778", "9800", "9806"}
=> nil

A: If you're using the PG gem, use PG::TextEncoder::Array to convert a Ruby Array to a PostgreSQL Array.
connection.exec(
  "select $1::int[]",
  [PG::TextEncoder::Array.new.encode([1, 2, 3])]
)

If you're using Ruby on Rails, simply pass the Array as a parameter and it will convert for you.
Model.where(nums: [1,2,3])

Note that most things you can do with PostgreSQL Arrays are better done with JSONB.


text:
Q: Appending to a list in Python: adds last element every time? I want to append a dict to a list, but the result I'm getting isn't what I want.
My code:
records=[]
record={}
for i in range(0,2):
  record['a']=i
  for j in range (0,2):
    record['b']=j
    records.append(record)
print records

I expected:
[{'a': 0, 'b': 0}, {'a': 0, 'b': 1}, {'a': 1, 'b': 0}, {'a': 1, 'b': 1}]

I get instead:
[{'a': 1, 'b': 1}, {'a': 1, 'b': 1}, {'a': 1, 'b': 1}, {'a': 1, 'b': 1}]

Why is it only adding the last element every time?

A: You are reusing and adding one single dictionary. If you wanted separate dictionaries, either append a copy each time:
records = []
record = {}
for i in range(2):
    record['a'] = i
    for j in range(2):
        record['b'] = j
        records.append(record.copy())

Or create a new dictionary each time:
records = []
for i in range(2):
    for j in range(2):
        record = {'a': i, 'b': j}
        records.append(record)

The latter approach lends itself to translation to a list comprehension:
records = [{'a': i, 'b': j} for i in range(2) for j in range(2)]

A: record.copy() will not work if you've nested dictionary, since it returns shallow copy. Use deepcopy instead which is full proof.
from copy import deepcopy
records.append(deepcopy(record))


text:
Q: Installshield error 1001 without installshield installed I have an application with an installshield installer. I install a service and a windows form.
Whenever I install the application on computers where I have installshield it installs, but when I try to install it on other machines it gives me Error 1001.
I am using Installshield LE, Visual Studio 2010. I am using the same OS on the development machines and on the machines where I would like to install, Windows 7.
Anyone has any idea how could that problem sorted? I tried to add all of the installshiled references what I could, but it did not change anything.
Regards
Daniel

A: I had the exact scenario and error, installing a service and one winform. It turns out I was getting the 1001 error (apparently) because my service was already running on that machine. (Which is why i suspect you were only getting the error on your development machine?) When I uninstalled the service through add/remove programs, the installation went as planned.

A: This installation error can occur because the incorrect version of InstallUtilLib.dll has been streamed into the MSI package for the .NET Installer Class custom actions.
Q112469: INFO: Error 1001 Occurs During Installation
Are you using both VS10 and VS12 ?
Have you activated the InstallShield ?

A: I had a similar problem. Mine was being caused by a similar service that was already installed. Uninstalling the already installed service worked for me.

A: This error occurs when you have a referenced Framework that you have not installed in the server where you are trying to install your app, select installshield le in menu bar, select options and then .NET, finally select the framework's folder in my case was v2.0 because that's the framework i have installed in the server,
hope can help

A: Hopefully this will help some of you encountering the Error 1001 when trying to install a .NET Windows Service using InstallShield 2015 LE installer project with the Primary Output set as an Installer.
It's a known InstallShield bug when .NET 4.6 is installed on Windows 10.
https://flexeracommunity.force.com/customer/articles/en_US/ISSUE/HOTFIX-Install-Fails-With-Error-1001-When-a-NET-Installer-Class-Component-is-Present-in-InstallShield-2015-SP1

A: Verify that you have the correct version of the .NET framework installed on the machine that you are installing the software to.   The version is shown in the project properties.


text:
Q: TryParseExact doesn't receive valid format c# I am trying to input a datetime value from the console. However, The TryParseExact method doesn't receive valid formats:
string startdate;
DateTime inputDate;
while (true)
{
   Console.WriteLine("Input time [HH:MM TT]");
   startdate = Console.ReadLine();
   if (DateTime.TryParseExact(startdate, "hh:mm tt",
                              CultureInfo.CurrentCulture,
                              DateTimeStyles.None, out inputDate))
   {
      break;
   }
}

Any suggestions?

A: If it is not accepting input that you think is valid then there are two possible causes of the problem:
1) The input is not what you think it is. This could be caused by copying and pasting from somewhere else that is including non-valid characters or something. IF you are manually typing the number then this is unlikely to be an issue.
2) The format you are accepting is not what you think it is. This is most likely since there are some subtleties that can bite you on this. The key think is to look up everything in http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx and be aware that several elements you are using are culture dependant. You are obviously at least partially aware of cultures since you are explicitly stating you want the current culture. Without knowing what that culture is though its hard to say what the input should be.
A case in point is that in your format : doesn't mean a literal colon but the "Time Separator". To quote the MSDN page: "The ":" custom format specifier represents the time separator, which is used to differentiate hours, minutes, and seconds. The appropriate localized time separator is retrieved from the DateTimeFormatInfo.TimeSeparator property of the current or specified culture."
As you can see this means that it is not always :.
Often the best fix, especially since you are hard definining the format, is to use CultureInfo.InvariantCulture which will guarantee not to change depending on where you run the software, etc. Otherwise you should generate the string that specifies the correct input using the relevant components of your current culture object.

A: An example of how to write this without the white(true) loop / to try to make it easier for your users:
string startdate;
DateTime inputDate;
while (inputDate == null)
{
    Console.WriteLine("Input time [HH:MM TT]");
    startdate = Console.ReadLine();
    if (!DateTime.TryParseExact
    (
        startdate, "hh:mm tt"
        ,CultureInfo.CurrentCulture
        ,DateTimeStyles.None
        , out inputDate
    ))
    {
        Console.WriteLine(String.Format("'{0}' is an invalid value."));
        //http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
        Console.WriteLine(
            String.Format("Example: The time now is '{0}'"
            ,DateTime.Now.ToString("hh:mm tt", CultureInfo.CurrentCulture))
        );
    }
}
Console.WriteLine("That's a valid time :)");

NB: your above code works in so much as given the correct input (for your user's current culture) the code exits the loop.


text:
Q: How can I turn off Gradle error popup notifications on Ubuntu 18.04? I am developing gradle scripts on Ubuntu.
Whenever an error occurs one or more of these kind of popups appear:

Does anyone know how to turn these off?
I tried Ubuntu's notification panel without success:

A: The question is answered in this post on askubuntu.  In short, you will need to create a shell script to intercept, classify, and conditionally kill the notifications as they arrive at the notification service.


text:
Q: Significance of 1e8 in divisions I am trying to understand a small function call in SQL Server 2012. I tried to search for it online but could not find much info.
The function itself is simple. It has two parameters @value and @default, both being int. This function DivFix returns @default when @value is null or 0, else it returns the @value itself.
This function is called in various SQL statements to avoid divide by zero error.
Select col1 / DivFix(col2,1e8)

My question is, what does 1e8 stand for here, and how does it help in overcoming the divide by zero error?

A: It means 10^8 (10 power 8), thus 100000000.
It's a short for "power(10, 8)"
From a mathematical point of view, it's not really a great way to handle "divide by 0" issue IMHO.
It would have more sense to use a very little number (which returns something close to infinite rather than a NaN / a failure) instead of this very big one (which makes the calculus return "something close to 0 but not exactly", unless the final rounding makes it equal to 0).

A: xEy is a common short hand for x * 10^y. So 2e8 = 2 * 10^8.
As to how it helps with divide by zero or null: I have no idea what your requirement is. x/0 isn't a valid math operation. In calculus, the result can either be positive infinity of negative infinity, depending on how you approach 0.
The current intention seems to be make the result a very small number. So why not define a constant or just set the result to 0:
DECLARE @VerySmallNumber float = 1E-8 -- ha! the exponent can be negative too

SELECT IIF(col2 = 0 OR col2 IS NULL, @VerySmallNumber, col1 / col2)


text:
Q: No separators in certain Analytics API metrics output I've started using the Analytics API since a little while, and I noticed that some metrics are a bit off in the output. For example, I'd expect the ga:adCost metric to give me numbers such as 55.96, while it produces something like 55961449. So it doesn't provide the period (or comma).
The same is true for other (mostly calculated) metrics, such as ga:CPC, ga:pageviewsPerSession, ga:avgTimeOnPage and ga:avgSessionDuration.
What my output looks like.

Then there's also other metrics (such as ga:timeOnPage and ga:sessionDuration) which put ".0" behind every number. Since we use comma's instead of periods in my language, I have to use Excel formulas to convert all these periods into comma's before I'm able to use these numbers in my calculations. I was wondering if there's a workaround for this too.
Thanks for reading and hopefully one of you has a solution for (one of) these issues!

A: It's not a problem with Analytics but it depends on your Excel settings and/or your computer settings.


text:
Q: Using SelectArg in ormlite Having clause? I need to us a placeholder in the having clause of my query builder.
I tried using a "?" mark but then I get:
java.sql.SQLException: argument holder index 1 not valid, only 1 in statement
This is the thing I try to accomplish:
QueryBuilder<ArchiefTag, Integer> archiefTagQb = helper
        .getArchiefTagDao().queryBuilder();

tagSelectArg = new SelectArg();

archiefTagQb.where().in(ArchiefTag.TAG_FIELD, tagSelectArg);
archiefTagQb.groupBy(ArchiefTag.ARCHIEF_ENTRY_FIELD);

QueryBuilder<ArchiefEntry, Date> archiefEntryQb = helper
       .getArchiefEntryDao().queryBuilder();
archiefEntryQb.join(archiefTagQb);

//the having must be on the outer join query. Don't know why
archiefEntryQb.having(String.format("COUNT(%s) = ?",ArchiefTag.TAG_FIELD));

preparedGetArchiefForTags = archiefEntryQb.prepare();

The generated sql is:
SELECT `ARCHIEF_ENTRY`.*
FROM `ARCHIEF_ENTRY`
INNER JOIN `ARCHIEF_TAG` ON `ARCHIEF_ENTRY`.`id_entry` = `ARCHIEF_TAG`.`entry`
GROUP BY `ARCHIEF_TAG`.`entry`
HAVING COUNT(tag) = ?

But when I call:
preparedGetArchiefForTags.setArgumentHolderValue(1, 3);
The above Exception occurs.
Any ideas how to solve this?

A:
But when I call: preparedGetArchiefForTags.setArgumentHolderValue(1, 3); The above Exception.

If you take a look at the javadocs for the setArgumentHolderValue(...) method, the index argument should be 0 based and not 1 based like SQL.
To quote:

index - The index of the holder you are going to set, 0 based. See NOTE above.

So your code should be:
preparedGetArchiefForTags.setArgumentHolderValue(0, 3);

I've tweaked the exception to make this more plain.
throw new SQLException("argument holder index " + index + " is not valid, only "
    + argHolders.length + " in statement (index starts at 0)");


text:
Q: Maven/Gradle way to calculate the total size of a dependency with all its transitive dependencies included I would like to be able to perform an analysis on each of my project POMs to determine how many bytes each direct dependency introduces to the resulting package based on the sum of all of its transitive dependencies.
For example, if dependency A brings in B, C, and D, I would like to be able to see a summary showing A -> total size = (A + B + C + D).
Is there an existing Maven or Gradle way to determine this information?

A: Here's a task for your build.gradle:
task depsize  {
    doLast {
        final formatStr = "%,10.2f"
        final conf = configurations.default
        final size = conf.collect { it.length() / (1024 * 1024) }.sum()
        final out = new StringBuffer()
        out << 'Total dependencies size:'.padRight(45)
        out << "${String.format(formatStr, size)} Mb\n\n"
        conf.sort { -it.length() }
            .each {
                out << "${it.name}".padRight(45)
                out << "${String.format(formatStr, (it.length() / 1024))} kb\n"
            }
        println(out)
    }
}

The task prints out sum of all dependencies and prints them out with size in kb, sorted by size desc.
Update: latest version of task can be found on github gist

A: I keep the a small pom.xml template on my workstation to identify heavy-weight dependencies.
Assuming you want to see the weight of org.eclipse.jetty:jetty-client with all of its transitives create this in a new folder.
<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>not-used</groupId>
  <artifactId>fat</artifactId>
  <version>standalone</version>

  <dependencies>
    <dependency>
      <groupId>org.eclipse.jetty</groupId>
      <artifactId>jetty-client</artifactId>
      <version>LATEST</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-shade-plugin</artifactId>
        <executions>
          <execution>
           <phase>package</phase>
           <goals>
              <goal>shade</goal>
           </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

Then cd to the folder and run mvn package and check the size of the generated fat jar. On Unix-like systems you can use du -h target/fat-standalone.jar for that.
In order to test another maven artifact just change groupId:artifactId in the above template.

A: I do not know any way to show the totals but you may get a report for your project which can show per dependency size information. Please check this maven plugin : http://maven.apache.org/plugins/maven-project-info-reports-plugin/dependencies-mojo.html

A: If you have a configuration which includes all the necessary dependencies that you wish to calculate the size for you can simply put the following snippet in your build.gradle file:
def size = 0
configurations.myConfiguration.files.each { file ->
    size += file.size()
}
println "Dependencies size: $size bytes"

This should print out when you run any gradle task after the build file is compiled.


text:
Q: Positive subsequence of a double sequence Suppose for the double sequence $\{a_{m,\,n}\} \subset \mathbb{R}$ we have $\lim_{n\rightarrow\infty}\lim_{m\rightarrow \infty} a_{m,\,n} = L$, where $L \in (0,+\infty]$. In particular, there exists some $n_0$ such that $n > n_0$ implies $\lim_{m \rightarrow \infty}  a_{m,\,n} > 0$. Is it possible to find a subsequence $\{a_{m_k,\,n}\}$ such that $a_{m_k,\,n} > 0$ for all $n > n_0$?

A: Well if I get you right, the answer is no. Think of a sequence of the form
$$a_{m,n}=1-\frac{b_n}m.$$
Since for each $n\in \mathbb N$
$$\lim_{m\to\infty} a_{m,n}=1>0,$$
and then for $n>n_0=1$ we have $\lim_{m\to\infty} a_{m,n}>0,$ there should be a subsequence $a_{m_k,n}$ such that for each $n>1$ and —I think you omitted this— for each $k\in \mathbb N$)
$$a_{m_k,n}>0.$$
But suppose, for instance, that $b_n=n$ (or any other sequence which is unbounded above)... In this case, that condition holds if and only if
$$1-\frac nm>0\iff m>n.$$
So no matter how big you choose $m_k$, there will always be infinite numbers $n$ such that $a_{m_k,n}\le 0$.
Note also that this says that the result is not true not only for the chosen $n_0$, but that no matter which $n_0$ such that the first condition holds you choose, the conclusion is always false for this sequence.


text:
Q: I need an assistance in finding new word driven out of "Neutralization" word I need help in finding the most suitable words derived from the word neutralization. I am using the word neutralization to describe a particular mathematical situation where the problem can be resolved rather than solving it. Can I use the word neutralizable to refer to that situation as in this problem is neutralizable, and if yes, which one is the more suitable word:

This problem is unneutralizable.

or

This problem is un-neutralizable.

or

This problem is inneutralizable.

A: The antonym for neutralizable would be unneutralizable.

unneutralized
ADJECTIVE
  Not neutralized, not rendered neutral.
Source

So the correct example would be your first one:

This problem is unneutralizable


text:
Q: How does Qt::DirectConnection act when used in multi-threaded environment? Though Qt::QueuedConnection or Qt::AutoConnection (in certain cases) are preferred in a multithreaded environment, I am asking this question for my understanding purpose.

*

*If signal MySignal() is emitted in thread A & slot MySlot() belongs to object of thread B. Both are connected via Qt::DirectConnection, how does the execution happen? i.e. If thread A sends a signal to thread B, while thread B is executing in middle of some function foo(). Will the slot MySlot() be called just after the foo() finishes or will it be called in parallel to foo()?

*Are there any scenario when Qt::DirectConnection is desirable over others in a multithreaded app?

A:
Are there any scenario when DirectConnection is desirable over others in a multithreaded app?

Yes, if your thread B is only executing in a single function and has no event loop, then DirectConnection is the only choice you have. Using AutoConnection or QueuedConnection will not work because the corresponding slot call event will not be processed in B or anywhere else.
Another reason for DirectConnection might be if your parameters are not serializable/deserializable using the Qt meta object system. If the conditions for Qt::DirectConnection are satisfied (the slot is thread-safe), you can use it instead (be wary about consequences - see following text).
Another thing you have to take into account is signal distribution across multiple slots. If you use DirectConnection and the slot needs to wait on a mutex, other slots that were connected after that said slot will not be activated until the slot has returned. Using QueuedConnection in this case will provide for a non-blocking signal distribution. Then, the thread B will block (in its qt-internal event handler for the slot-call event), instead of thread A in its "emit" statement.
Another thing you have to take into account is slot invocation order. If you issue multiple emit statements one after another, and slots of the same object are called using QueuedConnection, they are called in this order, because what's behind it are ordinary slot-call events. If some of these slots are DirectConnection, then they are called synchronously in the emitting thread, with no order guarantee relative to the other queued slot invocations!
Edit: I think there's also an interesting case with QObject::deleteLater. I recommend connecting to it using Qt::DirectConnection. This function is thread-safe and will send a delete-later event to the object's target thread. What's more, the function also handles the case where the object's thread has no running event loop (in which case the object is deleted when its thread exits). If you were to use Qt::QueuedConnection and there's no event loop in the target thread, you would have created a memory leak.

A:
If thread A sends a signal to thread B, while thread B is executing in
  middle of some function foo(). Will the slot MySlot() be called just
  after the foo() finishes or will it be called in parallel to foo()?

Unfortunately (and as you suspect) Qt::DirectConnection is precisely that and B::MySlot() will be invoked on thread A concurrently with whatever is already happening on thread B -- foo() in this case.  So, without any other form of synchronization the use of Qt::DirectConnection is generally a bad idea when the sender and receiver may be on different threads.
If you really do require the concept of a synchronous cross-thread signal/slot call then you might want to look at Qt::BlockingQueuedConnection


text:
Q: Delete Multiple Selected Records from checkbox in a relation I have two Model. One is user and onother is UserProfile and in created their tables users and user_profiles respectivly. I want when i delete user data thenrelated UserProfile should also automatically deleted. I created hasone and belongs to relation. One more thing i am deleting data using checkbox with delete button so i could able to delete multiple record at once.
User.php
public $hasOne = array(
    'UserProfile' => array(
        'className' => 'UserProfile',
        'foreignKey' => 'user_id',
        'dependent' => false,
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'exclusive' => '',
        'finderQuery' => '',
        'counterQuery' => ''
    ),
);

UserProfile.php
public $belongsTo = array(
    'User' => array(
        'className' => 'User',
        'foreignKey' => 'user_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    ),
);

In UsersController i have a deleteSelected function
UsersController.php
public function deleteSelected()
{
    foreach($this->data['User'] as $key => $value)
    {
        if($value != 0)
        {
            $this->User->delete($value);
        }
    }
    $this->redirect($this->referer());
}

finaaly i am getting an Error: Table groups_users for model GroupsUser was not found in datasource default. Please tell whats wrong in my code. Thanks.

A: set dependent to true
public $hasOne = array(
    'UserProfile' => array(
        'className' => 'UserProfile',
        'foreignKey' => 'user_id',
        'dependent' => true,
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'exclusive' => '',
        'finderQuery' => '',
        'counterQuery' => ''
    ),
);


text:
Q: Rainfall value not assigned fully to Grids on map Aim: To create a gridded map over Singapore with 200x200m gridsize and assign rainfall value to it from rainfall station dataset.
Dataset: https://docs.google.com/spreadsheets/d/12Hhg9rMoCisFkMVeLIOajdCZ5nL2iFKgEERViww9nqg/edit#gid=1622479150
Code:
import requests, itertools, io
from pathlib import Path
import urllib
from zipfile import ZipFile
import fiona.drvsupport
import shapely.geometry
import webbrowser
import geopandas as gpd
import numpy as np
import pandas as pd

### Print options
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)

### Load data
datafr = pd.read_csv('Comb_Daily_Pr_Special.csv')

### Station geodataframe
Stn_data = pd.DataFrame(datafr,columns=['id','Longitude','Latitude'])
Stn_data_gdf = gpd.GeoDataFrame(Stn_data, geometry=gpd.points_from_xy(Stn_data.Longitude,Stn_data.Latitude), crs='EPSG:3414')

### Re-make Precipitation array to [id,Date,Rainfall,Stn_name]
dfr = datafr.melt(id_vars=["id","Station","Longitude","Latitude","Elevation"], var_name="Date", value_name="Rainfall (mm)")

### Join gdf and dfr by 'id'
gdf = pd.merge(left=Stn_data_gdf, right=dfr, how='outer',on='id' )
gdf = gdf.sort_values(['Date','id']).reset_index().drop(columns=['index','Longitude_x', 'Latitude_x', 'Elevation','Longitude_y', 'Latitude_y'])
#df.to_csv('final.csv')

### Applying multi-indexing - FINAL Dataset for filling NaNs
gdf.set_index(['Date','id'], inplace=True)

### Drop rows with NaN
gdf = gdf.dropna().to_crs('4326').reset_index()

### Make grid of Singapore
url = "https://geo.data.gov.sg/planning-area-census2010/2014/04/14/kml/planning-area-census2010.zip"
f = Path.cwd().joinpath(urllib.parse.urlparse(url).path.split("/")[-1])
if not f.exists():
    r = requests.get(url, stream=True, headers={"User-Agent": "XY"})
    with open(f, "wb") as fd:
        for chunk in r.iter_content(chunk_size=128):
            fd.write(chunk)
zfile = ZipFile(f)
zfile.extractall(f.stem)

fiona.drvsupport.supported_drivers['KML'] = 'rw'
gdf_sg = gpd.read_file([_ for _ in Path.cwd().joinpath(f.stem).glob("*.kml")][0], driver="KML") #Singapore area geometry

# Number of meters for grid
STEP = 200 #grid resolution size in nxn m
a, b, c, d = gdf_sg.to_crs(gdf_sg.estimate_utm_crs()).total_bounds #return minx, miny, maxx,maxy in this order to establish rectangular boundary

# Create a grid for Singapore
gdf_grid = gpd.GeoDataFrame(
    geometry=[
        shapely.geometry.box(minx, miny, maxx, maxy)
        for minx, maxx in zip(np.arange(a, c, STEP), np.arange(a, c, STEP)[1:])
        for miny, maxy in zip(np.arange(b, d, STEP), np.arange(b, d, STEP)[1:])
    ],
    crs=gdf_sg.estimate_utm_crs(),
).to_crs(gdf_sg.crs)

# Restrict grid to only squares that intersect with Singapore geometry
gdf_grid = (
    gdf_grid.sjoin(gdf_sg)
    .pipe(lambda d: d.groupby(d.index).first())
    .set_crs(gdf_grid.crs)
    .drop(columns=["index_right"])
)

### Join the gdf_grid to gdf rainfall datas
gdf_grid_rainfall = gpd.sjoin_nearest(gdf_grid, gdf).drop(columns=['Description', 'index_right'])

### Visualize map with folium
sg_gridded_snap = gdf_grid_rainfall.loc[lambda d: d["Date"].eq("20211231")].explore("Rainfall (mm)", height=400, width=600)
output_file = "FINAL_map.html"
sg_gridded_snap.save(output_file)
webbrowser.open(output_file, new=2)  # open in new tab

Problems:

*

*Are there any other ways for me to get a 200x200m gridmap without getting 'out of memory error'

*I require all the grids to have an assigned rainfall value. For demonstration, I ran it on 1000x1000m grid to avoid memory error, but I instead obtain a gridded map with empty areas as shown:
Thank you for your help!

A: *

*as previously noted on this subject.  There are over 11k dates with rainfall data.  However there are only ~1k combinations of stations in operation across all of these dates

*hence an optimisation is to do geometry join_nearest() for combinations of stations rather than all dates.   This by the nature of how this is constructed will generate different polygons for weather stations that cover the whole of Singapore

*as previously noted - voronoi with perform far better that a grid,  this solution does work for both

data
import pandas as pd

# get data from google docs, the slow bit!!!!
df_ = pd.read_csv("https://docs.google.com/spreadsheets/d/e/2PACX-1vS2ijDtnQnbjVhKO1n-9QcIWz2DTPIAxZ7GcIKzNdxEDlxDD6HOO0kITMBDv0sXOTuvLVDnBhx34DIv/pub?gid=186097297&single=true&output=csv")

core capability
import shapely.geometry, shapely.ops
import geopandas as gpd
import numpy as np

gdf_sg = gpd.read_file(
    "https://raw.githubusercontent.com/yinshanyang/singapore/master/maps/0-country.geojson"
)
# Singapore bounday as a shapely multipolygon
sg = gdf_sg.dissolve()["geometry"].values[0]
utm = gdf_sg.estimate_utm_crs()

# restucture rainfall data to be long
# stack() by default dropna=True
df = (
    df_.set_index([c for c in df_.columns if c[0].isalpha()])
    .stack(dropna=False)
    .reset_index()
    .rename(columns={"level_5": "Date", 0: "Rainfall (mm)"})
    .drop(columns=["Station", "Longitude", "Latitude", "Elevation"])
)

df_stations = df_.loc[:, [c for c in df_.columns if c[0].isalpha()]]

# make a grid of boxes covering Singapore
def make_grid(step=500):
    # number of meters
    STEP = step
    a, b, c, d = gdf_sg.to_crs(utm).total_bounds

    # create a grid for Singapore
    gdf_grid = gpd.GeoDataFrame(
        geometry=[
            shapely.geometry.box(minx, miny, maxx, maxy)
            for minx, maxx in zip(np.arange(a, c, STEP), np.arange(a, c, STEP)[1:])
            for miny, maxy in zip(np.arange(b, d, STEP), np.arange(b, d, STEP)[1:])
        ],
        crs=gdf_sg.estimate_utm_crs(),
    )
    return gdf_grid.sjoin(gdf_sg.to_crs(utm)).drop(columns=["index_right", "name"])

# define function for performance testing...
def station_polys(how="boxes", gdf_grid=None, ids=df_stations["id"].tolist()):
    df_stations_ = df_stations.merge(pd.Series(ids, name="id"), on="id")
    if how == "voronoi":
        # generate a voronoi for all weather station points, clipped to Singapore boundary
        gdf_v = gpd.GeoDataFrame(
            geometry=[
                p.intersection(sg)
                for p in shapely.ops.voronoi_diagram(
                    shapely.geometry.MultiPoint(
                        gpd.points_from_xy(
                            df_stations_["Longitude"], df_stations_["Latitude"]
                        ),
                    ),
                ).geoms
            ],
            crs=gdf_sg.crs,
        ).to_crs(utm)

    elif how == "boxes":
        gdf_v = gdf_grid

    # associate voronoi or grid polygons with correct attributes (id)
    gdf_stations = (
        gpd.sjoin_nearest(
            gdf_v,
            gpd.GeoDataFrame(
                df_stations_,
                geometry=gpd.points_from_xy(
                    df_stations_["Longitude"], df_stations_["Latitude"]
                ),
                crs=gdf_sg.crs,
            ).to_crs(utm),
        )
        .drop(columns=["index_right"])
        .dissolve("id")
    )
    return gdf_stations

def polys_for_combis(head=5, how="voronoi", gdf_grid=None):
    # have to be tuples so they are immutable and hashable for join
    # association between Date and combination of station ids
    s_combi = (
        df.dropna()
        .sort_values(["Date", "id"])
        .groupby("Date")["id"]
        .agg(tuple)
        .rename("combi")
    )

    # unique combinations, plus give them an id
    df_combi = pd.DataFrame({"combi": np.unique(s_combi)}).assign(
        combi_id=lambda d: d.index
    )
    # for testing use subset of combinations
    if head is not None:
        df_combi = df_combi.sample(n=head, random_state=44)

    # construct geometry for each combination of stations
    gdf_combi = pd.concat(
        [
            station_polys(how=how, ids=combi, gdf_grid=gdf_grid)
            .reset_index()
            .assign(combi_id=combi_id)
            for combi_id, combi in df_combi.set_index("combi_id")["combi"].iteritems()
        ]
    )

    # add date for combi and join in rainfall data
    gdf_rainfall = gdf_combi.merge(
        df_combi.merge(s_combi.reset_index(), on="combi").drop(columns=["combi"]),
        on="combi_id",
    ).merge(df, on=["id", "Date"])

    return gdf_rainfall

use it / visualise
import folium
from IPython.display import display, HTML

# voronoi or boxes
gdf_rainfall = polys_for_combis(head=10).sort_values("Date")
# gdf_rainfall = polys_for_combis(head=10, how="boxes", gdf_grid=make_grid(step=200)).sort_values("Date")

plot_opts = dict(
    column="Rainfall (mm)",
    height=200,
    width=250,
)

maps = []
for i,d in enumerate(gdf_rainfall["Date"].unique()):
    m = gdf_rainfall.loc[gdf_rainfall["Date"].eq(d)].explore(**plot_opts)
    m.get_root().html.add_child(folium.Element(f"
{d}
"))
    maps.append(m)

fmt = ''

rawhtml = ""
for i, m in enumerate(maps):
    # if i>3: break
    rawhtml += fmt.format(m.get_root().render().replace('"', """), plot_opts["height"], plot_opts["width"])

display(HTML(rawhtml))

` different stations to deal with different NaN on different dates


text:
Q: How do you describe polls based on their representativeness? Some surveys have representational samples (they survey people of different ages, sexes, etc., and the subgroups are proportional) and those that do not (non-professional online polls, for instance). What do you call the former and the latter? 'Representational' and 'non-representational'? Maybe, 'sampled'/'non-sampled' or something like that?

A: I would describe the surveys/polls as biased and unbiased, respectively

Giving results that are not accurate because information has not been collected correctly.

When the groups that are sampled are not proportional to their numbers in the population, the results of the survey/poll are going to be biased by that sampling. Of course, this assumes that the results are supposed to be representative of the population as a whole.


text: Q: Disable Voice but Keep Data (and Texting) I am soon traveling abroad and my phone plan includes unlimited data and texting but charges for phone calls. If I need to place a call I can always use FaceTime or WhatsApp. However, as a precaution I was wondering if there are settings to disable voice but keep data on an iPhone. Texting doesn't matter much to me much but bonus if it can be left on.


text:
Q: iPhone, is Reset Network settings necessary after a Carrier profile install? My phone carrier requested an update of the Carrier Profile (Delete + Install).
They suggested also to perform a Reset Network settings after the profile installation.
Is it really necessary?
I don't mind doing a reset-network, but among the things the reset does, all Wi-Fi passwords are deleted as well, which is annoying.

A: No, you don't have to reset the network settings. Your phone carrier is just being thorough, as updating the profile can result in some unexpected behaviour for some users and resetting network settings usually resolves this.
I've personally only ever had to reset network settings once on an iPhone after a profile update, so you can just install the new profile and reset network settings afterwards if you start noticing some weird behaviour.


text:
Q: Converting rows of MYSQL database into columns I currently have a database that has the following format:
ID    |    Year    |    Name    |    Address    |    Penalty
1     |    2015    |   Test 1   |    Test 1     |     0.2
2     |    2014    |   Test 1   |    Test 1     |     0.3
3     |    2013    |   Test 1   |    Test 1     |     0.4
4     |    2015    |   Test 2   |    Test 2     |     0.5
5     |    2014    |   Test 2   |    Test 2     |     0.6
6     |    2015    |   Test 3   |    Test 3     |     0.7

What I am trying to do is write a query that will generate a format similar to this:
ID    |    Name    |    Address    |    2015Penalty    |    2014Penalty    |    2013Penalty
1     |   Test 1   |    Test 1     |        0.2        |        0.3        |       0.4
2     |   Test 1   |    Test 1     |        0.5        |        0.6        |       0.2
3     |   Test 1   |    Test 1     |        0.7        |        0.8        |       0.3

Basically Instead of having a row for every year of each company, I need a row for each company and then a column with every year's penalty.
Is this possible to do?  I would like to IF possible to do it entirely in SQL because the rows basically get echo'd out to a page and it becomes an Excel Spreadsheet:
while($row = mysqli_fetch_assoc($res)) {
    if(!$flag) {
        // display field/column names as first row
        echo implode("\t", array_keys($row)) . "\r\n";
        $flag = true;
    }
    array_walk($row, 'cleanData');
    echo implode("\t", array_values($row)) . "\r\n";
}

I have been trying to see if there is a way to do it in PHP but I'm not really sure how to do that either so any help is greatly appreciated.  If any further clarification is necessary, please let me know.
EDIT
I probably should have been more specific, I would like it so that the columns would be automatically generated based on the years, as every year more data gets imported and then the SQL will have to get updated as well.  If there is a way to automate this, it would be much better.

A: You can do this using conditional aggregation:
select id, name, address,
       max(case when year = 2015 then penalty end) as penalty2015,
       max(case when year = 2014 then penalty end) as penalty2014
from table t
group by id, name, address;


text:
Q: How can I set a dynamic Custom Java Object in generic Interface during run time I'm new to Android. I have a task that download generic object from a server api and save it to a specific Object at runtime inside a loop.
Example: I have an Objects of Car, Bottle, Animal.
It is it possible to change this DownloadCallback<Object> during runtime?
  while (!finish) {
     retrofitHandler.downloadData("accounts", "1", new DownloadCallBack<Object>() {
         @Override
         public void onResponse(GenericResponse<Object> response) {

         }
         @Override
         public void onFailure(String response) {

         }
       });
  }

I know the Generic Class in set at Compile Time. but is this possible?


text:
Q: Lists append in a list in for loop In Python, I cannot create a list in which every item is a different list.
This is an example:
a = [1,2,3,4,5,6,7,8,9]
b = []
c = []

for i in a:
  b.append(i)
  c.append(b)
c

the result is:
[[1, 2, 3, 4, 5, 6, 7, 8, 9],
 [1, 2, 3, 4, 5, 6, 7, 8, 9],
 [1, 2, 3, 4, 5, 6, 7, 8, 9],
 [1, 2, 3, 4, 5, 6, 7, 8, 9],
 [1, 2, 3, 4, 5, 6, 7, 8, 9],
 [1, 2, 3, 4, 5, 6, 7, 8, 9],
 [1, 2, 3, 4, 5, 6, 7, 8, 9],
 [1, 2, 3, 4, 5, 6, 7, 8, 9],
 [1, 2, 3, 4, 5, 6, 7, 8, 9]]

instead, what I would reach is:
[[1],
 [1, 2],
 [1, 2, 3],
 [1, 2, 3, 4],
 [1, 2, 3, 4, 5],
 [1, 2, 3, 4, 5, 6],
 [1, 2, 3, 4, 5, 6, 7],
 [1, 2, 3, 4, 5, 6, 7, 8],
 [1, 2, 3, 4, 5, 6, 7, 8, 9]]

May you please help me?

A: By doing c.append(b) you're putting the b instance, so b is everywhere in c, and as you fill b you see it in all boxes of c, you need to make a copy with on these ways
c.append(list(b))
c.append(b[:])

Regarding the task itself, I'd propose another way to do it:
for end in a:
    c.append(list(range(1, end + 1)))

Which corresponds to c = [list(range(1, end + 1)) for end in a] in list comprehension

A: In Python, variables holds references to the Objects. When you append your list b to another list c, you basically copy the reference of b to your list c (NOT THE OBJECT'S CONTENT). Since, list are mutuable, when you modify your list b (after appending it to list c), it's updated value will also be reflected in c.
Try this code to learn more:
a = [10]
c = a
a.append(100)
print(c)

Outputs:
[10, 100]

You can either do:
c.append(b[:])

OR
c.append(list(b))

OR
You can also use deepcopy in Python.
import copy
a = [1,2,3,4,5,6,7,8,9]
b = []
c = []

for i in a:
    b.append(i)
    c.append(copy.deepcopy(b))
print(c)


text:
Q: Data Source and Delegate Options when creating a table view, ViewController class adopts "UITableViewDelegate" and "UITableViewDataSource" protocols. To create a table view, we have to benefit from methods of these protocols. I understood this.
However, when creating a table view, we also choose tableview-data source and tableview-delegate options and match them with ViewController class by dragging. These are performed in storyboard file.
Why is this match process important ?
Why do we perform this match process ?

A: You don't need to conform to both protocols and you don't need to set the delegate and dataSource in Storyboard, it can be done programatically as well.
You only need to do these if you are working with a UITableView in a ViewController that is not subclassing UITableViewController. UITableViewController automatically takes care of conforming to both protocols for you.
You need to set up the delegate/dataSource to a certain ViewController, because the system needs to know, which class' delegate/dataSource methods it needs to call when setting up the table view. If you have several view controllers with table views inside them in the same Storyboard, without setting up the delegate/dataSource to the current view controller, the system wouldn't know which class it needs to call for which tableview.
Conformance to UITableViewDelegate protocol is optional, if you only need to display data on a table view, but don't need user interaction with it, you only need to conform to the UITableViewDataSource protocol. This is needed in order to set up the number of sections/cells in the table view and to set up the content of these as well.


text:
Q: Function that returns generic function pointers Say I have two functions:
fn function_with_one_argument(one: i64) -> bool{
    one==one // irrelevant
}

fn function_with_two_arguments(one: i64, two: i64) -> bool {
    one==two // irrelevant
}

Given a different input value, I'd like to return a different function pointer:
fn main() {
    println!("\n\n{:?}\n\n", get_function_pointer(1)(321));
    println!("{:?}", get_function_pointer(2)(321/*, 321*/));
}

How can I represent the return value to return a pointer to different shaped functions?
fn get_function_pointer(id: i64) -> /***/(fn(i64) -> bool)/***/ {
    match id {
        1 => function_with_one_argument,
        // 2 => function_with_two_arguments, /*How do we make this work?*?
        _ => panic!("!?!?!")
    }
}

A: You can use an enum to represent the output of the function
enum Either<T, U> {
    Left(T),
    Right(U),
}

fn function_with_one_argument(one: i64) -> bool {
    one == one // irrelevant
}

fn function_with_two_arguments(one: i64, two: i64) -> bool {
    one == two // irrelevant
}

fn get_function_pointer(id: i64) -> Either<fn(i64) -> bool, fn(i64, i64) -> bool> {
    match id {
        1 => Either::Left(function_with_one_argument),
        2 => Either::Right(function_with_two_arguments),
        _ => panic!("!?!?!"),
    }
}

A: Here's a complete solution after using the suggestion above for enum.
extern crate quickcheck;
use quickcheck::{QuickCheck, Testable};
use std::collections::HashMap;

fn main() {
    let mut property_map = HashMap::new();
    property_map.insert("one", Property::One { func: one_argument });
    property_map.insert("two", Property::Two { func: two_arguments });

    test_property("one", &property_map);
    test_property("two", &property_map);
}

enum Property {
    One { func: fn(i64) -> bool },
    Two { func: fn(i64, i64) -> bool },
}

fn test_property(property: &str, property_map: &HashMap<&str, Property>) {
    match property_map.get(property) {
        Some(p) => fetch_property_and_run_quickcheck(p),
        None => println!("No matching property in property_map"),
    };
}

fn fetch_property_and_run_quickcheck(property: &Property) {
    match *property {
        Property::One { func: prop_to_test } => run_quickcheck(prop_to_test),
        Property::Two { func: prop_to_test } => run_quickcheck(prop_to_test),
    };
}

fn run_quickcheck<A>(property: A)
    where A: Testable
{
    QuickCheck::new().quickcheck(property);
}

fn one_argument(one: i64) -> bool {
    println!("testing one_argument() with {}", one);
    one == one // irrelevant
}

fn two_arguments(one: i64, two: i64) -> bool {
    println!("testing two_arguments() with {} and {}", one, two);
    one == one && two == two // irrelevant
}


text:
Q: What is the fastest way to load text file into RichTextBox? I load text file into RichTextBox using OpenFIleDialog. But when a large amount of text is (for example song text about 50-70 lines) and I click OPEN program hangs for a few second (~3-5). Is it normal? Maybe there is some faster way or component to load text file? If my question is an inappropriate just delete it. Thanx.
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            string text = File.ReadAllText(openFileDialog1.FileName);
            for (int i = 0; i < text.Length - 1; i++)
            {
                richTextBox1.Text = text;
            }
        }

I guess maybe ReadAllLines impeds it?

A: There is a similar question that deals with the fastest way of reading/writing files: What's the fastest way to read/write to disk in .NET?
However, 50-70 lines is nothing.. no matter how you read, it should fly in immediately. Are you maybe reading from a network share or something else that is causing the delay?
Edit:
Now that I see your code: Remove the loop and just write richTextBox1.Text = text; once. It doesn't make sense to assign the string in the loop since you already read the complete content of the file by using ReadAllText.
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
    string text = File.ReadAllText(openFileDialog1.FileName);
    richTextBox1.Text = text;
}

A: void LoadFileToRTB(string fileName, RichTextBox rtb)
{
      rtb.LoadFile(File.OpenRead(fileName), RichTextBoxStreamType.PlainText); // second parameter you can change to fit for you
      // or
      rtb.LoadFile(fileName);
      // or
      rtb.LoadFile(fileName, RichTextBoxStreamType.PlainText); // second parameter you can change to fit for you
}

A: Remove the for loop, because is useless:
string text = File.ReadAllText(openFileDialog1.FileName);
richTextBox1.Text = text;

text is a string that already contains all the text of the file to pass to the textBox.
Doing:
for(int i=0, i < text.Lengt-1; i++)
    richTextBox1.Text = text;

you're assigning the text read from the file text.Length-1 times (Length is the number of characters of the string) and that's useless.

A: if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    richTextBox1.Text = File.ReadAllText(openFileDialog1.FileName);
}


text:
Q: How to stop sortable in jquery? I'm using
$("#images").sortable();
for sorting some image in small game for kids,I want to remove the sort-ability.
How to do that ??

A: try this
 $( ".selector" ).sortable( "disable" );

A: The solution was by using the same function with the attribute 'destroy'
$( "#images" ).sortable('destroy');


text:
Q: Pass sql column values to an array usnig Javascript I am working with an ASP.net webform and have a SQL select statement that generates a table with a single column. All values of that column would need to be added to an array using javascript, to replace manual entry. Here is a working array example:
  <script type="text/javascript">

    var addressPoints = [

        [35.393617, -119.038301],
        [33.485073, -86.785173],
        [35.218721, -80.849652],
        [38.678598, -90.373175],
        [37.786996, -90.414874],
        [44.946816, -124.016506]

     </script>
      <script type="text/javascript">
        var tiles = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
            minZoom: 1,
            maxZoom: 12

        }),
            latlng = L.latLng(35.824322, -98.763128);

        var map = L.map('map', { center: latlng, zoom: 3.8, layers: [tiles] });

        var markers = L.markerClusterGroup();

        for (var i = 0; i < addressPoints.length; i++) {
            var a = addressPoints[i];
            var title = a[2];
            var marker = L.marker(new L.LatLng(a[0], a[1]), { title: title });
            marker.bindPopup(title);
            markers.addLayer(marker);
        }

        map.addLayer(markers);

    </script>

The Coordinates column has been formatted exactly as the Manual entry data you saw in the example above. The below example does not work:
<script type="text/javascript">

        var addressPoints = [
//    Values from a column  "Coordinates" go here//
//    [35.393617, -119.038301],
//    [33.485073, -86.785173],
//    [35.218721, -80.849652],
//    [38.678598, -90.373175],
//    [37.786996, -90.414874],
//    [44.946816, -124.016506]
        ];

</script>

If you have any idea how to plug in the Coordinates column into an array using Javascript,  I will really appreciate your help!

A: It looks like you have already displayed the Coordinates value in the DOM element "Coordinates" - so try this:
<script type="text/javascript">

    var addressPoints = [
        document.getElementById("Coordinates").value;
    ];

</script>


text:
Q: Count number of selected rows in ag-grid I want to count the number of selected rows but it seems onRowClicked or onRowSelected happens before the row i click actually is selected.
How can I count the number of rows when I select a row? I thought this was the way to go.
this.gridOptions.onRowSelected = function (params) {
    console.log(this.gridOptions.api.getSelectedRows().length)
    // Prints one less then the number of rows that is selected.
}

A: In a React (with ES6) project I use this:
onSelectionChanged = debounce((e) => {
    this.setState({
        selectedRows: this.api.getSelectedRows(),
    });
}, 1)

(this.api is https://www.ag-grid.com/javascript-grid-api/?framework=all#gsc.tab=0)
I use Lodash's debounce to solve a performance problem if many rows are selected at the same time. (Although after some quick testing, looks like this has been fixed in ag-grid at some point.)
The simplest version could look like (untested):
this.gridOptions.onSelectionChanged = function () {
    console.log(this.gridOptions.api.getSelectedRows().length);
}


text:
Q: Trouble with creating a grouped Boxplot in R Studio I am trying to create a grouped Boxplot in R Studio with ggplot2.
My Data looks like this:

(4 different APP.mm values in total)
And a sample dput() of my dataset:
structure(list(APP.mm = c(408.5, 408.5, 408.5, 408.5, 408.5,
408.5, 408.5, 408.5, 408.5, 408.5, 408.5, 237.5, 237.5, 237.5,
237.5, 237.5, 237.5, 237.5, 237.5, 237.5, 237.5, 237.5, 237.5,
237.5, 237.5, 132.1, 132.1, 132.1, 132.1, 132.1, 132.1, 132.1,
274, 274, 274, 274, 274, 274, 274, 274, 274), Weight_mg = c(112,
106.72, 118.4, 62.3, 86.2, 70.3, 56.5, 71, 61.4, 61.7, 62.7,
81.1, 125.5, 71, 120.4, 75.3, 68.1, 95.9, 77.5, 95.5, 85.3, 64.1,
27.6, 20.5, 77.9, 86.3, 120, 100.2, 86.4, 67.8, 104.4, 90.1,
71.1, 89, 77.4, 77.1, 60.5, 78.7, 87.9, 71.1, 76.5), Germination = c(0L,
1L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 0L, 0L, 1L, 1L, 1L, 0L, 1L, 1L,
1L, 1L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 1L, 0L, 0L, 0L, 1L,
1L, 0L, 1L, 1L, 1L, 0L, 1L, 0L)), .Names = c("APP.mm", "Weight_mg",
"Germination"), row.names = c(6L, 7L, 8L, 9L, 88L, 89L, 90L,
91L, 92L, 93L, 94L, 2111L, 2112L, 2113L, 2114L, 2115L, 2116L,
2117L, 2118L, 2119L, 2120L, 2121L, 2122L, 2123L, 2124L, 2674L,
2675L, 2676L, 2677L, 2678L, 2679L, 2680L, 3193L, 3194L, 3195L,
3196L, 3197L, 3198L, 3199L, 3200L, 3201L), class = "data.frame")

I am now trying to create a Grouped Boxplot with the APP.mm on the x-Axis, the Weight on the Y-Axis and the values grouped by APP.mm into Germination Succes (1) oder No Germination Success (0)
I tried these codes for R:
ggplot(data = gallsdtg, aes(x=APP.mm, y=Weight_mg)) +
  geom_boxplot(aes(fill=Germination))

Warning message:
Continuous x aesthetic -- did you forget aes(group=...)?

ggplot(data = gallsdtg, aes(x=APP.mm, y=Weight_mg)) +
 geom_boxplot(aes(group=Germination))

qplot(gallsdtg$APP.mm, gallsdtg$Weight_mg,
 fill=factor(galls$Germination), geom="boxplot")

resulting in this plot:

I tried the exact same code on the same structure of Data just from a different location and got the plot I wanted.
qplot(germination2017extras$APP.mm, germination2017extras$Weight_mg,
  fill=factor(germination2017extras$Germination), geom="boxplot",
  xlab="mean APP in mm", ylab="Weight in mg", ylim=c(0,200))

Can someone tell me what I am doing wrong here? Thank you so much!


text:
Q: Create a list by looping throug array list of type with that Java variable I have array list of type Warehouse. Each Warehouse has a stock amount. The method getStock() returns the stock level.
I have an ArrayList of Warehouse. I want to get the stock of each warehouse in the list and add it to a list.
My code:
import java.util.*;

public class Warehouses {

ArrayList<Warehouse> warehouses = new ArrayList<Warehouse>();

public Warehouses() {

    warehouses.add(new Warehouse("W1", 20, "RM13 8BB"));
    warehouses.add(new Warehouse("W2", 28, "RM13 8BB"));
    warehouses.add(new Warehouse("W3", 17, "RM13 8BB"));
}

public void stockList() {

    ArrayList<Integer> stockList = new ArrayList<Integer>();

    for(Warehouse warehouse : warehouses) {

        Integer stock = warehouse.getStock();

        System.out.println(stock);

    }

}
}

class Warehouse
{
// instance variables - replace the example below with your own
private String warehouseID;
private int warehouseStock;
private String location;

/**
 * Constructor for objects of class Warehouse
 */
public Warehouse(String warehouseID, int warehouseStock, String location)
{
    // initialise instance variables
    warehouseID = warehouseID;
    warehouseStock = warehouseStock;
    location = location;
}

public int getStock(){
    return warehouseStock;
}

public String getLocation() {
    return location;
}
}

When I call stockList() I just get three empty values. What is wrong here?
Thanks

A: Assign the constructor arguments of Warehouse to the class member variables rather than re-assigning the local variables themselves
public Warehouse(String warehouseID, int warehouseStock, String location) {
    this.warehouseID = warehouseID;
    this.warehouseStock = warehouseStock;
    this.location = location;
}


text:
Q: Unable to insert data in MySQL, if it contains " or ' I am using this code  to insert data into MySQL
<textarea name='description' class='description' placeholder='Enter Description'></textarea>

It works fine, but if the Text contains any ' then, I get this error:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 's friends learn they're about to be downsized' at line 2

However, If i Insert the data directly by opening PHPMyAdmin, it works fine. How to fix it?

A: Strings defined by ' in mysql and mariadb, so if a quote exist in string, escape it with backslash like \'.

A: You have to escape the character before inserting into DB like so \'.

A: use  mysqli_real_escape_string function. it Escape special characters in a string. in your case "'" is special character.


text:
Q: Google Container Registry pushing images into purgatory I do not understand where my images are going.
I cleared my docker login credentials, and then did the following:
$ gcloud auth print-access-token
aLongPrintedAccessToken

then
$ docker login -e not@val.id -u oauth2accesstoken -p aLongPrintedAccessToken https://gcr.io
Warning: '-e' is deprecated, it will be removed soon. See usage.
Login Succeeded

And now is where the fun starts
I have been pushing images all day. I push a new one and see Mounted from emrys-dev/api-34320482-9eb1-4dd9-bbd8-178ced5ea9d2. However, that container is nowhere in my registry. It's not in any of my projects.
Additionally, when I push the image, it pushes all the layers even though it's exactly the same image as the one I just pushed (just different tag). I had this working earlier today, and I can not figure out what happened.
I did notice something odd. When I run gcloud docker info, I see Registry: https://index.docker.io/v1/. It's just reading the local docker info, but I perhaps gcloud is supposed to be overriding that config? I checked all my project registries, and they're not getting pushed to there.
Where did my images go?
Edit:
I didn't clarify. When I push, my push command looks like
docker push gcr.io/emrys-dev/api-whatever

A: Do you see nothing here?
gcloud docker just configures authentication and shells out to Docker, so what you are see running gcloud docker info is identical to docker info.  I don't see a Registry line in mine at all, but I'm not sure it is relevant.
All your data should be stored in gs://artifacts.emrys-dev.appspot.com, which you can poke around with via:
gsutil ls gs://artifacts.emrys-dev.appspot.com/

However, that shouldn't be necessary if the first link works.
You can also reach out to us at gcr-contact@google.com to help diagnose any problems.  Please do if the link above doesn't show anything.


text:
Q: As a jungler when should I push the lane after a gank? I'm getting fairly confidant in ganking abilities as a jungler. However, sometimes I don't know what I should do following a gank. This is what I typically do now for early/mid game ganks:

*

*Both my team mate and enemy laner are dead/recalled: I clear current wave then head back into jungle.

*Enemy laner is dead/recalled, team mate is alive: I will leave and let my laner farm (I don't usually tax the lane as some players get angry and I don't play junglers that require expensive builds).

*My team mate is dead/recalled and the enemy laner remains: I stay around to protect the tower and not let exp go to waste until team mate returns.

This makes sense to me but I'm wondering if this is ideal in the general sense. Certain circumstances can change priorities but is this a good start?

A: To answer your original question:
Clearing waves is bad in some cases.
By just clearing the current wave, you are allowing the minions on your team to push closer to their turret. If their champion is capable of freezing the lane, this will put your buddy at a disadvantageous position if the wave you cleared was in the middle of the lane.
In general, you want to do one of the following if both are dead:

*

*Last hit the current wave or simply leave. (If the lane is neutral)

*Push the wave up to the tower and make the tower kill one or two of your waves. (This is to reset the lane, the closer minions are to pushing into an enemy tower, the more priority you should give this.)

*Clear part of a wave so they don't push into your own tower. (To prevent resetting the lane in the enemy's favour)

In other words, it depends on the situation, but a general rule is that you want to keep the lane as close to your side of the map as possible, and as the game drags on (if you are winning) you want to shift that balance from your side to their side more and more, so you can start putting pressure and forcing down turrets.
If the enemy is alive:
You either want to:

*

*Keep the lane so that you don't lose a turret as fast. (This is mostly true for strong pushing champs)*

*Leave the lane if the enemy is weak at pushing if you can do more beneficial stuff. (Get / give buffs, secure dragon, gank another lane, whatever)

*Kill the enemy champ. (If you think you can do so)
*Note: In some cases it is recommended to let your tower get destroyed, if the player who is laning against an enemy is performing really bad. Letting the tower get destroyed allows the minions to get pushed into your side of the map even further, allowing the bad laner to freeze his lane at the second turret and farm there. (Of course, you should pay attention at this point because otherwise you're just giving away turrets)
If teammate is alive but enemy is dead:
Either:

*

*Leave and let him continue farming.

*Help him push down the turret.*

*(Situational, mostly for bot-ganks) Kill Dragon

*: Pushing down turrets at botlane can be especially helpful as it allows you to pressure them more, thus giving you more leeway to take dragon out, as they can't permit to stay close to it if they don't maintain vision of the river and jungle 24/7.

Also, if there are other lanes that you can gank right away, you should of course do that instead of just farming minions for your buddy. A few minions aren't worth as much as another kill + assist.
And as a closing note: Ultimately it also sort of depends on the champion composition. Sometimes you have a team (or jungler) that is capable of pressuring a lot more than the enemy team, in which case again, you want to push up a bit more so you can take more control of the map, sooner.

A: When to push:
(Enemy laner is dead OR forced to back) AND (The lane will end up moving in the enemies direction OR Your teammate wishes to back quickly also)
This gives you 100% the time you want to push and this should be the ONLY time you ever tax.
Times you DO NOT want to push.
The lane can be frozen easily on your laners side AND your laner wishes to keep it frozen.
In the time to push, this part is the most important (Enemy laner is dead OR forced to back).  If this is true, do not tax or push or your laner has every right to be pissed at you.
The second part of the AND clause is a little less clear:  (The lane will end up moving in the enemies direction OR Your teammate wishes to back quickly also)  Basically, if the wave is beginning a slow push towards the enemy turret, make it a fast push so it gets there before the enemy is back to lane.  If it can be frozen and your laner wishes to keep it frozen, DO NOT TAX or push.
One key thing that throws out the rules.  If an enemy is missing AND you are low health do not push.
So fully:
(Enemy laner is dead OR forced to back) AND (The lane will end up moving in the enemies direction OR Your teammate wishes to back quickly also) AND (You have high health OR no enemies are missing)


text:
Q: Equi integrability and weak convergence of measures Let $f_n$ be a sequence of functions in $L^1(K, m ; \mathbb{C})$, $K$ metric compact and $m$ a Radon measure on $K$. Assume that $\| f_n \|_1 \leq 1$.
From what I understand, there is a subsequence converging weakly in $L^1$ if and only if the $f_n$ are equi integrable, which means :
$$\forall \epsilon>0 \exists \delta >0 \forall A, m(A) \leq \delta \forall n \int_A |f_n| dm \leq \epsilon $$
Now remark that the measures $f_n m$ have bounded total variation, and therefore there exists weakly-* converging subsequences. Would I be correct to assume that there are no weakly converging subsequences in $L^1(m)$ if and only if all weak-* adherence values of $f_n m$ are singular with respect to $m$ ?
I'm pretty sure of the implication "no weak $L^1$ adherence values $\Rightarrow$ all adherence values of $f_n m$ must be singular". The other implication seems clearly true but I have no argument.
All help appreciated !

A:
there is a subsequence converging weakly in $L^1$ if and only if the $f_n$ are equi integrable

Not true as stated. One can interlace a convergent sequence with a non-equi-integrable sequence; the result will still have a convergent subsequence. What is true (and what you probably meant) is that equi-integrability is equivalent to precompactness in the weak topology.

"no weak $L^1$ adherence values $\Rightarrow$ all adherence values of $f_n m$ must be singular

No. Let $K=[0,1]$ and consider the sequence $$f_n = 2^n \chi_{[2^{-n-1},2^{-n}]}-2^{-n-1}\chi_{[2^{-n},2^{-n+1}]}$$
It satisfies $\|f_n\|_1=1$ and has no weakly convergent subsequence in $L^1$ (test the convergence with $$\phi = \sum_{n \text{ even }} \chi_{[2^{-n},2^{-n+1}]}$$ to see that it fails.) Yet, the measures $f_n \,dm$ converge to $0$ in the weak* topology of $C(K)^*$.

On the other hand, it is true that having a subsequence that weakly converges in $L^1$ implies having a non-singular weak* cluster point. This is simply because weak $L^1$ convergence implies weak* convergence of associated measures.


text:
Q: When I type a URL in the address bar, then why does it always use "HTTP" and not some other protocol I want to understand http protocol in depth. Does anyone know where can I find relevant material for HTTP. A few questions that I have in particular are:

*

*Why does when press enter after typing for eg. "google.com" it gets translated to "http://www.google.com" and not "ftp://www.google.com" or something else.

*How does the http request gets transferred to a server, what routing algorithm it uses to decide which server to used, and inside that server where to locate the uniform resource".

Any pointers in this direction are most welcome!!

A: Because HTTP is simply the web standard for requests. We all agreed on using that when the web started, and now we are stuck with it (whether it is good or not).
HTTP stands for 'Hypertext Transfer Protocol' and is in fact the way how to exchange that information you see on your display when browsing.
FTP, and numerous other protocols are their standards (or in general methods) for their purpose. HTTP serves the purpose of communicating between client and server for the web.
And about how HTTP works internally, well, they wrote a few books on it. The standard is described by the IETF: Hypertext Transfer Protocol -- HTTP/1.1.


text:
Q: Trouble getting data into an inner class I'm trying to write a program that is just a little beyond my abilities.The program is supposed to retrieve GPS data and display it on a nice page of graphics.  I can access the GPS data fine, by implementing the necessary listener interfaces.  I can display nice graphics using a sophisticated program structure employing a SurfaceView.  But when I try to pull these two functionalites (incoming data and graphics) together things fall apart.
The graphics structure of the program is, in schematic form:
Activity implements several gpsStatus/Location interfaces
Anonymous inner class Panel extends SurfaceView  implements SurfaceHolder.Callback
        onDraw() which does the drawing

        inner (instance) class Thread
            run() which does the canvas locking and calls onDraw()

I hope that makes sense. I got this structure from the Droidnova site, the 2D graphics tutorial.  The graphics are drawn in the separate thread.  I've been able to get very nice smooth graphics out of this.
The class "Panel," the one which extends SurfaceView is created in the onCreate of the Activity, like this: setContentView(new Panel(this));  The inner class is created as an instance, i.e. Thread thread=new Thread() by the Panel's constructor.
My data from the GPS chip comes in via methods in the Activity.  The problem is, how do I get these objects inside the "Panel" and into the onDraw()?  From within the onDraw() the objects in the Activity (my GPS data) are inaccessible.
I've tried creating the SurfaceView as an instance, I've tried moving the SurfaceView out so it's a separate class (with the thread still inside).  I've tried implementing the interfaces in the Panel  These always crash, with debug data I can't fathom.
Any help much appreciated.

A: I would think that if you wrapped your GPS data into a class foo, and pass a reference to an instance of foo into a constructor on Panel, you should have all you need.

A: If the inner class is declared inside the Activity class (listening to the gps data), then the inner class should be able to access the member variables of the Activity class.
It is not very OO, but it should work.