Q: harmless coloured water vs harmlessly coloured water In the passage...

The remarkable thing about many of the medicines dismissed then as 'snake oil' is not so much that they failed to live up the outrageous claims made for them - those that weren't harmless coloured water could be positively dangerous."

I tried to decompose this super complex sentence, however it is beyond my capability now. I need to study more! I decomposed it like this:
The remarkable thing about many of the medicines (that then are dismissed as 'snake oil' that is not so much that the medicines failed to live up the claims that were made for them - those that were harm coloured water)  could be positively dangerous.

*

*Is that correct?

*Why did they use "harmless coloured water"? Shouldn't the correct form be "adv+adj+N"?

*shouldn't it be "harmlessly coloured water"?

A: Adjectives modify nouns and pronouns (and words that are used as nouns). Adverbs modify verbs and adjectives.
Harmless is an adjective. As @Kugelblitz indicates in his answer, it modifies water. The water is both harmless and coloured (we AmEs understand it despite the superfluous U).
If harmlessly were used, it would mean the coloration was harmless, rather than the water. While such a meaning is conceivable, as in

the water was harmlessly colored with vegetable dye

it does not really fit in this context. The discussion is about the harmlessness (or lack thereof) of the product itself. The false medicines could be dangerous regardless of the appearance.
This does not rule out the possibility that in some instances, the so-called snake oil was made harmful by the very adulterants that provided the coloration. But in the sentences as offered, the characteristics, harmless and colored, are effectively independent.

A:
The remarkable thing about many of the medicines dismissed then as
  'snake oil' is not so much that they failed to live up [to] the outrageous
  claims made for them — those that weren't harmless coloured water
  could be positively dangerous."

Eels have slippery slimy bodies.
Adjective adjective.
Some potions that used to be called medicines were simply harmless colored water.
Adjective adjective.
The two adjectives are modifying the noun.  It is possible to have an adverb modify the adjective:
I would like some lightly steeped tea, please.

...dismissed then as "snake-oil"...

dismissed back in those days as "snake-oil"
Normally we would expect to find "but" or "rather" or "but rather" instead of the dash. Let's look at the clauses (this clause-layout could be refined further but we won't do that right now):
The remarkable thing about many of the medicines
  {which were} dismissed then as 'snake oil'
  is not so much
  that they failed to live up [to] the outrageous claims made for them
 {but rather that those which} weren't harmless coloured water could be positively dangerous.
The dash was used here instead of the somewhat wordy "but rather that those which", although the wordy version might have been clearer, especially since the author used a rhetorical phrase ("is not so much") that seems to promise a parallel clause structure.  BTW, this practice of leaving out a conjunction is called asyndeton.

A: *

*I think the sentence is right. I would make one change by adding a comma after 'them'. (I think it's not necessary; just personal preference...):
The remarkable thing about many of the medicines dismissed then as
'snake oil' is not so much that they failed to live up the
outrageous claims made for them , - those that weren't harmless
coloured water could be positively dangerous.

*In this case, I believe both the words 'harmless' and 'coloured' are adjectives to the word 'water'.

A: We have a composite noun

coloured water

And we describe that coloured water as being harmless.
We could also start with

water

and decide to undertake a process to colour it, and want to do that colouring harmlessly. We would then have

harmlessly coloured water

The sentence you are analysing the author is describing the medicine, the coloured water. So harmless is used.


Q: Duplicating items already in array Every time I run the app, and then re-run it, it saves the same items into the NSUserDefaults even if it is already there.
I tried to fix that with contains code, but it hasn't worked.
What am I missing?
    for days in results! {
        let nD = DayClass()
        nD.dayOfTheWeek = days[“D”] as! String
        let defaults = NSUserDefaults.standardUserDefaults()
            if var existingArr = defaults.arrayForKey("D") as? [String] {
                if existingArr.contains(days["D"] as! String) == false {
                    existingArr.append(nd.dayOfTheWeek)
                }
            } else {
                defaults.setObject([nD.dayOfTheWeek], forKey: "D")
            }
        }

A:
Every time I run the app, and then re-run it, it saves the same items into the NSUserDefaults even if it is already there.

Yes, because that's exactly what your code does:
defaults.setObject(existingArr, forKey: "D")

But what is existingArr? It's the defaults you've just loaded before:
if var existingArr = NSUserDefaults.standardUserDefaults().arrayForKey("D") as? [String]

So what happens is that when you enter the .contains branch, you always do the same operation: you save the existing array.
Contrary to what your comment in the code states, you're not appending anything to any array in that block, you're saving the existing one.


Q: Error inflating class  Android Добрый день. Подскажите, какие причины могут вызывать Error inflating class ? Например 2 разметки. В первой все отрабатывает, при загрузки торой приложение падает.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.widget.lavkaviews.text.Text
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="3 товара на сумму"
        android:id="@+id/description"
        android:textColor="@color/black" />
    <com.widget.lavkaviews.text.Text
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/summ"
        android:layout_alignParentRight="true"
        android:textColor="@color/black"
        android:layout_toLeftOf="@+id/ruble"
        android:layout_alignBottom="@+id/description" />
    <com.widget.lavkaviews.PriceText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/finish"
        android:text="ОФОРМИТЬ"
        android:layout_below="@+id/description"
        android:gravity="center"
        android:textColor="@color/main"
        android:background="@color/lavka_main_red" />

</RelativeLayout>

Вторая
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="8dp"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <!--android:background="@color/main"-->

    <ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:id="@+id/image" />
    <com.widget.lavkaviews.text.Text
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text=""
        android:id="@+id/title"
        android:textColor="@color/black"
        android:maxLines="2"
        android:layout_toRightOf="@+id/image" />

    <com.widget.lavkaviews.PriceText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/price"/>

    <!--<com.widget.lavkaviews.PriceText-->
        <!--android:layout_width="80dp"-->
        <!--android:layout_height="20dp"-->
        <!--android:id="@+id/price"-->
        <!--android:textColor="#262626"-->
        <!--android:layout_alignParentRight="true" />-->

    <com.widget.lavkaviews.Dropdown
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/portion"
        android:layout_toLeftOf="@+id/incrementor" />
    <!--android:layout_below="@+id/price"-->

    <com.widget.lavkaviews.Incrementor
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/incrementor"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/portion" />
    <com.widget.core.view.ProductNDIndicator
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/nd"/>

</RelativeLayout>

Класс, который не распознаётся - PriceText.Ошибка появляется и на физическом устройстве и на эмуляторе, в одном и том же месте, на второй разметке. Судяпо стектрейсу - в месте объявления. Отличий на мой взгляд нет.
FATAL EXCEPTION: main
                                                                       android.view.InflateException: Binary XML file line #23: Error inflating class <unknown>
                                                                           at android.view.LayoutInflater.createView(LayoutInflater.java:613)
                                                                           at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)
                                                                           at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
                                                                           at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
                                                                           at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
                                                                           at com.lavkalavka.pages.cart.CartFragment$CartAdapter.onCreateViewHolder(CartFragment.java:241)
                                                                           at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:5223)
                                                                           at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4449)
                                                                           at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4359)
                                                                           at com.widget.core.layoutmanagers.LinearLayoutManager.measureChild(LinearLayoutManager.java:235)
                                                                           at com.widget.core.layoutmanagers.LinearLayoutManager.onMeasure(LinearLayoutManager.java:125)
                                                                           at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:2563)
                                                                           at android.view.View.measure(View.java:15172)
                                                                           at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:617)
                                                                           at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:399)
                                                                           at android.view.View.measure(View.java:15172)
                                                                           at android.widget.ScrollView.measureChildWithMargins(ScrollView.java:1196)
                                                                           at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                                                                           at android.widget.ScrollView.onMeasure(ScrollView.java:318)
                                                                           at android.view.View.measure(View.java:15172)
                                                                           at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814)
                                                                           at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                                                                           at android.view.View.measure(View.java:15172)
                                                                           at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814)
                                                                           at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1390)
                                                                           at android.widget.LinearLayout.measureVertical(LinearLayout.java:681)
                                                                           at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
                                                                           at android.view.View.measure(View.java:15172)
                                                                           at android.widget.ScrollView.measureChildWithMargins(ScrollView.java:1196)
                                                                           at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                                                                           at android.widget.ScrollView.onMeasure(ScrollView.java:318)
                                                                           at android.view.View.measure(View.java:15172)
                                                                           at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:617)
                                                                           at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:399)
                                                                           at android.view.View.measure(View.java:15172)
                                                                           at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:940)
                                                                           at android.view.View.measure(View.java:15172)
                                                                           at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814)
                                                                           at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                                                                           at android.support.v7.internal.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
                                                                           at android.view.View.measure(View.java:15172)
                                                                           at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814)
                                                                           at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1390)
                                                                           at android.widget.LinearLayout.measureVertical(LinearLayout.java:681)
                                                                           at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
                                                                           at android.view.View.measure(View.java:15172)
                                                                           at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814)
                                                                           at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                                                                           at android.view.View.measure(View.java:15172)
                                                                           at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814)
                                                                           at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1390)
                                                                           at android.widget.LinearLayout.measureVertical(LinearLayout.java:681)
                                                                           at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
                                                                           at android.view.View.measure(View.java:15172)
                                                                           at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814)
                                                                           at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                                                                           at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2148)
                                                                        at android.view.View.


Q: Single postgres transaction locks xmin for the whole cluster One of my applications performs a lock with a following request
SELECT … FROM locks WHERE id = 1 FOR UPDATE SKIP LOCKED;

This query lasts as long as application lifetime. Table itself contains only one column with a single row id = 1. I know it's not the best approach to acquire locks and I expect xmin for that database to stuck with this SELECT … FOR UPDATE … xid.
But in fact I'm getting situation where all transactions in my cluster, even in another databases are stuck with that xmin, including autovacuum process.
At first I was thinking that streaming replication with enabled hot_standby_feedback may be involved somehow, but it's continues to happen even with replication turned off at all.
Server version is 11.3.
There is no long running prepared transactions in pg_prepared_xacts or any replication running. Xmin blocks cluster-wide exactly on SELECT FOR UPDATE xid.


Q: Vim: no highlighting at startup I am using vim together with NERDTree and MiniBufExplorer. My colorscheme is peaksea. If I start vim, no syntax is highlighted in the first buffer. The other buffers have syntax highlighted. I have "syntax enable" in my vimrc. If I type :edit the syntax gets highlighted. So I tried
autocmd VimEnter * edit

but still nothing is highlighted. Did anyone encounter a similar problem or has anyone an idea how to fix this?

A: I remapped F12 to redo my syntax highlighting in case it gets messed up:
nnoremap <F12> :syntax sync fromstart<cr>

