How can I reverse the effect of this webkit transition?

Question: I want the content div to go from blurry to sharp, but i can only figure out how to do the opposite thing.
div {
    -webkit-filter: blur(5px);
    -moz-filter: blur(5px);
    -o-filter: blur(5px);
    -ms-filter: blur(5px);
    filter: blur(5px);

    -webkit-transition: all 2s linear;
    -moz-transition: all 2s linear;
    -ms-transition: all 2s linear;
    -o-transition: all 2s linear;
    transition: all 2s linear;

    -webkit-transition-delay: 1s;
    transition-delay: 1s;

}
Answer: run this example that toggles between blur and sharp by adding/removing a CSS class on the targets

var $ = jQuery;

var btn = $('button').click(function() {
  $('.target').toggleClass('blurry');
});
.target {
  transition: all 2s linear;
  transition-delay: 1s;
}

.blurry {
  filter: blur(5px);
}

<button> Toggle blur/sharp </button>

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse fermentum pellentesque leo et porttitor. Ut luctus augue vel venenatis tincidunt. Nullam aliquam tempus cursus. Morbi quis aliquam sem. Fusce et ornare neque, a ultrices ipsum. Integer lorem sem, rhoncus non tempor non, mattis quis diam. Nunc ullamcorper tempor dolor sit amet feugiat. Etiam pretium lectus ut nisi ornare, quis euismod lacus feugiat. Donec scelerisque luctus sem at vulputate.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse fermentum pellentesque leo et porttitor. Ut luctus augue vel venenatis tincidunt. Nullam aliquam tempus cursus. Morbi quis aliquam sem. Fusce et ornare neque, a ultrices ipsum. Integer lorem sem, rhoncus non tempor non, mattis quis diam. Nunc ullamcorper tempor dolor sit amet feugiat. Etiam pretium lectus ut nisi ornare, quis euismod lacus feugiat. Donec scelerisque luctus sem at vulputate.


Prime pair points slope approaches 1

Question: Take the list of primes,
$$2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, \ldots$$
and create ordered $(x,y)$ pairs by grouping in sequence,
$$(2, 3), (5, 7), (11, 13), (17, 19), (23, 29), (31, 37), (41,
  43), (47, 53), (59, 61), (67, 71), \ldots$$
and now plot these points:

The best-fit slope for the first $10^3$ primes (shown) is $1.00046$;
for the first $10^5$ primes, the slope is $1.0000024$.
Why such rapid and close approach to a slope of $1$?
I (naively) expected more variation/spread...
What property of an increasing list of numbers would ensure this pairing
will closely approach a slope of $1$?
Comment: The distance from a prime $p$ to the next prime is, on average, about $\log p$, and, conjecturally, never much more that $(\log p)^2$; these are tiny, compared to $p$ (for large $p$). I suspect you'd get similar behavior for $(n^2,(n+1)^2)$, though maybe not converging as fast.
Comment: Thank you, Gerry & Will! It is a vivid demonstration of just how small is $\log p$.
Answer: It is really just that prime gaps remain quite small. If $q$ is the next prime larger than $p,$ then for all known primes, $$ q < p + 3 \log^2 p.  $$ This is currently unprovable but consistent with Cramer's conjecture. All that can be proved is something like $q < p + p^{0.55}$ for sufficiently large $p,$ i don't think there is even a known bound for beginning of that behavior. So proof is far behind observation.
Here is a nice table of prime gaps. Since the merit is the gap over $\log p,$ all one needs to do to get the gap divided by $\log^2 p$ is divide by another $\log p.$ They tell you the number of digits in each P, and then $\log P$ is about 2.3 times $\log_{10} P.$ It would be nice HINT HINT to see this big table with each gap divided by $\log^2 p,$ as Guy does below.
Richard K. Guy, in Unsolved Problems in Number Theory, gives the gaps divided by $\log^2 p.$ In the second edition (1994), page 21, in the third edition (2004), page 36.

<code> Stolen from
 http://users.cybercity.dk/~dsl522332/math/primegaps/maximal.htm

 the size of the gap is g

 next are the number of decimal digits in p

 for 4 * 10^18 > p >= 11, g < log^2 p = (log p)^2.

 Oh, logarithms base e == 2.718281828459

 ==================================
          g   digits of p             p    log p   g/log p  g/log^2 p
   1      1   1                        2 0.693147   1.4427    2.08137
   2      2   1                        3  1.09861  1.82048    1.65707
   3      4   1                        7  1.94591  2.05559    1.05637
   4      6   2                       23  3.13549  1.91357   0.610294
   5      8   2                       89  4.48864  1.78228   0.397065
   6     14   3                      113  4.72739  2.96147   0.626449
   7     18   3                      523  6.25958  2.87559    0.45939
   8     20   3                      887  6.78784  2.94644   0.434076
   9     22   4                     1129  7.02909  3.12985   0.445271
  10     34   4                     1327  7.19068  4.72835   0.657566
  11     36   4                     9551   9.1644  3.92824   0.428642
  12     44   5                    15683  9.66033  4.55471   0.471486
  13     52   5                    19609  9.88374  5.26116   0.532305
  14     72   5                    31397  10.3545  6.95352   0.671548
  15     86   6                   155921  11.9571  7.19238   0.601515
  16     96   6                   360653  12.7957  7.50254   0.586334
  17    112   6                   370261   12.822  8.73501   0.681254
  18    114   6                   492113  13.1065    8.698   0.663642
  19    118   7                  1349533  14.1153  8.35974   0.592248
  20    132   7                  1357201  14.1209  9.34782   0.661983
  21    148   7                  2010733   14.514   10.197   0.702566
  22    154   7                  4652353  15.3529  10.0307   0.653342
  23    180   8                 17051707  16.6518  10.8097   0.649161
  24    210   8                 20831323   16.852  12.4615   0.739466
  25    220   8                 47326693  17.6726  12.4487   0.704405
  26    222   9                122164747  18.6209  11.9221   0.640254
  27    234   9                189695659  19.0609  12.2764   0.644062
  28    248   9                191912783  19.0726   13.003   0.681764
  29    250   9                387096133  19.7742  12.6427   0.639356
  30    282   9                436273009  19.8938  14.1753   0.712549
  31    288  10               1294268491  20.9812  13.7266   0.654231
  32    292  10               1453168141   21.097  13.8408   0.656056
  33    320  10               2300942549  21.5566  14.8447   0.688637
  34    336  10               3842610773  22.0694  15.2247   0.689855
  35    354  10               4302407359  22.1824  15.9586   0.719423
  36    382  11              10726904659   23.096  16.5396   0.716125
  37    384  11              20678048297  23.7523  16.1668   0.680642
  38    394  11              22367084959  23.8309  16.5332   0.693772
  39    456  11              25056082087  23.9444  19.0441   0.795349
  40    464  11              42652618343  24.4764  18.9571   0.774506
  41    468  12             127976334671  25.5751   18.299   0.715502
  42    474  12             182226896239  25.9285   18.281   0.705055
  43    486  12             241160624143  26.2087  18.5434   0.707529
  44    490  12             297501075799  26.4187  18.5475   0.702059
  45    500  12             303371455241  26.4382   18.912   0.715328
  46    514  12             304599508537  26.4423  19.4386   0.735133
  47    516  12             416608695821  26.7554  19.2858   0.720819
  48    532  12             461690510011  26.8582  19.8078   0.737495
  49    534  12             614487453523  27.1441  19.6728   0.724756
  50    540  12             738832927927  27.3283  19.7597   0.723048
  51    582  13            1346294310749  27.9284   20.839   0.746159
  52    588  13            1408695493609  27.9737  21.0198   0.751412
  53    602  13            1968188556461  28.3081   21.266   0.751232
  54    652  13            2614941710599  28.5923  22.8034   0.797536
  55    674  13            7177162611713  29.6019  22.7688   0.769166
  56    716  14           13829048559701  30.2578  23.6633   0.782057
  57    766  14           19581334192423  30.6056  25.0281   0.817762
  58    778  14           42842283925351  31.3885  24.7861   0.789655
  59    804  14           90874329411493  32.1405  25.0152   0.778307
  60    806  15          171231342420521   32.774  24.5926   0.750369
  61    906  15          218209405436543  33.0165  27.4408   0.831126
  62    916  16         1189459969825483  34.7123  26.3884   0.760203
  63    924  16         1686994940955803  35.0617  26.3535   0.751632
  64   1132  16         1693182318746371  35.0654  32.2825   0.920639
  65   1184  17        43841547845541059  38.3194  30.8982   0.806335
  66   1198  17        55350776431903243  38.5525  31.0745   0.806032
  67   1220  17        80873624627234849  38.9317   31.337   0.804922
  68   1224  18       203986478517455989  39.8568  30.7099   0.770506
  69   1248  18       218034721194214273  39.9234  31.2598   0.782995
  70   1272  18       305405826521087869  40.2604  31.5943   0.784749
  71   1328  18       352521223451364323  40.4039  32.8681   0.813489
  72   1356  18       401429925999153707  40.5338  33.4536   0.825325
  73   1370  18       418032645936712127  40.5743  33.7652   0.832181
  74   1442  18       804212830686677669  41.2286  34.9757   0.848335
  75   1476  19      1425172824437699411  41.8008  35.3103   0.844728
        g   digits of p             p    log p   g/log p  g/log^2 p
 ==================================
</code>

Prime pair points slope approaches 1


Ballades (Chopin) Harmony Question

Question: I don't listen to much classical; however, I recently found this beautiful work by Chopin.  I am wondering if you could help me explain a particularly amazing moment in the piece. Please refer to minute 26:00-26:10 for reference in the attached youtube clip. Below is an image of the section:

The first five (5) bars have a minor quality to them and sound quite hopeless.  But then the sixth measure comes out of nowhere with that G-flat -> D-flat chord sequence that just feels like a breath of fresh air.
Could you explain this to me?  My first guess would be that in the first 5 measures we are in the relative minor of the key and then move to a PAC in the relative major key, thus bringing the positivity.  But the key with 4 flats is A-flat major (D-flat being the subdominant chord), so that doesn't really seem to be it.  The G-flat -> D-flat change is a dominant-tonic one, but not in the current key.  So were we modulating to D-flat major just for a moment?
Answer: Your intuition is correct; it's just a move to the relative major! But we can clear up some details.
Although the key signature is four flats, the music is really in B♭ minor for these first few measures; it certainly cadences in that key at the end of the first system.
Following this B♭-minor chord, a sudden appearance of G♭-major shifts the mood. You say that G♭ to D♭ is a dominant to tonic motion, and you're mostly there! Dominant to tonic is a descending perfect fifth, and G♭ to D♭ is an ascending perfect fifth. As such, I hear this progression as a plagal IV–I motion in the relative major of D♭ major.
Answer: Dolce begins in Ab: I - viidim7 leading to the relativ chord (Bbm) of the subdominant (Db) by Ebm-F7 => Bbm which  is (iv-V7) ii and from here he just uses the well known half-cadence to F (the V of Bbm): i-VI-III-iv-V. (Bbm-Gb-Db-Ebm-F).

Ballades (Chopin) Harmony Question


I want to omit addressLine1 if element attribute has Attention

