Number of ways of reaching a point from origin

Question:
Possible Duplicate:
How can I find the number of the shortest paths between two points on a 2D lattice grid?

If we have a point $P(x,y)$ in a coordinate system $[$with $x \geq 0$, $y \geq 0$; that is, in the 1st quadrant$]$
How can we find the number of ways of reaching $P$ from the origin $(0,0)$.
<code>Ex: If P(2,1);

way1: 0,0 -> 1,0 -> 2,0 -> 2,1
way2: 0,0 -> 1,0 -> 1,1 -> 2,1
way3: 0,0 -> 0,1 -> 1,1 -> 2,1
</code>
Is it possible to have a mathematical equation for it? and How? if we don't have one, what's the best possible way to find those.
Rules:

You can move only in horizontal, vertical directions (diagonal is not possible)
you can only move to the point $(a,b)$ such that  $0 \leq a \leq x$ and $0\leq b\leq y$
$a, b$ can be only natural numbers
Comment: What counts as a way? From your examples, it's not clear what kinds of moves are allowed. For example, Does $(0,0) \rightarrow (42542, 152345) \rightarrow (2,1)$ count as a way to get to $(2,1)$ from the origin?
Comment: Or $\:\: (0,0) \to \left(\frac13,\operatorname{ln}(2)\right) \to (2,1) \:\:$? $\;\;\;\;$
Comment: sorry for not mentioning rules, please look at the question, I added
Comment: If there is no bound, you can go reach it in infinitely many ways, like specified above, $(0,0)\to(\infty,\infty)\to(2,1)$, do you take it to be a valid one ? , if not, specify some constraints and bounds @Surya
Comment: only natural numbers are possible
Comment: @iyengar please look at the rules.
Comment: The move '0,1 -> 1,2' is diagonal.
Comment: @ByronSchmuland sorry, there was a mistake in example. However, I got the right answer. Please look at it now
Comment: For those interested: I answered this question, but then noticed that the same question (written a little more precisely) appeared previously.
Answer: It is well known that the number of ways to get to the lattice point $(x,y)$ (supposing $x, y \geq 0$) by taking steps of one unit each either in the eastward or northward direction is exactly
$$
{x + y \choose x} = {x+y \choose y} = \frac{(x+y)!}{x! y!}.
$$
Such paths are called lattice paths.  See, for example, here.
Comment: Why the down vote?
Comment: Downvote ? , I gave an upvote. It wasn't me @JavaMan
Comment: @iyengar: Thanks for the upvote, but I'm not too worried about who downvoted.  I'm more worried about what part of my answer wasn't deemed satisfactory.
Comment: Haven't you noticed that your answer has been selected, your answer was very good, and seems to fit in a good sense, its only some fools around here, who unnecessarily down-vote the answer, without leaving any comments, it happened to me quite many times, even got the worst votes. But if someone down-votes the answers without a comment, it surely acts as a cause of annoying the person who answers the question. But let us leave this topic, and why should we bother about points here, if your answer is perfect. Does points earn us anything in reality apart from an apparent fame here .
Comment: @iyengar: Just for the record, I never thought you downvoted, and actually I don't really care who downvoted just as I do not care about the reputation.  I was merely more curious as to _why_ the downvoter did so, and how I could improve my answer.
Comment: @JavaMan I wonder if you could answer another question which is based on this one. [Link](http://math.stackexchange.com/questions/103506/what-is-the-maximum-point-for-which-number-of-way-to-reach-is-given)
Comment: @JavaMan : I too was curious in knowing the problems, even I posted a feature request in Meta, I too suggested the same thing, I said I am not bothering about down-votes, I suggested that if the person who down-votes the answer leaves the reason for doing so, it would be helpful for person who posted the answer, both in formatting and correcting himself. But majority people said, we dont need to keep such feature. So I left, but wont it hurt you ( not only you but any one who answers and gets downvoted without a reason ) ?, I don't know about you, but it hurts me a lot.
Comment: @JavaMan and : Do not worry about down or upvotes, I have seen many times other poeple's good answer (not only mine) have been downvoted for no reason, now a days I think it is comical for a good answer to get downvoted by some bozo without leaving a comment, I just do my bit and upvote, BTW : It wasn't me who downvoted :)
Comment: @Arjang : But is there any solution to eradicate that comical "Down-voting" foolishness ? .
Comment: @iyengar : Aaah yes, it has already been implemented, downvoting costs points, so it is not free to downvote!
Answer: It is a combinatorial question, where you have $x+y$ things and you have to pick $x$ (or $y$, both are symmetric) times when you can make a choice. In other words, you have $x$ ways to move in $x$ direction, $y$ way to move in $y$ direction. However, once you pick any $x$ direction, the choices for $y$ is fixed. Therefore, the total number of way you can do the above is $(x+y)$ choose $x$ (or $y$, respectively). Mathematically, it will be
$$\left( \begin{matrix} x+y \\ x \end{matrix} \right) = \left( \begin{matrix} x+y \\ y \end{matrix} \right).$$


What is "CHAD" in the context of Albion Online?

Question: I keep hearing people referring to "dungeon CHADs" in Albion Online. What are they talking about? Is this is an acronym for something?
Comment: Are you sure they aren't just talking about Chads in general?
Comment: @Penguin I don't know. What is a Chad?
Comment: @TylerDurden https://knowyourmeme.com/memes/virgin-vs-chad
Answer: Chad (Full name: Chad Thundercock) basically means someone who is super good or super bad. It's extremely hard to explain because it literally means two opposites but is generally means at the very least noteworthy. Most of the time when Chad is used, it is someone who is amazing and someone who (idk how to say this) wettens. I don't play this game but in this context I assume the Dungeon Chads are either:

Players who are really good at the dungeons
Very good bosses (or whatever enemies are called) in the dungeons

Chad is one of those words that doesn't really have a definition, just everyone who knows what a Chad is knows Chad. Chad has no real meaning, and it can mean anything the user wants really, just most people know what a Chad is.
Answer: In the context of Albion this mostly refers to a popular YouTube video guide for Albion where the thumbnail says "Dungeon Chad" on it. The YouTuber is also in his own alliance named [CHADS]. It's just the Chad meme being used to describe a meta build for running dungeons.


VLC player issue on ubuntu 14.04

Question: VLC player isn't working in Ubuntu 14.04. It gives this error:
VLC media player 2.1.5 Rincewind (revision 2.1.2+git20140426+r54526+18+11~ubuntu14.04.1)
Segmentation fault (core dumped)

How can I solve this issue?
Comment: The way to solve it is reporting a bug.
Answer: Try resetting the configuration as follows:
vlc -I qt4 --reset-config --reset-plugins-cache

Comment: Worked!! Tried for 2 hours with that thing to work... Thanks man.
Answer: Seems to be missing something
sudo apt-get install --reinstall vlc

VLC player issue on ubuntu 14.04


How to correctly dock/undock a laptop under Ubuntu?

Question: I'm with lenovo x1 yoga and lenovo onelink dock.
There is just one button on the dock for power on/off
Is there something i should do before pulling out the dock cable from the laptop to gracefully undock? Or just pull it like a barbarian and call it a day?
Comment: What does the machine's instruction manual recommend?
Comment: Not a word about that
Answer: It is safe for your laptop to pull the cable.
Laptops usually have an UPS (uninterruptible power supply) integrated. The UPS switches to the Battery immediately when pulling a power cable.
That said, you must take care of USB Storage devices connected to the dock like external HDDs and USB Sticks. To prevent data loss unmount them before pulling the cable.
Comment: Is there anything I need to do, so the windows are in tact when I return to the dock?
External monitor and laptop are different resolution.s


some variables in xml have a 'dot'

Question: I am now studying a opensource android mobile browser, notice some variables in xml have a 'dot' to define a long name variable.
such as:
TextView android:id="@+id/BookmarksListActivity.EmptyTextView"

and i notice the reference in *.java is *BookmarksListActivity_EmptyTextView*
is it a correct way to use the variables like that?
Answer: I've just tried the same in my project and it works. I don't know why one would need that but that works.
Comment: I get used to search a specific variable using "CTRL + H", if i try to search "BookmarksListActivity_EmptyTextView", I get no result.
it seems not convenient to find such variable in a big project.

some variables in xml have a 'dot'


openshift installation error on centos 7

Question: I have install the openshift in centos 7.
Installed the prerequisite and then installing the openshift via this command.
atomic-openshift-installer install
getting this error..  Please guide how to solve the same.
[WARNING]: Could not match supplied host pattern, ignoring: oo_lb_to_config
There was a problem fetching the required information. Please see /tmp/ansible.log for details.
tail -f /tmp/ansible.log
2018-07-21 12:36:47,139 p=23956 u=root |  skipping: [10.142.0.2]
2018-07-21 12:36:47,160 p=23956 u=root |  TASK [openshift_version : Set openshift_version for rpm installation] ************************************************************************************

2018-07-21 12:36:47,209 p=23956 u=root |  included: /usr/share/ansible/openshift-ansible/roles/openshift_version/tasks/check_available_rpms.yml for 10.142.0.2
2018-07-21 12:36:47,233 p=23956 u=root |  TASK [openshift_version : Get available origin version] **************************************************************************************************

2018-07-21 12:36:47,767 p=23956 u=root |  fatal: [10.142.0.2]: FAILED! => {"changed": false, "module_stderr": "Shared connection to 10.142.0.2 closed.\r\n", "module_stdout": "Traceback (most recen
t call last):\r\n  File \"/tmp/ansible_aWcbKG/ansible_module_repoquery.py\", line 642, in \r\n    main()\r\n  File \"/tmp/ansible_aWcbKG/ansible_module_repoquery.py\", line 632, in main\r\
n    rval = Repoquery.run_ansible(module.params, module.check_mode)\r\n  File \"/tmp/ansible_aWcbKG/ansible_module_repoquery.py\", line 588, in run_ansible\r\n    results = repoquery.repoquery()\r
\n  File \"/tmp/ansible_aWcbKG/ansible_module_repoquery.py\", line 547, in repoquery\r\n    rval = self._repoquery_cmd(repoquery_cmd, True, 'raw')\r\n  File \"/tmp/ansible_aWcbKG/ansible_module_re
poquery.py\", line 385, in _repoquery_cmd\r\n    returncode, stdout, stderr = _run(cmds)\r\n  File \"/tmp/ansible_aWcbKG/ansible_module_repoquery.py\", line 356, in _run\r\n    stderr=subprocess.P
IPE)\r\n  File \"/usr/lib64/python2.7/subprocess.py\", line 711, in init\r\n    errread, errwrite)\r\n  File \"/usr/lib64/python2.7/subprocess.py\", line 1327, in _execute_child\r\n    raise c
hild_exception\r\nOSError: [Errno 2] No such file or directory\r\n", "msg": "MODULE FAILURE", "rc": 1}
2018-07-21 12:36:47,770 p=23956 u=root |  PLAY RECAP ***********************************************************************************************************************************************