Maybe you can just run it as an autocmd event in your vimrc based on reading a new buffer?
autocmd BufReadPost * :syntax sync fromstart


Q: AWK Replace strings by the same strings with underscores I have three files. One is the original file, another contains a part of the lines of the original and another file with the modified parts have to replace the original.
And do not even know where to start. Can you help me?
Match file:

a demandé de montrer
grandes vacances
de faire
a montré
a remis
bien posé
n '
quand il l '
arrière du véhicule
modèle essence

Replace file:

a_demandé_de_montrer
grandes_vacances
de_faire
a_montré
a_remis
bien_posé
n_'
quand_il_l_'
arrière_du_véhicule
modèle_essence

Original file:

A 120km/h, la consommation tourne autour de 7.5l/100km si le vent est dans le dos...
A ce jour, je suis totalement satisfaite
A ce moment-là aux grandes vacances on m'a demandé de montrer le bon.
A chacun son choix
A chaque fois c'est moi qui dois les recontacter.
A eux de faire leurs avis....
A l'achat, le vendeur m'a montré comment rabattre le siège arrière, mais quand il l'a remis en place, ce n'était pas bien posé.
A l'arrière du véhicule, il était inscrit qu'il s'agissait d'une diesel, alors que c'est un modèle essence.
A la décharge du garage nous avons constaté un changement de personnel (nouveau directeur nouveau préposé a l accueil) laissons leur un temps d adaptation ...
A la limite, chacun son garagiste.

Desired output:

A 120km/h, la consommation tourne autour de 7.5l/100km si le vent est dans le dos...
A ce jour, je suis totalement satisfaite
A ce moment-là aux grandes vacances on m'a_demandé_de_montrer le bon.
A chacun son choix
J'avais droit aux grandes_vacances à l'entretien kit vacances.
A chaque fois c'est moi qui dois les recontacter.
A eux de_faire leurs avis....
A l'achat, le vendeur m'a_montré comment rabattre le siège arrière, mais quand il l'a_remis en place, ce n'était pas **bien_posé**.
A l'arrière_du_véhicule, il était inscrit qu'il s'agissait d'une diesel, alors que c'est un modèle_essence.
A la décharge du garage nous avons constaté un changement de personnel (nouveau directeur nouveau préposé a l accueil) laissons leur un temps d adaptation ...
A la limite, chacun son garagiste.

A: You didn't show any effort on the implementation but this should solve your problem.
awk -F"\t" 'NR==FNR{a[$1]=$2;next}
                   {for(k in a) gsub(k,a[k])}1' <(paste search replace) text

create a lookup table, do the replacement based on lookup.

A: There may be a better way to do this, but if you would like to use AWK, you can asssign a variable for each file you read, build some arrays with the find and replace string, and then loop through each find/replace value:
awk '
  file == 1 { source[++s] = $0 }
  file == 2 { replace[++r] = $0 }
  file == 3 {
    for (i = 1; i < s; i++)
      { gsub (source[i], replace[i], $0)  }
    print
  }
' file=1 match_file \
  file=2 replace_file \
  file=3 original_file

I don't claim this is the most efficient way to do it, but I think it will do what you describe.

A: Here is one approach of solving this using awk:
#!/usr/bin/awk -f
FILENAME == ARGV[1] { m[FNR]=$0 } # Store the match word in an array
FILENAME == ARGV[2] { r[FNR]=$0 } # Store the replacement word in a second array
FILENAME == ARGV[3] { for (i in m) gsub(m[i],r[i]); print } # Do the replacement for every line in file3

Run it like this:
./script.awk match_file replace_file original_file

A: This is the output the first three codes.This is the output the first two codes. Perhaps the encoding?

a_demand▒_de_montreraa_demand▒_de_montreria_demand▒_de_montrersa_demand▒_de_montrersa_demand▒_de_montreroa_demand▒_de_montrerna_demand▒_de_montrersa_demand▒_de_montrer a_demand▒_de_montrerla_demand▒_de_montrerea_demand▒_de_montrerua_demand▒_de_montrerra_demand▒_de_montrer a_demand▒_de_montrerua_demand▒_de_montrerna_demand▒_de_montrer a_demand▒_de_montrerta_demand▒_de_montrerea_demand▒_de_montrerma_demand▒_de_montrerpa_demand▒_de_montrersa_demand▒_de_montrer a_demand▒_de_montrerda_demand▒_de_montrer a_demand▒_de_montreraa_demand▒_de_montrerda_demand▒_de_montreraa_demand▒_de_montrerpa_demand▒_de_montrerta_demand▒_de_montreraa_demand▒_de_montrerta_deman
d▒_de_montreria_demand▒_de_montreroa_demand▒_de_montrerna_demand▒_de_montrer a_demand▒_de_montrer.a_demand▒_de_montrer.a_demand▒_de_montrer.a_demand▒_de_montrer
a_demand▒_de_montrerAa_demand▒_de_montrer a_demand▒_de_montrerla_demand▒_de_montreraa_demand▒_de_montrer a_demand▒_de_montrerla_demand▒_de_montreria_demand▒_de_montrerma_demand▒_de_montreria_demand▒_de_montrerta_demand▒_de_montrerea_demand▒_de_montrer,a_demand▒_de_montrer a_demand▒_de_montrerca_demand▒_de_montrerha_demand▒_de_montreraa_demand▒_de_montrerca_demand▒_de_montrerua_demand▒_de_montrerna_demand▒

I tried this..

    BEGIN {
    while ((getline ln1 < mt) > 0)
    {
        source[++s] = ln1;
    }
    while ((getline ln2 < rp) > 0)
    {
        replace[++r] = ln2;
    }
    }
    {
    for ( i = 1; i < s; i++)
        gsub (source[i], replace[i], $0)
        print;
    }

A: With GNU awk for ARGIND (with other awks just add FNR==1{ARGIND++}):
$ cat tst.awk
ARGIND==1 { a[FNR] = $0; next }
ARGIND==2 { map[a[FNR]] = $0; next }
{
    for (m in map) {
        gsub(m,map[m])
    }
    print
}

$ awk -f tst.awk match.txt replace.txt original.txt
A 120km/h, la consommation tourne autour de 7.5l/100km si le vent est dans le dos...
A ce jour, je suis totalement satisfaite
A ce moment-là aux grandes_vacances on m'a_demandé_de_montrer le bon.
A chacun son choix
A chaque fois c'est moi qui dois les recontacter.
A eux de_faire leurs avis....
A l'achat, le vendeur m'a_montré comment rabattre le siège arrière, mais quand il l'a_remis en place, ce n'était pas bien_posé.
A l'arrière_du_véhicule, il était inscrit qu'il s'agissait d'une diesel, alors que c'est un modèle_essence.
A la décharge du garage nous avons constaté un changement de personnel (nouveau directeur nouveau préposé a l accueil) laissons leur un temps d adaptation ...
A la limite, chacun son garagiste.

Like all other solutions posted so far, the above will behave undesirably if you have regexp metachars in your match file or regexp capture group identifiers in your replace file. If that can happen use index() and substr() instead of gsub().


Q: GStreamer - Sample Plugin I am a newbie in gstreamer and trying to develop a sample plugin for captions decoding.
I have downloaded the gStreamer Plugin template: based on this information.
When I launched the plugin from command line, it is working fine.
I wrote a sample application to verify the plugin. But now, I am facing a problem in setting pipeline state to PLAYING. Below is the code snippet
Any inputs would be of great help.
Thanks in advance,
Kranti

gst_init(NULL, NULL);

loop = g_main_loop_new (NULL, TRUE);

g_print("\n Gstreamer is Initialized and Created the loop ");

pipeline = gst_pipeline_new ("pipeline");

source = gst_element_factory_make ("filesrc", "source");

filter = gst_element_factory_make ("myfilter", "testfilter");

sink = gst_element_factory_make ("fakesink", "sink");

if((NULL != pipeline) && (NULL != source) && (NULL != filter) && (NULL != sink))
{
    g_print("\n Successfully created the factory elements ");

    g_object_set(G_OBJECT (source), "location", fileName, NULL);
    g_print("\n Set the file name \n");

    g_object_set(G_OBJECT (filter), "silent", 1, NULL);
    g_print("\n Set the silent type \n");

    /* we add a message handler */
    bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline));
    bus_watch_id = gst_bus_add_watch (bus, bus_call, loop);
    gst_object_unref (bus);
    g_print("\n Created bus and a monitor to watch it");

    gst_bin_add_many(GST_BIN(pipeline), source, filter, sink, NULL);
    gst_element_link_many(source, filter, sink);
    g_print("\n Added and Linked the factory elements");

    g_signal_connect (filter, "pad-added", G_CALLBACK (on_pad_added), filter);

    g_print ("Now reading: %s\n", "test.txt");
    g_print ("Setting the pipeline state to PLAYING ");
    ret = gst_element_set_state (pipeline, GST_STATE_PLAYING);
    if(ret == GST_STATE_CHANGE_FAILURE)
    {
        g_print("\n Failure in setting pipeline state to PLAYING \n");
    }

    else
    {
        g_print("\n Successfully set the pipeline state to playing \n");
    }
}

else
{
    g_print("\n Failure in creating factory elements");
}

A: After trying with few examples on gstreamer elements, found the problem.
Apart from filesrc, filter, fakesink:: If I add 'decoder' element also to the pipeline, then I am able to change the state to PLAYING
But why is that required - I am still trying to figure it out
And sometimes, the name used to create pipeline is also causing problems: Better to use some unique name rather than pipeline in gst_pipeline_new ("pipeline");


Q: how to decompose a nested list? I have a nested list and want to decompose it, exactly inverse of merging.
suppose i have list bellow:
f=[[1,2,3],[1,2,3],[1,2,3],[1,2,3]]

I am trying to obtain :
a1=[1,1,1,1]
a2=[2,2,2,2]
a3=[3,3,3,3]

I have tried this command:
a1=f[:][0:1]
a2=f[:][1:2]
a3=f[:][2:3]

but it does not work right. do you know my wrong ?

A: Try this:
f=[[1,2,3],[1,2,3],[1,2,3],[1,2,3]]

for i in zip(*f):
    print(i)

Output:
(1, 1, 1, 1)
(2, 2, 2, 2)
(3, 3, 3, 3)

A: zip() in conjunction with the * operator can be used to unzip a list and it return iterator of tuples.
Using map() to apply list on the iterator of tuples that we are getting from zip and it return an iterator. And then passing the iterator to list().
a = list(map(list, zip(*f)))

Or
a = []
for i in iter(map(list, zip(*f))):
    a.append(i)

A: What you should do in here is to use a for loop.
f=[[1,2,3],[1,2,3],[1,2,3],[1,2,3]]
a1=[x[0] for x in f]
a2=[x[1] for x in f]
a3=[x[2] for x in f]
print(a1,a2,a3)