Question: If the type attribute of the Address element = "Standard With Attention" I do not want to display AddressLine1. Instead I want to only display AddressLine2, AddressLine3 and AddressLine4.
My output
Attn: Michael, 134 W Broadway ST NW, APT 3B, Washington, DC, 12345
Expected output:
134 W Broadway ST NW, APT 3B, Washington, DC, 12345
My xml
<ProtectedAddresses>
    <Address InternalAddressID="1618613567" Type="Standard With Attention">
        <AddressLine1>Attn: Michael</AddressLine1>
        <AddressLine2>134 W Broadway ST NW</AddressLine2>
        <AddressLine3>APT 3B</AddressLine3>
        <AddressLine4>Washington, DC, 12345</AddressLine4>
        <Attention>James</Attention>
       </Address>
</ProtectedAddresses>

Xslt
<xsl:for-each select="Addresses/Address">
   <xsl:for-each select="ancestor::ProtectionOrder/ProtectionOrderParties/ProtectionOrderParty/DCProtectionOrderPartyAdditional/ProtectedAddresses/Address[@InternalAddressID=current()/@InternalAddressID]">
     <xsl:for-each select="AddressLine1 | AddressLine2 | AddressLine3 | AddressLine4">
       <xsl:value-of select="."/>
       <xsl:if test="position()!=last()">, </xsl:if>
     </xsl:for-each>
     <xsl:text>; </xsl:text>
   </xsl:for-each>
</xsl:for-each>

Answer: If you replace <xsl:for-each select="AddressLine1 | AddressLine2 | AddressLine3 | AddressLine4"> with <xsl:for-each select="AddressLine1[not(../@Type = 'Standard With Attention')] | AddressLine2 | AddressLine3 | AddressLine4"> you construct the node-set with only three elements if the condition ../@Type = 'Standard With Attention' is true.
Answer: Your example is rather confusing, because you only show us a partial XML. As a result, it is difficult to give an accurate answer because the context is not clear enough, and it is impossible to test the given answer against your input.
IMHO, you should be using a key instead of this:
<xsl:for-each select="ancestor::ProtectionOrder/ProtectionOrderParties/ProtectionOrderParty/DCProtectionOrderPartyAdditional/ProtectedAddresses/Address[@InternalAddressID=current()/@InternalAddressID]">

Now, to address your question (as best as possible): to exclude AddressLine1 under some circumstances, you should append it with a predicate -  i.e. something like:
<xsl:for-each select="AddressLine1[not(../@Type='Standard With Attention')] | AddressLine2 | AddressLine3 | AddressLine4">

This will work if - as it seems - the condition exists in the parent element of the actual AddressLine1.
Comment: Thanks for your help. This worked as I used same code you provided as provided by Martin Honnen. I am not sure how to use a Key as you suggested instead of using my code ``
Comment: @Angela I suggest you post another question regarding that, with a minimal but complete example of your XML.


Setting current time in input type time in ASP.Net MVC

Question: I am quite new to ASP.Net Core MVC. I am trying to display the current time  in input type time. But I am not able to do so. Below is the code I am trying.

  <input type="time" id="starttime" value="@DateTime.Now.ToString("hh::mm::ss tt")" />

The time picker shows blank. I also tried by setting time by script  but no luck.
Could someone please help? Isnt it possible to display current time in this manner?
Comment: Q: Is your question answered/your problem resolved?
Answer: Per the documentation: "The control's user interface varies from browser to browser".
SUGGESTIONS:

Look at the actual HTML rendered in Chrome Dev Tools.
If the HTML looks OK, experiment with different ".ToString()" format patterns until your time picker looks OK, too.
Once it works on one browser (e.g. Chrome), be sure to also test on other browsers (e.g. IE11, Firefox, Safari and Edge).

FYI, I don't think the format "hh::mm::ss tt" is valid for any browser.
I tried these different format strings on Chrome:
Format         Status  Display:
------         ----    -------
hh::mm::ss tt  FAILS   --:-- --
hh:mm          OK      12:33 PM
hh:mm:ss       OK      12:33:38 PM
hh:mm:ss tt    FAILS   --:-- --
hh::mm         FAILS   --:-- --

Comment: Thanks for the update. I see that hh:mm works for chrome.
Comment: IMPORTANT POINTS: 1) "hh:mm" should work for ANY browser.On the other hand, "hh::mm::ss tt" is NOT a valid time format, and probably *WON'T* display a time value in most (all?) browsers. 2) As a web developer, you'll need to make it a point to *ALWAYS* test on *MULTIPLE DIFFERENT BROWSERS*.  ALSO: Please feel free to "upvote" and/or "accept" the answer if you found it helpful.


Error when trying to start Apache after installing SSL cert


An equality for conditional probabilities

Question: Let $(\Omega, \mathcal F, \mathbb P)$ be a probability space, $\mathcal G$ a sub-sigma-field, and $\mathbb P^{\mathcal G}$ denote the conditional probability.
In another question, I confirmed that for all $A,B \in \mathcal F$
$$\int_A \mathbb P^{\mathcal G}(B)d \mathbb P = \int_B \mathbb P^{\mathcal G}(A)d \mathbb P.$$

Is it also true that for all $A,B,C \in \mathcal F$
$$\int_{C \cap A} \mathbb P^{\mathcal G}(B)d\mathbb P = \int_{C \cap B} \mathbb P^{\mathcal G}(A)d\mathbb P?$$

Intuitively, this seems to me like it should be true, just by applying the first result to the trace space $\{A \cap C: A \in \mathcal F\}$. But I haven't been able to convert that idea into a rigorous proof, nor have I found a counterexample.
Answer: For $C \in \mathcal{G}$ it is true and the proof is effectively the same as your previous question's answer.
For $C \in \mathcal{F}\setminus\mathcal{G}$, however, I don't see a reason why it ever should be true.  For instance, if $\mathcal{G} = \{\emptyset, \Omega\},$ then it becomes $$\mathbb{P}(B)\mathbb{P}(A\cap C) = \mathbb{P}(A)\mathbb{P}(B\cap C)$$
which isn't true in general.
Answer: Let $A$ and $B$ be any two disjoint events with $P(A) >0$ and $P(B) >0$. Let $\mathcal G$ be  sigma field independent of $B $ and take $C=A$. Then RHS is $0$ and LHS is $P(A)P(B) >0$.


Using theme_preprocess_node i'm trying to add a class to all images on the page

Question: My code below is not working and i'm not sure why. I've tried a few variants.
according to the KPR variables output, the image I'm trying to access is here.
$variables['field_about_image'][0]
i think the 0 signifies it is the first (and only in this case) image on the page w/ the machine field name 'field_about_image'. so i wrote my code as:
function myTheme_preprocess_node(&$variables){
    if($variables['type']=='basic_page_with_pic') {
echo ''; //Verified it's working
    $variables['field_about_image'][0]['class'] = 'myclass;
}
}

i've also tried this, just to get a class attribute added
$variables['field_about_image'][0][] = 'class';

also the title attribute comes up as empty. so just as an execrcise i tried this.
$variables['field_about_image'][0]['title'] = 'some title;

any help on how to do this would be greatly appreciated!
Answer: From what I can tell, hook_preprocess_node() won't let you add both classes and title attributes to images from image fields. Try using hook_preprocess_field() as in the example below:
function myTheme_preprocess_field(&$variables) {
  if (($variables['element']['#field_name'] == 'field_about_image') && ($variables['element']['#bundle'] == 'basic_page_with_pic')) {
    $variables['items'][0]['#item']['title'] = t('This is the title text that will display when hovering.');
    $variables['items'][0]['#item']['attributes']['class'][] = 'class1';
    $variables['items'][0]['#item']['attributes']['class'][] = 'class2';
  }
}

Be sure to clear your cache.
Comment: thank you. the title worked but adding the class did not. i tried a few diff things to get it to work like, $variables['items'][0]['#attributes']['class'][] = 'about_main_pic';   hmmmm.....?


How do I add library paths of C libraries that I want to use in C++ to the environment

Question: I want to use the VLFeat Libaries in C from a C++ file. Their tutorial for g++ presents a basic "Hello World" example which is compiled as follows:
g++ main.cpp -o vlfeat-test -I /disk/no_backup/lesi/vlfeat-0.9.20/ -L /disk/no_backup/lesi/vlfeat-0.9.20/bin/glnxa64/ -lvl

This works fine. What I want now is to add the library to my .bashrc, so I don't need the extra flags:
export CPLUS_INCLUDE_PATH=$CPLUS_INCLUDE_PATH:/disk/no_backup/lesi/vlfeat-0.9.20
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/disk/no_backup/lesi/vlfeat-0.9.20/bin/glnxa64

and use it like this:
g++ main.cpp -o vlfeat-test

Unfortunately I get the following error:
/tmp/cc6tzB55.o: In function `main':
main.cpp:(.text+0x10): undefined reference to `vl_get_printf_func'
collect2: error: ld returned 1 exit status

What am I doing wrong?
Here's the "Hello World" code from the tutorial:
extern "C" {
  #include <vl/generic.h>
}

int main (int argc, const char * argv[]) {
VL_PRINT ("Hello world!\n") ;
  return 0;
}

VLFeat Library Link: http://www.vlfeat.org/index.html
Answer: You specify where to find the header, but you don't tell the compiler to link against the library.
There is no magic mapping from "this C file included this header" to "I better link this program with this library", it doesn't work like that.
I could make a library with a single unwind-mess.h header, that declares functions implemented in three different library files, and call the libraries libcream.a, libmeringue.a and libberry.a.
You still need the -lvl option to tell the compiler there's extra library code that needs to be linked against.


Android: Progress Bar is not dismissing even though Page loading is finished

Question: Progress Bar is not dismissing even though Page loading is finished
I'm trying to load the url in the webview in background so that user doesn't able to recognize that it is some other website that opens.. I want them to think that the whatever is opening in the webview is the part of the application itself. Therefore I'm trying to open url in background and till the time url loads I want progress bar to appear but as page loaded I'm dismissing progress bar but it continues to appear.. it is not dismissing, thats the problem.. please help me out
Here is my code...
package com.example.urlopeningwithprogressbar;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

ProgressDialog pg;
Background bg;
WebView wv;
Button b1;

static boolean buttonpressed=false;

@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    b1=(Button)findViewById(R.id.button1);
    wv = (WebView)findViewById(R.id.webView1);

    b1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            bg = new Background();
            bg.execute();

        }
    });

}
public void progress(){
    pg = new ProgressDialog(MainActivity.this);
    pg.setTitle("");
    pg.setMessage("Please Wait.........");
    pg.setCancelable(false);
    pg.setIndeterminate(true);
    pg.show();
}

class Background extends AsyncTask<Void, Void, Void>
{

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected Void doInBackground(Void... arg0) {
        // TODO Auto-generated method stub

            try{
                wv.loadUrl("URL");
                }catch(Exception e){
                    e.printStackTrace();
                }

                wv.getSettings().setJavaScriptEnabled(true);
                wv.getSettings().setLoadWithOverviewMode(true);
                wv.getSettings().setUseWideViewPort(true);
                wv.getSettings().setBuiltInZoomControls(true);
            //  wv.setWebViewClient(new ourViewClient());

        return null;
    }
    @Override
    protected void onPostExecute(Void result) {

        Toast.makeText(MainActivity.this, "Process Complete", Toast.LENGTH_SHORT).show();

    }