2018-07-21 12:36:47,770 p=23956 u=root |  10.142.0.2                 : ok=24   changed=2    unreachable=0    failed=1
2018-07-21 12:36:47,770 p=23956 u=root |  localhost                  : ok=12   changed=0    unreachable=0    failed=0
2018-07-21 12:36:47,770 p=23956 u=root |  INSTALLER STATUS *****************************************************************************************************************************************
Answer: You can ignore this warning:
<code>[WARNING]: Could not match supplied host pattern, ignoring: oo_lb_to_config
There was a problem fetching the required information. Please see
/tmp/ansible.log for details.
</code>
All this is saying is that you have not defined a load balancer (haproxy).  So your DNS needs to point to the masters or your are installing an haproxy manually.
tail -f /tmp/ansible.log
2018-07-21 12:36:47,139 p=23956 u=root | skipping: [10.142.0.2] 2018-07-21 12:36:47,160 p=23956 u=root | TASK [openshift_version : Set openshift_version for rpm installation] ************************************************************************************
2018-07-21 12:36:47,209 p=23956 u=root | included: /usr/share/ansible/openshift-ansible/roles/openshift_version/tasks/check_available_rpms.yml for 10.142.0.2 2018-07-21 12:36:47,233 p=23956 u=root | TASK [openshift_version : Get available origin version] **************************************************************************************************
I had a similiar problem.  It was due to an inconsistent setup of all of the nodes, having different versions of the rpms.  But I have the feeling that this isn't going on here.
Try running the ansible-playbooks with the -vvvv option (the advanced install).  This may help you find what the issue is.


Does Javascript date toLocaleString account for DST?

Question: I have set a deadline in UTC, as shown below, and I'm wondering what exactly the toLocaleString() method will do to it on user's local machines. For instance, will it account for daylight savings if they are in a timezone that recognizes it? Or will I need to insert additional code that checks where the user is, and then fixes the displayed time?
http://javascript.about.com/library/bldst.htm
var deadline = new Date('5/1/2013 ' + "16:15" + ' UTC');
alert(deadline.toLocaleString());

Answer: In general, the answer is yes.  JavaScript will represent the UTC value at the appropriate local time based on the time zone settings of the computer it is running on.  This includes adjustment for DST.  However, as others have pointed out, the details are implementation specific.
If you want a consistent output, I would use a library to format your dates instead of relying on the default implementation.  The best library (IMHO) for this is moment.js.  The live examples on their main page will give you an idea of what it can do.
UPDATE
If you are passing UTC values that you want converted to the correct local time, and that time falls into a period where the time zone rules are different than the current one - then the results will be invalid.  This is crazy, but true - and by design in the ECMA spec.  Read - JavaScript Time Zone is wrong for past Daylight Saving Time transition rules
Comment: Awesome, thanks. Looks like best library of this type that I've seen too
Comment: How does moment.js deal with different timezones?
Comment: It doesn't - yet.  Javascript can only natively work with Local or UTC.  You can pass different offsets in, but they will be applied internally.  You can't represent a non-local, non-utc offset on the way out.  See https://github.com/timrwood/moment/issues/611
Answer: We don't know what exactly the toLocaleString method does (§220.127.116.11):

This function returns a String value. The contents of the String are
  implementation-dependent, but are intended to represent the Date in
  the current time zone in a convenient, human-readable form that
  corresponds to the conventions of the host environment's current
  locale.

But yes, most implementations will consider DST if it is active in the current local timezone. For your example I'm getting "Mittwoch, 1. Mai 2013 18:15:00" - CEST.

Will I need to insert additional code that checks where the user is, and then fixes the displayed time?

I think you can trust toLocaleString - the browser should respect the user's settings. If you want to do it manually, check out timezone.js.
Answer: As you use "UTC" the date itself will be UTC format, but the  toLocaleString() takes client's locale into account, which means it'll return the date in string updated with all and every changes typical to client's regional and locale settings (DST, date/time format, etc).As JS documentation describes this: "The toLocaleString() method converts a Date object to a string, using locale settings.".If you want to avoid this, use the toUTCString() method instead.I'd also recommend reading the accepted solution for the question Javascript dates: what is the best way to deal with Daylight Savings Time? to avoid (at least, to try to avoid :) future issues related to JS, browsers and locales.Hope this helps!


How to replace html tag with other tags using preg-match?

Question: I have a string like the following.
value1:value

value2:value

value3:value

and i need to arrange this as following

value1value