>>>[1, 1, 1, 1] [2, 2, 2, 2] [3, 3, 3, 3]

A: You may do so like the following:
a = [list(i) for i in zip(*f)]

Now:
a[0] will be [1, 1, 1, 1]
a[1] will be [2, 2, 2, 2]
a[2] will be [3, 3, 3, 3]


Q: Building the computation graph form an expression I'm trying to implement different differentiation algorithms.
I'm having trouble breaking up an expression like this:
x = Variable()
y = Variable()
F_x = (x**2) * y + y + 2

I want to build the graph for F_x.
Edit: To clarify the graph of F_x would look something like

       Add
      / \
    Mult  Add
    /  \  / \
  EXP  y  y  2
  /  \
 x   2

A: You can use a python library called scipy which has functions that can produce graphs


Q: Generate 6 digit random number I just want to generate 6 digit random number, and the range should be start from 000000 to 999999.
new Random().nextInt(999999) is returning me number but it is not in 6 digit.

A: Its as simple as that, you can use your code and just do one thing extra here
String.format("%06d", number);

this will return your number in string format, so the "0" will be "000000".
Here is the code.
public static String getRandomNumberString() {
    // It will generate 6 digit random Number.
    // from 0 to 999999
    Random rnd = new Random();
    int number = rnd.nextInt(999999);

    // this will convert any number sequence into 6 character.
    return String.format("%06d", number);
}

A: If you need a six digit number it has to start at 100000
int i = new Random().nextInt(900000) + 100000;

Leading zeros do not have effect, 000000 is the same as 0. You can further simplify it with ThreadLocalRandom if you are on Java 7+:
int i = ThreadLocalRandom.current().nextInt(100000, 1000000)

A: 1 + nextInt(2) shall always give 1 or 2. You then multiply it by 10000 to satisfy your requirement and then add a number between [0..9999].
already solved here
public int gen()
{
    Random r = new Random( System.currentTimeMillis() );
    return ((1 + r.nextInt(2)) * 10000 + r.nextInt(10000));
}

A: i know it’s very difficult but you can do something like this:
create a class for BinaryNumber;
create a constructor that generate a char[] of 6 character where every single one is generated with a randomiser from 0 to 1
override the toStrig() method so that it will return the digits char[] as a string if you want to display it. then crate a method toInt() that esaminate the string char by char with a for and turn it in a decimal base number by multiplying current digit to 10 to the pow of i:
char[] digits = {‘1’ , ‘0’ , ‘1’ , ‘1’ , ‘0’ , ‘1’};
//random

int result = 0;
for( int i = 0; i < digits.length; i++) {
    result += Integer.parseInt(digits[i]) * Math.pow(10, i);
}

return result;

A: This is the code in java which generate a 6 digit random code.
import java.util.*;
public class HelloWorld{

     public static void main(String []args)
     {

        Random r=new Random();
                        HashSet<Integer> set= new HashSet<Integer>();
                        while(set.size()<1)
                        {
                            int ran=r.nextInt(99)+100000;
                            set.add(ran);
                        }
                        int len = 6;
                        String random=String.valueOf(len);
                        for(int  random1:set)
                        {
                            System.out.println(random1);
                            random=Integer.toString(random1);

                        }
     }
}


Q: How could I open an individual python file (or any code file) in an editor from the comand ( os.system (Path) ) or (os.startfile(path/Filename))? I am creating a script that opens an external file through two methods:
os.system(Path)

or
os.startfile(Path)

This works for Test files, however, it runs all code files like python which gets executed. I would like the option to open it in a text editor.
How would I do this in a python 2.7 script?
The text editor I use is VS Code.

A: you can use it like this:
os.system('code test_01.py')

A: You can use either one, but first, read the docs on what os.system and os.startfile does.

os.system(command)

Execute the command (a string) in a subshell. This is implemented by calling the Standard C function system(), and has the same limitations. Changes to sys.stdin, etc. are not reflected in the environment of the executed command.

So this basically runs the command string you pass to it. If your intention is to open a file in VS Code, then you need to check if you can use the VS Code command for opening files/folders from the command line:
code myfile.py

If that works on your terminal, then your Python script would basically just be:
os.system("code myfile.py")

os.startfile(path[, operation])

Start a file with its associated application.
When operation is not specified or 'open', this acts like double-clicking the file in Windows Explorer, or giving the file name as an argument to the start command from the interactive command shell: the file is opened with whatever application (if any) its extension is associated.

I assume you are on Windows, because startfile is only available on Windows.
The main thing here is that startfile is the same behavior as double-clicking the file in Windows Explorer. So, first make sure that when you double-click on a file, that it opens in VS Code. If it doesn't, then you need to associate that file with VS Code first. This is usually done by right-click > "Opens with.." then selecting VS Code from the list.

Once double-clicking on a file opens it in VS Code, then your Python script would simply be:
os.startfile("myfile.py", "open")

The "open" here is optional, but I prefer to be explicit.


Q: Setting a select option default to a previously set option In my modal window, I have a select where a user can select a breakfast meal from my database. By selecting a meal and submitting it, a record is saved in the database. However, I would like to achieve that when the user enters into the same modal window, whatever meal they have selected before hand will appear as the default option. I have created a query that checks to see if a meal has already been selected (optionquery1). Any ideas to achieve this? Thanks
On a side note, I'm not sure that I'm setting the date php variable currently. The day, month and year is stored in the html hidden inputs but not sure how to extract the values.

×

  <form action="my_planner.php" method="post">

  <input class="test" type="text" name="id1" value="" style="text-align:center; border:0px; font-weight:bold; font-size: 25px;"/>

  <input type="hidden" name="id" value=""/>
  <input type="hidden" name="month" value=""/>
  <input type="hidden" name="year" value=""/>

Breakfast:

<select id="breakfast" name="breakfast">
<option value="" disabled selected>Select your breakast</option>
<?
$meal='breakfast';
$date='<input type="hidden" name="id" value=""/>'.'<input type="hidden" name="month" value=""/>'.'<input type="hidden" name="year" value=""/>';
$query = $db->prepare("select * from recipe_category where categoryID=1");
$query->execute();

while ($results = $query->fetch()) {
    $recipeID=$results["recipeID"];
    $query3 = $db->prepare("select * from recipe where id=:recipeID");
    $dbParams3=array('recipeID'=>$recipeID);
    $query3->execute($dbParams3);
    $breakfast = $query3->fetchAll();

    $optionquery = $db->prepare("select * from user_planner where userID=:userID and date=:date and meal=:meal");
    $optionParams= array ('userID'=>$thisUser, 'date'=>$date,'meal'=>$meal);
    $optionquery->execute($optionParams);

    while ($results12 = $optionquery->fetch()) {
        $selectedmeal = $results12['recipeID'];
    }

    $optionquery1 = $db->prepare("select * from recipe where id=:recipeID");
    $optionParams1= array ('recipeID'=>$selectedmeal);
    $optionquery1->execute($optionParams1);

    while ($results123 = $optionquery1->fetch()) {
        $selectedrecipe = $results123['name'];
    }

    foreach($breakfast as $breakfast): ?>
        <option  value="<?= $breakfast['id']; ?>"><?= $breakfast['name']; ?></option>
    <?php endforeach;} ?>
</select>

A: Of course you can, you need to use the selected attribute on the <option> you want to show.
First remove the selected attribute from the first <option>:
<option value="" disabled>Select your breakast</option>

Then in the foreach loop you need an if condition:
$results123 = $optionquery1->fetch();
$selectedrecipe = $results123['id'];

foreach($breakfast as $breakfast): ?>
    <option  value="<?= $breakfast['id']; ?>" <?php if ($breakfast['id'] == $selectedrecipe) echo 'selected' ?>><?= $breakfast['name']; ?></option>
<?php endforeach;} ?>

Notice I have removed the while loop since we are sure Mysql will return only one record (WHERE ID = <ID>).


Q: How do I test code that uses `requestAnimationFrame` in jest? I want to write a jest unit test for a module that uses requestAnimationFrame and cancelAnimationFrame.
I tried overriding window.requestAnimationFrame with my own mock (as suggested in this answer), but the module keeps on using the implementation provided by jsdom.
My current approach is to use the (somehow) builtin requestAnimationFrame implementation from jsdom, which seems to use setTimeout under the hood, which should be mockable by using jest.useFakeTimers().
jest.useFakeTimers();

describe("fakeTimers", () => {
    test.only("setTimeout and trigger", () => {
        const order: number[] = [];

        expect(order).toEqual([]);
        setTimeout(t => order.push(1));
        expect(order).toEqual([]);
        jest.runAllTimers();
        expect(order).toEqual([1]);
    });

    test.only("requestAnimationFrame and runAllTimers", () => {
        const order: number[] = [];

        expect(order).toEqual([]);
        requestAnimationFrame(t => order.push(1));
        expect(order).toEqual([]);
        jest.runAllTimers();
        expect(order).toEqual([1]);
    });
});

The first test is successful, while the second fails, because order is empty.
What is the correct way to test code that relies on requestAnimationFrame(). Especially if I need to test conditions where a frame was cancelled?

A: I'm not sure this solution is perfect but this works for my case.
There are two key principles working here.
1) Create a delay that is based on requestAnimationFrame:
const waitRAF = () => new Promise(resolve => requestAnimationFrame(resolve));

2) Make the animation I am testing run very fast:
In my case the animation I was waiting on has a configurable duration which is set to 1 in my props data.
Another solution to this could potentially be running the waitRaf method multiple times but this will slow down tests.
You may also need to mock requestAnimationFrame but that is dependant on your setup, testing framework and implementation
My example test file (Vue app with Jest):
import { mount } from '@vue/test-utils';
import AnimatedCount from '@/components/AnimatedCount.vue';

const waitRAF = () => new Promise(resolve => requestAnimationFrame(resolve));

let wrapper;
describe('AnimatedCount.vue', () => {
  beforeEach(() => {
    wrapper = mount(AnimatedCount, {
      propsData: {
        value: 9,
        duration: 1,
        formatDisplayFn: (val) => "£" + val
      }
    });
  });

  it('renders a vue instance', () => {
    expect(wrapper.isVueInstance()).toBe(true);
  });

  describe('When a value is passed in', () => {
    it('should render the correct amount', async () => {
      const valueOutputElement = wrapper.get("span");
      wrapper.setProps({ value: 10 });

      await wrapper.vm.$nextTick();
      await waitRAF();

      expect(valueOutputElement.text()).toBe("£10");
    })
  })
});

A: So, I found the solution myself.
I really needed to override window.requestAnimationFrame and window.cancelAnimationFrame.
The problem was, that I did not include the mock module properly.
// mock_requestAnimationFrame.js