    @Override
    protected void onPreExecute() {
        Toast.makeText(getApplicationContext(), "pre execute is working??", Toast.LENGTH_SHORT).show();
        progress();
    }
}
 public class myWebClient extends WebViewClient
    {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // TODO Auto-generated method stub
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // TODO Auto-generated method stub

            view.loadUrl(url);
            return true;

        }

        @Override
        public void onPageFinished(WebView view, String url) {
            // TODO Auto-generated method stub
            super.onPageFinished(view, url);

            pg.dismiss();
        }
    }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}
Comment: is onPageFinished called?
Comment: Refer this: http://stackoverflow.com/questions/3903895/how-to-show-progress-bar-on-webview
Comment: @Ascorbin onPageFinished Doesn't called...
Comment: @Ameeshmg I followed the same which is given in the link u gave.. But still facing the problem.. Can anyone point out where is the flaw in the code..?
Answer: You are never instantiating or using your myWebClient class.
You have to
wv.setWebViewClient(new myWebClient());

to actually use it.
Also note that class names should be upper case.
Comment: Thanks a lot buddy :) Its working now :) I wish I could vote up for u but as I joined stackoverflow just a day before so doesn't have reputation above 15 so can't voteup for u


Simplify $ \sum\limits_{i=0}^l{n\choose i}{m\choose l-i}$

Question: Is there a nice way to simplify $ \sum\limits_{i=0}^l{n\choose i}{m\choose l-i}$? I tried to tinker a bit with telescope sums but it did not get me nowhere...
Comment: https://en.wikipedia.org/wiki/Vandermonde%27s_identity
Comment: Suppose that you are select $~l~$ elements out of $~(m+n)~$ elements, sampling without replacement, where order of selection is deemed irrelevant.  Further suppose that the $~m+n~$ elements are partitioned into two subsets; one subset has $~m~$ elements and the other subset has $~n~$ elements.  Then, for each selection of the $~l~$ elements from the $~m+n~$ elements, there will exist some $~i \in \{0,1,2,\cdots,l\},~$ such that $~i~$ elements are taken from the subset with $~m~$ elements and $~(l-i)~$ elements are taken from the subset with $~n~$ elements.
Comment: Re my previous comment, and re the original problem, note the convention that when $~k,n \in \Bbb{Z^+},~$ and $~k > n,~$ then $~\displaystyle \binom{n}{k} = 0.$
Answer: The sum should be equal to $\binom{n+m}{l}$
One way to see this is to give a combinatorial proof of this. Let us consider the following scenario, we have a group of $n$ boys and $m$ girls, and we wish to choose $l$ people from the group of $n+m$ people. Thus, on the one hand, that value is $\binom{n+m}{l}$. On the other hand, we can choose $l$ people from the group by considering how many boys and girls we choose, if we choose no boys, then we need to pick $l$ girls, and there are $\binom{n}{0}\binom{m}{l}$ ways to do this, then if we choose $1$ boy we must have $l-1$ girls, and there will be $\binom{n}{1}\binom{m}{l-1}$, and continuing on if we choose $i$ boys, we must pick $l-i$ girls, and there will be $\binom{n}{i}\binom{m}{l-i}$. Thus, adding up all of these ways we have the way of choosing $l$ people from a group of $n+m$ people will be $\sum_{i=0}^l\binom{n}{i}\binom{m}{l-i}$


How can I check if a variable in an array in an array in an array is defined and not null?

Question: I am trying to check to see if wordDefinitionId is defined and not null.  Here's what I have been trying to do but  think even this code seems to give some problems. Is there an easy way for me to do this check and set the value of wos.wordDefinitionId to either the value (if it exists) or zero if it does not exist.
if (wos.word.wordForms) {
   if (wos.word.wordForms[0].wordDefinitions) {
      if (wos.word.wordForms[0].wordDefinitions[0].wordDefinitionId)
         wos.wordDefinitionId = wos.word.wordForms[0].wordDefinitions[0].wordDefinitionId
      }
   }
}

Note that if set then I want to get the wordDefinitionId that is in the first array position of wordDefinitions etc.
Update:
I tried the answer suggested:
if (wos.word.wordForms && wos.word.wordForms[0].wordDefinitions && wos.word.wordForms[0].wordDefinitions[0].wordDefinitionId)
    wos.wordDefinitionId = wos.word.wordForms[0].wordDefinitions[0].wordDefinitionId;
if (wos.word.wordForms && wos.word.wordForms[0].synonyms && wos.word.wordForms[0].synonyms[0].synonymId)
    wos.synonymId = wos.word.wordForms[0].synonyms[0].synonymId

// When I debug the code does not reach the next line.

if (wos.word.wordForms && wos.word.wordForms[0].sampleSentences && wos.word.wordForms[0].sampleSentences[0].sampleSentenceId)
    wos.sampleSentenceId = wos.word.wordForms[0].sampleSentences[0].sampleSentenceId

However when I debug the code does not reach the final "if"
Here for reference are the objects:
console.log(JSON.stringify(wos.word))
VM6085:1 {"wordId":"tyyyyyy","wordIdentity":160,"ascii":116,"categoryId":1,"groupId":1,"lessonId":1,"ielts":null,"toefl":true,"toeic":null,"wordForms":[{"wordFormId":"qwqwqwqwq","wordFormIdentity":145,"ascii":113,"wordId":"tyyyyyy","primary":false,"posId":1,"sampleSentences":[],"synonyms":[],"wordDefinitions":[{"wordDefinitionId":142,"wordFormId":"qwqwqwqwq","text":"wrwrwrwrwr","ascii":119}],"pos":null,"version":"AAAAAAAADn0=","createdBy":2,"createdDate":"2016-05-03T13:23Z","modifiedBy":2,"modifiedDate":"2016-05-03T20:23Z"}],"lesson":null,"wordCategory":null,"wordGroup":null,"version":"AAAAAAAADf4=","createdBy":2,"createdDate":"2016-05-03T13:23Z","modifiedBy":2,"modifiedDate":"2016-05-03T20:23Z","current":true}

Same here but maybe easier to see:
console.log(JSON.stringify(wos.word))
VM6085:1 {"wordId":"tyyyyyy","wordIdentity":160,"ascii":116,"categoryId":1,"groupId":1,"lessonId":1,"ielts":null,"toefl":true,"toeic":null,"wordForms":[{"wordFormId":"qwqwqwqwq","wordFormIdentity":145,"ascii":113,"wordId":"tyyyyyy","primary":false,"posId":1,"sampleSentences":[],"synonyms":[],"wordDefinitions":[{"wordDefinitionId":142,"wordFormId":"qwqwqwqwq","text":"wrwrwrwrwr","ascii":119}],"pos":null,"version":"AAAAAAAADn0=","createdBy":2,"createdDate":"2016-05-03T13:23Z","modifiedBy":2,"modifiedDate":"2016-05-03T20:23Z"}],"lesson":null,"wordCategory":null,"wordGroup":null,"version":"AAAAAAAADf4=","createdBy":2,"createdDate":"2016-05-03T13:23Z","modifiedBy":2,"modifiedDate":"2016-05-03T20:23Z","current":true}
Comment: possibly change of the data structure?
Comment: smells like a recursive approach is required :-)
Answer: Use &&(AND) logical operator  between conditions, if first condition fails second condition will not check and so on
if (wos.word.wordForms && wos.word.wordForms[0].wordDefinitions && wos.word.wordForms[0].wordDefinitions[0].wordDefinitionId)
  wos.wordDefinitionId = wos.word.wordForms[0].wordDefinitions[0].wordDefinitionId

var wos = {
  word: {
    "wordId": "tyyyyyy",
    "wordIdentity": 160,
    "ascii": 116,
    "categoryId": 1,
    "groupId": 1,
    "lessonId": 1,
    "ielts": null,
    "toefl": true,
    "toeic": null,
    "wordForms": [{
      "wordFormId": "qwqwqwqwq",
      "wordFormIdentity": 145,
      "ascii": 113,
      "wordId": "tyyyyyy",
      "primary": false,
      "posId": 1,
      "sampleSentences": [],
      "synonyms": [],
      "wordDefinitions": [{
        "wordDefinitionId": 142,
        "wordFormId": "qwqwqwqwq",
        "text": "wrwrwrwrwr",
        "ascii": 119
      }],
      "pos": null,
      "version": "AAAAAAAADn0=",
      "createdBy": 2,
      "createdDate": "2016-05-03T13:23Z",
      "modifiedBy": 2,
      "modifiedDate": "2016-05-03T20:23Z"
    }],
    "lesson": null,
    "wordCategory": null,
    "wordGroup": null,
    "version": "AAAAAAAADf4=",
    "createdBy": 2,
    "createdDate": "2016-05-03T13:23Z",
    "modifiedBy": 2,
    "modifiedDate": "2016-05-03T20:23Z",
    "current": true
  }
};

if (wos.word.wordForms && wos.word.wordForms[0].wordDefinitions && wos.word.wordForms[0].wordDefinitions[0].wordDefinitionId)
  wos.wordDefinitionId = wos.word.wordForms[0].wordDefinitions[0].wordDefinitionId