i have tried for this last 2 days, but no luck.Any help?
Comment: TH̘Ë͖́̉ ͠P̯͍̭O̚N̐Y̡ H̸̡̪̯ͨ͊̽̅̾̎Ȩ̬̩̾͛ͪ̈́̀́͘ ̶̧̨̱̹̭̯ͧ̾ͬC̷̙̲̝͖ͭ̏ͥͮ͟O̮̪̝͍ͮM̲̖͊̒ͪͩͬ̚̚͜Ȇ̴̟̟͙̞ͩ͌͝S̨̥̫͎̭ͯ̿̔̀ͅ
Comment: pigmentation match? match based on colour?
Comment: You can't parse HTML with regex. http://stackoverflow.com/a/1732454/477127
Comment: sorry brother. spelling mistake.
Comment: should the second `` be ``? and the last `` be ``?
Answer: This really isn't something you should do with regex.  You might be able to fudge together a solution that works provided it makes a lot of assumptions about the content it's parsing, but it will always be fragile and liable to break should that content deviate from the expected by any significant degree.
A better bet is using PHP's DOM family of classes.  I'm not really at liberty to write the code for you (and that's not what SO is for anyway), but I can give you a pointer regarding the steps you need to follow.

Locate text nodes that follow a label and precede a BR (XPath may be useful here)
Put the text node into a span.
Insert the span into the DOM after the label
Remove the BR.
wrap label and span in an li
Answer: If, for the sake of regex, you should use it then follow as below :
$string = <<<TOK
value1:value

value2:value

value3:value

TOK;
preg_match_all('/(.*?)\:(.*?)
/s', $string, $matches);
print_r($matches);
/*
Array
(
    [0] => Array
        (
            [0] => value1:value
            [1] => value2:value
            [2] => value3:value
        )
    [1] => Array
        (
            [0] => value1
            [1] => value2
            [2] => value3
        )

    [2] => Array
        (
            [0] => value
            [1] => value
            [2] => value
        )
)
*/
$content = "";
foreach($matches as $key => $match)
{
    $content.= "
{$matches[1][$key]}{$matches[2][$key]}
\n";
}
echo($content);
/*
Output:

value1value

value2value

value3value

*/


Why were these 2 questions closed as 'language-specific'?

Question: https://linguistics.stackexchange.com/q/12181/5306
https://linguistics.stackexchange.com/q/12440/5306
In both cases, I wish to ask about the word as it existed in Latin, French, and English, and possibly other languages entailed.
Answer: Your first question was deleted by "Community". I don't have access to any more activity on that. As far as I can see, no one flagged or closed the question.
Your second question was about the meanings of in- in Latin, which is a language-specific usage issue.

PS: to elaborate, I closed the second question because it was of the form "What are the meanings of X in language Y". It seems to be a dictionary look-up question.


error C3892: 'std::_Tree_unchecked_const_iterator

Question: plz help me for this error and ... (visual studio 2010)
void file_remove(u32 id, int action) {
    file f;
    f.id = id;

    **file_set::iterator i = fs.find(f);**

    if(i == fs.end()) return;

    // move cursor away
    if(conf.expose.cursor == id) cursor_down();
    if(conf.expose.cursor == id) cursor_up();
    if(conf.expose.cursor == id) conf.expose.cursor = 0;

    if(action != 1 && i->size >= conf.files.incomp_min_size &&
        (u64)segment_summ(i->seg) * 100 / i->size >= conf.files.incomp_percent)
    {   action = 2;     }

    char n1[0x100];
    char n2[0x100];

    if(!i->deleted){
        cache_close(i->h);

        snprintf(n1, sizeof(n1), "%s/%s", conf.fnames.dir_temp, i->name.c_str());

        if(action == 0)
        {   // just close
        }
        else if(action == 1)
        {
            snprintf(n2, sizeof(n2), "%s/%s", conf.fnames.dir_ok, i->name.c_str());         seg(*i, conf.fnames.dir_temp, false);
        cache_move(n1, n2);
        }
        else if(action == 2)
        {
            snprintf(n2, sizeof(n2), "%s/%s", conf.fnames.dir_incomplete, i->name.c_str());
        seg(*i, conf.fnames.dir_incomplete, true, true);
        seg(*i, conf.fnames.dir_temp, false);
        cache_move(n1, n2);
        }
        else if(action == -1)
        {
            seg(*i, conf.fnames.dir_temp, false);
        cache_move(n1, ""); // unlink
        }
    } else {
        ffs_remove(i->size, i->tag);
        fs.erase(i);
        sort_files();
        return;
    }

    if(!i->tmp){
        ffs_remove(i->size, i->tag);
        fs.erase(i);
    } else {
        **i->deleted = true;**
    }
    sort_files();
}

compile it and error with this element : i->deleted = true; + view this result

1>main.cpp(478): error C3892:
  'std::_Tree_unchecked_const_iterator<_Mytree,_Base>::operator ->' :
  you cannot assign to a variable that is const 1>          with 1>
  [ 1>
  _Mytree=std::_Tree_val,std::allocator,false>>,
  1>              _Base=std::_Iterator_base 1>          ]

http://up.vbiran.ir/images/w21nnbxc7tf5okzk0lr.png
http://up.vbiran.ir/images/x0coajrixr764g49ibeh.png
plz help me for resolve this error
Comment: Hello, your is completely unreadable as it is posted. Please edit your question, delete the whole block, then simply paste your code back, highlight it and click on the `{}` button.
Comment: The best way to get help is to post a minimal working example that we can copy/paste/compile to reproduce the error. See http://sscce.org
Answer: Yes, it is this line that is the problem
i->deleted = true;

In a std::set all the elements are const (because changing the value might invalidate the order of the set).


More than one file was found with OS independent path 'META-INF/proguard/okhttp3.pro'

Question: I am trying okhttp and i have the next error:\

More than one file was found with OS independent path
  'META-INF/proguard/okhttp3.pro'

This is what i have in my build.gradle
apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.woooba.login2"
        minSdkVersion 23
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0-rc01'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    implementation 'com.squareup.okhttp3:okhttp:3.11.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

And this is the MainActivity.java
OkHttpClient client = new OkHttpClient();

String u = "https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22k";
task.execute(u);
Request request = new Request.Builder().url(u).build();

client.newCall(request).enqueue(new Callback() {
     @Override
     public void onFailure(Call call, IOException e) {
          e.printStackTrace();
     }

     @Override
     public void onResponse(Call call, Response response) throws IOException {
           if (response.isSuccessful()){
             Log.i("Response", response.body().string());
           }
         }
  });

Anyone know what happen? It said ' More that one file was found' but not sure what it is talking about. I am new with android
Thanks
UPDATE
proguard-rules.pro code displayed as per @vivek request
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
#   http://developer.android.com/guide/developing/tools/proguard.html

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
#   public *;
#}

# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable

# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

UPDATE 2
Adding to build.grade within android{} the next:
link
packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/ASL2.0'
        exclude 'META-INF/proguard/okhttp3.pro'
}

Pressed "Sync now" and play and the error's gone but when you go to 4:run I see another error.

More than one file was found with OS independent path
  'okhttp3/internal/publicsuffix/publicsuffixes.gz'

So i added to packagingOptions{}

exclude 'okhttp3/internal/publicsuffix/publicsuffixes.gz'

and I get the next error

Compilation failed to complete

Android issues:

Program type already present: okhttp3.Call$Factory Message{kind=ERROR,
  text=Program type already present: okhttp3.Call$Factory,
  sources=[Unknown source file], tool name=Optional.of(D8)}

Any idea? i've seen here that suggest to remove the implementation of okhttp3 but come up erros when I call this class in MainActivity

OkHttpClient client = new OkHttpClient();
Comment: show your proguard file
Comment: @VivekMishra done. I havent got anything there. Thanks
Comment: https://stackoverflow.com/questions/44342455/more-than-one-file-was-found-with-os-independent-path-meta-inf-license
Comment: thanks @VivekMishra. tried that and other instructions but still having problems.
Comment: if that didn't try with some older versions of okhttp library
Comment: good idea. I'll give some time just in case that someone knows the answer.
Answer: It looks like your build is attempting to include multiple copies of OkHttp in your binary. Do any of your dependencies include their own copies of OkHttp? Are you including multiple versions?
Comment: Hi @Jesse. Thanks for your reply.
It is a new android's project. Just playing around with it. You can see above all the dependencies.
Maybe the problem come from this implementation that was created by default?
> implementation fileTree(dir: 'libs', include: ['*.jar'])
I dont think so because when i remove

implementation 'com.squareup.okhttp3:okhttp:3.11.0'

i have an error when i call okhttp3 class


Spatial Correlation calculation in python: Concatenation Error-Mismatched array sizes along dimension 0

Question: I am attempting to plot the spatial correlation between two variables, SIC and spco2, which are stored in separate NetCDF files. However, the spco2 dataset has a different coordinate type than the 'SIC' dataset. Below is some brief information about both datasets:
Sea Ice data
Dimensions:

LON: 360
LAT: 173
TIME: 444
bnds: 2

Coordinates:

LON (float64): -179.5, -178.5, ..., 178.5, 179.5
LAT (float64): -82.5, -81.5, -80.5, ..., 88.5, 89.5
TIME (datetime64[ns]): 1985-01-01, ..., 2021-12-01

Data variables:

TIME_bnds (TIME, bnds): datetime64[ns]
SIC (TIME, LAT, LON): float32

Carbon Data:
Dimensions:

time: 444
latitude: 173
longitude: 360

Coordinates:

time (datetime64[ns]): 1985-01-15, ..., 2021-12-15
latitude (float32): -82.5, -81.5, -80.5, ..., 88.5, 89.5
longitude (float32): 0.5, 1.5, 2.5, ..., 357.5, 358.5, 359.5

Data variables:

spco2 (time, latitude, longitude): float32
tco2 (time, latitude, longitude): float32
fgco2 (time, latitude, longitude): float32
ph (time, latitude, longitude): float32
talk (time, latitude, longitude): float32

In the following the code I transformed the coordinates of carbon data from 0:360 to -180:180 so that the format matches but I am not sure if worked:
import xarray as xr
import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from scipy.interpolate import griddata

# Load sea ice data
sea_ice_data = xr.open_dataset(path_ice)
sea_ice_sic = sea_ice_data['SIC']

# Load carbon data
carbon_data = xr.open_dataset(path_carbon)
carbon_spco2 = carbon_data['spco2']

# Convert carbon longitudes to -180 to +180 range
carbon_spco2['longitude'] = (carbon_spco2['longitude'] + 180) % 360 - 180

# Flatten latitude and longitude coordinates
carbon_coords = np.column_stack((carbon_spco2['latitude'].values.flatten(), carbon_spco2['longitude'].values.flatten()))

# Calculate spatial correlation map
correlation_map = np.empty((len(sea_ice_sic['LAT']), len(sea_ice_sic['LON'])))
for lat_idx, lat in enumerate(sea_ice_sic['LAT']):
    for lon_idx, lon in enumerate(sea_ice_sic['LON']):
        sic_values = sea_ice_sic.sel(LAT=lat, LON=lon, method='nearest').values

        # Interpolate carbon data to sea ice grid
        spco2_values = griddata(
            carbon_coords,
            carbon_spco2.values.flatten(),
            (lat, lon),
            method='nearest'
        )

        correlation_map[lat_idx, lon_idx] = np.corrcoef(sic_values, spco2_values)[0, 1]

# Create a Cartopy projection
projection = ccrs.PlateCarree()

# Plot the spatial correlation map using Cartopy
plt.figure(figsize=(12, 8))
ax = plt.axes(projection=projection)
ax.set_extent([-180, 180, -90, 90], crs=ccrs.PlateCarree())
ax.coastlines()

# Plot the correlation map as an image
plt.imshow(correlation_map, cmap='RdBu_r', vmin=-1, vmax=1, extent=(-180, 180, -90, 90), origin='upper', transform=ccrs.PlateCarree())

# Add a colorbar
cbar = plt.colorbar(label='Correlation Coefficient', orientation='vertical', shrink=0.7)
cbar.ax.tick_params(labelsize=10)

plt.title('Spatial Correlation between Sea Ice and Carbon')
plt.show()

However, I am ending up with the following error message:
ValueError                                Traceback (most recent call last)
<ipython-input-8-1d668216ff21> in <cell line: 20>()
     18
     19 # Flatten latitude and longitude coordinates
---> 20 carbon_coords = np.column_stack((carbon_spco2['latitude'].values.flatten(), carbon_spco2['longitude'].values.flatten()))
     21
     22 # Calculate spatial correlation map

2 frames
/usr/local/lib/python3.10/dist-packages/numpy/core/overrides.py in column_stack(*args, **kwargs)

/usr/local/lib/python3.10/dist-packages/numpy/lib/shape_base.py in column_stack(tup)
    654             arr = array(arr, copy=False, subok=True, ndmin=2).T
    655         arrays.append(arr)
--> 656     return _nx.concatenate(arrays, 1)
    657
    658

/usr/local/lib/python3.10/dist-packages/numpy/core/overrides.py in concatenate(*args, **kwargs)

ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 0, the array at index 0 has size 173 and the array at index 1 has size 360

I am assuming the regridding did not work properly. I would appreciate any help or suggestions, regarding this. I am also attaching the Google Drive links to my dataset below:

Sea ice
Carbon

Thank you so much for considering to take a look at my issue.
Answer: I can propose solution like this, although the loops make it very slow and at the moment do not check that time-moments are really the same (I just assume that time values are equal i.e. values correspond correctly in time):
#!/usr/bin/env ipython
# --------------------
import xarray as xr
import numpy as np
# --------------------
filein_a = 'extracted_sea_ice.nc'
filein_b = 'Carbon-rep-monthly_1985-2021.nc'
# ------------------------------------------
def nc_varget(fin,vin):
    with xr.open_dataset(fin) as ncin:
        return ncin.variables[vin].values
# ------------------------------------------
xa = nc_varget(filein_a,'LON')
ya = nc_varget(filein_a,'LAT')
# -----------------------------------------------------------
# ===========================================================
corrmat = np.zeros((np.size(ya),np.size(xa)))
# -------------------------------------------
dfin_a = xr.open_dataset(filein_a)
dfin_b = xr.open_dataset(filein_b)

for ix,xval in enumerate(xa):
    for iy,yval in enumerate(ya):
        corrmat[iy,ix] = 0.e0
        serie_a = dfin_a.sel(LON=xval,LAT=yval,method='nearest')
        serie_b = dfin_b.sel(longitude=xval,latitude=yval,method='nearest')
        # ---------------------------------------------------
        serie_a = serie_a['SIC']
        serie_b = serie_b['spco2']
        # ---------------------------------------------------
        if np.nanstd(serie_a) == 0.e0 or np.isnan(np.nanstd(serie_a))==1: continue
        if np.nanstd(serie_b) == 0.e0 or np.isnan(np.nanstd(serie_b))==1: continue
        # ---------------------------------------------------
        corrmat[iy,ix] = np.nanmin(np.corrcoef(serie_a,serie_b))
# ===================================================================================
ds = xr.Dataset(data_vars=dict(corrmat=(["lat", "lon"], corrmat)),coords=dict(lon=(["lon"], xa),lat=(["lat"], ya)),attrs=dict(description="Spatial correlation"))
ds.to_netcdf('test_output.nc')

Comment: Hello, I was able to get a correlation plot using your code. Thanks for your time and effort in writing it. I have a question though. Some areas of the plot show correlations greater than 1. Do these areas/grids have NaN values or do they only have values for one variable?
Comment: In addition, I experimented with an alternate method where I converted the coordinate values of the carbon dataset from the range of -360 to 360 degrees to the equivalent range of -180 to 180 degrees. Next, I applied your code to process these transformed datasets. Upon inspection, I found that the regridded output using the -180 to 180 degree coordinates provided superior results. You may find it interesting to examine the comparison: https://imgur.com/a/4w1Ubus
Comment: There should not be any values larger than 1 - otherwise the correlation is wrongly calculated :). The coordinate systems/values I did not check -- in any case, it's better and reasonable to have both datasets with same coordinate system, otherwise the interpolation might be wrong. Glad that you found some parts of the answer useful!