class RequestAnimationFrameMockSession {
    handleCounter = 0;
    queue = new Map();
    requestAnimationFrame(callback) {
        const handle = this.handleCounter++;
        this.queue.set(handle, callback);
        return handle;
    }
    cancelAnimationFrame(handle) {
        this.queue.delete(handle);
    }
    triggerNextAnimationFrame(time=performance.now()) {
        const nextEntry = this.queue.entries().next().value;
        if(nextEntry === undefined) return;

        const [nextHandle, nextCallback] = nextEntry;

        nextCallback(time);
        this.queue.delete(nextHandle);
    }
    triggerAllAnimationFrames(time=performance.now()) {
        while(this.queue.size > 0) this.triggerNextAnimationFrame(time);
    }
    reset() {
        this.queue.clear();
        this.handleCounter = 0;
    }
};

export const requestAnimationFrameMock = new RequestAnimationFrameMockSession();

window.requestAnimationFrame = requestAnimationFrameMock.requestAnimationFrame.bind(requestAnimationFrameMock);
window.cancelAnimationFrame = requestAnimationFrameMock.cancelAnimationFrame.bind(requestAnimationFrameMock);

The mock must be imported BEFORE any module is imported that might call requestAnimationFrame.
// mock_requestAnimationFrame.test.js

import { requestAnimationFrameMock } from "./mock_requestAnimationFrame";

describe("mock_requestAnimationFrame", () => {
    beforeEach(() => {
        requestAnimationFrameMock.reset();
    })
    test("reqest -> trigger", () => {
        const order = [];
        expect(requestAnimationFrameMock.queue.size).toBe(0);
        expect(order).toEqual([]);

        requestAnimationFrame(t => order.push(1));

        expect(requestAnimationFrameMock.queue.size).toBe(1);
        expect(order).toEqual([]);

        requestAnimationFrameMock.triggerNextAnimationFrame();

        expect(requestAnimationFrameMock.queue.size).toBe(0);
        expect(order).toEqual([1]);
    });

    test("reqest -> request -> trigger -> trigger", () => {
        const order = [];
        expect(requestAnimationFrameMock.queue.size).toBe(0);
        expect(order).toEqual([]);

        requestAnimationFrame(t => order.push(1));
        requestAnimationFrame(t => order.push(2));

        expect(requestAnimationFrameMock.queue.size).toBe(2);
        expect(order).toEqual([]);

        requestAnimationFrameMock.triggerNextAnimationFrame();

        expect(requestAnimationFrameMock.queue.size).toBe(1);
        expect(order).toEqual([1]);

        requestAnimationFrameMock.triggerNextAnimationFrame();

        expect(requestAnimationFrameMock.queue.size).toBe(0);
        expect(order).toEqual([1, 2]);
    });

    test("reqest -> cancel", () => {
        const order = [];
        expect(requestAnimationFrameMock.queue.size).toBe(0);
        expect(order).toEqual([]);

        const handle = requestAnimationFrame(t => order.push(1));

        expect(requestAnimationFrameMock.queue.size).toBe(1);
        expect(order).toEqual([]);

        cancelAnimationFrame(handle);

        expect(requestAnimationFrameMock.queue.size).toBe(0);
        expect(order).toEqual([]);
    });

    test("reqest -> request -> cancel(1) -> trigger", () => {
        const order = [];
        expect(requestAnimationFrameMock.queue.size).toBe(0);
        expect(order).toEqual([]);

        const handle = requestAnimationFrame(t => order.push(1));
        requestAnimationFrame(t => order.push(2));

        expect(requestAnimationFrameMock.queue.size).toBe(2);
        expect(order).toEqual([]);

        cancelAnimationFrame(handle);

        expect(requestAnimationFrameMock.queue.size).toBe(1);
        expect(order).toEqual([]);

        requestAnimationFrameMock.triggerNextAnimationFrame();

        expect(requestAnimationFrameMock.queue.size).toBe(0);
        expect(order).toEqual([2]);
    });

    test("reqest -> request -> cancel(2) -> trigger", () => {
        const order = [];
        expect(requestAnimationFrameMock.queue.size).toBe(0);
        expect(order).toEqual([]);

        requestAnimationFrame(t => order.push(1));
        const handle = requestAnimationFrame(t => order.push(2));

        expect(requestAnimationFrameMock.queue.size).toBe(2);
        expect(order).toEqual([]);

        cancelAnimationFrame(handle);

        expect(requestAnimationFrameMock.queue.size).toBe(1);
        expect(order).toEqual([]);

        requestAnimationFrameMock.triggerNextAnimationFrame();

        expect(requestAnimationFrameMock.queue.size).toBe(0);
        expect(order).toEqual([1]);
    });

    test("triggerAllAnimationFrames", () => {
        const order = [];
        expect(requestAnimationFrameMock.queue.size).toBe(0);
        expect(order).toEqual([]);

        requestAnimationFrame(t => order.push(1));
        requestAnimationFrame(t => order.push(2));

        requestAnimationFrameMock.triggerAllAnimationFrames();

        expect(order).toEqual([1,2]);

    });

    test("does not fail if triggerNextAnimationFrame() is called with an empty queue.", () => {
        requestAnimationFrameMock.triggerNextAnimationFrame();
    })
});

A: Here solution from the jest issue:
beforeEach(() => {
  jest.spyOn(window, 'requestAnimationFrame').mockImplementation(cb => cb());
});

afterEach(() => {
  window.requestAnimationFrame.mockRestore();
});

A: Here is my solution inspired by the first answer.
beforeEach(() => {
  jest.useFakeTimers();

  let count = 0;
  jest.spyOn(window, 'requestAnimationFrame').mockImplementation(cb => setTimeout(() => cb(100*(++count)), 100));
});

afterEach(() => {
  window.requestAnimationFrame.mockRestore();
  jest.clearAllTimers();
});

Then in test mock the timer:
act(() => {
  jest.advanceTimersByTime(200);
});

Directly call cb in mockImplementation will produce infinite call loop. So I make use of the Jest Timer Mocks to get it under control.

A: My solution in typescript. I figured by making time go very quickly each frame, it would make the animations go very (basically instant) fast. Might not be the right solution in certain cases but I'd say this will help many.
let requestAnimationFrameSpy: jest.SpyInstance<number, [callback: FrameRequestCallback]>;

beforeEach(() => {
    let time = 0;
    requestAnimationFrameSpy = jest.spyOn(window, 'requestAnimationFrame')
      .mockImplementation((callback: FrameRequestCallback): number => {
        callback(time+=1000000);
        return 0;
      });
});

afterEach(() => {
    requestAnimationFrameSpy.mockRestore();
});

A: The problem with previous version is that callbacks are called directly, which does not reflect the asynchronous nature of requestAnimationFrame.
Here is a mock which uses jest.useFakeTimers() to achieve this while giving you control when the code is executed:

beforeAll(() => {
  jest.useFakeTimers()
  let time = 0
  jest.spyOn(window, 'requestAnimationFrame').mockImplementation(
    // @ts-expect-error
    (cb) => {
    // we can then use fake timers to preserve the async nature of this call

    setTimeout(() => {
      time = time + 16 // 16 ms
      cb(time)
    }, 0)
  })
})
afterAll(() => {
  jest.useRealTimers()

  // @ts-expect-error
  window.requestAnimationFrame.mockRestore()
})

in your test you can then use:
yourFunction() // will schedule a requestAnimation
jest.runAllTimers() // execute the callback
expect(....) // check that it happened

This helps to contain Zalgo.