document.write('
' + JSON.stringify(wos, 0, 3) + '
');
Comment: I tried this and updated the answer.  When I debug every line the code gets as far as the check for synonyms and then no further in the chrome developer tools debugger. So it seems that the if() is causing it to exit. Do you have any ideas what might cause this?
Comment: Can you explain what this means. How could I check for this so the code doesn't stop or exit ?  I updated the question to show the data so many that helps. Thanks
Comment: thanks. Can you add in the three checks that I have so we could see if it gets to end and sets the Ids. I would do this but I am not sure how to edit a code snippet that you created. Thanks
Comment: @SamanthaJ :  just put an alert or console.log statement inside the if
Comment: I tried adding the three condition checks in my own snippet but it doesn't run to the end. Do you think your answer is maybe not accounting for all possibilities?
Answer: You don't reach the third if, because in your second if statement, the wos.word.wordForms[0].synonyms will evaluate to true as it is defined and is an empty list. You can check it yourself:
if (wos.word.wordForms[0].synonyms) { alert('Yes!'); } // will alert 'Yes!'

But right next to it, you try to access wos.word.wordForms[0].synonyms[0], which does not exist, hence the TypeError: wos.word.wordForms[0].synonyms[0] is undefined. The same situation is with your wos.word.wordForms[0].sampleSentences
In order to fix this, check the length of the list as well:
if (wos.word.wordForms
  && wos.word.wordForms[0].synonyms
  && wos.word.wordForms[0].synonyms.length  // <-- check for element existence
  && wos.word.wordForms[0].synonyms[0].synonymId) {
    ...
}


How to create multiple Swiper sliders with one pagination?

Question: I want to make 2 sliders with one pagination. I use Swiper 2.7.6.
Both sliders should have different effects. I haven't found an example on official page. I want it to look like  this. Here's a code:
  if ($('.photo-slider').length) {
    $('.photo-slider').each(function(i){
        var $this = $(this);
        //slider ID
        var id = 'photo_slider_'+i;
        // $this.find('.slider').attr('id', id);
        $this.find('.slider').attr('id', id);
        // pagination
        var paginationClass = 'pagination-photo'+i;
        $('.photo-slider').append('

');

        var $slider = new Swiper('#'+id, {
            slidesPerView: 1,
            loop: true,
            grabCursor: true,
            calculateHeight: true,
            pagination: '.'+paginationClass,
            paginationClickable: true
        });

        $this.find('.slider-arrow').on('click', function(){
            if ($(this).hasClass('prev')) {
                $slider.swipePrev();

            } else {
                $slider.swipeNext();
            }

            return false;
        });

        i++;
    });
}

Answer: Are you trying to link 2 separate instances of Swiper slideshows with only 1 set of pagination / nav?
Why not just set the pagination & nav buttons on one instance? If you have them linked movement on either will affect the other.


Drupal Json Output strange characters when pulling from other language

Question: Hi Fellow drupal experts,
I have a problem, I developed a custom page intended to do a drupal json output :
and here is the code :

    function blogpull_menu() {
$items = array();

$items['blogpull'] = array(
    'page callback' => 'blogpull_view',
    'delivery callback' => 'drupal_json_output',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
);
return $items;

}
function blogpull_view() {
    global $base_url;
    global $language;
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'blog')
      ->propertyCondition('status', 1)
      ->propertyCondition('language', $language->language, '=') // filter by current language
      ->range(0, 5)
      ->addMetaData('account', user_load(1)); // Run the query as user 1.
    $result = $query->execute();
    if (isset($result['node'])) {
      $blog_items_nids = array_keys($result['node']);
      $blog_items = entity_load('node', $blog_items_nids);
    }
foreach ($blog_items as $key => $blog_item) {
    $arr = array('date' => date('M. j, Y', $blog_items[$key]->created), 'title' => $blog_items[$key]->title, 'description' => $blog_items[$key]->body['und'][0]['value'], 'href' => $base_url.'/node/'.$blog_items[$key]->nid);
    $arrs[] = $arr;
}

return $arrs;

}

and some how when it's loading the japanese language it is showing this strange characters :
クラウドゲーム事業ã®æ–°ä¼šç¤¾ã€Œã'·ãƒ³ãƒ©ãƒ»ãƒ†ã'¯ãƒŽãƒã'¸ãƒ¼ã€ç™ºè¶³
I tied using utf-encoding, mb_encoding and so on but nothing happen
can someone help?
thank you!
Answer: just check HTTP response headers it should have utf-8 charset.
Comment: the page just throw out nothing without the headers, I tried adding drupal_add_headers into it but still not working


Meaning of $\nabla \cdot \mathbf{A}$ for matrix $\mathbf{A}$ and $\nabla \cdot (\mathbf{u} \otimes \mathbf{v})$ in Euler equations.

Question: What is $\nabla \cdot \mathbf{A}$ when $\mathbf{A} \in \mathbb{R}^{m \times n}$ is a matrix, and where is there a consise definition of this notation?
The Euler equations on Wikipedia contain terms on the form $\nabla \cdot (\mathbf{u} \otimes \mathbf{u} - w\mathbf{I})$ where $\mathbf{I}$ is the identity matrix. Other material on the Euler equations simply writes $\nabla \cdot (\mathbf{u} \mathbf{u} - w\mathbf{I})$. I assume $\mathbf{u} \otimes \mathbf{v} = \mathbf{u}\mathbf{v}^T \in \mathbb{R}^{m \times n}$ for $\mathbf{u} \in \mathbb{R}^m$ and $\mathbf{v} \in \mathbb{R}^n$.
Is $\nabla \cdot \mathbf{A}$ defined when $\mathbf{A}$ is not square / not symmetrical?
Comment: Your interpretation of $\otimes$ as outer product is correct, and indeed the Wikipedia page mentions this within the 'derivation of the conservation form' section (which needs to be clicked to be revealed). The use of Einstein notation within that section may further clarify the definitions used.
Comment: So $\nabla \cdot \mathbf{A}, \ \mathbf{A} \in \mathbb{R}^{m \times n}$ is a column vector in $\mathbb{R}^n$ with elements $\sum_i \partial_i A_{ij}$, or is it a column vector in $\mathbb{R}^m$ with elements $\sum_j \partial_j A_{ij}$? The section appears to allude to a general definition of $\nabla \cdot \mathbf{A}$ but the definition is not given.
Comment: It should, I think, be the same interpretation as in this [previous question](https://math.stackexchange.com/q/78818/137524). But without a specific definition it's hard to be sure.
Answer: Clicking "show" next to "Demonstration of the conservation form" reveals more context: the matrix
$$\begin{pmatrix}{\mathbf {u}}\otimes {\mathbf {u}}+w{\mathbf {I}}\\{\mathbf {u}}\end{pmatrix}$$
is written out in components as
$$
{\begin{pmatrix}u_{1}^{2}+w&u_{1}u_{2}&u_{1}u_{3}\\u_{2}u_{1}&u_{2}^{2}+w&u_{2}u_{3}\\u_{3}u_{1}&u_{3}u_{2}&u_{3}^{2}+w\\u_{1}&u_{2}&u_{3}\end{pmatrix}}$$
Other formulas clarify that $\nabla$ is applied to this matrix by differentiating the first column with respect to $x_1$, the second with respect to $x_2$, the third with respect to $x_3$, and then adding the results. The result being
$$
\nabla\cdot {\begin{pmatrix}u_{1}^{2}+w&u_{1}u_{2}&u_{1}u_{3}\\u_{2}u_{1}&u_{2}^{2}+w&u_{2}u_{3}\\u_{3}u_{1}&u_{3}u_{2}&u_{3}^{2}+w\\u_{1}&u_{2}&u_{3}\end{pmatrix}}
=\begin{pmatrix}
(\operatorname{div} \mathbf u)\mathbf u + \operatorname{grad} \mathbf w
\\
\operatorname{div} \mathbf u
\end{pmatrix}
$$
where I used explicit names to avoid any further $\nabla$-confusion.
If we think of $\nabla$ as a symbolic vector of partial derivatives, $\nabla = \begin{pmatrix} \partial /\partial x_1 \\ \partial /\partial x_2 \\ \partial /\partial x_3 \end{pmatrix}$, then the above is more properly
$$
\begin{pmatrix}{\mathbf {u}}\otimes {\mathbf {u}}+w{\mathbf {I}}\\{\mathbf {u}}\end{pmatrix} \nabla =
{\begin{pmatrix}u_{1}^{2}+w&u_{1}u_{2}&u_{1}u_{3}\\u_{2}u_{1}&u_{2}^{2}+w&u_{2}u_{3}\\u_{3}u_{1}&u_{3}u_{2}&u_{3}^{2}+w\\u_{1}&u_{2}&u_{3}\end{pmatrix}} \begin{pmatrix} \partial /\partial x_1 \\ \partial /\partial x_2 \\ \partial /\partial x_3 \end{pmatrix}
$$
This makes sense for any matrix where the number of columns matches the dimension.


How to use rsyslog to log files from client to server

Question: I've setup an rsyslog server which accepts log information from clients.
I can successfully receive syslog messages however I'm interested in logging a number of files too.
Here is what my client looks like:
<code>$ModLoad imfile

$InputFileName /var/log/drew-error.log
$InputFileTag drew:
$InputFileStateFile stat-drew-error
$InputFileSeverity error
$InputRunFileMonitor

$InputFilePollInterval 1
</code>
I'm not sure exactly what to put in my server config. Ideally I'd like the server to output something like this:
<code>/var/log/remote/$HOSTNAME/drew-error.log</code>
Am I going about this the right way? Is this reasonable to try to achieve?
Best Case Scenario: I'd like to be able to update the files I'm watching on the client, without having to reconfigure the server. If that's not possible, or too hard, I can probably work around a hard-coded solution.
What I've tried
So far I've tried a few configurations for the server (though I feel they're not the right solution/approach):
<code>$template syslog, "/var/log/remote/%hostname%/%programname%/%$year%%$month%%$day%/syslog"
*.*;auth,authpriv.none          ?syslog
</code>
and
<code>$template DrewTemplate,"/var/log/remote-DREWAPP-%HOSTNAME%.log"
if $programname == 'drew:' then -?DrewTemplate
& ~

$template PerHostLog,"/var/log/remote-%HOSTNAME%.log"
if $fromhost-ip startswith '1.2.' then -?PerHostLog
& ~
</code>
Answer: One solution is to check the $programname (which gets populated with the value from $InputFileTag on the client for each file you monitor).
Client Configuration
On the client, create your file monitor(s), and make sure $InputFileTag starts with 'file-'. Here is an example with log files foo and bar:
<code>######################### START /var/log/foo.log
$InputFileName /var/log/foo.log
$InputFileTag file-foo:
$InputFileStateFile stat-foo
$InputFileSeverity info
$InputRunFileMonitor
######################### END /var/log/foo.log

######################### START /var/log/bar.log
$InputFileName /var/log/bar.log
$InputFileTag file-bar:
$InputFileStateFile stat-bar
$InputFileSeverity info
$InputRunFileMonitor
######################### END /var/log/bar.log
</code>
Server Configuration
And then on the server, check that $programname starts with 'file-' (as should be the case for all of your file monitors, but not for any of the standard syslog messages). Here is an example:
<code>$template FileTemplate,"/var/log/remote-%HOSTNAME%-%programname%.log"
if $programname startswith 'file-' then -?FileTemplate
& ~
</code>

This solution checks to see if the $programname starts with 'file-'
As long as you have control over how you label $InputFileTag (on the client) this solution works quite well
The template uses programname and hostname to keep file names unique on the server
The & ~ makes sure this syslog message doesn't get processed further down in the config
This solution provides ONE configuration on the server that doesn't need to be updated each time you add a new file monitor on the client.


How to add markers and set custom tap events on markers with Google Maps Plugin?

Question: I have a list of markers like this
List<Marker> markers = <Marker>[
    new Marker("1", "Name 1", 28.421364, 77.333804,
        color: Colors.amber),
    new Marker("2", "Name 2", 28.418684, 77.340417,
        color: Colors.purple),
  ];

And the basic code to show and draw the map
class  HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => new _HomePageState();
}
class _HomePageState extends State<HomePage> {
  Completer<GoogleMapController> _controller = Completer();
  static final CameraPosition _kGooglePlex = CameraPosition(
    target: LatLng(11.052992, 106.681612),
    zoom: 11,
  );
  @override
  Widget build(BuildContext context){
    return new Scaffold(
      body: GoogleMap(
        initialCameraPosition: _kGooglePlex,
        onMapCreated: (GoogleMapController controller) {
          _controller.complete(controller);
        },
      ),
    );
  }
}

How can I add markers from my List<Marker> to Google Maps and add onTap method to those markers?
Comment: Please vote and mark my answer as solved if you have no further questions about this and you think my answer is useful.
Answer: As with google_maps_flutter 0.3.0, marker api has changed. Before 0.3.0, you have to add your markers on controller like that.
mapController.addMarker(
  MarkerOptions(
    position: LatLng(37.4219999, -122.0862462),
  ),
);

After the change on marker api,GoogleMap widget has a property named markers which takes Set of markers, not list of Markers. So you can give a set of markers to your GoogleMap widget. Also markers have onTap property for tapping.


How can I override group policy using a local administrator account?

Question: I have local administrator access on my machine but somehow still can't change the screensaver setting. I believe it is being disabled by group policy somehow, is there a way to override this?
Answer: You "own" the machine if you have local "Administrator" rights so, yeah, you can.
Mark Russinovich talks about circumventing group policy in this blog post, and just happens to use display settings as an example. Lucky for you, eh?
Basically, remove all access to the registry key where the policy setting you're looking for is set and the policy stops applying (since Explorer can't read the policy setting). This might not work in the general case, but Explorer happily ignores not being able to read its policy settings.
For types of policies that don't apply via registry settings (i.e. policies that use other extension handlers like IE policy, folder redirection, etc) you'll need to employ other means to circumvent the settings client-side.
Before anybody critisizes me for letting a user in on a "secret" way to circumvent their IT department's policies think about how the sysadmins, in this case, shouldn't be granting users local Administrator rights to begin with.