Does accept function return error(-1) if TCP server goes out of network

Question: Does the accept function returns error(-1) if the Ethernet interface it is attached goes out of network?if not how does the application(TCP server) will know that its interface is not active any more ??
I am using one thread for accepting the connection and not using any "select" statement for doing so.Directly calling accept() function but somehow it is not retuning error if I remove the IP address from Ethernet interface.
using C and working environment is linux.
Comment: Pick a language ... any language ...
Comment: I am not sure it does quickly, because TCP has some timeouts which are bigger than a minute. Still, using `select` or `poll` is always sensible...
Comment: @Basile Starynkevitch These timer helps once we close the socket connection.I am just trying to find out how an application server will know that interface is no more active
Comment: @Brian Roach Just edited my post.Can you please comment it now.
Answer: Usually you don't bind your server socket to a specific IP address (you use INADDR_ANY). So even if you remove your ethernet IP address, you could still contact your server using the loopback interface. Or some other interface with an IP address.
If you want to make sure that your server is reachable from the net, checking the interface status does not get you much. It's just a single hop on a long path through the network. You'd need a testing client somewhere else to check the reachability of your server.


Get Bitmap/DC of a tabbed MDI forms

Question: I have a set of forms which are visualized as MDI tab children of a main form (through an Infragistics UltraTabbedMDIManager, but this API is not so important)
I use GetDC(), CreateCompatibleDC(), CreateCompatibleBitmap(), SelectObject(), BitBlt().. to blit the bitmap of the device contexts of these forms into some memory.
This works, but only for the active MDI child form, the one that is visible to the user.
If I do it for forms that are not active (any tabs that are not currently shown), I get a black screen in the memory area, or I even get a "copy" of the screen that's above it.
If I do it for forms that are no longer visible, I also get a black screen.
What should I do to get a bitmap of these hidden forms? Do I have to resort to caching or is there some other trickery I can use?
I cannot use Winforms DrawToBitmap() function, because the forms contain some low-level graphical things that cannot be retrieved with it.
How can I use the winapi to retrieve a bitmap of these "hidden" forms' DC?
Comment: Your exact question has no simple answer.  What exactly do you need drawn?  The contents, full form, ...
Comment: See my own answer below. I don't agree that the nature of the contents being shown has any relevance, by the way.
Answer: I managed to do it using the PrintWindow API in user32.dll.
It solves the MDI tabs problem, however it didn't solve the problem for hidden forms.
I solved that problem by showign the forms briefly in some off-screen location.
It seems the "ultimate" way is to use the (undocumented) dwm.dll, but this is not so advisable because interfaces differ between versions of Windows.

Get Bitmap/DC of a tabbed MDI forms


Add corresponding elements in arrays

Question: What is the most compact way of adding corresponding elements of multiple arrays of same length  ?
var a = [1,2,3];
var b = [5,5,5];
var c = [1,1,1];
resultant array should be [7,8,9]

I can do this with a simple for loop but could it be possible for jquery/lodash solution with minimum lines of code?
Comment: What you have tried?
Comment: You can do this in a simple for loop
Comment: http://stackoverflow.com/questions/7135874/element-wise-operations-in-javascript
Comment: http://stackoverflow.com/questions/1230233/how-to-go-through-an-array-and-add-their-values
Comment: Please try to understand the question before marking it as a duplicate and referring to links that are completely different questions.
Comment: @diEcho that's not the same question.
Answer: Simple loop:
var result = [];
for(var i=0;i<3;i++)
 result.push(a[i]+b[i]+c[i]);

Note: Assuming all array of same length 3.

DEMO
Comment: Surely there's an easier way to do this with lodash
Answer: Well i'm not sure what you mean by the word 'Compact', either reduced number of lines or increased performance.. but the most reasonable and recommended way of doing it is through a simple loop:
var a = [1,2,3];
var b = [5,5,5];
var c = [1,1,1];
var result = [];
for(var i=0; i<a.length; i++){result[i] = a[i]+b[i]+c[i];}

result will contain [7,8,9]

Add corresponding elements in arrays


Do epoxy and shelac-based paint mix well together?

Question: I have a lot of clear epoxy resin intended for use on MDF or formica or partical board kitchen countertops.
I want to dye half of the epoxy white and dye half of the epoxy grey and do a fake marble look.
I do not want the white shelac-based paint and epoxy to seperate.
Does white shellac based paint mix well with epoxy or do the two seperate like oil and water?
Comment: Don't use paint. Use pigment
Comment: Last time I used a brush to paint some epoxy paint and tried to clean the brush with thinner, the stuff turned into cottage cheese. So *since you are asking generally*, the answer is "HARD no".
Comment: Do you want it to separate?  last time I had paint separate on me it was by applying a second coat before the first was dry enough.  I got a marbled effect as the pigments separated but I didn't want it.
Answer: As in Harpers comment, mixing different types of coating may not end well, especially when they use different solvents. I had a similar experience.
Instead add paint tinter to the epoxy,  take it to a paint store and have them add tint it or add powered pigment to the epoxy.
Large hardware stores will probably refuse to tint it  for you, go to a paint store, speak to a paint expert.


Laying your own telephone cable (from demarcation point)

Question: So my telephone cable from the demarcation point to my apartment is broken and there's no way to get a proper technician to fix it in the next few weeks. So I tried to do it myself, but the router keeps blinking, indicating that the connection isn't functional.
I made some pics from my phone to illustrate what I did. In this first picture, there is a little Telecom box which the Telecom technician connected. This is right at the demarcation point. Instead of plugging the telephone cable in there, I cut the wires and connected them to a telephone cable. This can be seen in the background. Its a 2x2 telephone cable, but I only connected the white and red cables. The second picture shows what I did at the other end, in my appartment. cable then goes straight into the router, but without any effect. Does anyone have an idea how to proceed? Would it make sense to get a Multimeter to detect it there are some voltages measurable, or is that doubtful even it it works? Any advice is appreciated.
Comment: :) we'll, living without an internet connection is not really an option these days, especially if you need it for work. Technicians I reached offered appointments for 2020 .... Is there a particular reason why this is a bad idea?
Comment: Is there any reason to believe the trouble is in the underground section? If it is above ground it can simply be spliced.
Comment: You might try reversing the wire connections.  (Are you sure of the orientation of the original connections?)  The best repair would be to open up the customer side of the central junction box and directly connect a pre-wired RJ45 wire assembly to the matching socket, then connect that directly to your modem.  With the existing repair does your phone work correctly? If you have a filter module it should only go on the line branches going to the phone connections.
Comment: "*So I tried to do it myself*", don't.
Comment: does it go thru a high pass filter?  Time to make friends with neighbours and use guest wifi
Comment: I don't understand your photos. Probably because I'm not familiar with your country's telephone cabling devices. What country are you in? Which wires are coming from the phone company? What is the demarcation device? Have you tried connecting your modem directly to the demarcation device? What type of DSL service do you have? What is the model of your modem?
Comment: How do you know that the feed at the demarcation point is not dead? | Why do you think it's the feed in cable that's broken? | Are you sure that the original wire colours now go, via the extension, to the same indoor terminals as before. | Are you sure your pushed in wires are making good contact? | How? |In correct holes?| Correct polarity? | Clean all 4 wires at demarcation point with sand paper or file then twiwst together well and ideally solder. || There are vast numbers of people who know enough to help at sensible rates and able to arrive this week rather than in 2020.
Answer: Step 1: Bring your router to the demarc point and verify that it works there. You did not mention if you had done this, but if not, you should, as the whole point of a demarc is to say: "If it does not work here the provider needs to fix it. If it does work here the problem is in your wiring." So you need to test that.
THEN you can start to concern yourself with the wiring onward from that point. Which appears to bear no resemblance to the North American standards I'm familiar with...


Ubuntu + XFCE + the Albatross theme

Question: I like the look of this theme:
http://shimmerproject.org/project/albatross/
But I can't figure out how to get xfce to look like this.
Help!
Comment: http://gnome-look.org/content/show.php/Albatross?content=123952
Comment: That's theme from Xubuntu  9.10 -Albatross
Answer: Download the theme from Github
And follow this instructions to install it.
Comment: Welcome to Ask Ubuntu! Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.
Comment: Oops, didn't knew that. Thanks.

Ubuntu + XFCE + the Albatross theme


Script not printing word count

Question: I have a script to find the word repetition in alist:
newm = [u'life', u'selection', u'squire', u'naturalist', u'patriarch', u'home', u'man', u'public', u'nbsp', u'born', u'naturalist', u'theory', u'selectionbecame', u'foundation', u'country', u'gentleman', u'suggesting', u'class', u'time', u'death', u'evolutionary', u'imagery', u'ofscience', u'literature']
print newm

#count for list
counts = defaultdict(int)
print "uyti"
for x in newm:
    counts[x]+=1

print counts

This program does not even print "uyti". What is the error?
Comment: do you have `from collections import defaultdict` ?
Comment: @njzk2 only if he is using 2.7+
Comment: did you `from collections import defaultdict`?
Comment: How are you trying to run it? Can you run python in interactive mode?
Comment: did you `from collections import defaultdict` ?
Comment: what does it print, then ?
Comment: (also, for what you do, you could use a Counter)
Comment: @JoranBeasley : i don't know anyone still using prior versions, but yes, it is true.
Comment: 2.6 is still widely in use(and I assume plenty use even earlier versions)
Answer: from collections import defaultdict
newm = [u'life', u'selection', u'squire', u'naturalist', u'patriarch', u'home', u'man', u'public', u'nbsp', u'born', u'naturalist', u'theory', u'selectionbecame', u'foundation', u'country', u'gentleman', u'suggesting', u'class', u'time', u'death', u'evolutionary', u'imagery', u'ofscience', u'literature',u'home']

#count for list

counts = defaultdict(int)

for x in newm:
   counts[x]+=1

print counts

Answer: assuming python 2.5+
from collections import defaultdict

newm = [u'life', u'selection', u'squire', u'naturalist', u'patriarch', u'home', u'man', u'public', u'nbsp', u'born', u'naturalist', u'theory', u'selectionbecame', u'foundation', u'country', u'gentleman', u'suggesting', u'class', u'time', u'death', u'evolutionary', u'imagery', u'ofscience', u'literature']
print newm