Q: How can I print information from a database (retrieved using java code) into html? I'm doing a web-development project in Java Eclipse IDE. I was wondering if there is a way I can print information from a database and show it on html. In my code below, I have a login function which searches the database table in mySQL for employee_id and password and then validates the login. In that table, there is a column called FirstName, which is the first name of the employee. How can I print the first name of the employee on the home page when they log in? (employeeHome.html)
Validate.java
public static boolean userIsAdmin(String employee_id, String password)
    {
        boolean st = false;
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/payroll_system", "root", "");
            PreparedStatement ps = con.prepareStatement("select * from employee_login where employeeID = ? and pwd = ? and Admin = 1 ");
            ps.setString(1, employee_id);
            ps.setString(2, password);
            ResultSet rs =ps.executeQuery();
             st = rs.next();

Login.java
if(Validate.userIsNotAdmin(employee_id, password)) {
            RequestDispatcher rs = request.getRequestDispatcher("employeeHome.html");
            rs.forward(request, response);

employeeHome.html
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Employee Home Page</title>

  <form action="Welcome" method="post">

Employee Home Page

    <input type="submit" value="View Personal Information" name="vpi">

    <input type="submit" value="View Expense Claims" name="vec">

    <input type="submit" value="View Payslips" name="vps">

    <input type="submit" value="Change Password" name="cp">
     </form>

A: We use Apache Wicket. We have been using it for 9 years or so and have built large scale enterprise applications for financial institutions. It works well with many technologies and it also has a unit testing framework which we use quite a bit. I highly recommend it. Here's a link. http://wicket.apache.org/
I've never used JSF so I can't vouch for it, but a lot of people use it and it is a Java standard. Either one of these technologies are built for solving the problem that you need to solve in an efficient way.
Now, if you want to do everything yourself and you don't want any frameworks in the way you could write a Java Servlet and output the HTML yourself. Here's a tutorial. There are many on the web. http://www.tutorialspoint.com/servlets/servlets-first-example
I recommend using a framework. Hopefully my answer will help you make an educated decision for your needs.


Q: Git commands in Visual Studio Code Terminal are not working, yet they work on the cmd prompt Error when trying a Git command in cmd:

The term 'git' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

I need this to work in the integrated terminal on Visual Studio Code!
I've already tried editing the path variables and the settings in Visual Studio Code. Nothing works.

A: "Not recognized" is normally the way terminals politely tell you they don't know what you typed means.
If you can use Git from a command line, then it's installed properly. You can use where git or which git depending on your command line to find the path of the functioning Git (if those don't work, please specify your terminal type in the question).
Once done, open Visual Studio Code, hit Ctrl + , to open settings and type git path in the search. Add this path, and you should be able to use Git in Visual Studio Code.


Q: Is it possible to store PART of the URL in to a variable or somehow using cypress and use it later? i need to store the url from my website in to an URL and use part of it for an API call

A: ...coming from the comments, I leave an answer here:
With version 6.0.0, Cypress introduced a new command: .intercept().
.intercept() allows you to manage the behavior of network requests. It supports fetch, it can intercept both request and response of your app API calls and so much more, official docs here.
Related to your case, make sure you declare your intercept command before the proper fetch action, let's say on the top of the test. Then, simply call it below in the body of the test by its alias:
cy.intercept('GET', '/project/*').as('myObject')

// ...

cy.wait('@myObject').its('response.body.data.id').then(objUUID => {
// here is your uuid
   cy.log(objUUID)
})

Note, that any other action related to this uuid should be done inside above callback: .then(objUUID => {}). In case you need it shared between different tests, then intercept your request inside .beforeEach() hook and assign the uuid in a context shared variable, however, this is a bad practice (more about aliases and variables, here)


Q: Call function when PyQt QWebEngineView is finished rendering QWebEngineView and QWebEnginePage have loadFinished, however, per the docs, "This signal is independent of script execution or page rendering." I want to call QWidget.render() (QWebEngineView implements QWidget) when the website is finished RENDERING... the only solution i've seen to this problem is to just give up and use QTimer to just wait 1000ms, which is a very bad solution in my opinion. If it takes less than 1000ms to render, time is wasted just waiting. If it takes more than 1000ms, then it's not finished rendering and even bigger problems emerge. I need to know exactly when QWebEnginePage completes its rendering so I can save it as an image as fast as possible.


Q: Finding the highest probability balls I'd appreciate any insights or references to research regarding the following:
Suppose you have a discrete metric space with a probability distribution on it. also, suppose that I'm given a number $k$. My problem is finding the highest probability ball.
A ball is the set of all points whose distance from a given point is less than or equal to $k$, and the "probability of the ball" is just the sum of the probabilities of this set of points.
The continuous case (less interesting in my case, but potentially helpful) would be to have a probability distribution on $R^n$, an finding the n-ball with the highest integral when integrating the density function on the $n$-ball.
This problem is an abstraction of a practical problem I try to solve. the solution of special case of $k=0$ (e.g. in which case a "ball" is just a single point) is just the mode of the distribution.
The general case arises for example in the following prediction problem: suppose you try to "predict" $n$ independent binary events. So every prediction is a binary $n$-tuple (with a probability distribution imposed on that space, based, for example, on assumptions, previous data, etc.). Now, suppose you are allowed to have a few mistakes in your prediction, and you try to find a prediction that maximizes the probability of "success" (that is, not making too many mistakes). The solution is exactly an n dimensional "ball" in the n-tuple space with the hamming metric.
Any idea, insight, or reference to relevant research would be much appreciated.

A: While the problem is in general intractable, your motivating example assumes independent events, which provides more than enough structure to solve this problem. Let me restate what you are trying to show to make sure that I understand:

You have $n$ independent Binomial random variables $X_i\sim \mathrm{Binomial}(p_i)$, $i=1,\dotsc,n$. Your goal is to find a point $\hat x \in \{0, 1\}^n$ that maximizes the probability
  $$\mathbb{P}\{\mathrm{d}_H(\hat x, {X})\le k\},$$
  where $\mathrm{d}_H$ denotes the Hamming metric and ${X}=(X_1,\dotsc,X_n)$ is the vector of binomial random variables.

Because of independence, the answer is trivial: Choose the most likely point, i.e., set
$$ \hat{x}_i = \begin{cases}  0,& p_i \le 0.5 \\ 1, &p_i >0.5.\end{cases}$$
Let's see why this is true using induction. The recipe above is trivially true for $n=1$. Let $n>1$ and suppose that the recipe holds for $n-1$. Then by independence,
$$ \mathbb{P}\{ \mathrm{d}_H(x,X)\le k\} = \mathbb{P}\{x_n = X_n\} \mathbb{P}\{\mathrm{d}_H({x}^{(n-1)}, X^{(n-1)}) \le k\} + \mathbb{P}\{x_n \ne X_n\} \mathbb{P}\{\mathrm{d}_H({x}^{(n-1)}, X^{(n-1)}) \le k-1\}$$
where we use the shorthand $x^{(n-1)} = (x_1,\dotsc,x_{n-1})$. By the induction hypothesis, our best possible choice of $x^{(n-1)}$ is $\hat{x}^{(n-1)}$, the most likely point of $X^{(n-1)}$. Moreover, since we always have
$$\mathbb{P}\{\mathrm{d}_H({x}^{(n-1)}, X^{(n-1)}) \le k\} \ge \mathbb{P}\{\mathrm{d}_H({x}^{(n-1)}, X^{(n-1)})\le k-1\},$$
we should always choose ${x}_n$ to maximize $\mathbb{P}\{\hat x_n = X_n\}$, which is the claimed recipe. #
Near independence?
Independence is clearly a very strong assumption, but in many cases we have reason to believe that the elements are nearly independent.   On common way to measure the "nearness" of (say, binary) random variables $X$ and $Y$ is the total variation metric:
$$ d_{TV}(X,Y):= \sup_{A \subset \{0,1\}^n} | \mathbb{P}\{ X \in A\} - \mathbb{P}\{Y\in A\} | $$
Taking, for example, $A:= \{y \mid d_H(x,y) \le k\}$, we find that for any binary random variables $X$, $Y$
$$ |\mathbb{P}\{ d_H(x, X) \le k\} - \mathbb{P}\{d_H(x,Y)\le k\}| \le d_{TV}(X,Y).$$
We conclude that when $Y$ is "almost independent" in the sense that the TV norm distance to an RV variable $X$ with independent entries is very small, then it is possible to argue that taking $\hat x$ to be the most likely vector for $X$ is a also a good choice for $Y$.
Care must be taken to apply this logic, however.  First of all, I've given no clue how to compute a TV metric; you'll need to use the specific facts at hand and some ingenuity.
A more subtle danger lies in the fact that the TV norm estimate will typically be useless unless $k$ is large. This is because the supremum in the TV will often occur for sets $A$ with measure near $1/2$.  Unless $k$ is large, it is likely that the Hamming ball of width $k$ has miniscule measure compared to the TV norm.
You may be able to refine your arguments somewhat, but the ability to control the error using this approach is (once again) strongly dependent on your particular situation.


Q: How to Simulate Random Multivariate Correlated Data and Uncorrelated Data for a given correlation coefficient and P value in R? I want to simulate data with the same effect sizes and structure of my real data to perform sensitivity analysis for a pathway analysis(sem). Wesley has demonstrated how to simulate multivariate correlated data here. Is it possible to simulate data sets for a specified correlation and p-value and how? There are ten variables. The correlation and p value are as follows:
correlation matrix:
#          [,1]    [,2]    [,3]    [,4]    [,5]    [,6]    [,7]    [,8]    [,9]   [,10]
#  [1,]  1.0000 -0.3549  0.1522  0.0486  0.1426 -0.2742 -0.2421  0.0664  0.0419  0.1728
#  [2,] -0.3549  1.0000 -0.0428  0.1441 -0.5491  0.5022 -0.3591 -0.2976 -0.1794 -0.0635
#  [3,]  0.1522 -0.0428  1.0000  0.0300  0.3837 -0.3823  0.0217  0.0898  0.1018  0.0239
#  [4,]  0.0486  0.1441  0.0300  1.0000 -0.1121  0.0302 -0.1347 -0.0365 -0.0462 -0.0092
#  [5,]  0.1426 -0.5491  0.3837 -0.1121  1.0000 -0.2604  0.2168  0.3011  0.1409 -0.1480
#  [6,] -0.2742  0.5022 -0.3823  0.0302 -0.2604  1.0000 -0.1130 -0.0385 -0.0881  0.0599
#  [7,] -0.2421 -0.3591  0.0217 -0.1347  0.2168 -0.1130  1.0000  0.0697  0.1179 -0.1223
#  [8,]  0.0664 -0.2976  0.0898 -0.0365  0.3011 -0.0385  0.0697  1.0000  0.4907 -0.2471
#  [9,]  0.0419 -0.1794  0.1018 -0.0462  0.1409 -0.0881  0.1179  0.4907  1.0000 -0.1243
# [10,]  0.1728 -0.0635  0.0239 -0.0092 -0.1480  0.0599 -0.1223 -0.2471 -0.1243  1.0000

p-value:
#        [,1]  [,2]  [,3]  [,4]  [,5]  [,6]  [,7]  [,8]  [,9] [,10]
#  [1,]    NA 0.023 0.349 0.766 0.374 0.043 0.127 0.680 0.795 0.280
#  [2,] 0.023    NA 0.793 0.375 0.001 0.001 0.021 0.059 0.262 0.693
#  [3,] 0.349 0.793    NA 0.814 0.002 0.002 0.865 0.481 0.423 0.851
#  [4,] 0.766 0.375 0.814    NA 0.378 0.812 0.288 0.774 0.717 0.943
#  [5,] 0.374 0.001 0.002 0.378    NA 0.036 0.083 0.015 0.263 0.239
#  [6,] 0.043 0.001 0.002 0.812 0.036    NA 0.370 0.761 0.486 0.636
#  [7,] 0.127 0.021 0.865 0.288 0.083 0.370    NA 0.581 0.349 0.332
#  [8,] 0.680 0.059 0.481 0.774 0.015 0.761 0.581    NA 0.001 0.047
#  [9,] 0.795 0.262 0.423 0.717 0.263 0.486 0.349 0.001    NA 0.324
# [10,] 0.280 0.693 0.851 0.943 0.239 0.636 0.332 0.047 0.324    NA

A: $p$-values for Pearson's correlation are usually derived from $t$-distribution with $n-2$ degrees of freedom using the formula
$$ t = r\sqrt{\frac{n-2}{1 - r^2}} $$
where $r$ is the estimated correlation coefficient and $n$ is sample size. So if you already know how to simulate correlated data, then the only thing that you need is use appropriate sample size for $p$-value to match.


Q: SFTP logs to different files I'm configuring an SFTP server and having some issues with logs ending up in different places, depending on a group membership. This is on RHEL 8 but the same issue exists on an old RHEL 6 machine. Most users are SFTP only and have no shell access, this is configured by membership in the ftpnoshell group. Some users have a shell and can ssh to the server as well.
Here's the operative part of /etc/ssh/sshd_config:
Subsystem       sftp    internal-sftp -f LOCAL4 -l VERBOSE -d %u

Match Group ftpnoshell
        ChrootDirectory /home
        X11Forwarding no
        AllowTCPForwarding no
        ForceCommand internal-sftp -f LOCAL4 -l VERBOSE -d %u

This is in /etc/rsyslog.conf:
local4.*                                                /var/log/sftp.log

I would expect logs for all users to end up in /var/log/sftp.log, however logs for members of ftpnoshell are instead written in /var/log/secure.
Any ideas?


Q: Cleanup after exception I have a bit of code that resembles the following:
try:
    fn()
except ErrorA as e:
    ... do something unique ...
    cleanup()
except ErrorB as e:
    ... do something unique ...
    cleanup()
except ErrorC as e:
    ... do something unique ...
    cleanup()

Is there any mechanism in Python that would allow me to call cleanup just once, only if an exception is raised? Basically the opposite of else.
The best I can think of is:
error = True
try:
    fn()
    error = False
except ErrorA as e:
    ... do something unique ...
except ErrorB as e:
    ... do something unique ...
except ErrorC as e:
    ... do something unique ...

if error:
    cleanup()

A: def _cleanup():
    # clean it up
    return

cleanup = _cleanup

try:
    # stuff
except:
    # handle it
else:
    cleanup = lambda: None

cleanup()

A: The most clear way I can think of is do exactly the opposite of else:
do_cleanup = True
try:
    fn()
except ErrorA as e:
    ... do something unique ...
except ErrorB as e:
    ... do something unique ...
except ErrorC as e:
    ... do something unique ...
else:
   do_cleanup = False

if do_cleanup:
    cleanup()

If the code is enclosed and lets itself be done, you can simplify it by returning or breaking in the else.

A: How about catching all the exceptions with one except clause and dividing up the different parts of your handling with if/elif blocks:
try:
    fn()
except (ErrorA, ErrorB, ErrorC) as e:
    if isinstance(e, ErrorA):
        ... do something unique ...
    elif isinstance(e, ErrorB):
        ... do something unique ...
    else: # isinstance(e, ErrorC)
        ... do something unique ...
    cleanup()


Q: Why gradle plugin 3.3.0 doesn't want to build google-services? I'm trying to Sync my project with gradle:3.3.0 , but in result file values.xml for google-services is not generated in folder: D:\Android\workspace\myproject\app\build\generated\res\google-services\debug\values\values.xml
Top level build file build.gradle:
 apply plugin: 'kotlin'

    buildscript {
        ext.kotlin_version = '1.3.11'
        repositories {
            google()
            jcenter()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:3.3.0'
            classpath 'com.google.gms:google-services:4.1.0'
            classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
          }
    }

    allprojects {
        repositories {
            mavenLocal()
            google()
            jcenter()
            mavenCentral()
            maven { url "https://jitpack.io" }
        }

        configurations.all {
            exclude group: 'org.jetbrains.kotlin', module: 'kotlin-stdlib-jre7'
        }
    }

    dependencies {
        implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    }

    compileKotlin {
        kotlinOptions {
            jvmTarget = "1.8"
        }
    }
    compileTestKotlin {
        kotlinOptions {
            jvmTarget = "1.8"
        }
    }

app/build.gradle:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'

android {
    ...
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

implementation "com.google.firebase:firebase-database:16.0.5"
implementation "com.google.firebase:firebase-messaging:17.3.4"
implementation "com.google.firebase:firebase-auth:16.1.0"
implementation 'com.google.android.gms:play-services-auth:16.0.1'
implementation 'com.google.firebase:firebase-storage:16.0.5'
}

apply plugin: 'com.google.gms.google-services'

google-services.json
File google-services.json is located in D:\Android\workspace\myproject\app\google-services.json
In result after run of app the error occurs:
 01-23 10:31:31.578 30044-30073/E/FA: GoogleService failed to initialize, status: 10, Missing google app id value from from string resources with name google_app_id.
01-23 10:31:31.578 30044-30073/E/FA: Missing google_app_id. Firebase Analytics disabled. See
01-23 10:31:33.758 30044-30044/ E/AndroidRuntime: FATAL EXCEPTION: main
    Process: , PID: 30044
    java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process . Make sure to call FirebaseApp.initializeApp(Context) first.
        at com.google.firebase.FirebaseApp.getInstance(com.google.firebase:firebase-common@@16.0.4:240)
        at com.google.firebase.auth.FirebaseAuth.getInstance(Unknown Source)

A: Remove dependencies block from top-level gradle file:
dependencies {
        implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    }

And update to classpath 'com.android.tools.build:gradle:3.3.0' and classpath 'com.google.gms:google-services:4.2.0'
In result your Gradle Files should be Like This For Android Studio 3.3 (stable channel)
build.gradle(project:yourProject)
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.3.11'
    repositories {
        google()
        jcenter()

        // Add repository
        maven {
            url 'https://maven.fabric.io/public'
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.2.0'
        classpath 'io.fabric.tools:gradle:1.26.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()

        // Add repository
        maven {
            url 'https://maven.google.com/'
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

build.gradle(Module:app)
apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

apply plugin: 'kotlin-kapt'

apply plugin: 'com.google.gms.google-services'

apply plugin: 'io.fabric'

repositories {
    maven { url 'https://maven.fabric.io/public' }
}

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "sanaebadi.info.teacherhandler"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE-FIREBASE.txt'
        exclude 'META-INF/NOTICE'

    }

    dataBinding {
        enabled = true
    }
}

dependencies {
    def room_version = "2.1.0-alpha03"
    def lifecycle_version = "2.0.0"

    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0-alpha01'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.0-alpha3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'

    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'com.google.android.material:material:1.1.0-alpha02'
    implementation 'androidx.recyclerview:recyclerview:1.0.0'

    //Firebase
    implementation 'com.google.firebase:firebase-core:16.0.6'
    implementation 'com.crashlytics.sdk.android:crashlytics:2.9.8'
    implementation 'com.google.firebase:firebase-messaging:17.3.4'
    implementation 'com.google.firebase:firebase-storage:16.0.5'
    implementation 'com.google.firebase:firebase-auth:16.1.0'
    implementation 'com.google.android.gms:play-services-auth:16.0.1'
    implementation 'com.google.firebase:firebase-database:16.0.5'
}

gradle-wrapper.properties
#Tue Jan 15 07:24:23 EST 2019
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.1-all.zip

A: update to classpath 'com.google.gms:google-services:4.2.0' in project level build.gradle.


Q: Chance constrained stochastic programming A stochastic programming optimizes the expectation of a cost function with respect to values.
\begin{cases}
{\boldsymbol x}=\text{argmin}~ E(f({\boldsymbol x}))\\
{\boldsymbol g}({\boldsymbol x})<{\boldsymbol 0}
\end{cases}
where $E$ refers to expectation.
A chance constrained programming is a programming with constrained chance
\begin{cases}
{\boldsymbol x}=\text{argmin}~ f({\boldsymbol x})\\
P({\boldsymbol g}({\boldsymbol x})<{\boldsymbol 0})>\alpha
\end{cases}
where $P$ refers to probability and $\alpha$ refers to the confidence level.

But I am looking for a different programming with both expectation and chance constrained properties like
\begin{cases}
{\boldsymbol x}=\text{argmin}~ E(f({\boldsymbol x}))\\
P({\boldsymbol g}({\boldsymbol x})<{\boldsymbol 0})>\alpha
\end{cases}

*

*Does such an optimization exist?

*Is such an optimization common?

*If yes, what is the name of this optimization?

*Is there any academic publication about this optimization?

A: I think your definition of a stochastic program is suspect (I have never seen it defined this way). It seems that you're saying that a stochastic program is an optimization problem of the form
\begin{equation}
\begin{array}{rl}
\min\ & \mathbb{E}_\xi[f(x,\xi)]\\
\text{s.t.}\ & g(x)\leqslant0
\end{array}
\end{equation}
where $\xi$ is some random variable. In many cases, such a problem would be uninteresting. For example, suppose (as is often done in the literature) that $f$ has the form
\begin{equation}
f(x,\xi)=\xi_1x_1+\dots+\xi_nx_n.
\end{equation}
where $\xi_i$ are  independent random variables. Then the objective function is given by
\begin{equation}
\mathbb{E}_\xi[f(x,\xi)]=\mathbb{E}_\xi[\xi_1x_i+\dots+\xi_nx_n]=\mathbb{E}[\xi_1]x_1+\dots+\mathbb{E}[\xi_n]x_n.
\end{equation}
Since the values $\mathbb{E}[\xi_i]$ are just constants, we've reduced the objective function to a (deterministic) affine function of $x$. This isn't really a stochastic program at all--we just replaced some random variables with their expected values.
This confusion makes it hard to address the rest of your question. In principle, chance constraints can be combined with lots of different models--it really depends on what you're modeling.
I would suggest two books to read up on this subject:

*

*Birge and Louveaux have a very good textbook (published by Springer) that introduces the fundamentals of stochastic programming. In particular, they introduce the concept of linear programming with recourse, which is at the heart of most stochastic programming as it is studied today.

*Prekopa wrote a seminal text (called simply "Stochastic Programming") which is much more technical than Birge and Louveaux, but treats chance constraints much more thoroughly. In particular, they explore different places where chance constraints can appear.


Q: ASP.NET Error with Database I have been learning ASP.NET and building a little customer portal. I used the built in CreateUserWizard. I wanted to look inside the ASPNETDB.MDF file to see how it was storing the users and maybe add some rows of my own. I opened the file in SQL Server Management Studio and viewed the file. I closed it with out saving.
Now when I try to run the program I get this new error:
The database 'C:\PROJECTS\PORTAL\PORTAL\APP_DATA\ASPNETDB.MDF' cannot be opened because it is version 706. This server supports version 662 and earlier. A downgrade path is not supported.
So I assume opening the project in SQL Server it upgraded the version to 706, How can I either delete this database and create a new one or change the version of the database to an support version.
Thanks

A: The following blog entry will help you
http://conceptdev.blogspot.com/2009/04/mdf-cannot-be-opened-because-it-is.html

A: As soon as you attached it to SQL Server 2012, the database was upgraded to version 706. As the error message suggests, there is no way to downgrade the file back to version 662 (SQL Server 2008 R2).
You can run the script found in your Visual Studio folder -
[drive:]\%windir%\Microsoft.NET\Framework\version\asp_regsql.

It'll display a UI for you to select the server to install a new copy on. Here's a MSDN article about it.


Q: css - vertical nested menu - can't get the nested styles right, it makes a bigger rectangle I am trying to make a vertical menu, but everytime when i show the sub menu on hover, it expands the previous element, making a 'bigger box'. I have no idea how to style that.
Dont want to use some jquery plugin if there is an css solution. I have also bootstrap3, but there is no support for nested dropdowns, dropdowns inside dropdowns ... the nested ones did not open...
JSFiddle link:  http://jsfiddle.net/WqW5j/
index.html

1

2

   3

3-1

3-2

3-2-1

3-2-2

3-2-2-1

3-2-2-2

css
        .main{
            list-style: none;
            padding:0px;
            margin: 0px;
        }
        .main li{
            background-color:#f1f1f1;
            padding: 10px;
            margin: 5px;
            float:left;
            clear:both;
        }
        .main li:hover{
            background-color:#d8d8d8;
        }

          .main .sub{
            display: none;
          }
          .sub > li > .sub{
            display: none;
          }

          .main > li:hover > .sub:nth-of-type(1){
            display: block;
            position: relative;
            left: 20px;
            top:-30px;
            list-style: none;
            float:left;
            width: 100px;
            clear: both;
          }

          .sub > li:hover > .sub{
            display: block;
            position: relative;
            left: 20px;
            top:-30px;
            list-style: none;
            float:left;
            width: 100px;
          }

A: To get the nested menu work make all the li items position:relative and make the ul displayed on hover as position:absolute.
Check this fiddle
HTML:

1

1-1

1-1-1

1-2-1

1-2

1-2-1

1-2-2

2

CSS
.main{
    list-style: none;
    padding:0px;
    margin: 0px;
  }
  .main li{
    background-color:#f1f1f1;
    padding: 10px;
    margin: 5px;
    float:left;
    clear:both;
    position:relative;
  }
  .main li:hover{
   background-color:#d8d8d8;
  }

  .main .sub{
    display: none;
    list-style:none;
    padding-left:0;
    width:auto;
  }

.main .sub li{
    float:none;
}

.main > li:hover > .sub{
    display:block;
    position:absolute;
    top:0;
    left:100%;
}

.sub li:hover .sub{
    display:block;
    position:absolute;
    top:0;
    left:100%;
}


Q: Best Practices consuming a Soap request over SSL Just have a quick a question regarding best practices.
I am connecting to a 3rd party api via soap over HTTPS.
To do this I have simply added a service reference to my application by entering the 3rd party wsdl address.
In my C# application I have simply instantiated the service passed in my api key and can successfully retrieve data.
I am aware that this would of failed if the servers ssl certificate didn't meet the following requirements.

*

*the URL in the certificate matches the URL I'm posting to

*the certificate is valid and trusted

*the certificate has not expired

However, is this secure enough? Is it possible for the ssl certificate to be hijacked or faked? Do I need to store a copy of the valid certificate locally and check the server certificate against the local copy?
Thanks
Ant


Q: UWP SerialDevice works only if I read it's properties So, I have some code for setting up my serial port in UWP (which is used with an USB-to-Serial adapter):
public async Task Init()
{
        string qFilter = SerialDevice.GetDeviceSelector("COM5");
        DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(qFilter);
        deviceId = devices.First().Id;
        var serialPort = await SerialDevice.FromIdAsync(deviceId);

        serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
        serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000);
        serialPort.BaudRate = 4800;
        serialPort.Parity = SerialParity.None;
        serialPort.StopBits = SerialStopBitCount.One;
        serialPort.DataBits = 8;
        serialPort.Handshake = SerialHandshake.None;
}

now, somewhere later in the code, I read a stream from the SerialDevice:
public async Task<string> ReadValueFromSerial()
{
        var dataReaderObject = new DataReader(serialPort.InputStream);
        uint ReadBufferLength = 1024;
        dataReaderObject.InputStreamOptions = InputStreamOptions.Partial;

        CancellationTokenSource cts = new CancellationTokenSource();
        //set timeout here.
        cts.CancelAfter(10000);
        var bytesRead = await dataReaderObject.LoadAsync(ReadBufferLength).AsTask(cts.Token);
        (...)
}

no above code hangs on the last line, altough I know, that the serial device is sending bytes to the serial port.
Funny thing is, that it works, when I put a breakpoint on the set-up part (the first snippet). But without a breakpoint and stepping through it, it just hangs, or times out.
By trials and errors I found out, that reading the serial device properties which I set in the set-up code, makes it magically work.
So after the code in the first snippet, I have added:
public async Task Init()
{
         (...)
         var s1 = " " + serialPort.BaudRate;
         var s2 = " " + serialPort.DataBits;
         var s3 = " " + serialPort.Parity.ToString();
}

And now the var bytesRead = await dataReaderObject.LoadAsync(ReadBufferLength).AsTask(cts.Token); doesn't hang anymore and the bytes are loaded. It works, which is great, but why?


Q: Is it necessary to build another project to fit mobile devices when using reactjs plus redux? As a simple project, we built the website using reactjs+redux. But now, business grows, we need to build the native apps to fit mobile devices, not only the mobile browser.
I did some read work about React Native, it seems not possible to use current JS code directly to build native apps for mobile.
Some of my colleague suggested to build another project for the mobile. But I'm wandering, how could the JS technique show its power to do fast iteration if I have to build another project just to do the same thing on the mobile.
I know Cordova and did some work on it, but not very much.
So, is there some guideline of integrating current JS code to Cordova?
or is there any suggestion?
Thanks.


Q: Updating displayed results after modifying Firestore doc React Native I have a list of games that I'm able to add to without issue using UseEffect and onSnapshot. I can modify an item in the list without issue, and return one set of results (with the updated data properly displaying). When I try to modify another item (or the item same again), I get this error:
Could not update game: TypeError: undefined is not an object (evaluating '_doc.data().numPlayers') because the results/list of games are null. I'm sure I have something wrong with my code, but I can't figure it out.
Thanks in advance!
Here is my code:
useEffect(() => {
      setIsLoading(true)
      let results = [];
      const unsubscribe = db
        .collection('games')
        .onSnapshot(
          (querySnapshot) => {
            querySnapshot.docChanges().forEach(change => {
              const id = change.doc.id;

              if (change.type === 'added') {
                const gameData = change.doc.data();
                gameData.id = id;
                results.push(gameData);
              }
              if (change.type === 'modified') {
                console.log('Modified game: ', id);
                results = results.map(game => {
                  if (game.id === id) {
                    return change.doc.data()
                  }
                  return game
                })
                console.log(results)
              }
              if (change.type === 'removed') {
                console.log('Removed game: ', id);
              }

          });
          setIsLoading(false);
          setGame(results);
          return () => unsubscribe
        },
        (err) => {
          setIsLoading(false);
          console.log("Data could not be fetched", err);
        }
      );
    }, []);

A: I forgot to add the doc ID to the gameData before adding it to the results. I did that in the "added" section, but not in the "modified" section (thinking that it was already included), forgetting that I hadn't added it as an actual field in the database (it just exists as the doc id).


Q: How to make HTML element square I would like to have square tiles in my react calendar. Currently width is calculated based on width of the whole calendar and I would like my height to be the same.

Html
<button class="react-calendar__tile react-calendar__tile--active react-calendar__tile--range react-calendar__tile--rangeStart react-calendar__tile--rangeEnd react-calendar__tile--rangeBothEnds react-calendar__month-view__days__day" type="button" style="flex: 0 0 14.2857%; overflow: hidden;">
    14
</button>

I have tried this
.booking-calendar .react-calendar__tile {
    flex: 0 0 14.2857%;
    overflow: hidden;
}
.booking-calendar .react-calendar__tile--active abbr {
    outline: 2px solid #444444;
    box-sizing: border-box;
    width: 100%;
    height: 100%;
    border-radius: 40px;
    font-weight: 700;
}

.booking-calendar .react-calendar__month-view__days__day abbr {
    padding: 10px;
    border-radius: 40px;
    display: inline-block;
    vertical-align: middle;
}

A: You can use the aspect-ration css property
https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio

.booking-calendar  {
    width: 400px;
    display: flex;
}

.booking-calendar .react-calendar__tile {
    width: 100%;
    aspect-ratio: 1 / 1;
    margin: 10px;
}

.booking-calendar .react-calendar__tile--active abbr {
    outline: 2px solid #444444;
    box-sizing: border-box;
    width: 100%;
    height: 100%;
    border-radius: 40px;
    font-weight: 700;
}

.booking-calendar .react-calendar__month-view__days__day abbr {
    padding: 10px;
    border-radius: 40px;
    display: flex;
    justify-content: center;
    align-items: center;

}

     <button class="react-calendar__tile react-calendar__tile--active react-calendar__tile--range react-calendar__tile--rangeStart react-calendar__tile--rangeEnd react-calendar__tile--rangeBothEnds react-calendar__month-view__days__day" type="button" style="overflow: hidden;">
    11
</button>
  <button class="react-calendar__tile react-calendar__tile--active react-calendar__tile--range react-calendar__tile--rangeStart react-calendar__tile--rangeEnd react-calendar__tile--rangeBothEnds react-calendar__month-view__days__day" type="button" style="overflow: hidden;">
    12
</button>
  <button class="react-calendar__tile react-calendar__tile--active react-calendar__tile--range react-calendar__tile--rangeStart react-calendar__tile--rangeEnd react-calendar__tile--rangeBothEnds react-calendar__month-view__days__day" type="button" style="overflow: hidden;">
    13
</button>
  <button class="react-calendar__tile react-calendar__tile--active react-calendar__tile--range react-calendar__tile--rangeStart react-calendar__tile--rangeEnd react-calendar__tile--rangeBothEnds react-calendar__month-view__days__day" type="button" style="overflow: hidden;">
    14
</button>

You will need to remove the flex inline style that collides with the aspect-ratio effect.


Q: How is the many-to-one function $f(x) = \frac{1}{x-1} + \frac{2}{x-2} + \frac{3}{x-3}$ decreasing? The function $f(x) = \frac{1}{x-1} + \frac{2}{x-2} + \frac{3}{x-3}$ is many-to-one, despite it having a strictly negative derivative (the domain being $\mathbb{R} - \{1,2,3\}$).  Why is this so?  Is there any way of knowing this without actually graphing $f(x)$, which seems rather difficult?

A: When we approach $x=1$ very close from the negative direction, $x-1$ will be a very small negative value and so $\frac{1}{x-1}$ will be a very large negative value. Approaching from the other side we have $\frac{1}{x-1}$ becoming a very positive value. In fact, it can become as large or as small as you like, provided you get as close to $x=1$ as necessary.
By looking at the other terms, we see that the same thing happens at $x=2$ and $x=3$ and we see that, near each of these points, the function can attain any value we like. Therefore, there exist distinct $x$ values for which $f(x)$ is the same, and so the function is not one-to-one.

By the way, the reason we can have a function with a strictly negative derivative that isn’t one-to-one is because it isn’t continuous. Specifically, this function isn’t continuous at the points $x=1, x=2, x=3$. Even if we remove these points from the domain as we have, we still find that our function can attain a particular value more than once without the derivative ever becoming zero or switching sign. This is because, at a certain point, the function ‘blows up’ to negative infinity and then magically returns again from positive infinity, so on the domain we have defined, the derivative is always negative.

A: It's because it goes from plus infinity to minus infinity on both $(1,2)$ and $(2,3)$ (so by Intermediate value theorem it assumes every real value at least twice) which you can see by computing the appropriate limits.

A: If a $C^1$-function's derivative is negative then it's decreasing on any interval where it's defined.

A: $f(x)=\displaystyle\sum_{k=1}^{n}f_{k}(x)$
$f_{n}(x)=\frac{n}{x-n}:n\in N^{*},x\in R-\{ n \}$
$\forall n\in N^{*},x\in R-\{ n \} :f_{n}'(x)=\frac{-n}{(x-n)^{2}}\lt 0$
$\Rightarrow \displaystyle\sum_{k=1}^{n}f_{k}(x)\lt 0$
$\forall n\in N^{*},x\in R-\{ n \} : f'(x)\lt 0$


Q: ngcsv - Trouble in safari and IE Browsers I am using Angular js to load table in my page. Now i want to export the data to excel. For that i find a solution of using ngcsv. It is mentioned as it can easily convert json array to .csv file. I tried with that and got succeeded in Firefox and Chrome Browser. But in safari and IE it is not working.
  I tried the following fiddler example given in internet
`http://jsfiddle.net/asafdav/dR6Nb/`

It is also not working in Safari and IE. Is there any work around for this?

A: No, there is no workaround as such, unless you decide to write your own library.
On the github page of ng-csv : https://github.com/asafdav/ng-csv
It is clearly stated that Safari is not supported and only IE 10+ are supported.


Q: Reverse order of glDatePicker selectable date range Specs changed apparently and I can't get my head around why this won't work. I have a form with a #StartDate and #EndDate fields

        Start Date
        <input type="text" id="StartDate" name="StartDate">

        End Date
        <input type="text" id="EndDate" name="EndDate">
        <input type="submit" id="Button6" value="foo" />

        <input type="checkbox" name="AllDates" id="AllDates" value="YES">All Dates

Previously when the date range was from today - forward this worked:
$("#bottomContent").on('focus', "#StartDate", function(){
    var today = new Date();
    var datelimit = new Date(today);
    datelimit.setDate(today.getDate() + 31);

    $(this).glDatePicker({
        showAlways: false,
        allowMonthSelect: true,
        allowYearSelect: true,
        prevArrow:'<',
        nextArrow:'>',
        selectedDate:today,
        selectableDateRange: [{
            from: today,
            to: datelimit
        }, ],
        onClick: function (target, cell, date, data) {
            target.val((date.getMonth() +1) + '/' + date.getDate() + '/' + date.getFullYear());
            $('#AllDates').prop('checked', false);
            if (data != null) {
                alert(data.message + '\n' + date);
            }
        }
}).glDatePicker(true);

var to = $('#EndDate').glDatePicker({
    showAlways: false,
    onClick: function (target, cell, date, data) {
        target.val((date.getMonth() +1) + '/' + date.getDate() + '/' + date.getFullYear());
        $('#AllDates').prop('checked', false);
        if (data != null) {
            alert(data.message + '\n' + date);
        }
    }
}).glDatePicker(true);
$("#bottomContent").on('focus', "#EndDate", function(){
    var dateFrom = new Date($("#StartDate").val());
    var toLimit = new Date();
    toLimit.setDate(dateFrom.getDate() + 31);
    to.options.selectableDateRange = [{
    from: dateFrom,
    to: toLimit
}, ],
    to.options.showAlways = false;
    to.render();
});});

I need to make it start from today = newDate() and have it go BACKWARDS (-365 days), but simply switching all the "+ 31" which makes it go forward a month to "- 365" is not working, any ideas?

A: This did it, if anyone ever runs across the same problem.
$("#bottomContent").on('focus', "#StartDate", function(){
var today = new Date("January 1, 2013");
var datelimit = new Date();
datelimit.setDate(today.getDate() +14);

$(this).glDatePicker({
    showAlways: false,
    allowMonthSelect: true,
    allowYearSelect: true,
    prevArrow:'<',
    nextArrow:'>',
    selectedDate:today,
    selectableDateRange: [{
        from: today,
        to: datelimit
    }, ],
    onClick: function (target, cell, date, data) {
    target.val((date.getMonth() +1) + '/' + date.getDate() + '/' + date.getFullYear());
        $('#AllDates').prop('checked', false);
    if (data != null) {
        alert(data.message + '\n' + date);
    }
}
}).glDatePicker(true);

var to = $('#EndDate').glDatePicker({
    showAlways: false,
    prevArrow:'<',
    nextArrow:'>',
    selectedDate:today,
    onClick: function (target, cell, date, data) {
        target.val((date.getMonth() +1) + '/' + date.getDate() + '/' + date.getFullYear());
        $('#AllDates').prop('checked', false);
        if (data != null) {
            alert(data.message + '\n' + date);
        }
    }
    }).glDatePicker(true);
$("#bottomContent").on('focus', "#EndDate", function(){

var dateFrom = new Date($("#StartDate").val());
var toLimit = new Date();
//toLimit.setDate(dateFrom.getDate());
to.options.selectableDateRange = [{
    from: dateFrom,
    to: toLimit
}, ],
to.options.showAlways = false;
to.render();
});
});


Q: Package cmap or `\input glyphtounicode`? I'm sending PDFs to some folks who are supposed to copy some of the content elsewhere. It is important that my files are searchable and copyable (while I doubt these words to be proper English...)
So I'm using the package cmap. Recently I have been told, that cmap comes with a limitation, and indeed the manual says: »The main limitation currently is inability to work with virtual fonts, and this is because of limitation of pdftex, and may be resolved in a future versions of pdftex.«
In a question about ligatures and the libertine font here the advice was to use
\input glyphtounicode
\pdfgentounicode=1

instead of the package cmap.
The pdftex manual on p. 29 explaines:

The glyphtounicode.tex file (distributed with pdfTEX and other
  software) contains thousands of such definitions, covering most common
  glyph names. ... LaTeX users could load the cmap package to achieve the
  same effect.

I can't find any hint to the limitation, which is mentioned by the cmap manual. So my question is:
Does  \input glyphtounicode \pdfgentounicode=1work with virtual fonts? Has the limitation mentioned in the cmap manual been resolved?


Q: Matlab face alignment code I am attempting to do some face recognition and hallucination experiments and in order to get the best results, I first need to ensure all the facial images are aligned. I am using several thousand images for experimenting.
I have been scouring the Internet for past few days and have found many different programs which claim to do so, however due to Matlabs poor backwards compatibility, many of the programs no longer work. I have tried several different programs which don't run as they are calling onto Matlab functions which have since been removed.
The closest I found was using the SIFT algorithm, code found here
http://people.csail.mit.edu/celiu/ECCV2008/
Which does help align the images, but unfortunately it also downsamples the image, so the result ends up quite blurry looking which would have a negative effect on any experiments  I ran.
Does anyone have any Matlab code samples or be able to point me in the right direction to code that actually aligns faces in a database.
Any help would be much appreciated.

A: You can find this recent work on Face Detection, Pose Estimation and Landmark Localization in the Wild. It has a working Matlab implementation and it is quite a good method.
Once you identify keypoints on all your faces you can morph them into a single reference and work from there.

A: The easiest way it with PCA and the eigen vector. To found X and Y most representative data. So you'll get the direction of the face.
You can found explication in this document : PCA Aligment

A: Do you need to detect the faces first, or are they already cropped?  If you need to detect the faces, you can use vision.CascadeObjectDetector object in the Computer Vision System Toolbox.
To align the faces you can try the imregister function in the Image Processing Toolbox.  Alternatively, you can use a feature-based approach.  The Computer Vision System Toolbox includes a number of interest point detectors, feature descriptors, and a matchFeatures function to match the descriptors between a pair of images.  You can then use the estimateGeometricTransform function to estimate an affine or even a projective transformation between two images. See this example for details.


Q: When I open Terminal, I get an "I have no name!" prompt Suddenly, this morning, I open a Terminal window and I get this:
I have no name!@macbook:~$ whoami
502

** I am not a number!  I am a human being! **
What gives?  Anyone know what I need to do to get my name back?
I suppose there are two problems here, one is that my hostname is undefined, the other is that whoami reports my name as a number.

A: Something in memory got corrupted, and the mapping between your userID (502) and your username (ipd) was lost.  I've seen it happen (usually when I've manually killed hung system processes), although I'm not sure exactly what causes it.  launchd maybe?
Because that mapping is lost, whoami can't convert your ID into a username so returns the ID, and your prompt defaults to the "I have no name!" message because you effectively don't have a name.
Logging out and back in might fixit, but restarting is the best way (as you discovered).
Basically, it's a symptom of another problem, and not a problem in and of itself.