Centering divs in a row

Question: I have a row of divs with classes called card. There can be up to three cards within a row. Each card has a width of 33%.
The html looks like...

card

card 2

card 3

card

card 2

The CSS looks like...
.row {
  padding: 20px;
}

.card {
  width: 33%;
  float: left;
  border: solid 1px black;
  position: relative;
}

I've also created a codepen here.
What I want is to center these cards if there are less than 3 cards in a row.
How do I do this?
Normally 3 cards in a row would look like...
-------------------------------------------------------------------------------------------
|                             |                                |                          |
|                             |                                |                          |
|                             |                                |                          |
|                             |                                |                          |
|        card                 |            card                |        card              |
|                             |                                |                          |
|                             |                                |                          |
|                             |                                |                          |
|                             |                                |                          |
|                             |                                |                          |
-------------------------------------------------------------------------------------------

When we have 2 cards in a row it looks like...
--------------------------------------------------------
|                        |                             |
|                        |                             |
|                        |                             |
|                        |                             |
|                        |                             |
|         card           |            card             |
|                        |                             |
|                        |                             |
|                        |                             |
|                        |                             |
--------------------------------------------------------

We want the 2 cards to be centered like so...
                   -----------------------------------------------------
                   |                        |                          |
                   |                        |                          |
                   |                        |                          |
                   |                        |                          |
                   |                        |                          |
                   |         card           |          card            |
                   |                        |                          |
                   |                        |                          |
                   |                        |                          |
                   |                        |                          |
                   -----------------------------------------------------

Answer: Use inline-block instead of float and text-align: center;
.row {
  padding: 20px;
  text-align: center;
}

.card {
  width: 33%;
  display: inline-block;
  border: solid 1px black;
}

http://codepen.io/anon/pen/PbeZgd
Answer: you can use css3 flexbox concept concept for this,set the display property of your parent tag(.row) to flex.and then use justify-content property and set it's value to center.

.row {
  padding: 20px;
  display: flex;
  justify-content :center;
}

.card {
  width: 33%;
  height:100px;
  /*float: left;*/
  border: solid 1px black;
  /*position: relative;*/
}

card

card 2

card 3

card

card 2

Comment: Hmm this works really well. The only problem is that this solution isn't mobile friendly for me. In smaller widths the boxes overlap when in reality I would like for them stack on top of one another.
Answer: You can consider using display:flex and justify-content:center for this
check this snippet

.row {
  display: flex;
  justify-content: center;
}
.card {
  width: 20%;
  height: 50px;
  border: 1px dashed;
}

card

card 2

card 3

card

card 2

Hope it helps
Comment: I would recommend giving flexbox a shot, too. It's a great skill to have!

Centering divs in a row


Spectral sequences on their own right