#count for list
counts = defaultdict(int)
print "uyti"
for x in newm:
   counts[x]+=1

print counts

will create the defaultdict, populate it with counts and keys and do your printing (which i assume was just debugging/sanity-check stuff...)
Answer: If all you want to know is which words are duplicates, there is an easier way:
words = set(newm)
dups = [(w, newm.count(w)) for w in words if newm.count(w) > 1]
print dups

This will give you [(u'home', 2), (u'naturalist', 2)]. To find out the count for all the words, simply remove the if statement from the list comprehension.

Script not printing word count


Getting error while creating multiple file in python

Question: I'm creating two files using python script, first file is JSON and second one is HTML file, my below is creating json file but while creating HTML file I'm getting error. Could someone help me to resolve the issue? I'm new to Python script so it would be really appreciated if you could suggest some solution
#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import json

JsonResponse = '[{"status": "active", "due_date": null, "group": "later", "task_id": 73286}]'

def create(JsonResponse):
    print JsonResponse
    print 'creating new  file'
    try:
        jsonFile = 'testFile.json'
        file = open(jsonFile, 'w')
        file.write(JsonResponse)
        file.close()
        with open('testFile.json') as json_data:
            infoFromJson = json.load(json_data)
            print infoFromJson
            htmlReportFile = 'Report.html'
            htmlfile = open(htmlReportFile, 'w')
            htmlfile.write(infoFromJson)
            htmlfile.close()
    except:
        print 'error occured'
        sys.exit(0)

create(JsonResponse)

I used below online Python editor to execute my code:

https://www.tutorialspoint.com/execute_python_online.php
Comment: Using `with open` in some places but not others is ... uncanny.
Answer: infoFromJson = json.load(json_data)

Here, json.load() will expect a valid json data as json_data. But the json_data you provided are not valid json, it's a simple string(Hello World!). So, you are getting the error.

ValueError: No JSON object could be decoded

Update:
In your code you should get the error:

TypeError: expected a character buffer object

That's because, the content you are writing to the file needs to be string, but in place of that, you have a list of dictionary.
Two way to solve this. Replace the line:
htmlfile.write(infoFromJson)

To either this:
htmlfile.write(str(infoFromJson))

To make infoFromJson a string.
Or use the dump utility of json module:
json.dump(infoFromJson, json_data)

Comment: Thanks for your response. I gave a proper json now - I've update my post with valid json in my message but still I'm getting the same error.
Answer: If you delete Try...except statement, you will see errors below:
Traceback (most recent call last):
  File "/Volumes/Ithink/wechatProjects/django_wx_joyme/app/test.py", line 26, in <module>
    create(JsonResponse)
  File "/Volumes/Ithink/wechatProjects/django_wx_joyme/app/test.py", line 22, in create
    htmlfile.write(infoFromJson)
TypeError: expected a string or other character buffer object

Errors occurred because htmlfile.write need string type ,but infoFromJson is a list .
So,change htmlfile.write(infoFromJson) to htmlfile.write(str(infoFromJson)) will avoid errors!


How to extract meaningful and frequent words from concatenated strings in python?

Question: I have a list of concatenated string as given below which I wish to split into meaningful and frequent words. Code which I have created is giving me all sorts of un-frequent words as well.
con_words = ["stainlesssteel", "screwhammerwing", "goldplated", "bearingball", "inchcountry"]

Expected output:
{"stainlesssteel": ["stainless", "steel"],
"screwhammerwing": ["screw", "hammer", "wing"],
"goldplated": ["gold", "plated"],
"bearingball": ["bearing", "ball"],
"inchcountry": ["inch", "country"]}

My code
from nltk.corpus import words
from nltk.corpus import stopwords

#list of all words from english dictionary
words = words.words()

#list of all english stopwords
stops = list(set(stopwords.words('english')))

alphabets = [chr(x) for x in range(ord('a'), ord('z') + 1)]
cleaned_word_list = list(set(words)|set(stops))
cleaned_word_list = list(set(cleaned_word_list)|set(alphabets))
cleaned_word_dict = dict((i, 0) for i in cleaned_word_list)

def extract_words(x):
    res = []
    subs = [x[i:j+1] for i in range(len(x)) for j in range(i,len(x))if (i - (j+1)) < -1]
    for sub in subs:
        try:
            l = cleaned_word_dict[sub]
            res.append(str(sub))
        except:
            pass

    return sorted(res, key = len, reverse=True)

common_words_dict = dict((i, extract_words(str(i))[:5]) for i in con_words)

Output:
{'stainlesssteel': ['stainless', 'stain', 'steel', 'tain', 'less'],
 'screwhammerwing': ['hammer', 'screw', 'ammer', 'crew', 'wham'],
 'goldplated': ['plated', 'plate', 'lated', 'gold', 'plat'],
 'bearingball': ['bearing', 'earing', 'bear', 'ring', 'ball'],
 'inchcountry': ['country', 'count', 'inch', 'try', 'in']}

Is there any other way of doing this?
Please help me in understand how to get the expected output.
Comment: Your code is doing exactly what you're telling it to do,  in a nutshell you're telling your program "Give me all combinations of strings in this word based off this corpus". If you only want the top two answers I would suggest placing all your results in a list and slicing the list accordingly.
Answer: I think the simplest way to get your expected output (although it might use a lot of memory) would be to run the extract_words() function on the first output, but remove words that are contained in other answers. This would prevent the fragmented words ('stainless'-'stain' ; 'hammer'-'ammer') and would still allow for multiple full words.
I will update my answer with code once I make something that works.


How can I map over object values using Ramda.js and take only first element?

Question: I have input like that:
{
  a: [obj1, obj2, obj3...],
  b: [obj1, obj2, obj3...],
  c: [obj1, obj2, obj3...]
}

I want to have that output (only first object from array for every key)
{
  a: [obj1],
  b: [obj1],
  c: [obj1]
}

I want to do it using ramda.js
Answer: The simplest answer is just map(head, obj), or if you want a reusable function, map(head).
You can see this in action on the Ramda REPL.
Comment: Yes, that is much better! Simpler and more elegant! I was trying to use head, but not in exactly right way before.
Answer: const data = {
  a: [obj1, obj2, obj3],
  b: [obj1, obj2, obj3],
  b: [obj1, obj2, obj3]
}

const updatedData = R.mapObjIndexed( value => ([value[0]]), data)

(This exact code won't work because obj1, obj2, and obj3 aren't defined)
Comment: Note that since `key` is not used, you could simplify this to `R.map(value => value[0], data)`.  (Ramda treats Objects as functors that it knows how to map.)  But Ramda's `head` is essentially `xs => xs[0]`, so this could also be written as `R.map(R.head, data)`, and we arrive at my solution.


Object of class wpdb could not be converted to string

Question: I'm trying to get an organisation's ID by giving its name.
I have the following code:
$orgid= $wpdb->get_var("SELECT organisationid FROM $wpdb->$table_name1 WHERE organisationname=' " . $organisation . "'");

This line returns this error:
Catchable fatal error:
Object of class wpdb could not be converted to string

I wish to echo this ID onto the page.
I have read the codex but do not understand. How can I fix this?
Comment: could be in `FROM $wpdb->$table_name1` then. From what I found so far in regards to the error message, try using braces around it ie: `FROM {$wpdb->$key}` as per a finding here https://wordpress.org/support/topic/object-of-class-wpdb-could-not-be-converted-to-string-1
Comment: there's a space in here `' " . $organisation . "'` remove it. `'" . $organisation . "'` and make sure this is spelled correctly `organisaitonname` - might be `organisationname` in your db? that's how it should be spelled anyway. and do a var_dump on that variable. use `trim()` also should there be whitespace introduced.
Comment: Hi Fred, I have done this but it did not fix my problem. Thanks
Comment: while I was Googling this ^, an answer's been posted with the same method.
Answer: If you're going to use variable variables inside the string, remember to wrap it with curly braces:
"SELECT organisaitonid FROM {$wpdb->$table_name1} WHERE organisaitonname = '" . $organisation . "'"
                       //    ^  important       ^

Note: Just make sure that the value of $table_name1 does correspond to $wpdb's properties of course so that it matches.
Comment: This worked great. Thanks! Another note on this is that you don't need the $wpdb-> in {$wpdb->$table_name1}
Answer: Try also
$wpdb->table_name1

instead of:
$wpdb->$table_name1

without dollar "$"


Struts 2 Validation clearing out url parameter

Question: If I am at http://foo.bar?fooId=123 and the validation fails (validate method in action class) I get redirected to http://foo.bar without the fooId param. This causes form fields to lose their values. Any ideas why this is happening?
Answer: You are using GET to send your parameters, server on validation failure is sending you the same input page, instead of GET use POST and everything should work fine.
Your configuration would look like this :
<result name="input">inputPage.jsp</result> which discards any parameter that you submitted.
Also note as per HTML specification GET shouldn't be called if operation will result in any updatation, instead POST should be used.


What is animation canceling all about in Blade & Soul?

Question: I've seen this mentioned more than once but I'm not exactly sure what it is or how it works. Can someone explain?

What is animation canceling?
Why animation cancel? What advantages does it give over not canceling?
Is it more applicable for certain classes or is it class agnostic?
How do you do it? How do you know if you're doing it properly?
Comment: Just a comment because I don't play B&S. **What is**: There are two reasons. First example: Reload in COD MW games, keep trying to sprint, boom you reloaded faster. Another example is Counter Strike 1.6 and Source. You can fast double-tap the recent weapon after an AWP/sniper shot. | Second example: You start to reload in Black Ops 3, but you hear someone, and reload takes too long. Swap weapons, and you are ready to fire in 1 seconds. || **Why**: See above.  Sometimes it's possible to speed things up. Sometimes, second example, it's helpful. || For the rest, well, players will reply to that.
Answer: Many games use attack animations.  Typically, animations must complete before the next action can be taken.  Animation canceling is when an animation does not block the next action.
Generally, one cancels an animation after the ability has produced its effect in order to avoid waiting.  Occasionally, one cancels an animation before the effect in order to do something else better with the time.
Examples:

In Bayonetta, it is possible to cancel any attack at any time into a dodge.  This encourages a playstyle where all incoming attacks are avoided.
In Mass Effect 3, the Claymore is a one-shot shotgun that takes a long time to reload, but it is reloaded pretty early in the animation.  The reload animation can't be canceled by shooting, but it can be canceled by ducking into cover or using a power.  The advantage of canceling the animation is that the overall shooting rate is improved, which improves the damage per second.

In Blade And Soul, animation canceling allows faster attacks.  This can lead directly to more damage, or generate resources faster which allows bigger attacks.  These resources can also lead to better crowd control/stuns.
In this video, the kung-fu master (KFM) is canceling Straight Jab and Swift Strike into each other with the idea to generate crits and chi to allow the use of Cyclone kick.
At about 1:10, the non-canceling speed is shown.  The rest of the time, canceling!

A bit of jargon: 2 and F are the abilities bound to those keys.  R is the ability bound to the R key as well as the left mouse button.  2R2RF means to use those keys in sequence.
Most animation canceling is done with R - don't forget: same as left mouse button.
All classes can benefit from animation canceling.


Stuck on boot ubuntu 18.04 5.3.0-59-generic

Question: Last night, I did apt-get update and upgrade, and when tried to enter to system it got stuck on boot and then show me this error :
failed to start load/save screen backlight brightness of acpi_video0

If I add nomodeset I can boot and enter but with very low resolution. Is there any solution? I have a  HP PAVILION 15-CW0053LA . Meanwhile im using 5.0.0-37-generic to enter.
Thanks in advance.
Answer: Boot to Recovery Mode, if required.
Edit /etc/default/grub:
sudo -H gedit /etc/default/grub
or
sudo pico /etc/default/grub
Find:
"quiet splash"

Change it to:
"quiet splash acpi_backlight=vendor"

Or:
"quiet splash acpi_backlight=video"

sudo update-grub
reboot


Where do I place block loot table in 1.14 data pack?