A: This happens to me randomly when I resume from standby (i.e. opening my laptop). A log out or reboot is the only way for me to fix it. I don’t know exactly what causes it. As I type it is happening right now. As the comment in the original post asked, I ran id -p and it crashed. (Crash report: http://pastebin.com/nmFFQELq)
Console commands:
whoami — returns 501
id -p — crashes
cat /etc/passwd — my user is not in the document.
Any ssh attempt fails with the error:

You don't exist, go away!

I also checked out the console, from waking up, a bunch of random "Socket not connected" errors appear (which I think might be normal, being that wireless doesn’t connect immediately) from programs like Dropbox. An interesting error appears though:

4/12/12 8:37:09.045 PM coreservicesd: _scserver_ServerCheckin: client uid validation failure; getpwuid(501) == NULL
4/12/12 8:37:09.400 PM coreservicesd: _scserver_ServerCheckin: client uid validation failure; getpwuid(501) == NULL

Still not sure what is causing it, but thought I would share these diagnostics.
I’m on a Mid 2009 MacBook Pro with 10.7.3 installed.

A: I see it's an old thread, but here is the solution to this problem (without restarting the whole computer).
The problem is in the opendirectoryd daemon and the earliest reports date from the beginning of 2011. Restarting the daemon (switching users with an admin one via Fast User Switching) fixes the problem.
While writing this answer, I've found a similar question in the Serverfault here, which also covers my answer.

A: See if the permissions of the file /etc/passwd are set up like this:
-rwxr--r--

because it reads the user name from the passwd file.

A: I had this same baffling problem today (Lion 10.7.5) and dscacheutil -flushcache fixed it for me, as suggested in a comment in some blog.

A: I solved the problem by using iterm=>preferences=>URL_handler and connecting whoami to my username .. after restart on iterm, problem was no more

A: Make sure your /etc/passwd file permissions are 644
chmod 644 /etc/passwd

After changing permissions , logout and log back in

A: Go to the home folder in Terminal and run . ~/.bashrc.
It works!!

A: My problem is the permission in passwd archive,
The old permission is
-rw------- 1 root root    1280 Jun  9 15:41 passwd
I used the command "chmod a+r /etc/passwd" and now all users can read this archive.
-rw-r--r-- 1 root root    1280 Jun  9 15:41 passwd
Logout the user and try.
=)

A: I had this weird issue on my ubuntu when I created a new user
I reviewed the /etc/passwd file
`cat /etc/passwd`

I saw my record had the following details -
`ajit:x:1002:1002::/home/ajitp:/bin/sh`

I changed it as follows -
`ajit:x:1002:1002::/home/ajitp:/bin/bash`