Question: I have begun to read a bit about Spectral Sequences. I have been studying some topics of algebraic topology and this "tool" came up from time to time. I didn't need to go deep, but I felt I had to read a bit. Things started to get more delicate, e.g. the Adams S.S., and more stuff. So I wondered (before attempting this), if these things are important in their own right. I guess so, but I wonder what part of mathematics concentrate on them, and what "gadgets" and conjectures exist about them, independently if may be of where you will use them. I would ask for reference, also, thanks in advance.
Comment: I tried to add the reference request tag to your post - is there a relevant related field you also wanted to look at? I'm not familiar with Spectral Sequences, but that sounds a bit like Linear Algebra, while you have mentioned it in algebraic topology and tagged category theory ...
Comment: I think a lot of spectral sequences can be viewed as special cases of the spectral sequence where $E^2_{ij} = R^i F (R^j G (X))$ and $\bigoplus_{i+j=n} E^\infty_{ij} \simeq R^n (F \circ G)(X)$ - which is a fairly general category theoretic construction relating compositions of derived functors to derived functors of compositions.  (Not completely sure about the details of this, though, so I'm not sure I could expand this to a full answer.)
Comment: Thanks, interesting viewpoint, I 'll try to check it out
Answer: Spectral sequences are very useful, but they're not studied in their own right. The book of McCleary, "User's Guide to Spectral Sequences", is the most extensive reference.
Answer: Actually, spectral sequences are studied in their own right as a technical tool. The first spectral sequences you see are probably the bounded ones, like first-quadrant spectral sequences. Those are pretty easy to use. But there are some subtle convergence questions that arose when more advanced spectral sequences were necessary.
A classic is Boardman's "Conditionally Convergent Spectral Sequences", where he develops convergent criteria for half-plane and whole-plane spectral sequences. The main focus of this paper is the study of spectral sequences.
Comment: Those are good news!

Spectral sequences on their own right


Permutations but with some numbers kept in an order

Question: Ok, I have had a browse around and I have looking for either a C or python solution to this problem. I would prefer python...although it is my weaker language (of 2 very weak languages).
A set of numbers, such as 0 0 1 7 0 0 3 0 0 4

Find all permutations of the set.
The numbers >0 must stay in that order (NOT POSITION!)
There MUST be a 0 between numbers, a 0 is not required at the start and end of the set though. As long as there is AT LEAST ONE 0 between numbers >0.

So firstly, I thought of just finding all possible permutations and then removing the chaff (checking that if n>0 , !n+1>0) for each permutation and then the first number >0 == 1, 2nd # >0 ==7 etc. etc.
I then stopped and thought that was daft, say there were 12 numbers, that would give 12! permutations. This in the order of 500,000,000 permutations of which I would have to run through again to get rid of chaff.
Say I had 40-50 sets of these number sets to go through, that is a fair whack of time.
Is there a more logical way?
I thought of somehow having python do permutations somehow taking those rules in to account (if n>0, n+1 MUST == 0) and (n=first number, n2=2nd etc.)
An example of a smaller set would be (NOT ALL PERMUTATIONS, but gives idea):
1,2,3,0,0,0,0,0

1,0,2,0,3,0,0,0
0,1,0,2,0,3,0,0
0,0,1,0,2,0,3,0
0,0,1,0,0,2,0,3
0,1,0,0,2,0,3,0

etc. etc.
So 1,2,3 is in order but the "0"s are just shifted about?
Thanks!
Comment: The second result of the smaller example seems to violate rule 3.
Comment: In the end, are you going to compare each one of these strings to some input, in order to validate that input?  If so, maybe research "edit distance" calculations instead of trying to brute-force every permutation.
Comment: If you do want to generate every permutation, it's actually a much smaller problem than `n!`. In your first example `1 0 7 0 3 0 4` is the inviolable core ordering, according to your three rules, into which you must now insert 3 extra zeros, placing them anywhere you like.  There are 8 positions for the first zero, 9 for the second, 10 for the third, so 720 possibilities.
Comment: Sorry, it is not homework. I am actually a science teacher and programming is my new hobby I am trying to learn. Sorry if I do not know the lores of StackOverflow.

Was told problems are the best way to go about it so found a problem and can not fathom the best solution.
Comment: Oooops....rushed thinking. Fixing it now.
Comment: @jez Thanks! I am looking that up now. Seems more of what I needed. Just did not know what it was called! Shift the space between and before/after the numbers.
Comment: @jez Adding a 0 before or after another 0 doesn't really give a unique sequence, though I suppose you could just filter them out in a later step.
Comment: Some comments: since the numbers stay in order you are left with just permuting on moving the excess zeros around right? So in your example 3 zeros are moved. Stack exchange is not here to do your homework for you. You indicate language by using tags. Read this: http://www.catb.org/esr/faqs/smart-questions.html, it helps you ask better questions and avoid irritating the people who you want to help you with their free time.
Answer: Basically you want to reduce the number of combinations you have to compute by grouping things according to their invariants.  Since the non-zero numbers must be in a fixed order let's start with that:
   1 2 3

Since there must be 0's between them add them in
   1 0 2 0 3

Now what you are left with is three 0's to place and you need to figure how many combinations give distinct sequences.  Clearly from this example the possible positions you have are: before the 1, between the 1 and 2, between the 2 and 3 and after the 3.  You have 4 positions in which to decide how to split up the remaining three 0's.  This is a combination problem with repetition, for which the solution here is (3 + 4 - 1) Choose 3 (which is 20).
Hopefully the way that I went through this example problem is enough for you to generalize this to arbitrary sequences, so I will leave that as an exercise to the reader.
Comment: @Jcov That was fast, did you implement and test this already?
Comment: Yep, this is bang on what I want. It is like I want to share a number between x spaces, getting all permutations of that instead.

Ticked and upvoted thanks!
Comment: Oh sorry, is the tick to say "I have done it" or to say "the best answer to the problem"? I am noob here :(.
Comment: @Jcov, I don't think it's a hard rule, but it is best to make sure that solved your problem first for a couple of reasons.  If there is a mistake in my work, people will be more likely to miss it because it's already marked correct.  Also, people are much less likely to answer a question with an accepted answer, so you're less likely to get better (or correct, if my answer has a mistake) answers, or other interesting input.
Comment: @Jcov, There's no harm in waiting for an answer, but at the same time if this answer does really solve your problem as well as you need and you don't really need more input (which may or may not come, if others answer or don't) then it's fine to mark it as correct right away and move on.
Comment: @Jcov, Again, these aren't rules, just my observations from questions I've seen go by and from ones I've asked myself.
Answer: def find_permutations(l):
    n = [e for e in l if e] # Strip zeros.
    # Interspace non-zeros with zeros.
    m = [j for i in n for j in (i,0)][:-1]
    def fill(m):
        if len(m) == len(l):
            yield tuple(m)
        else:
            # Recursively fill with zeros.
            for i in range(len(m)+1):
                for o in fill(m[:i] + [0] + m[i:]):
                    yield tuple(o)
    return sorted(set(fill(m)))

I think this should cover it. So for instance (in python 3), you could do:
>>> [print(p) for p in find_permutations([1,2,3,0,0,0,0,0])]
(0, 0, 0, 1, 0, 2, 0, 3)
(0, 0, 1, 0, 0, 2, 0, 3)
(0, 0, 1, 0, 2, 0, 0, 3)
(0, 0, 1, 0, 2, 0, 3, 0)
(0, 1, 0, 0, 0, 2, 0, 3)
(0, 1, 0, 0, 2, 0, 0, 3)
(0, 1, 0, 0, 2, 0, 3, 0)
(0, 1, 0, 2, 0, 0, 0, 3)
(0, 1, 0, 2, 0, 0, 3, 0)
(0, 1, 0, 2, 0, 3, 0, 0)
(1, 0, 0, 0, 0, 2, 0, 3)
(1, 0, 0, 0, 2, 0, 0, 3)
(1, 0, 0, 0, 2, 0, 3, 0)
(1, 0, 0, 2, 0, 0, 0, 3)
(1, 0, 0, 2, 0, 0, 3, 0)
(1, 0, 0, 2, 0, 3, 0, 0)
(1, 0, 2, 0, 0, 0, 0, 3)
(1, 0, 2, 0, 0, 0, 3, 0)
(1, 0, 2, 0, 0, 3, 0, 0)
(1, 0, 2, 0, 3, 0, 0, 0)

Was this similar to what you had in mind?
Edit: basically what the function called fill does is insert a zero between each number of the list, and recurse. Whenever enough numbers are recorded in the fill function (list length of recursively generated numbers equals list length of original input) a tuple of numbers is returned.
The only reason for converting to tuples when returning is that the type must be hashable to use in a set, as seen on the last line of the find_permutations function. sorted is for niceness.
Comment: Zero stripping is using [list comprehension](https://docs.python.org/3.5/tutorial/datastructures.html#list-comprehensions). It's an extremely powerful language construct, which basically just rolls up your for loop in one line and returns a new list, functional style.
Comment: Whoa ummm yeah bang on.
Now I need to spend about a week knowing how on Earth that works! Thanks.
Even the stripping zeros has me lost.


VLAN over VPN (ASA 5520)? if not any other options available?

Question: Is it possible to extend the local VLANs to a Remote site connected by IPSEC VPN using ASA 5520 / Cisco 1841 DSL router.
can we have many VPN tunnels between the ASAs? (from every VLAN one vpn each?)
if not any other options/combinations available?
Comment: I presume you're asking about L2 vlans? As in extending a broadcast domain over your tunnel?
Answer:
Is it possible to extend the local VLANs to a Remote site connected by IPSEC VPN

No, per definition. IpSec is an IP level security tunnel. Vlans are ethernet level.

can we have many VPN tunnels between the ASAs

Yes. This is a maintenance nightmare if it gets too much and is not automated in management, but it is possible.

if not any other options/combinations available?

If you put up an ethernet tunnel between them - not sure this is possible - you can then use the "normal" VLAN packets.
http://www.cisco.com/en/US/docs/ios-xml/ios/interface/configuration/xe-3s/ir-eogre.html
has some information, though I am not sure this works on the 1841. But this would allow you to basically send ethernet frames with VLAN information embedded.
Alternatively a multi routing table setup may work - depends on WHY you have VLANS in the first place. or something based on MPLS - VPLS. The 1841 does not talk that one though.
More professional routers may allow something like NVGRE for that purpose. Well, not exactly professional - but the 1841 is more an edge level router not something to use in the core.
It seems that the 1841 can do VPLS - that would work best then. Requires you to configure a MPLS setup.
Main problem answering is that a lot of the choices depends on what you actually try to do from a  business point of view and how much control you have over the routers at each endpoint.
Answer: Normally you can extend your local LAN to a remote site using common IPsec / Layer 3. Search for Site-to-site, lan-to-lan ipsec VPN.
There are a lot of options, my favorite one is to use GRE over IPsec, but you need routers on both ends. If you can tell us what devices you have available on hub/spoke sites it would help in order to give you a more specific answer.
If you want to extend your layer 2 network, which is not a very good idea for many reasons, I believe that the best option is to use L2TPv3 over IPsec. Again you need routers on both ends.
You have to take care of many issues though, such as MTU sizes which could overload your router if you don't pay attention to details, broadcast, multicast, spanning-tree, redundancy etc which are handled easier on Layer3 VPN.
Comment: +1 for example of a protocol combo that actually allows VLAN bridging over ip router boundaries (and the caveats of doing it).
Answer: You can use NAT on the ASA and router IPSec tunnel to connect the overlapping subnets.  You can put additional subnets in the IPSec tunnel by adding them to the IPSec tunnel protected networks (the ACL referenced by the tunnel configuration), instead of creating a tunnel for each subnet to subnet connection.  If the devices at each site have to communicate with each other at layer 2, you will need to extend the LAN with a layer 2 wan link or layer 2 tunneling protocol.  If you use NAT on an IPSec tunnel, the devices at each site will not be able to communicate with each other at layer 2.


Overwrite the url function of a specific node entity

Question: Can I overwrite the url function of a specific content type of node entity ?
 So to have a different pattern when i use: $node->url();
Answer: Entity URI callback
You can implement an URI callback. Example in comment.module:
/**
 * Entity URI callback.
 */
function comment_uri(CommentInterface $comment) {
  return new Url(
    'entity.comment.canonical',
    [
      'comment' => $comment->id(),
    ],
    ['fragment' => 'comment-' . $comment->id()]
  );
}

and add the callback to the annotations of the entity type:
*   uri_callback = "comment_uri",

For an existing entity use a hook_entity_type_alter().
Bundle specific URI callback
A URI callback for a specific content type can be defined in the bundle definitions:
**
 * Implements hook_entity_bundle_info_alter().
 */
function mymodule_entity_bundle_info_alter(&$bundles) {
  if (isset($bundles['node']['my_content_type'])) {
    $bundles['node']['my_content_type']['uri_callback'] = 'my_content_type_uri';
  }
}

The callback:
/**
 * Bundle URI callback.
 */
function my_content_type_uri(NodeInterface $node) {
  // build a url object $url
  return $url;
}

A bundle-specific callback takes precedence over the generic one for the entity type and a link template (defined in the links array of the entity type) takes precedence over both, so you need to remove the link template if you want to override an existing one, e.g. canonical, which makes you responsible to provide the route needed for the custom url, if it was built before by a route provider and is not defined in a *.routing.yml file.

Edit:
To modify the url in links to a specific content type you can use a hook_link_alter():
function mymodule_link_alter(&$variables) {
  $url = $variables['url'];
  if ($url->isRouted() && $url->getRouteName() == 'entity.node.canonical') {
    if (isset($variables['options']['entity'])) {
      $node = $variables['options']['entity'];
      if ($node->bundle() == 'article') {
        // modify the links to articles
      }
    }
  }
}

Comment: This is what I understand how the code works, but how does the mentioned uri callback of the comment module gets called for canonical urls, when the comment entity has a link template defined?
Comment: Indeed the uri callback in the comment module does not run during normal operation of the site. comment::permalink() adds the fragment instead.
Comment: ! Don't work:

  function commerce_entity_bundle_info_alter(&$bundles) {
    if (isset($bundles['node']['product_display'])) {
      $bundles['node']['product_display']['uri_callback'] = 'product_display_uri';
    }
  }

  function product_display_uri(NodeInterface $node) {
    return Url::fromRoute('my.route');
  }

$node->url(); get canonical url @4k4
Comment: This is the problem I've described. If you use url() without parameter you get the canonical link and this will be returned according to the link template  in the entity definition.
Comment: I would like to overwrite the method, so that the views (for example, content) automatically have the new url. What do you advise ?
Comment: You can use a hook_link_alter(), see edit.
Comment: This is incorrect. If i use $node->link() i have correct url generated by: mymodule_link_alter but if i use $node->url the hook does not work. Please, u know a specific hook for ->url() ?
Comment: The original question was about the entity level. Then you've asked in the comment before about links in views and I tried to help with an approach to overwrite the url for a specific content type on this level. Of course this happens later than the url() method of the entity.
Comment: So what would you recommend?
Comment: If you can use a custom link relation instead of canonical in url(), then it's easy to implement a bundle specific callback as described. For the canonical link template it is theoretically possible, but there are a lot of things that can go wrong. So I would look for another approach, like the one for view links.
Comment: I solved using the function: -> toUrl () and using a non-existent "$ ref", so read the uri_callback
Comment: But in this way I can not define more uri_callback for bundle
 :(
Comment: I have an example of a bundle specific uri callback for one node bundle with a fallback for all the other bundles: https://drupal.stackexchange.com/a/246712/45409


Does std::list guarantee that items will never be moved to a different memory location?

Question: Is it guaranteed that once std::list or std::forward_list item is allocated, it will remain at the same memory location (address) until destroyed? Except, of course, for the list itself being copied.
Comment: If it could move, wouldn't that invalidate all pointers against it?  That doesn't sound like it could happen.
Comment: @TrippKinetics: my point exactly. I want to know if it's safe to store direct pointer to nodes, as opposed to always accessing the items via `std::list` interface.
Comment: The accepted answer to [this question](http://stackoverflow.com/q/16027044/3549027) confirms that `insert` and `remove` will not invalidate iterators, but that is not quite a full answer to the question, IMO...
Answer: If you look at the documentation for all the functions which don't destroy elements, (insert, emplace, push_back, etc...), you will see that they have a note that "no references are invalidated", which is equivalent to what you are asking (objects staying at the same memory location). So, yes.


Detecting a Click on Stage but not on Shape in KineticJS

Question: In KineticJS, how do you detect a Click event where the click occurs outside an object/shape?
I am trying to get a Rect to change its scale to 2 when a user clicks on it, and return back to a scale of 1 when the user clicks anywhere outside it.
JSfiddle: http://jsfiddle.net/ABTAD/8/
Managed to detect a click on stage, but clicking on the Rect also fires the click handler!!! And somehow the .setScale(1) does not do anything, while console.log printes something out. How can I prevent the click handler from firing when the click is made on the Rect instead of the empty stage?
JS Code to detect click on stage
window.stage.getContainer().addEventListener('click', function(e) {
    $.each(window.layer.get('.box'), function(index, box) {
       box.setScale(1);
       console.log('clicked on stage');
    });
});

Comment: http://jsfiddle.net/ABTAD/11/
Comment: You know Im still learning Kinetic, but heres a JS pointer.  You dont need to put window before things to make them global.  If you put var before a variable decleration then it will be only available in the scope/function it was created in.  Not putting the var before the variable decleration will make it global (the same as putting window. before it).  Did you see this post?.. http://stackoverflow.com/questions/13866660/create-a-rectangle-with-mousedown-event-in-kineticjs he put a rect as the first layer that you can then check against.  Also, is it a good idea to use normal events?
Comment: Thanks!! I actually namespaced them with like `var App = {}; App.stage = ...` Havent seen that post, sounds like a gd idea
Comment: Awesome, you've nailed it.
Answer: you can access the stage content wrapper with stage.getContent().  From there, you can add an event handler like this:
stage.getContent().addEventListener('click', ...); // regular javascript
or
$(stage.getContent()).on('click', ...); // jquery
Comment: From KineticJS 4.3.1 getDOM() is renamed to getContent()
Comment: Hi, can this be done on layers, without having to set a background rect and bind the click event on it?


Drupal aligning blocks and content next to each other

Question: i have a view page and two blocks which i want to display next to each other. I want view content on left and two blocks on right, with one block on top and other just below it. But i am having trouble in achieving the same. My html guy says its not possible to do that without a wrapper container as we need to have things in center as well.
I have omega 4 installed, so sidebar is also below the content block. Also i don't have consistent layout view, as on some pages i have only content with full screen background, and with no side content and on some i have content in which i am facing a problem.
I have searched on google and SO but every solution says to have a wrapper, which is not possible as placing a wrapper globally will limit the display on every screen, which i can't have.
One solution i can think of is use javascript to add classes on page load where i have two column display but it is not a good way to do that i believe.
How can i solve this, can anyone please help??
Answer: You can make use of  Panels Module to achieve any kind of Complex Layouts
Answer: My friend.
Your Html guy is right about the wrapper things.
Don't worry in drupal it is very simple to create a custom 'block-table-type' layout .
It is can be achieved by Panels and Minipanels.
Now, How will you do it ?
This markup your HTML guy needs will be generated in three easy steps

Download and enable the Panels and  Mini panel module by going to admin/modules page. (You will get 5 new modules with this main module - panels_node, panels_mini, panels_ipe, i18n_panels, panels).
All these 5 modules hold their dependencies on [ctools] module which you need to download and enable before enabling these modules2
Then go to Structure > Mini Panel > Add mini panel button and complete the simple creation wizard. STEPS. settings - Add the Administrative title for the minipanel. Hit next -> Context- (Here You add the context for the mini panel - In our case we don't need it). Hit next. Then , Select the layout from the drop box.
Finally , Add the blocks or fields you want that minipanels in the different frames by selecting Add Content link comes when you will click on the cogwheel placed on the top right part. And hit save. Now you will get this mini panel as a block in your blocks list . Just go to structure > blocks . This block will be a div which will wrap your other blocks (That you have added to it) in the proper markup your HTML guy needs ;). Now you just need to place this block to some region.

The beauty of this module is that you can add a minipanel into another mini panel and can accomplish any complex grid design. Moreover if you enable Panel Node module than you can add new node specific grid page , called panel variant n drupal way of speaking.
Hope this helps . Have fun !
Comment: Only i can accept one correct answer and first Pravin guided me into right direction so hence his answer is accepted as an answer :)
Comment: Its alright . The main motive is to give you the proper Idea about this module .:)


Obter valor 3 linhas após determinada palavra

Question: Tenho o OCR abaixo e estou precisando obter o valor 254.878,00, no regex que fiz está pegando o valor 8.571.962,06. Pela palavra OUTRAS INFORMAÇÕES seria o ideal em função do texto ser negrito e sempre tem uma qualidade boa após a extração do OCR.
9135,456,07
8.571.962,06
OUTRAS INFORMAÇÕES
Rendimentos isentos e não tributáveis
0.00
254.878,00
0,00
Rendimentos sujeitos a tributação exclusiva/definitiva
Rendimentos tributáveis - imposto con exigibilidade suspensa

REGEX:
(?<valor>\d{1,3}(?:\.\d{3})*,\d{2})(?=\s*(?:\r\n?|\n)OUTRAS INFORMA.*?.*?ES\s*(?:\r\n?|\n))

Answer: Na sua regex você colocou o trecho referente à "OUTRAS INFORMAÇÕES" depois do número, mas como o número que você quer está depois, então você deve inverter e colocar "OUTRAS INFORMAÇÕES" antes:
OUTRAS INFORMA..ES.*(?:\r\n?|\n)(?:.+(?:\r\n?|\n)){2}(\d{1,3}(?:\.\d{3}),\d{2})

Depois de "OUTRAS INFORMAÇÕES", eu coloco .*(?:\r\n?|\n) (zero ou mais caracteres e a quebra de linha).
Depois temos (?:.+(?:\r\n?|\n)){2}:

.+ é "um ou mais caracteres". Mas como o ponto por padrão não corresponde a quebras de linha, eu garanto que ele só vai até o fim da linha (mas se quiser ser mais explícito, também pode trocar por [^\n\r]+ - qualquer coisa que não seja \n nem \r).
depois eu pego a quebra de linha: um \r seguido ou não de um \n, ou um \n sozinho (contemplando assim as quebras de linha do Windows, MacOs e Unix)
tudo isso se repete duas vezes, garantindo que vou pular duas linhas depois de "OUTRAS INFORMAÇÕES" (o quantificador {2} indica que o trecho "vários caracteres + quebra de linha" se repete várias vezes, então nesse caso ele indica a quantidade de linhas a serem puladas)

Depois, eu pego o número. Como ele está entre parênteses, isso forma um grupo de captura, e por isso estará no primeiro grupo de captura (os demais parênteses começam com (?: e com isso eles não formam grupos de captura).

Algumas engines suportam o atalho \R, que corresponde a uma quebra de linha (seja o \n ou \r sozinhos, ou a sequência \r\n, entre outros - a lista completa varia conforme a linguagem). Então a regex também poderia ser:
OUTRAS INFORMA..ES.*\R(?:.+\R){2}(\d{1,3}(?:\.\d{3}),\d{2})

Comment: Excelente, deu certo aqui. Muito obrigado
Comment: @user2254936 Ah, é porque a regex que pega o número exige que a parte `\.\d{3}` exista. Basta deixá-la opcional, assim: `(\d{1,3}(?:\.\d{3})*,\d{2})` - [veja](https://regex101.com/r/4F0wED/1/)
Comment: Se fosse para eu pegar o valor 0,00 como eu faria para pular mais uma linha? @hkotsubo
Comment: @user2254936 No trecho `(?:.+(?:\r\n?|\n)){2}`, o número 2 indica que vai pular duas linhas. Então basta trocar pela quantidade de linhas que vc quer pular
Comment: deu certo não :( estou testado no https://regex101.com/
Comment: Agora sim, muito obrigado


How to express the agreement between experiment and theoretical observation?

Question: Let us suppose I have a value measured from experiment and given by
$$V_{\text{exp}}  \pm \sigma_{V_{\text{exp}}}$$ and a theoretical value given as
$$V_{\text{the}}  \pm \sigma_{V_{\text{the}}}$$
Is there a statistical way to measure how well $V_{\text{the}}$ matches with the $V_{\text{exp}}$.
In other words, what is the right way to tell that $V_{\text{the}}$ is a valid theory (or not) for the given experimental result?
It seems to be that we should take the difference,
$$ (V_{\text{exp}}  \pm \sigma_{V_{\text{exp}}})- (V_{\text{the}}  \pm \sigma_{V_{\text{the}}})$$
and that is $$(V_{\text{exp}} - V_{\text{the}}) \pm \sqrt{\sigma_{V_{\text{exp}}}^2 + \sigma_{V_{\text{the}}}^2} \equiv \Delta V \pm \sigma_{\Delta V}$$
If $$\Delta V - \sigma_{\Delta V} < 0 < \Delta V + \sigma_{\Delta V}$$ we say that the theory is valid I guess. But is a there a measure of how valid...like at which $\sigma$ ?
I guess it is $$\frac{\sigma_{\Delta V}}{\Delta V}$$, but I am not sure. Any help would be appreciated.
Answer: Since you are only dealing with mean values and their standard errors, you can rephrase the task as comparing the (assumed) norm distribution of the sample mean and the distribution of the theoretical mean (and its variation, given a certain sample size).
Assuming normal distributions, this task can be achieved by the KS-test which allows to compare two distributions.
Comment: The KS test doesn't work that way: you don't get to construct two distributions from a few parameters, estimated or not.  It only applies to actual *iid* samples, which is not the case here.
Comment: The KS test is not the solution to this problem.
Comment: @whuber why can't we use the KS test? If only the mean and the standard deviations matter, then we can compute the KS test for the two corresponding normal distributions in order to see if the experimental distribution matches the theoretical normal distribution. Note that the original question omits higher moments so assuming a normal distribution looks good to me. I am curious to learn why this approach is not sound :)


Calender and SimpleDateFormat outputting the wrong date

Question: Whenever i do this code
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("D:M:Y");

System.out.println("Date Launched: " + "[" + sdf.format(cal.getTime()) + "]");

It prints out
 Date Launched: [285:10:2015]

How can i get it so it prints out the actual date like [12/10/2015]?
Comment: Please search StackOverflow before posting. This problem has been covered hundreds of times already. Rather than intuiting the parsing pattern codes, study the [class documentation](http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html). And copy working code provided in the many examples found here.
Answer: SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");//d small

SimpleDateFormat doc
Answer: You are setting wrong format.
Instead of:
SimpleDateFormat sdf = new SimpleDateFormat("D:M:Y");

Use:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

Where:
y   Year            Year    1996; 96
Y   Week year       Year    2009; 09
M   Month in year   Month   July; Jul; 07
w   Week in year    Number  27
W   Week in month   Number  2
D   Day in year     Number  189
d   Day in month    Number  10

You can read more about SimpleDateFormat in oracle's documentation here.
Answer: Use
SimpleDateFormat sdf = new SimpleDateFormat("d/M/Y");

Answer: try below code
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

symbol 'd' means day in month
symbol 'D' means day in year
Answer: use dd/MM/yyyy instead of D:M:Y so your code looks like
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

System.out.println("Date Launched: " + "[" + sdf.format(cal.getTime()) + "]");

because D gives Day in year bt u want day in month
M gives Month in year
Y gives Year


How to call the refreshing of data-aware (live-binding) component in FireMonkey?

Question: I have a TListView linked in LiveBindings with a TFDMemTable. I load data in the FDMemTable using LoadFromFile (I have for example 20 record).
When I delete a record from the FDMemTable, the RecordCount is decreased but the TListView is not refreshed, it continue to display the 20 records loaded on the LoadFormFile.
If, with the FDMemTable: I .SaveToFile, .Close, and reload with .LoadFromFile, the TListView now display the change.
This is the same behavior if I use the CachedUpdate of FDMemTable or not.
I've tried to call TFDMemTable.Refresh and TListView.Repaint without succes.
Is it possible to call the TListView to refresh his "linked" set of data ?
When I delete a record in the FDMemTable, why no visible refresh occur on the TListView ?
EDIT:
I must add a thing, the record is deleted programmatically.
The desired functionality is to delete sone unwanted record in the FDMemTable and display the remaining record to the user with the TListView.
Comment: @Fabrizio:  Uh?  Isn't the whole idea of live bindings is to be able to use non-db-aware components with datasets ...
Comment: @MartynA Ops, I misread, sorry
Answer: In LiveBindings Designer, by linking the Synch of the ListView to the * of the FDMemTable, the ListView now display the resulting record.

Also in my last algorithm, because I use .BeginBatch / .EndBatch (that disable data-aware refreshing), while processing data for removing unwanted record I've to disable the LiveBinding link temporarily (cause I use different sorting index whitin the processing of the data): LinkListControlToField1.Active := false; and "re-link" it after processing: LinkListControlToField1.Active := true;
Answer: The livebindings isn't consistently bi-directional here. The ListView livebindings was designed to work from the UI to the dataset direction, but only mostly.
If you enable CanSwipeDelete, you can expect that to work, if you know how.
In my case, on Android, I found myself writing code to ensure that the listview kept sync with the dataset, even though there is livebindings active. In my case is  a TClientDataset named CDSAnimals, with a unique key value of TagID. I hope this helps.
procedure TfrmLiveMain.ListView1DeletingItem(Sender: TObject; AIndex: Integer;
  var ACanDelete: Boolean);
var
  LI: TListViewItem;
  LIO: TListItemText;
begin

  // check that the livebindings is doing it's job, if not
  // do it myself
  ACanDelete := False;
  LI := ListView1.Items[AIndex];
  LIO := LI.Objects.FindObjectT<TListItemText>('Text1');
  FTagID := LIO.Text;
  if ClientModule2.CDSAnimals.FieldByName('TagID').AsString <> FTagID then
    ClientModule2.CDSAnimals.Locate('TagID', FTagID, []);
  if ClientModule2.CDSAnimals.FieldByName('TagID').AsString = FTagID then
  begin
    ACanDelete := True; // causes the listview item to be deleted without
                        // affecting the corresponding dataset record
  end;

end;

procedure TfrmLiveMain.ListView1DeleteItem(Sender: TObject; AIndex: Integer);
begin

  // this is called with the wrong index!
  if ClientModule2.CDSAnimals.Locate('TagID', FTagID, []) then
    if ClientModule2.CDSAnimals.FieldByName('TagID').AsString = FTagID then
      begin
        // now delete the corresponding record too
        ClientModule2.CDSAnimals.Delete; // and it works!
      end;

end;

Comment: Your idea drive me to a possible workaroud: deleting the item object of the `TListView` WHILE deleting record in the `TFDMemTable`. I don't know if it's a bug in Delphi but I've tried with some TMS component and this problem do not occur.
Comment: Another workaround is to work with 2 `TFDMemTable`, One for process the deleting of unwanted record and one for display (using LiveBindings) then usigng `CopyDataSet` to copy the process dataset in the display dataset. This is working (we must `.Close` the display dataset before unsing `CopyDataSet`).
Comment: Did you ever encounter any of the errors mentioned [here](https://stackoverflow.com/questions/69791689/how-to-delete-a-database-record-linked-to-a-listview-item)? this happens after calling `delete` on the dataset record and LiveBinding is trying to delete the `listViwItem` that doesn't exist anymore.


ArgumentOutOfRangeException with data-binding when debugger is running [VS2010]

Question: Problem
Suppose that you are having a class that you want to perform data-binding on. It looks like that:
public class DataClass
{
    private DateTime date;

    public DataClass()
    {
        date = new DateTime(2014, 1, 1);
    }

    public DateTime Date
    {
        get { return date; }
        set { date = value; }
    }

}

Now suppose that you have a form and that you want to bind an instance of DataClass on a DateTimePicker in that form. You create and initialize the databinding like this (Designer code):
bindingSource = new System.Windows.Forms.BindingSource(this.components);
bindingSource.DataSource = typeof(DataBindTest.DataClass)

Then you (inevitably) bind to the date picker (Designer code):
dateTimePicker.DataBindings.Add(new System.Windows.Forms.Binding("Value", this.bindingSource, "Date", true));

and set the desired object to the data source:
bindingSource.DataSource = new DataClass();

When you try to debug your app, you get that Exception:

ArgumentOutOfRangeException Value of '1/1/0001 00:00:00' is not valid for 'Value'. 'Value' should be between 'MinDate' and 'MaxDate'.

Funny thing though, when you try to run (i.e. no debugger) the app, everything is fine.
Attempted Solutions
I tried to set the Data Source Update Mode to "Never", I tried to set Format Type to "Date Time", I tried to set Null Value to something like "01/01/2000" (without quotes) and guess what, nothing significant happened.
Now there are some solutions eg

don't use data binding or
subclass the date picker and "override" Value so that it's not punishing you for giving it such a low value or (even better)
find out why the heck the binding process passes an unused value to the binded control while the desired value is right there, in the object.

That's true for every range checking control such as NumericUpDowns. So I am looking for an answer (and hopefully a solution) for the last question. I can't believe that somebody, while implementing the binding process, had the idea to pass default values in the properties and did not predict for the case of range checking controls.
Edit
One more important thing: The problem is not reproducible on .net framework 3.5 it's on 4.0 that I use.
Comment: This code must works without problem.
Answer: I found that I had the same problem while binding the Value property of the DateTimePicker (in .Net 4.5).
The problems disappeared when binding the same DateTime struct to the Text property of the picker.
It is a bit counter-intuitive, but it works fine both ways (displaying an existing value and storing a selected date to the struct.
It still throws a First chance exception of type 'system.argumentoutofrangeexception', but that is caught by the dll where the same exception is not caught when binding to the Value property.
Hope that helps someone.
With regards,
Leo Prast


Module not found: Can't resolve 'axios' when importing module to react

Question: I'm creating a npm package, that requires axios.
When i import it in my react application i get

Module not found: Can't resolve 'axios' in
  '/Users/******/nodework/consume/node_modules/myModule'

I want the client to be able to install my package module, without having to install another dependency on their end. How would i do that give that im already using peerDepencies and devDependencies ?
for example this is my package.json for my module.
{
  "name": "myModule",
  "version": "1.6.4",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "axios": "^0.19.0"
  },
  "peerDependencies": {
    "axios": "^0.19.0"
  }
}

Comment: Your question is a bit confusing: So, are you saying that' you've "installed" your package, and listed axios as a dependency, but after installation your module is complaining that axios cannot be found?
Answer: Peer dependencies lets developers who are using your library know they need to install those libraries themselves because the library you wrote is using it. They will get "missing peer dependency" warnings when they install your library and do not have those installed yet.
The dev dependencies are typically for build tools like webpack, compilers, etc.
Both peer and dev dependencies will not be installed when a developer installs your library.
The clients will have to do something like npm i your-library axios to install both your library and the peer dependency.
If you want the developers to solely install your library without having to install extras on their own, like axios in this case, you will have to list is as a regular dependency.
{
  "dependencies": {
    "axios": "^0.19.0"
  }
}

Cheers


Enviar formulario sem aparecer o alerta do navegador

Question: Estou submetendo um formulário com JS e depois de dar tudo certo, faço o redirecionamento da página da seguinte forma:
window.location.href = '/admin/lojas/produtos';

O problema é que sempre aparece o alerta abaixo e o usuário tem que ficar clicando em "sair da página" para completar o redirect.

Eu sei que é normal aparecer esse alerta quando se faz o submit do formulário por POST, mas teria alguma forma de mudar a forma que estou fazendo o redirect para contornar esse aviso?
Comment: Cara, tem como mostrar o código? Tipo, geralmente esse alerta é ativado quando tem algo sendo processado ainda(se não me engano).
Comment: Não deveria dar esse aviso, a não ser que esteja direcionando para a mesma página. Neste caso, o navegador pode entender que o usuário pode perder os dados ao direcionar...
Answer: Caso alguém passe pelo mesmo problema, acabei conseguindo resolver ao inserir antes do redirecionamento o seguinte código:
window.onbeforeunload = null;


Ajustar tamanho da DIV ao conteúdo

Question: Estou trabalhando em um chat para um site, o chat está Ok, mas como sempre apanho para configurar o CSS.
Quero ajustar a DIV ao tamanho do conteúdo e colocar, só que a DIV ocupa 100% da largura.
.div-chat-i {
color:#000000;
background-color:#C6E2FF;
padding:5px 12px;
border-radius:10px;
border:1px solid #ddd;
width: auto; }

Answer: A div é um elemento do tipo bloco, e por default ocupa 100% da largura da tela, ou do elemento do qual estiver dentro.
Veja no exemplo abaixo que eu coloquei ela com 15% da largura do pai, que no caso é o body, que por default tem 100% da largura da tela...
EDIT: No exemplo que fiz, deixe a div, com largura mínima de 15% e máxima de 25%, então se o conteúdo for pequeno ocupa no mínimo 15%, e se form maior que 25% a linha vai quebrar.
OBS: usei position:absolut para posicionar o chat no canto inferior direito

.div-chat-i {
    color:#000000;
    background-color:#C6E2FF;
    padding:5px 12px;
    border-radius:10px;
    border:1px solid #ddd;
    /* estilo de posicionamento e largura*/
    min-width: 15%;
    max-width: 25%;
    position: absolute;
    bottom: 10px;
    right: 10px;
    left: auto;
}

Lorem, ipsum dolor.

Lorem ipsum dolor sit amet consectetur adipisicing elit. Numquam asperiores ratione adipisci dolorem animi ut.

Comment: Value Hugo, ajustei tamanhos para não coupar 100%

Ajustar tamanho da DIV ao conteúdo


How can I add sort criteria for search api views?

Question: I set up a view with search api data according to this, but the sort criteria available in each view are not complete. I'd like to sort on some fields (indexed) that are not showing in the list. I'm wondering if I need to use a hook to alter the query, or if there's a configuration option somewhere that I've not read about.
Comment: exactly what you want to sort?
Answer: I just discovered that if I re-index the fields (in this case, first name and last name) as strings, rather than the default fulltext, they are made available to sort on in views. This is great news.


delete the duplicate record, and keep the one that has the lower id

Question: id  | MEMBER_BADGE_ID | MEMBER_ID
3127| 859986          | 2320
3128| 859986          | 2320
2461| 860058          | 1915
2545| 860062          | 1921
2546| 860062          | 1921
2460| 860063          | 1164
2468| 860064          | 1919
2469| 860064          | 1919
2472| 860067          | 1921
2476| 860076          | 1923
2547| 860077          | 1930
2489| 860086          | 1930
2474| 860089          | 1922
2475| 860089          | 1922
2477| 8600102         | 1924

I would like to remove the duplicate row with the oldest ID in the whole table.
select id,MEMBER_BADGE_ID,MEMBER_ID
from MEMBERS
order by MEMBER_BADGE_ID

Comment: What database system are you using?
Answer: This this:
    DELETE FROM MEMBERS
    WHERE id IN (
    SELECT MIN(id) id
    FROM MEMBERS
    group by MEMBER_BADGE_ID, MEMBER_ID
    having count(*) >1)

Comment: Care to share why it won't work? I just tried it and it works.
Comment: This is a valid answer @VarunMehta. Result will be
(3128, 859986, 2320) and  (2546, 860062, 1921)
Comment: If you're using GROUP BY in a query, all items in your SELECT statement must either be contained as part of an aggregate function, e.g. Sum() or Count() , else they will also need to be included in the GROUP BY clause. ... You need to use an Aggregate function and then group by any non-aggregated columns.
Comment: @VarunMehta Isn't MIN() an aggregate function? https://learn.microsoft.com/en-us/sql/t-sql/functions/aggregate-functions-transact-sql


How to get Java, Java EE and Hibernate plugins for Eclipse Helios by yum?

Question: I need Java, Java-EE, and Hibernate plugins for Eclipse Helios. I installed Eclipse Helios in Cent OS using the following command:
<code>yum install eclipse-platform
</code>
But it does not contain any plugins. I want to work with Java, Java EE and Hibernate. From where can I get the plugins?
Comment: Check the eclipse marketplace.
Answer: Don't use yum to install Eclipse. It's far better to get it from the eclipse.org web site. Remove whatever you've installed via yum, then go to http://www.eclipse.org/downloads and get the package you want. Install that, and then make sure you're using the Sun/Oracle JDK, not gcj, by specifying it as described here.
Answer: Why not check Help->Eclipse Marketplace menu and search for whatever you want.
Comment: I dont have a option in my eclipse..I tried through adding install new software option but i failed...
Comment: Eclipse Marketplace wasn't present in all packages in Helios. Go by the answer provided by E-Riz. It is always better to get standalone software directly from the source rather than relying on OS package maintainers whose database may be years out of date.


Show Distance in table from openlayers

Question: So I followed the instructions from this thread; Need a simple Google Maps solution; lost in the labyrinth of modules. I've gotten everything to work how I need it on my test server a few months ago. The SS below shows how it looks with the distance/proximity working.

Just before I got it working. I had a problem that the distance would not show based off the address or zip searched for. After some tinkering with views (atleast I think it was views), I finally got the distance working.
Now, my boss wants me to push it live and I can't remember how I got the distance to calculate based off an address or zipcode when I expose the proximity in views. It looks like the following;

I've opened both my test server and live side by side and checked over tons of the settings MANY MANY times over and still haven't been able to figure out what I missed. I've tried the following;

Refreshing the Proximity calculations via the openlayers/proximity tab
Tinkering with many different views settings.
Creating new test nodes
Rebuilding the process from the beginning

If you guys can maybe point me in the right direction or just mention SOMETHING that maybe I haven't thought about it would be great help. Thanks in advanced.
Answer: Have you got this sorted yet?
Ensure that you're using the "Geofield - proximity" field for output and not the Proximity - distance field. I've tried using the latter and not had it working (yet).

Show Distance in table from openlayers