Question: I'm creating a loot table for some blocks in minecraft 1.14 snapshot, and would like to know where to place those loot tables within my data pack... just giving me the file directory lineup i.e World/datapacks/datapack/data/name/function is where my functions go, where would my loot tables go?
Comment: You should probably edit [your old question](https://gaming.stackexchange.com/questions/340987/minecraft-1-14-snapshot-loot-table-how-to) instead of just deleting it and asking a new one.
Comment: @Frank That could have caused confusion if people read the comments, and this question has very little to do with the original... I also gave upon getting an answer for the original.
Comment: Did you look at the wiki? If not, do that. If yes, what didn't work despite reading it?
Comment: I feel this is the same question as before, just worded differently.
Comment: @FabianRöling The wiki does not describe what I'm asking in this question for 1.14, only for 1.13, and the loot table I want is unique to 1.14
Comment: @Frank The previous question was basically asking for a full how to guide, this question is literally asking for the answer I am about to give (got in MC Forums)
Answer: AS I got from MC Forums when I posted the same question:

.minecraft\saves\[your world]\datapacks\[datapack name]\data\[namespace]\loot_tables\blocks\[json files]


How to display image thumbnails in a Panorama(or pivot) page and scroll horizontally?

Question: I have some Thumbnail images .I want to display image thumbnails in a Panorama(or pivot) page and scroll horizontally as in native windows phone 7 photo viewer application.Is it possible?
Answer: Set the Orientation on the PanoramaItem to Horizontal to recreate the behaviour of the Pictures hub.
The pivot does/should not support horizontal scrolling within an item.
Comment: How do we control how much horizontal scrolling should occur?


Determine the largest magnitude and the angle of a force applied at a point

Question: The following problem comes from "Vector Mechanics for Engineers: Statics" from F.Beer

The solution goes on with law of cosines to find $P$ for item (a) and law of sines to find $\beta$ and then find $\alpha$ for item (b). What I don't understand is why the angle between the $600$N and $1200$N forces is $85°$, I thought it should be $180°-35°-50°=95°$. So, I want to know why the angle between the tension forces is their sum and not what I've thought in the first place.
Answer: In the force diagram, the arrows are placed so that they follow each other. This is because the total vector sum is zero since the system is in equilibrium.
Comment: So we put a parallel line to the shown horizontal line, and translate $T_{BC}$ force to the head of arrow of $T_{AC}$, and the angle between then must be $50° + 30$? since $35°$ its an alternate interior angle.
Comment: Yes that's right


How can one find the root of sesquilinear form with positive definite matrix?

Question: I cane accross the problem of this kind dealing with fuzzy regression analysis.
$$(x^{T}Mx)^{1/2}$$
I would like to know how this root can be expressed explictly using x. (Here of course x is $(n \times 1)$ real-valued column, and M is $(n \times n)$ positive-definite matrix, so the above form is some inner product. And of course it has only one root, as it is a real number.)
I wonder whether there are some formulas for that or not?
Thank you.
I mean finding the root, in some form. That is having expression where x is out of the parenthesis.
Comment: It is a norm, not an inner product. It is already explicitly depending on $x$. What do you mean?
Answer: If you mean by root that $(x^T M x)^(1/2)  =  0$, then $x^T M x = 0$, then $x$ should fall in the null space of $M$. Therefore, $x$ is a vector the lies in the null-space of $M$.
Comment: I think it is root as in  square root and not zero of a function.


Overwrite a file?

Question: I have a file named config.yml in a directory I need to be able to edit it and then overwrite it. When ever I would edit it and save it with the same name it would ask to overwrite and I would say yes but it had overwritten a config.yml in another place not the one I had wanted. I need help because I need to overwrite the right config file.
Thanks
Answer: You should cd into the directory before opening the file and make sure that it's saving the file to the right place
Comment: I am using nano I need to be able to do so in it.
Comment: @ebank36 Sorry, I don't quite get what you mean by that comment. Where is the file you are editing? Where did it save the file?
Comment: ok so I edited my file in /home/ebank36/minecraft/plugins/ChatManager/config.yml and i need to overwrite it in the exact same place, but when I try it saves it in /home/ebank36/minecraft
Comment: @ebank36 You should `cd /home/ebank36/minecraft/plugins/ChatManager/` then run `nano config.yml` and see if that works

Overwrite a file?


How could I log that a Windows service is terminating because of a system shutdown?

Question: I have a diagnostic version of a service that logs as much as possible in the OnStart() and OnStop() methods.
One event that I am unable to capture is when the computer is physically restarted. My logging function usually records its output to a table in a database, but when that is not available it posts to the EventLog.
On a reboot my service neither logs to the table nor to the EventLog.
It makes sense to me that I would not be able to post to the table, since SQL Server is in the process of shutting down, but it also seems that due to a timing issue the EventLog may also be shutting before the service can default to write there.
In the case of a shutdown, MSSQLSERVER reports an information message in the EventLog:

SQL Server is terminating because of a system shutdown. This is an informational message only. No user action is required.

Is there a way to do something similar for my service?
Answer: There is an OnShutdown method your can override in your service. It will be called when the machine is shutting down. Write to the event log from that method, then call base.OnShutdown().
Comment: Frode--in my eventual solution I found that it was also helpful to override OnShutdown(), since OnStop() does not seem to get raised on a system shutdown. Thanks as well!
Answer: You can specify the dependencies of your Windows Service to have it require another service. If you specify a dependency on the EventLog service, then Windows will wait until your service is shut down before shutting down the Event Log.
http://kb2.adobe.com/cps/400/kb400960.html describes how to do it by modifying a few registry keys.

Navigate to
  HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services
  and locate the service that you need
  to set a dependency for. Open the
  'DependOnService' key on the right
  side. If the selected service does not
  have a 'DependOnService' key, then
  create one by right-clicking and
  selecting New > Multi-String Value. In
  the value field, enter the names of
  all services that the current service
  will depend on. Each service name must
  be entered properly and on a separate
  line.
Comment: Thanks David--that was the solution I used. At first I was hoping to set the dependency programmatically, but with possible permissions issues I think the only way to do that reliably is with installer code. I did mitigate the deployment complexity though by creating a .reg file that I could run. So thanks!
Answer: Capture SystemEvents.SessionEnding
On the OnStart you could capture it and handle
like
<code>Microsoft.Win32.SystemEvents.SessionEnding += new Microsoft.Win32.SessionEndingEventHandler(this.zomgRebootinglol);
</code>
Comment: His issue isn't capturing the shutdown event, its that the logger is already gone by the time his service tries to log.
Answer: You can capture windows events by using the SystemEvents-Class.
Also take a look at the events.
I think the Event you are looking for is: SystemEvents::PowerModeChanged Event and/or SystemEvents::SessionEnded
Comment: His issue isn't capturing the shutdown event, its that the logger is already gone by the time his service tries to log.


How to execute two "aggregate" functions (like sum) concurrently, feeding them from the same iterator?

Question: Imagine we have an iterator, say iter(range(1, 1000)). And we have two functions, each accepting an iterator as the only parameter, say sum() and max(). In SQL world we would call them aggregate functions.
Is there any way to obtain results of both without buffering the iterator output?
To do it, we would need to pause and resume aggregate function execution, in order to feed them both with the same values without storing them. Maybe is there a way to express it using async things without sleeps?
Comment: @tobias_k Nice catch! I can't speak for the OP, but assuming that does sound like a bit of a stretch because then you're really working with binary functions (`+` and the binary `max`), and not with aggregate functions. The question refers to aggregate functions in general, describing them as "accepting an iterator as the only parameter", only using `sum` and `max` as examples. In that context I would argue that an answer needs to work for aggregates that cannot be reduced to a stateless series of applications of a binary function (e.g. an aggregate that returns the median of the sequence).
Comment: `sum(a,b,c)` is the same as `sum(a,sum(b,c))`, likewise for `max`. Can we assume that that's always the case? Then just apply the aggregator functions for each element in the iterator.
Comment: @user4815162342 I thought it would be a nice and simple way that works with O(1) memory and without threads, but you are right; `average` would be another example. (Also, it's pretty slow.)
Comment: @tobias_k *Also, it's pretty slow.* I tried it out of curiosity, and for `sum` and `max` and `range(10000)` it clocks at 4.9 ms on my machine, way faster than solutions from my answer (except the initial ones that buffer everything).
Comment: @user4815162342 I just compared it to buffering the entire iterator with `list` or `tee`. Anyway, I posted it as an answer, maybe it's useful in some cases. At least it's simpler than the thread-based approaches.
Comment: @tobias_k *At least it's simpler than the thread-based approaches* For the record, the approaches in my answer are not thread-based, at least not all of them. They're still complex, though, but that's probably unavoidable without loss of generality.
Answer: Let's consider how to apply two aggregate functions to the same iterator, which we can only exhaust once. The initial attempt (which hardcodes sum and max for brevity, but is trivially generalizable to an arbitrary number of aggregate functions) might look like this:
def max_and_sum_buffer(it):
    content = list(it)
    p = sum(content)
    m = max(content)
    return p, m

This implementation has the downside that it stores all the generated elements in memory at once, despite both functions being perfectly capable of stream processing. The question anticipates this cop-out and explicitly requests the result to be produced without buffering the iterator output. Is it possible to do this?
Serial execution: itertools.tee
It certainly seems possible. After all, Python iterators are external, so every iterator is already capable of suspending itself. How hard can it be to provide an adapter that splits an iterator into two new iterators that provide the same content? Indeed, this is exactly the description of itertools.tee, which appears perfectly suited to parallel iteration:
def max_and_sum_tee(it):
    it1, it2 = itertools.tee(it)
    p = sum(it1)  # XXX
    m = max(it2)
    return p, m

The above produces the correct result, but doesn't work the way we'd like it to. The trouble is that we're not iterating in parallel. Aggregate functions like sum and max never suspend - each insists on consuming all of the iterator content before producing the result. So sum will exhaust it1 before max has had a chance to run at all. Exhausting elements of it1 while leaving it2 alone will cause those elements to be accumulated inside an internal FIFO shared between the two iterators. That's unavoidable here - since max(it2) must see the same elements, tee has no choice but to accumulate them. (For more interesting details on tee, refer to this post.)
In other words, there is no difference between this implementation and the first one, except that the first one at least makes the buffering explicit. To eliminate buffering, sum and max must run in parallel, not one after the other.
Threads: concurrent.futures
Let's see what happens if we run the aggregate functions in separate threads, still using tee to duplicate the original iterator:
def max_and_sum_threads_simple(it):
    it1, it2 = itertools.tee(it)

    with concurrent.futures.ThreadPoolExecutor(2) as executor:
        sum_future = executor.submit(lambda: sum(it1))
        max_future = executor.submit(lambda: max(it2))

    return sum_future.result(), max_future.result()

Now sum and max actually run in parallel (as much as the GIL permits), threads being managed by the excellent concurrent.futures module. It has a fatal flaw, however: for tee not to buffer the data, sum and max must process their items at exactly the same rate. If one is even a little bit faster than the other, they will drift apart, and tee will buffer all intermediate elements. Since there is no way to predict how fast each will run, the amount of buffering is both unpredictable and has the nasty worst case of buffering everything.
To ensure that no buffering occurs, tee must be replaced with a custom generator that buffers nothing and blocks until all the consumers have observed the previous value before proceeding to the next one. As before, each consumer runs in its own thread, but now the calling thread is busy running a producer, a loop that actually iterates over the source iterator and signals that a new value is available. Here is an implementation:
def max_and_sum_threads(it):
    STOP = object()
    next_val = None
    consumed = threading.Barrier(2 + 1)  # 2 consumers + 1 producer
    val_id = 0
    got_val = threading.Condition()

    def send(val):
        nonlocal next_val, val_id
        consumed.wait()
        with got_val:
            next_val = val
            val_id += 1
            got_val.notify_all()

    def produce():
        for elem in it:
            send(elem)
        send(STOP)

    def consume():
        last_val_id = -1
        while True:
            consumed.wait()
            with got_val:
                got_val.wait_for(lambda: val_id != last_val_id)
            if next_val is STOP:
                return
            yield next_val
            last_val_id = val_id

    with concurrent.futures.ThreadPoolExecutor(2) as executor:
        sum_future = executor.submit(lambda: sum(consume()))
        max_future = executor.submit(lambda: max(consume()))
        produce()

    return sum_future.result(), max_future.result()

This is quite some amount of code for something so simple conceptually, but it is necessary for correct operation.
produce() loops over the outside iterator and sends the items to the consumers, one value at a time. It uses a barrier, a convenient synchronization primitive added in Python 3.2, to wait until all consumers are done with the old value before overwriting it with the new one in next_val. Once the new value is actually ready, a condition is broadcast. consume() is a generator that transmits the produced values as they arrive, until detecting STOP. The code can be generalized run any number of aggregate functions in parallel by creating consumers in a loop, and adjusting their number when creating the barrier.
The downside of this implementation is that it requires creation of threads (possibly alleviated by making the thread pool global) and a lot of very careful synchronization at each iteration pass. This synchronization destroys performance - this version is almost 2000 times slower than the single-threaded tee, and 475 times slower than the simple but non-deterministic threaded version.
Still, as long as threads are used, there is no avoiding synchronization in some form. To completely eliminate synchronization, we must abandon threads and switch to cooperative multi-tasking. The question is is it possible to suspend execution of ordinary synchronous functions like sum and max in order to switch between them?
Fibers: greenlet
It turns out that the greenlet third-party extension module enables exactly that. Greenlets are an implementation of fibers, lightweight micro-threads that switch between each other explicitly. This is sort of like Python generators, which use yield to suspend, except greenlets offer a much more flexible suspension mechanism, allowing one to choose who to suspend to.
This makes it fairly easy to port the threaded version of max_and_sum to greenlets:
def max_and_sum_greenlet(it):
    STOP = object()
    consumers = None

    def send(val):
        for g in consumers:
            g.switch(val)

    def produce():
        for elem in it:
            send(elem)
        send(STOP)

    def consume():
        g_produce = greenlet.getcurrent().parent
        while True:
            val = g_produce.switch()
            if val is STOP:
                return
            yield val

    sum_result = []
    max_result = []
    gsum = greenlet.greenlet(lambda: sum_result.append(sum(consume())))
    gsum.switch()
    gmax = greenlet.greenlet(lambda: max_result.append(max(consume())))
    gmax.switch()
    consumers = (gsum, gmax)
    produce()

    return sum_result[0], max_result[0]

The logic is the same, but with less code. As before, produce produces values retrieved from the source iterator, but its send doesn't bother with synchronization, as it doesn't need to when everything is single-threaded. Instead, it explicitly switches to every consumer in turn to do its thing, with the consumer dutifully switching right back. After going through all consumers, the producer is ready for the next iteration pass.
Results are retrieved using an intermediate single-element list because greenlet doesn't provide access to the return value of the target function (and neither does threading.Thread, which is why we opted for concurrent.futures above).
There are downsides to using greenlets, though. First, they don't come with the standard library, you need to install the greenlet extension. Then, greenlet is inherently non-portable because the stack-switching code is not supported by the OS and the compiler and can be considered somewhat of a hack (although an extremely clever one). A Python targeting WebAssembly or JVM or GraalVM would be very unlikely to support greenlet. This is not a pressing issue, but it's definitely something to keep in mind for the long haul.
Coroutines: asyncio
As of Python 3.5, Python provides native coroutines. Unlike greenlets, and similar to generators, coroutines are distinct from regular functions and must be defined using async def. Coroutines can't be easily executed from synchronous code, they must instead be processed by a scheduler which drives them to completion. The scheduler is also known as an event loop because its other job is to receive IO events and pass them to appropriate callbacks and coroutines. In the standard library, this is the role of the asyncio module.
Before implementing an asyncio-based max_and_sum, we must first resolve a hurdle. Unlike greenlet, asyncio is only able to suspend execution of coroutines, not of arbitrary functions. So we need to replace sum and max with coroutines that do essentially the same thing. This is as simple as implementing them in the obvious way, only replacing for with async for, enabling the async iterator to suspend the coroutine while waiting for the next value to arrive:
async def asum(it):
    s = 0
    async for elem in it:
        s += elem
    return s

async def amax(it):
    NONE_YET = object()
    largest = NONE_YET
    async for elem in it:
        if largest is NONE_YET or elem > largest:
            largest = elem
    if largest is NONE_YET:
        raise ValueError("amax() arg is an empty sequence")
    return largest

# or, using https://github.com/vxgmichel/aiostream
#
#from aiostream.stream import accumulate
#def asum(it):
#    return accumulate(it, initializer=0)
#def amax(it):
#    return accumulate(it, max)

One could reasonably ask if providing a new pair of aggregate functions is cheating; after all, the previous solutions were careful to use existing sum and max built-ins. The answer will depend on the exact interpretation of the question, but I would argue that the new functions are allowed because they are in no way specific to the task at hand. They do the exact same thing the built-ins do, but consuming async iterators. I suspect that the only reason such functions don't already exist somewhere in the standard library is due to coroutines and async iterators being a relatively new feature.
With that out of the way, we can proceed to write max_and_sum as a coroutine:
async def max_and_sum_asyncio(it):
    loop = asyncio.get_event_loop()
    STOP = object()

    next_val = loop.create_future()
    consumed = loop.create_future()
    used_cnt = 2  # number of consumers

    async def produce():
        for elem in it:
            next_val.set_result(elem)
            await consumed
        next_val.set_result(STOP)

    async def consume():
        nonlocal next_val, consumed, used_cnt
        while True:
            val = await next_val
            if val is STOP:
                return
            yield val
            used_cnt -= 1
            if not used_cnt:
                consumed.set_result(None)
                consumed = loop.create_future()
                next_val = loop.create_future()
                used_cnt = 2
            else:
                await consumed

    s, m, _ = await asyncio.gather(asum(consume()), amax(consume()),
                                   produce())
    return s, m

Although this version is based on switching between coroutines inside a single thread, just like the one using greenlet, it looks different. asyncio doesn't provide explicit switching of coroutines, it bases task switching on the await suspension/resumption primitive. The target of await can be another coroutine, but also an abstract "future", a value placeholder which will be filled in later by some other coroutine. Once the awaited value becomes available, the event loop automatically resumes execution of the coroutine, with the await expression evaluating to the provided value. So instead of produce switching to consumers, it suspends itself by awaiting a future that will arrive once all the consumers have observed the produced value.
consume() is an asynchronous generator, which is like an ordinary generator, except it creates an async iterator, which our aggregate coroutines are already prepared to accept by using async for. An async iterator's equivalent of __next__ is called __anext__ and is a coroutine, allowing the coroutine that exhausts the async iterator to suspend while waiting for the new value to arrive. When a running async generator suspends on an await, that is observed by async for as a suspension of the implicit __anext__ invocation. consume() does exactly that when it waits for the values provided by produce and, as they become available, transmits them to aggregate coroutines like asum and amax. Waiting is realized using the next_val future, which carries the next element from it. Awaiting that future inside consume() suspends the async generator, and with it the aggregate coroutine.
The advantage of this approach compared to greenlets' explicit switching is that it makes it much easier to combine coroutines that don't know of each other into the same event loop. For example, one could have two instances of max_and_sum running in parallel (in the same thread), or run a more complex aggregate function that invoked further async code to do calculations.
The following convenience function shows how to run the above from non-asyncio code:
def max_and_sum_asyncio_sync(it):
    # trivially instantiate the coroutine and execute it in the
    # default event loop
    coro = max_and_sum_asyncio(it)
    return asyncio.get_event_loop().run_until_complete(coro)

Performance
Measuring and comparing performance of these approaches to parallel execution can be misleading because sum and max do almost no processing, which over-stresses the overhead of parallelization. Treat these as you would treat any microbenchmarks, with a large grain of salt. Having said that, let's look at the numbers anyway!
Measurements were produced using Python 3.6 The functions were run only once and given range(10000), their time measured by subtracting time.time() before and after the execution. Here are the results:

max_and_sum_buffer and max_and_sum_tee: 0.66 ms - almost exact same time for both, with the tee version being a bit faster.
max_and_sum_threads_simple: 2.7 ms. This timing means very little because of non-deterministic buffering, so this might be measuring the time to start two threads and the synchronization internally performed by Python.
max_and_sum_threads: 1.29 seconds, by far the slowest option, ~2000 times slower than the fastest one. This horrible result is likely caused by a combination of the multiple synchronizations performed at each step of the iteration and their interaction with the GIL.
max_and_sum_greenlet: 25.5 ms, slow compared to the initial version, but much faster than the threaded version. With a sufficiently complex aggregate function, one can imagine using this version in production.
max_and_sum_asyncio: 351 ms, almost 14 times slower than the greenlet version. This is a disappointing result because asyncio coroutines are more lightweight than greenlets, and switching between them should be much faster than switching between fibers. It is likely that the overhead of running the coroutine scheduler and the event loop (which in this case is overkill given that the code does no IO) is destroying the performance on this micro-benchmark.
max_and_sum_asyncio using uvloop: 125 ms. This is more than twice the speed of regular asyncio, but still almost 5x slower than greenlet.

Running the examples under PyPy doesn't bring significant speedup, in fact most of the examples run slightly slower, even after running them several times to ensure JIT warmup. The asyncio function requires a rewrite not to use async generators (since PyPy as of this writing implements Python 3.5), and executes in somewhat under 100ms. This is comparable to CPython+uvloop performance, i.e. better, but not dramatic compared to greenlet.
Comment: An excellent answer, but why rolling back the edit to use the API of concurrent futures executor correctly?
Comment: @wim Thanks for the suggestion, but both versions are in fact correct. In this case a `lambda` was used intentionally to make the code consistent with the later version that changes `lambda: sum(it1)` to `lambda: sum(consume())`, and where the transformation to the positional argument wouldn't work.
Answer: If it holds for your aggregate functions that f(a,b,c,...) == f(a, f(b, f(c, ...))),then you could just cycle through your functions and feed them one element at a time, each time combining them with the result of the previous application, like reduce would do, e.g. like this:
def aggregate(iterator, *functions):
    first = next(iterator)
    result = [first] * len(functions)
    for item in iterator:
        for i, f in enumerate(functions):
            result[i] = f((result[i], item))
    return result

This is considerably slower (about 10-20 times) than just materializing the iterator in a list and applying the aggregate function on the list as a whole, or using itertools.tee (which basically does the same thing, internally), but it has the benefit of using no additional memory.
Note, however, that while this works well for functions like sum, min or max, it does not work for other aggregating functions, e.g. finding the mean or median element of an iterator, as mean(a, b, c) != mean(a, mean(b, c)). (For mean, you could of course just get the sum and divide it by the number of elements, but computing e.g. the median taking just one element at a time will be more challenging.)
Answer: I was trying to solve the same problem and understand asyncio a little better and I came up with an answer that I believe is the same as user4815162342, but uses an asyncio.queue per consumer instead of creating two futures per iteration. Of course, it still has the downside of needing to re-write all your aggregation functions as async def coroutines.
import asyncio

# Provided an iterable and an integer, return N iterables that will each yield
# the values of the input iterable. All iterables must be iterated
# simultaneously.
def tee_async(it, N):
    # larger queues would provide less context switching, but use more memory.
    qs = [asyncio.Queue(1) for _ in range(N)]
    # value to send to the queue to signal end of iteration
    STOP = object()

    # we have a sync iterator, we need an async iterator
    # use a queue to pass values from the sync iterator to here
    # implement an async iterator here to pass the values to the consumer coroutine
    # bug warning: this hangs if one of the consumers does not finish iterating
    async def QueueIterator(q: asyncio.Queue):
        while True:
            i = await q.get()
            print(f"got {i}")
            if i is STOP:
                break
            yield i

    # A coroutine to consume the input iterator
    async def IteratorConsumer():
        # note: the iterator might advance to the next value before the
        # consumers have started with the previous value. IE the first aggregator
        # will work on it[0] AFTER we have loaded it[1] here.
        for i in it:
            for j, q in enumerate(qs):
                print(f"putting {i} in {j}")
                await q.put(i)
        for j, q in enumerate(qs):
            print(f"putting END_ITER in {j}")
            await q.put(STOP)

    asyncio.create_task(IteratorConsumer())
    return [QueueIterator(q) for q in qs]

# Provided an iterable and a list of aggregation coroutines, send each iterated
# value to each aggregation coroutine and return a list of the return values.
async def aggregate(it, aggregators):
    tees = tee_async(it, len(aggregators))
    tasks = []

    # if using recent python, try: async with asyncio.TaskGroup() as tg:
    tasks = [asyncio.create_task(a(t)) for a, t in zip(aggregators, tees)]

    return [await t for t in tasks]

# Provided an iterable and a list of aggregation coroutines, send each iterated
# value to each aggregation coroutine and return a list of the return values.
def aggregate_without_storing_everything(it, aggregators):
    return asyncio.run(aggregate(it, aggregators))

async def amax(it):
    max = None
    async for i in it:
        if max is None or i > max:
            max = i
    return max

async def acount(it):
    c = 0
    async for i in it:
        c += 1
    return c

def main():
    print(aggregate_without_storing_everything(range(3), [amax, acount]))

if __name__ == "__main__":
    main()

I benchmarked this against the max_and_sum_asyncio_sync function, the queue based approach here is significantly slower until the queue size is greater than 5. However both are incredibly slow, the point of doing this is that the iteration would not fit in memory, but in my tests an iteration that would not fit in memory would take days to run. This is not a good approach in practice.


Find $5$ numbers where the sum of all pairs gives the results $110, 112, 113, 114, 115, 116, 117, 118, 120, 121$

Question:
Find $5$ numbers where the sum of the pairs gives the results $110, 112, 113, 114, 115, 116, 117, 118, 120, 121$

I have been trying on this question for some time and it seems easy at first glance, but later on, I was unable to start on the question. I tried turning these into equations with $a_1, a_2, a_3, a_4, \text{ and }a_5$ but couldn't as it is not determined which $2$ numbers give which sum. I was, however, able to achieve that $a_1+a_2+a_3+a_4+a_5=289$ (which is obvious). Now is there anyway I could continue without guessing. Thank you.
Answer: As there are no duplicates among the pair sums, the five numbers are distinct. So wlog. $a_1<a_2<a_3<a_4<a_5$. Then $110=a_1+a_2$, $112=a_1+a_3$, which makes $a_3=a_2+2$. Similarly, we find $a_4=a_3+1$ from the last two entries $120,121$. So far we have found that the numbers are
$$a_1, a_2, a_2+2, a_2+3, a_5.$$
This also tells us that $a_1+a_4=113$ and that $a_2+a_5=118$.
Now that the three pair sums $a_2+a_3=2a_2+2$, $a_2+a_4=2a_2+3$, $a_3+a_4=2a_2+5$ must occur among $114,115,116,117$. The only possible match is that $a_2+a_3=114$, i.e., $a_2=56$. The rest follows easily from here.


Displaying data on a map

Question: I have been asked to review a map based application. The map displays planning applications for a location and the user can filter results. Results are paginated to 10 per page.
The developer said that the information might become very dense and that paginating makes the map simpler:

I have many issues with this including:

the filters reduce map complexity, not pagination
pagination hides results from users

My question: Is pagination a good way to simplify the information on the map?
Answer: Yes, limiting the number of results on the map will simplify the map, however...
...it creates a bias that could influence your user in either a positive or negative way. There are a lot of factors that go into this though and there are two tracks of people I can see when using this map (Explorers and Beeliners). Explorers are going to go around the map, take their time, see what applications are out there, play with the filters, etc. Beeliners are going to go straight to the application they want with no goofing around, playing with filters, and so on.
With these two types of people in mind, there are a few other questions you need to ask yourself. Are your users going to be exploring or are they going to look up a specific application? What else can they do? Are they allowed to edit the application?
Based on the two groups of people I described above, my suggestion would be to show all of the points, and use a clustering algorithm to show a pod with a large number in them (like in the image below).

Clustering on Google Maps or Leaflet would be a great way to have all of your data available to the customer while not providing bias. It also allows for both scenarios of people (explorers and beeliners) which caters to the largest number of people. Finally, you would still be able to apply multiple filters to the markers and allow your users to see any variation of the data they choose.
Answer: Just a tip, your current example lacks two key aspects of design that all Google Maps implementations should heed to.

Difference
Remember to use different colours, shapes and styles to represent differing pins on the map. Right now I take it you have granted, refused and not yet decided, but how does one know whether a pin is of one type and not the other? What support do you have for colour-blind users when pins are differentiated simply by colour? Provide a light colour differing scheme and an even lighter shape differing scheme and you solve both these issues simultaenously.
A bad example:

A better example:

Layering
Pins should never overlap. There's nothing worse than destroying your model by making some pins unavailable simply because they're too hard to click on or are dominated by those around them. Clustering and grouping options play nice roles but eventually you have to provide an option to see this detail. This is up to you on how to implement, via pagination, etc.
I just wanted to provide my two points (cents).
Comment: already on the colours bro' ! http://i.imgur.com/wVAhjKr.png
Comment: Colours don't do much without shape though remember. ;)
Comment: working that in
Comment: i didnt down vote. no idea why it was downvoted.
Comment: People are silly. *shrug*

Displaying data on a map