text:
Q: Custom markers showing with white color on some devices (Google Maps v3 Android SDK) I have Google Maps SDK running with custom markers on an android app. Everything works fine on our test phones -- an A7000, an Samsung and other. However, when I run the app on Nexus 5 or LG devices, one type of custom marker displaying white  on the map.
While the markers are showing white,will perform desired behavior.
We're super confused about this, especially because another custom marker (that is very similar) works fine. Other than hardware, the only other difference between our test phones and the Nexus 5 is that the Nexus is running Android 6.0, vs 5.x and 4.x for our test phones.
Code using to add marker
for(i=0;i<latLngs.size;i++)
{
LatLng latLng=latLngs.get(i);
Marker m = mMap.addMarker(new MarkerOptions().position(latLng).title("Title").icon(BitmapDescriptorFactory.fromResource(R.drawable.marker)));
}

for change the marker icon using
 m.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.marker1));

On nexus device google map appear like below, some off the markers become white ,i am using loop to add markers.

A: EDIT: With version 9.2.56 of the Google Play Services app released on June 13th, the bug has been fixed.
I found a workaround to your problem, however it is quite ugly and it's probably not advised to use it unless you know you're going to use a little number of markers.
Instead of this:
//Getting a reference to your activity's resources
final Resources resources = myActivity.getResources();
//Defining your drawable res id
final int resId = R.drawable.my_drawable_res_id;
marker.setIcon(BitmapDescriptorFactory.fromResource(resId));

Do this:
//Getting a reference to your activity's resources
final Resources resources = myActivity.getResources();
//Defining your drawable res id
final int resId = R.drawable.my_drawable_res_id;
marker.setIcon(
    BitmapDescriptorFactory.fromBitmap(
        BitmapFactory.decodeResource(resources, resId)));

Workaround found after reading this link (thanks @antonio in your comments):
https://code.google.com/p/gmaps-api-issues/issues/detail?id=9765
The bug is caused on certain devices with a recent version of the Google Play Services library (probably 8.7+ or 9+).
It happens if you share a BitmapDescriptor with multiple markers, so the workaround is to re-create one every time. I think  BitmapDescriptorFactory.fromResource might cache read resources somehow, that's why you need to decode it as a bitmap.
Here is the quote of the #10 reply of transbao at the link antonio gave:

We can repro this bug which causes certain marker icons to render as
  white patches. Your app may be affected if an icon bitmap is shared
  among multiple markers, although the issue only manifests in specific
  usage scenarios.
In the short term, we'd recommend the workaround in #8 -- use a unique
  Bitmap object for each marker:
marker.setIcon(BitmapDescriptorFactory.fromBitmap(
    BitmapFactory.decodeResource(getResources(),
  R.drawable.drawableid)));
and
new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(
    BitmapFactory.decodeResource(getResources(),
  R.drawable.drawableid)));
Creating a BitmapDescriptor once and reusing it won't be sufficient.
  E.g. if you're doing:
BitmapDescriptor bd = ...; marker1.setIcon(bd); marker2.setIcon(bd);
...then the workaround would be:
marker1.setIcon(BitmapDescriptorFactory.fromBitmap(
    BitmapFactory.decodeResource(getResources(),
  R.drawable.drawableid)));
  marker2.setIcon(BitmapDescriptorFactory.fromBitmap(
    BitmapFactory.decodeResource(getResources(),
  R.drawable.drawableid)));
Please note that, if your app uses a lot of markers, this workaround
  could possibly result in higher memory consumption. Also,
  unfortunately the workaround doesn't apply when the default icon is
  used via BitmapDescriptorFactory.defaultMarker().


text:
Q: Weka NominalToBinary makes test and training sets incompatible So I have a training and testing sets and they contain multi-valued nominal values. As long as I need to train & test NaiveBayesMultinomial classifier, which doesn't support multi-valued nominal values, I do the following:
java weka.filters.supervised.attribute.NominalToBinary -i train.arff -o train_bin.arff -c last
java weka.filters.supervised.attribute.NominalToBinary -i test.arff -o test_bin.arff -c last

Then i run this:
java weka.classifiers.bayes.NaiveBayesMultinomial -t train_bin.arff -T test_bin.arff

And the following error arises:
Weka exception: Train and test files not compatible!

As far as I understood after I examined both .arff files, they became incompatible after I ran NominalToBinary, since train and test sets are different and thus different binary variables are generated.
Is it possible to perform NominalToBinary conversion in a way that sets keep being compatible?

A: Concatenate the two sets into one, perform the NominalToBinary conversion, then split them again. This way, they should be normalized the same way.
But are you sure the files were compatible before? Or does maybe your test and/or training set contain attribute cases that the other doesn't have?

redpajama_set_name: RedPajamaStackExchange


text:
Q: WooCommerce - send email when order was created I am trying to send emails to multiple email adresses when order was placed. I am using woocommerce_thankyou hook. But emails simply not sending.
add_action( 'woocommerce_thankyou', function( $order_id ){
    $order = new WC_Order( $order_id );
    $paymentType = $order->payment_method_title;
    $firstName = $order->billing_first_name;
    $lastName = $order->billing_last_name;
    $billing_address = $order->billing_address_1;
    $billing_address2 = $order->billing_address_2;
    $billing_postcode = $order->billing_postcode;
    $billing_city = $order->billing_city;
    $billing_country = $order->billing_country;
    $billing_email = $order->billing_email;
    $billing_phone = $order->billing_phone;
    $totalRefunded = $order->get_total_refunded();
    $totalTaxRefunded = $order->get_total_tax_refunded();
    $totalShippingRefunded = $order->get_total_shipping_refunded();
    $total = $order->get_order_currency() . $order->get_total();
    $notes = $order->get_customer_order_notes();
    $company = $order->billing_company;
    $orderItems = $order->get_items();
    $subject = 'Order ' . $order_id . ' was placed';

    $message = '';
    $message .= "Payment Type: $paymentType
";
    $message .= "First Name: $firstName
";
    $message .= "Last Name: $lastName
";
    $message .= "Adress1: $billing_address
";
    $message .= "Adress2: $billing_address2
";
    $message .= "Post Code: $billing_postcode
";
    $message .= "City: $billing_city
";
    $message .= "Country: $billing_country
";
    $message .= "Email: $billing_email
";
    $message .= "Phone: $billing_phone
";
    $message .= "Total Refunded: $totalRefunded
";
    $message .= "Total Tax Refunded: $totalTaxRefunded
";
    $message .= "Company: $company
";
    $message .= "Order Notes: $notes->post_excerpt
";
    $message .= "Total Shipping Refunded: $totalShippingRefunded

";
    foreach($orderItems as $product) {
        $message .= $product['name'] . ' x' . $product['qty'] . '
';
    }
    $message .= "
Total: $total";
    $headers  = "Content-type: text/html; charset=windows-1251 \r\n";
    $headers .= 'From: post@test.com' . "\r\n" .
    "Reply-To: $billing_email" . "\r\n" .
    'X-Mailer: PHP/' . phpversion();
    mail(get_option('ordemails'), $subject, $message, $headers);
});

get_option('ordemails') is a string which contain email addresses separated by comma(test@test.com, test2@test.com)


text:
Q: Folium / Black colored countries I am trying to visualize some Covid-19 data (Covid Cases Ratio per Country) using folium module. For some reason a few countries appear to be black on the map, for example United States, and I'm using fill_color="YlGn". What is the problem right here?
import os
import folium
import pandas as pd

states = os.path.join('datas', 'countries.geo.json')

country_covid = os.path.join('datas', 'df.csv')
covid_data = pd.read_csv(country_covid, skiprows=0)

bins = list(covid_data['Cases'].quantile([0, 0.25, 0.5, 0.75, 1]))
m = folium.Map(location=[16, 34], zoom_start=5)

folium.Choropleth(
    geo_data=states,
    name="choropleth",
    data=covid_data,
    columns=['Country', 'Cases'],
    key_on='feature.properties.ADMIN',
    fill_color='YlGn',
    fill_opacity=0.7,
    line_opacity=0.2,
    legend_name='Covid-19 Rate (%)',
    bins=bins,
    reset=True
).add_to(m)

folium.LayerControl().add_to(m)

m.save(outfile="map1.html")

Check out a screenshot of the map:

A: So the answer is that I had to actually edit the country's name in my geojson file in order to be the same with the equivalent name in the dataframe.

A: When a country is "black", it actually means that there is no data for this country.
As I assume you have data for the United States, you should check that the code for the countries in the geojson and the ones in your pandas DataFrame are the same. The error is most likely there, the join between the country data and the geojson can't be made because of different keys.
If you post an exemple of your data and geojson, I could help you more.

A: If anyone encounters the same error, one possible solution is the name. In my dataframe the name was marked as United States and so it is on the folium map.
However, the GeoJSON that can be used is marked United States of America.
Simply download (or whatever) the JSON and replace United States of America with United States.
# just replace United States of America with United States inside the JSON
# url = 'https://raw.githubusercontent.com/python-visualization/folium/master/examples/data/world-countries.json'
url = './world-countries.json'
m = folium.Map(location=[16, 34], zoom_start=5)

folium.Choropleth(
    geo_data=url,
    name="choropleth",
    data=covid_data,
    columns=['Country', 'Cases'],
    key_on='feature.properties.ADMIN',
    fill_color='YlGn',
    fill_opacity=0.7,
    line_opacity=0.2,
    bins=bins,
    reset=True
).add_to(m)


text:
Q: Rich text box replaces default Monospaced font for Box-drawing characters with Variable-width font I have a Windows rich text box control (RichTextBox) on my form. The box has Consolas monospaced font set. For most contents the box indeed renders it with the selected font.
But when I load/set contents with Box-drawing characters, the box renders when with variable-width font (Segoe UI Symbol). What defies the very purpose of those characters.
Simple example:
private void InitializeComponent()
{
    // ...
    this.richTextBox1 = new System.Windows.Forms.RichTextBox();
    this.richTextBox1.Font =
       new System.Drawing.Font("Consolas", 12F, System.Drawing.FontStyle.Regular,
                               System.Drawing.GraphicsUnit.Point, ((byte)(0)));
   this.richTextBox1.Location = new System.Drawing.Point(45, 34);
   this.richTextBox1.Name = "richTextBox1";
   this.richTextBox1.Size = new System.Drawing.Size(533, 318);
   this.richTextBox1.TabIndex = 0;
   this.richTextBox1.Text =
       "╔════════════════════════════════════════════════╗\n" +
       "║                 This is a test                 ║\n" +
       "╚════════════════════════════════════════════════╝";
    // ...
}

Results in:

If I copy-paste the contents to e.g. Microsoft Word, I can see that only this parts has the Consolas font:
                This is a test
The rest (all the Box-drawing characters) has Segoe UI Symbol font.
What I can I do to prevent RichTextBox from replacing the font?
My search resulted only in this article:
https://devblogs.microsoft.com/math-in-office/richedit-font-binding/
But it says that Rich text box replaces font only for characters that are not supported by the font. I'm sure that Consolas does support Box-drawing characters.


text:
Q: How can I show a link-ike text to open the Explorer to upload files/folders? I am trying to implement an upload-function but instead of the input I want to show a text for example Drop Folder instead of the default  Choose File <Filename> Upload using input like this:

        <input type="file"
               id="file"
               webkitdirectory
               multiple
               (change)="handleFileInput($event.target.files)">

        <button (click)="uploadFiles()">Upload</button>

How can I display the text Drag Folder with a ClickListener which opens the Explorer by clicking on it?
Thank you for helping me out. If anything is unclear, you can ask me anytime!

A: Use a dedicated label using the for attribute and hide your usual file upload entirely
 Drag folder

   <input id="fileupload" type="file" id="file" webkitdirectory multiple (change)="handleFileInput($event.target.files)">

   <button (click)="uploadFiles()">Upload</button>


text:
Q: Giving www-data permision to Dropbox subfolder? I want to give my website the permission to read files & folders from a Dropbox subfolder.
I think I have added the correct permissions, but I can't get the www-data user to get access to the folders.
$ cd /home/edent/Dropbox
$ ls -la
total 9944
drwxrwxr-x    6 edent edent       4096 Aug 14  2012 .
drwx------   67 edent edent      20480 Feb 27 09:11 ..
drwxrwxr-x+ 772 edent www-data  118784 Jan 29 20:45 Foo
drwxrwxr-x    4 edent edent       4096 Aug 14  2012 Bar

All the sub-folders and files of Foo are also drwxrwxr-x+    edent www-data
So, I switch to the user www-data but it doesn't have permission to access those files and folders!
$ sudo su www-data
$ groups
www-data
$ id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
$ cd /home/edent/Dropbox/Foo
sh: 3: cd: can't cd to /home/edent/Dropbox/Foo

However, if I start in /home/edent/Dropbox/Foo I can access files but not directories.
$ cd ~/Dropbox/Foo/
$ sudo su www-data
$ ls
(file listing)
$ tail example.txt
(file displayed)
$ cd Bar/
sh: 4: cd: can't cd to Bar

What am I doing wrong?  All I want is for Apache to access a limited set of folders - I don't want to open up my entire filesystem.

A: This is because the permissions are checked at every level to get to a directory, not just the target directory.
You can give a user or group permission to pass though a directory without being able to access what is inside it by setting the execute bit for that user or group without setting either the read or write bits.
For example:
chmod 710 /home/$USER
chmod 710 /home/edent/Dropbox
chmod 750 /home/edent/Dropbox/Foo

But for this to work you will need the group for all these levels to be www-data.  This is somewhat untidy as having to change the group of your home directory just for one specific scenario may conflict with other things you want to do later.
If you have root on the host an tidier solution is to use a bind mount.  In /etc/fstab add something like:
/home/edent/Dropbox/foo /var/www/html/foo none bind 0 0

This should make the directory in Dropbox appear in the /var/www/html directory, irrelevant of any other file system permissions.  Now you only need to worry about file permissions within that directory and not in the hierarchy above that.  You can think of this as a super symlink that can span file systems.
For example, I make use of this in a machine with a small SSD drive for / and all my large media files are on a separate larger disc.  I Make it look like those media files are in my home directory with:
/media/bigdrive/media /home/me/media none bind 0 0

A: That is because your /home attributes are
 drwx------   67 edent edent      20480 Feb 27 09:11 ..

no x for group or other, so
cd /home/.... will fail
But when already in edent's home dir,
cd ./Dropbox/...
would work, because you do not use /home
edit 1
chmod o+x /home will allow the cd to work.
Here's the Apache documentation to set up a Directory Alias


text:
Q: Show all data in Log I have:
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(Test.TEST_TABLE_NAME);

mCursor = queryBuilder.query(mDB, null, null, null, null, null, null);

This working good with Adapter, but how can i make simple foreach and show data in Log.i?
My table TEST have two field: name and title.

A: Use some dumpCursor variant:
mCursor = ...;
Log.i(TAG, DatabaseUtils.dumpCursorToString(mCursor));


text:
Q: Prove boundary of an open ball in $\mathbb{R^n}$ directly from definition I am trying to prove that the boundary of the open ball $B(a,\delta)=\{x \in \mathbb{R^n} : ||x-a||<\delta\}$ is the set $S(a,\delta)=\{x \in \mathbb{R^n} : ||x-a||=\delta\}$. I know there are other threads that discuss this topic but they all provide the answer recurring to other topological concepts such as the closure. In my case, I wanna prove it showing that every open ball centered in $x \in S(a,\delta)$ verifies that its intersection with $B(a,\delta)$ is non-empty and its intersection with $B(a,\delta)^C$ is also non-empty.
My attempt for the first non-empty intersection: If $x \in S(a,\delta)$, then $||x-a||=\delta$ and for every open ball $B(x,r)=\{y \in \mathbb{R^n}:||x-y||<r\}$, we need to show that $y \in B(a, \delta)$, that is to say, $||y-a||<\delta$. Then I have seen that, using the triangle inequality, $||y-a|| \leq ||x-a||+ ||y-x|| \leq \delta+r$ but this doesn't prove what I need.
Thanks for your help.

A: Fix open ball $B(a, \delta)$. Choose point on the sphere of the same radius $x \in S(a, \delta)$ and any positive $r > 0$. We want to prove that
$$
B(a, \delta) \cap B(x, r) \neq \emptyset, \quad
B(a, \delta)^c \cap B(x, r) \neq \emptyset.
$$
Second one is trivial: we have $x \not \in B(a, \delta)$, so $x \in B(a, \delta)^c \cap B(x, r)$ and the set is not empty.
For the first one consider line segment passing through $a$ and $x$, that is
$$
L = \{\lambda a + (1-\lambda)x : \lambda \in [0, 1]\}.
$$
Pick point $y\in L$ to correspond to lambda value of
$$
\lambda = \frac{\min\left\{\frac r 2, \frac \delta 2\right \}}  \delta.
$$
Note that $0<\lambda \leq 1/2$. We have
$$\|x - y\|=\|\lambda x-\lambda a\|=\lambda \delta < r,$$
and
$$
\|a - y\|=\|(1-\lambda) a-(1-\lambda) x\| = (1 - \lambda)\delta < \delta,
$$
so $y \in B(a, \delta) \cap B(x, r)\quad \square$

Note: the above proves that $S(a, \delta) \subseteq \partial B(a, \delta) $.
To show equality you need to know that open ball is open, and the set $\{x \in \mathbb R^n: \|x - a\| > \delta\}$ is open as well.


text:
Q: Datatable Cell Centre Alignment for createdRow I have a the following datatable with bootstrap 4. On one of my columns ('Status') I use a createdRow to add a bootstrap badge class. The problem is that the alignment of the badge is a bit off:

I've tried adding 'align-centre', 'text-align' etc to this createdRow add class function, but the badge still remains in the top left corner.

HTML:

   Client Database

          Address
          Location
          Name
          Joining Date
          Phone
          DB Serial
          Status
          Contract Payments
          Battery Reserve
          Action

    <?php
    if($result = $mysqli->query($sql)){
      if($result->num_rows > 0) {
        while($row = $result->fetch_array()) {
        echo '

          '.$row["client_address"].'
          '.$row["client_location"].'
          '.$row["client_name"].'
          '.$row["client_joining_date"].'
          '.$row["client_cell"].'
          '.$row["client_db_number"].'
          '.$row["client_status"].'
          '.$row["client_contract_payments"].'
          '.$row["client_battery_reserve"].'
          View

        ';
        }
      } else {echo "
No records were found.
";}
     }
     $mysqli->close();
    ?>

With the following:
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap4.min.css"/>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.2.0/css/responsive.bootstrap4.min.css"/>

A: It just looks like the alignment is off, the problem is that you are in fact attach bootstraps badge classes to the  itself, not the content of the , or whats inside. You could do this instead :
createdRow: function ( row, data, index ) {
  if ( data[6] == 'FB-PAYG' ) {
    var content = $('td', row).eq(6).text();
    $('td', row).eq(6).html(''+content+'')
  }
}

I would love a chained oneliner that uses .wrap(), but this is not possible with text() or html().


text:
Q: Goapp serve - Warning: There are too many files After upgraded to go_appengine SDK version 1.9.54, I always get following warning, even just one or two .go files are used in the app directory. As a result, file changes are not automatically detected and app is not rebuilt.
$ goapp serve
go_appengine-1.9.54/google/appengine/tools/devappserver2/mtime_file_watcher.py:182: UserWarning: There are too many files in your application for changes in all of them to be monitored. You may have to restart the development server to see some changes to your files.
  'There are too many files in your application for '
Any ideas?

A: I solved this issue by using vendor/ directory for large package sources used in my project, such golang.org or google.golang.org repositories. Using devappserver2.py via $ goapp serve, file changes in vendor directories are ignored. Works for go version 1.6 >

A: In my case, this problem occured, when I have a mixed content in the parent directory, including npm project and node_modules directory.To solve the problem, I changed _IGNORED_PREFIX variable in go_appengine/google/appengine/tools/devappserver2/watcher_common.py file as following:

Line 24: _IGNORED_PREFIX = ('.', 'node_modules')

Using appengine-1.9.57.

A: A corresponding error occurs when the file under the "$GOPATH" directory is subject to file monitoring and the number of files is large.
In my case, by specifying "vendor" or a project with many files in "skip_files" option of "app.yaml", I was able to prevent the corresponding error from occurring.
https://cloud.google.com/appengine/docs/standard/python/config/appref#skip_files
skip_files:
- .*node_modules
- .*vendor
- .*project-name-having-too-many-files


text:
Q: Solving a boundary value problem numerically, with high precision In the paper ON A PAINLEVÉ-TYPE BOUNDARY-VALUE PROBLEM, the authors consider the BVP given by the ODE
$$y''=y^2-x \tag{1} $$
with the boundary conditions
$$\begin{align} y(0)&=0, \tag{2a} \\ y(x)& \sim \sqrt{x} \text{ as }x \to \infty  \tag{2b}.\end{align}$$
They do so by studying the 1-parametric family of solutions $y_\alpha(x)$ of (1) with the initial conditions
$$\begin{align} y(0)&=0, \tag{3a} \\
y'(0)&=\alpha. \tag{3b} \end{align}$$
It is conjectured* that the family $y_\alpha$ is classified into 5 different categories, depending on the value of $\alpha$ (please see attached plots):

*

*If $\alpha > 0.924376$, $y_\alpha$ increases monotonically, and blows up in finite time (two "uppermost" red curves).

*If $\alpha \approx 0.924376$, $y_\alpha$ increases monotonically, and approaches $\sqrt{x}$ from below as $x \to \infty$ (upper green curve).

*If $-3.79199<\alpha<0.924376$, $y_\alpha$ oscillates about, and approaches $-\sqrt{x}$ as $x \to \infty$ (both blue curves).

*If $\alpha \approx -3.79199$, $y_\alpha$ goes down first, attains a minimum, and then goes up and approaches $\sqrt{x}$ from below as $x \to \infty$ (lower green curve).

*If $\alpha<-3.79199$, $y_\alpha$ goes down first, attains a minimum, and then intersecting $\sqrt{x}$ from below, resulting in a finite time blowup (two "lowermost" red curves).

I'm interested in finding those "critical slopes", which solve the BVP (1)-(2) (namely about 0.924376 and -3.79199). I don't understand how the authors obtained their decimal approximation to the upper critical slope, so I've decided to try and find them myself in the following way:
In order to find the upper slope for example, I have used Mathematica's numerical ODE solver. I noticed that using a slope of $1$ results in a blowup, and using a slope of $0$ results in oscillatory behaviour. From there I continued bisecting the interval $[0,1]$, closing in on the right slope. My problem with this method is that I'm at the mercy of the error tolerance of "NDSolve" and I'm not sure how good my approximation really is.
Here is my question:
What is a numerical method that can find both solutions of the BVP (1)-(2) to high precision (that is, determines both $\alpha$s up to $10^{-16}$, or preferably even better) efficiently?
To be clear, I am not interested as much in the actual solution $y_\alpha(x)$, the value of $\alpha$ itself suffices.
Thank you!

$*$ Part of this classification problem has been proven in a later paper.


text:
Q: svg gradient not working in app due to fill path relativity I have a SVG with lineargradient which works fine when opened independently in the browser. When I embed it in my single page app, the gradient does not appear.
When I assign the svg as backgroundimage or img src, it works fine. Also ,when I modify the fill url with respect to my app url(eg. fill: url(#graidentId) becomes fill: url('path#gradientId')), it works fine.
I want the svg to be independent of the code.And not modify the fill path in my code.
I do not want to use it as backgroundimage or img src as well.
Is there a way to fix this? Is there a way to generate SVGs such that this is fixed.


text:
Q: Is there a simple way to style text with gradients? it is possible to style a background with gradients like:
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#eeeeee), color-stop(100%,#cccccc));
Is there a way to style text with gradients?I've been looking for sth like:
color-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#eeeeee), color-stop(100%,#cccccc));but wasn't able to find anything simple.
Thanks for your help.

A: It IS possible. You just have to combine a background-image with a background-clip: text: See this most excellent example here.
background: url(/bgclip/img/paint.png) repeat, white;
-webkit-text-fill-color: transparent;
-webkit-background-clip: text;

A: its not possible with pure CSS unless you use a image to cover the font:
http://www.webdesignerwall.com/tutorials/css-gradient-text-effect/
You could use the same technique but use a color to transparent gradient in the overlay element.
here is an example with pure CSS and an additional element: http://jsfiddle.net/Lub7z/


text:
Q: How do I obtain the delta between two dates? I've been searching around before asking this.
I have Django template, which inputs a water account number, a beginning date, and an ending date. The dates define a search range, and are in mm/dd/yyyy format.
I'd like to convert these dates into a Python format, so I can find the difference between them. I'm aware of date and datetime objects, and I know I can parse -- for example -- 05/01/2012 -- and create a date object from that.
However, I'm interested in a better way to this, like converting the "05/01/2012" directly for start and end date range values, and then taking the delta between those Python date objects.
Thank you.
Edit:
This is what I'm using to calculate the delta:
d1 and d2 are date strings in the form: mm/dd/yyyy.
def time_delta(d1, d2):
    dd1   = datetime.strptime(d1, "%m/%d/%Y").date()
    dd2   = datetime.strptime(d2, "%m/%d/%Y").date()
    delta = dd2 - dd1
    return delta.days

A: Maybe something like this?
from datetime import *
d1 = datetime.strptime('05/01/2012', "%d/%m/%Y").date()
d2 = datetime.strptime('06/01/2012', "%d/%m/%Y").date()
delta = d2 - d1
print(delta.days)

A: You should be using Django forms for this kind of thing. If you use date fields, then start_date and end_date will be Python date objects when you you fetch them out of the form's cleaned data dictionary.
If you haven't used Django forms before, then I recommend that you read through the forms documentation. Here's a couple of snippets as a hint.
class MyForm(forms.Form):
    start_date = forms.DateField()
    end_date = forms.DateField()
    # other fields e.g. water account number

# in your view
if request.method == "POST":
    form = MyForm(request.POST)
    if form.is_valid():
        start_date = form.cleaned_data['start_date']
        end_date = form.cleaned_data['end_date']
        delta = end_date - start_date
        # do anything else you need to do

A: The dateutil module is really nice for parsing dates:
>>> from dateutil.parser import parse
>>> parse("05/01/2012") - parse("04/01/2012")
datetime.timedelta(30)


text:
Q: How to insert lines into a JSON document in MarkLogic [Update] I have a JSON document with say fields A,B,C. I want to add fields D,E,F to it. How do I add/concat them?
I'm using a cts.uris to first search for the right document to update and once I have that as a sequence then I'm converting it to an object for processing. I know how to update a particular field by not how to add new lines in it.
I'm coding in JavaScript in the query console.

A: You can do the following steps to update a json document:
declareUpdate();
// get the document
const uri = '/folder/doc.json';
const doc = cts.doc(uri);

// create an object from the document
const obj = doc.toObject();

// add the new fields to the object
obj.d = 'd';
obj.e = 'e';
obj.f = 'f';

// save the object as a json document
xdmp.documentInsert(uri, obj);

A: You can add a property to a JSON object by assigning a value to the belonging key.

const obj = {
  a: true,
  b: 42,
  c: 'Hello World!'
}

obj['d'] = 'To be, or not to be'
obj['e'] = 'foobar'
obj['f'] = false

console.log(obj)


text:
Q: HTML image preview of a mp4 file I build a file browser using phonegap.
Is there a way to show a preview-image or a thumbnail of a mp4 file?
The thumbnail for pictures is just this:

     <img class="imgListThumb" src=<%=fullpath%>>

.imgListThumb
{
   max-width: 80px;
   max-height: 60px;
}

I just want to display a thumbnail in my filebrowser, not a possibility for playback

A: You have to generate the thumbnails when you are converting/processing the video to the server. You cannot get an image from the mp4.


text:
Q: How to disappear keyboard from UITextView when touch in iOS? I don't want to appear any keyboard when i touched UITextView in iOS.
How can i do that?

A: You could make the UITextView non-editable.
UITextView* tv = [[UITextView alloc] init];
[tv setEditable:NO];

A: You can subclassing UITextView and override "-(BOOL)canBecomeFirstResponder", returning NO.


text:
Q: Grouping By Using a Conditional Statement from a Different Column I need to group a pandas Dataframe according to the following criteria, it is like-ish a ohlc aggregation:
open = last where volume > 0, in case there is no entry with volume > 0 use overall last
high = max
low = min
last = last
volume = max

My current implementation for these kinds of operations (ohlc aggregation) is:
ohlc_dict = {
'open': 'first',
'high': 'max',
'low': 'min',
'close': 'last',
'volume': 'sum',
}

df = df.groupby(pd.Grouper(freq='1Min',level=0,label='left')).agg(ohlc_dict)

How can I solve this? Thank you.
Sample:
                     fi  ts     open     high      low    close  volume
datetime
2017-11-17 12:35:00   0   0  0.96214  0.96214  0.96214  0.96214       0
2017-11-17 12:35:00   0   0  0.96214  0.96214  0.96214  0.96214       0
2017-11-17 12:35:00   0   0  0.96214  0.96220  0.96214  0.96220       0
2017-11-17 12:35:00   0   0  0.96214  0.96220  0.96214  0.96220       0
2017-11-17 12:35:00   0   0  0.96214  0.96220  0.96214  0.96220       0
2017-11-17 12:35:00   0   0  0.96213  0.96220  0.96213  0.96219      19
2017-11-17 12:35:00   0   0  0.96214  0.96220  0.96214  0.96219       0
2017-11-17 12:35:00   0   0  0.96214  0.96222  0.96214  0.96222       0
2017-11-17 12:35:00   0   0  0.96214  0.96222  0.96214  0.96220       0
2017-11-17 12:35:00   0   0  0.96214  0.96222  0.96214  0.96221       0
2017-11-17 12:35:00   0   0  0.96214  0.96223  0.96214  0.96223       0
2017-11-17 12:35:00   0   0  0.96214  0.96223  0.96214  0.96221       0
2017-11-17 12:35:00   0   0  0.96214  0.96223  0.96214  0.96220       0
2017-11-17 12:35:00   0   0  0.96214  0.96223  0.96214  0.96220       0
2017-11-17 12:35:00   0   0  0.96213  0.96223  0.96213  0.96220      29
2017-11-17 12:35:00   0   0  0.96213  0.96223  0.96213  0.96220      29
2017-11-17 12:35:00   0   0  0.96214  0.96223  0.96214  0.96221       0
2017-11-17 12:35:00   0   0  0.96214  0.96223  0.96214  0.96222       0

Desired Output:
                     fi  ts     open     high      low    close  volume
datetime
2017-11-17 12:35:00   0   0  0.96213  0.96223  0.96213  0.96222       29

Additional Information:
There are two data sources which can be identified by their 'Volume' values:
a. Volume = 0 (more frequent, less reliable)
b. Volume > 0 (less frequent, more reliable)

As type 'b.' is more reliable, it is preferrable to use its open value to type 'a' open value.
As to whether last aggregation, it doesn't really matter to be honest, other aggregations (first,max,min) would work, as the open value is the first quoted value in a minute (on this example) and never changes.
The issues of incorrect values arise when there is an interruption on the connection to the server. Type 'a' data cannot deal with this and will give me possibly wrong values, type 'b' data can deal with this just fine and will give me correct values.

A: You can use boolean indexing for max volume and tail(1) for last value of open inside apply since you have duplicate index i.e
ohlc_dict = {
   'high': 'max',
   'low': 'min',
   'close': 'last',
   'volume': 'max',
}
grp = df.groupby(pd.Grouper(freq='1Min',level=0,label='left'))
ndf = grp.agg(ohlc_dict)

ndf['open'] = grp['open','volume'].apply(lambda x : x[x['volume'] == x['volume'].max()].tail(1)['open'])

Output :

                        low  volume    close     high     open
datetime
2017-11-17 12:35:00  0.96213      29  0.96222  0.96223  0.96213

A: You can first aggregate by last of opencolumn:
ohlc_dict = {
   'high': 'max',
   'low': 'min',
   'close': 'last',
   'open':'last',
   'volume':'sum'
}

g = df.groupby(pd.Grouper(freq='1Min',level=0,label='left'))
df2 = g.agg(ohlc_dict)
print (df2)
                         low    close     high     open  volume
datetime
2017-11-17 12:35:00  0.96213  0.96222  0.96223  0.96215      77

Then filter out all 0 volumes and aggregate only last value of open:
g1 = df[df['volume'] > 0].groupby(pd.Grouper(freq='1Min',level=0,label='left'))
df1 = g1['open'].last().reindex(df2.index)
print (df1)
datetime
2017-11-17 12:35:00    0.96213
Freq: T, Name: open, dtype: float64

Last combine both DataFrames to one with to_frame and combine_first:
df3 = df1.to_frame().combine_first(df2)
print (df3)
                       close     high      low     open  volume
datetime
2017-11-17 12:35:00  0.96222  0.96223  0.96213  0.96213    77.0

Use custom function with condition (slowier):
def ohlc_func(x):
    a = x.loc[x['volume'] > 0, 'open'].tail(1)
    a = a.item() if len(a) == 1 else x['open'].tail(1)[0]
    b = x['high'].max()
    c = x['low'].min()
    d = x['close'].tail(1)[0]
    e = x['volume'].sum()
    col = ['open','high','low','close','volume']
    return pd.Series([a,b,c,d,e], index=col)

df = df.groupby(pd.Grouper(freq='1Min',level=0,label='left')).apply(ohlc_func)
print (df)
                        open     high      low    close  volume
datetime
2017-11-17 12:35:00  0.96213  0.96223  0.96213  0.96222    77.0


text:
Q: Bad request:Error function and timeout in ajax never fired Here is my ajax call
var settings = {
        "async": true,
        "crossDomain": true,
        "url": "http://sample.com/customer/api/v1/meetings/meeting",
        "method": "POST",
        "headers": {
          "x-api-key": token
        },
        "dataType":'json',
        "data": {
          "title": meetingData.title,
          "end_date": meetingData.endtdate,
          "from_date":  meetingData.startdate,
          "description": meetingData.description,
          "reminder_type": meetingData.remainder,
          "priority": meetingData.priority
        }
      }

$.ajax(settings).done(function (response) {
    console.log(response);
},function(err){
   alert('error');
});

Problem is error callback function is never fired if any error is present.
Also i want to add a timeout this ajax call ,how can i do that??
I've added  timeout:20000 parameter in my settings variable but the error call back is not fired
UPDATE
I will get a bad request error from the console ,how to solve that error??

A: I doubt the .done() has a error callback, instead you should use .then(successCB, errorCB) which has both callbacks:
$.ajax(settings).then(function (response) {
    console.log(response);
},function(err){
   alert('error');
});

Update
As per updates: I will get a bad request error from the console ,how to solve that error??
Then in this case the doubtful entities could be your data object you are sending, one of them or more might have some data which is causing this error. So you can inspect what data is getting through here:
"data": {
      "title": meetingData.title,
      "end_date": meetingData.endtdate,
      "from_date":  meetingData.startdate,
      "description": meetingData.description,
      "reminder_type": meetingData.remainder,
      "priority": meetingData.priority
    }

A: Write success and error within settings variable itself:
var settings = {
        "async": true,
        "crossDomain": true,
        "url": "http://sample.com/customer/api/v1/meetings/meeting",
        "method": "POST",
        "headers": {
          "x-api-key": token
        },
        "dataType":'json',
        "data": {
          "title": meetingData.title,
          "end_date": meetingData.endtdate,
          "from_date":  meetingData.startdate,
          "description": meetingData.description,
          "reminder_type": meetingData.remainder,
          "priority": meetingData.priority
        },
        "success":function(resp){
            //your work here
        },
        "error":function(resp){
            //your work here
        }
      }

$.ajax(settings);

Or remove it from settings and bind it globally to document as
$(document).ajaxSuccess(function( event, xhr) {
    //error code here
}).ajaxError(function(event,xhr){
   //error code here
});


text:
Q: Using ng-switch in angularjs directive and using that directive in ng-grid cellTemplate I made a following directive:
.directive('getData', function(){
        return {
            restrict: 'C',
            replace: true,
            transclude: true,
            scope: { myData:'@myData' },
            template: '
' +
                        '
Real Data
' +
                        '
False Data
' +
                        '
No Data
' +
                      '
'
        }

Then on a grid that uses ng-grid, I have a column that has 2 rows with values 4 and 5. I have following in cellTemplate for this column:
cellTemplate: '
'

The problem is both the rows display "No Data". I would like to show "Real Data" on the cell that has value 4 and "False Data" on the cell that has 5.
What I am not doing right? Any help would be greatly appreciated.

A: In your cellTemplate change myData to my-data. When using angular directives camel case is converted to dash case automatically by the angular library.
For example if you have a directive element defined as "mySuperAwesomeDirective". It would be declared in html using the following.
<my-super-awesome-directive></my-super-awesome-directive>
Here is a working version of your plunker example.
http://plnkr.co/edit/ENj00Re3bfaVGPlomhFG?p=preview


text:
Q: PHP's open_basedir value giving a binary value in Apache logs Reviewing logfiles to figure out why my site was down a few days ago, I found hundreds of lines like these (partially redacted with "x"):

[Fri Nov 27 23:14:36 2009] [error]
  [client xxx.xxx.xxx.xxx] PHP Warning:
  require_once(): open_basedir
  restriction in effect.
  File(/var/www/xxx/xxx.php) is not
  within the allowed path(s):
  (\xa0\x99\xc4) in
  /var/www/xxx/index.php on line 17

Note that the open_basedir value is binary, so it won't match anything.
No (admin) change was made on the server to cause this, and none was made to stop it.. it apparently resolved itself on its own (apache or other services weren't restarted/reloaded). The open_basedir directive in the apache conf file looks like this:

php_admin_value open_basedir
  /var/www:/usr/share/php

What would cause the open_basedir value to reload with a binary value, or where can I even start to troubleshoot this? This is the second time in the last two weeks this problem has arisen.
Apache version: 2.2.8, PHP: 5.3.0, Linux 2.6.24-23

A: Looks similar to this bug, which should be fixed in 5.3.1.


text:
Q: How can I share memory between two JVM instances? I build a huge graph in JVM (Scala) which I want to use repeatedly, tweaking algorithms.  I'd rather not reload it each time from disk.  Is there a way to have it sit in one JVM while connecting from another, where the algorithms are being developed?

A: Two JVMs sounds more complicated than it needs to be.  Have you considered doing a kind of "hot deploy" setup, where your main program loads up the graph, displays the UI, and then asks for (or automatically looks for) a jar/class file to load that contains your actual algorithm code?  That way your algorithm code would be running in the same jvm as your graph, but you wouldn't have to reload the graph just to reload a new algorithm implementation.
UPDATE to address OP's question in comment:
Here's how you could structure your code so that your algorithms would be swappable.  It doesn't matter what the various algorithms do, so long as they are operating on the same input data.   Just define an interface like the following, and have your graph algorithms implement it.
public interface GraphAlgorithm {
  public void doStuff(Map<whatever> myBigGraph)
}

If your algorithms are displaying results to some kind of widget, you could pass that in as well, or have doStuff() return some kind of results object.

A: Did you consider OSGi platform? It lives in a single JVM, but will allow you to upgrade bundles with algorithms without platform restart. Thus you may have a long-term running bundle with your huge data structures and short-term algorithm bundles taking access to the data.

A: Save your graph to disk, then map it into memory with MappedByteBuffer. Both processes should use the same memory, which will be shared with the page cache.

A: Woo! late to the party.
If its on a local machine, similar to mapped byte buffers, there is apache direct memory.  http://directmemory.apache.org/
If you want it distributed, give http://hazelcast.org/ a try.  Its used by a lot of large projects.  Of course, your objects must be serializable.

A: Using RMI perhaps? Have one instance working as server and the rest as clients?
I think it would be much more complicated than reloading from disk.

A: You can certainly create an interface onto it and expose it via (say) RMI.
My initial thoughts on reading your post, however, are

*

*just how big is this graph ?

*is it possible to optimise your loading procedure instead ?

I know LinkedIn have a vast graph of people and connections that is held in memory all the time and that takes several hours to reload. But I figure that's a truly exceptional case.

A: If is expensive to build your graph maybe you can serialize the object.
ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(bos);
        out.writeObject(graph);
        out.flush();
        byte b[] = bos.toByteArray();
//you can use FileOutputStream instead of a ByteArrayOutputStream

Then you can build your object from the file
ByteArrayInputStream inputBuffer = new ByteArrayInputStream(b);
        ObjectInputStream inputStream = new ObjectInputStream(inputBuffer);
        try {
            Graph graph = (Graph) inputStream.readObject();

        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }

Just replace the ByteArrayInputStream with a FileInputStream

A: if the problem is just to dynamicly load and run your code without name clashes a custom class loader could be enough.
for a new run just cache all class files in a new classloader.

A: Have you considered simply using a smaller amount of sample data for testing your algorithms?

A: Terracotta shares memory between many JVM instances so you can easily apply cluster to your system.


text:
Q: Changing session.save_path in php.ini not working Fedora 25 + PHP 7 + Apache 2.4.23
Hello, after I change session.save_path in php.ini and restart apache, I can successfully verify that it's modified with:
$ php -i | grep session.save_path
However, in the html/php pages themselves, the sessions are not written so the session.save_path I set, but they're stubbornly written to /var/lib/php/session/. Even setting the value in .htaccess isn't working:
php_value session.save_path "/mycustom/path/folder"
The only working solution that can override the default /var/lib/php/session/ is to set the value in the php file itself:
ini_set('session.save_path','/mycustom/path/folder');
Any ideas?

A: *

*create phpinfo() file in dir with this php file.

*open it via browser, and find list of applied ini-files.

*check all of these files to contain session.save_path override


text:
Q: Most efficient way to pull Last_Updated value from a table in Postgres? first post here. I need to pull the most recent value from a table, but for a given date, there are numerous entries in this particular table. I've done similar things to both options below.
Option 1..
Joining the main table to a subquery table:
select t1.key, t1.date, t2.value
  from table1 t1
  join
    (select key,
          date,
          max(updated_at) as last_update
          from table2
          group by 1,2) t2
    on t1.key = t2.key
    and t1.date = t2.date
    and t1.updated_at = t2.last_update
order by 1,2;

Option 2.. A subquery in the join and a descending 'order by' with a limit:
select t1.key, t1.date, t2.value
from table1 t1
join table2 t2
  on t1.key = t2.key
  and t1.date = t2.date
  and t2.updated_at = (
      select updated_at
      from table2
      where key = t2.key
      and date = t2.date
      order by updated_at desc
      limit 1)
order by 1,2;

Option 2 is a bit atypical, and requires ordering of the entire table in the subquery, so I doubt it's best practice, but it works and allows the subquery to live inside of the Join, so I've used it before.
Is Option 1, Option 2, or some Option 3 the most efficient method to solve this problem? What's best practice? Happy to join after browsing Stack for a while, thanks everyone.

A: This is best:
SELECT t1.key, t1.date, t2.value
FROM table1 t1
   JOIN table2 t2
      ON (t1.key, t1.date) = (t2.key, t2.date)
ORDER BY t2.updated_at
LIMIT 1;

For efficiency, you need an index on table2 (updated_at) and on table1 (key, date) (or table1 (key), if that is selective enough). Then PostgreSQL can use a fast nested loop join.

A: I would suggest distinct on.  I think this version:
select t1.key, t1.date, t2.value
from table1 t1 join
     (select distinct on (key, date) key, date, updated_at as last_update
      from table2
      order by key, date, updated_at desc
     ) t2
     on t1.key = t2.key and
        t1.date = t2.date and
        t1.updated_at = t2.last_update
order by 1, 2;

However, I suspect that the two tables are one table.  If so, you just want:
select distinct on (key, date) t1.*
from table1 t1
order by key, date, updated_at desc


text:
Q: Eclipse: The color used for text in a content assist popup I have problem with colour used for the background of a content assist popup. I try to change in the menu Window/Preferences/General/Appearance/Color and fonts -> these items without effect:

*

*Content Assist background colour

*Content Assist foreground colour

I can not get to the right one item had a half a day. Please help.

A: eclipse -> preference -> General -> Appearance -> Colors and Fonts

*

*Code assist
Basic > Content Assist background color    -> change
Basic > Content Assist foreground color    -> change

*java doc
Java  > Javadoc background ( overrides default: information background color) -> change


text:
Q: can not debug with flutter null-safety flutter-dependencies i can run my app only using
Flutter run --no-sound-null-safety
my mobile attached my my lab top samsung M21
using android studio
flutter version Flutter 2.2.1
dart version  Dart 2.13.1
on windows 10
my app it is a template i bought it from themeforest i dont have any support from them
this my first time with null-safety
i have made some change because of that
and i have run
dart pub outdated --mode=null-safety
dart pub upgrade --null-safety
dart pub get
dart migrate
but when click on deubg button
it does not work at all
this is my terminal
[  +88 ms] executing: [D:\flutter\flutter/] git -c log.showSignature=false log -n 1 --pretty=format:%H
[ +121 ms] Exit code 0 from: git -c log.showSignature=false log -n 1 --pretty=format:%H
[   +1 ms] 02c026b03cd31dd3f867e5faeb7e104cce174c5f
[   +1 ms] executing: [D:\flutter\flutter/] git tag --points-at 02c026b03cd31dd3f867e5faeb7e104cce174c5f
[ +102 ms] Exit code 0 from: git tag --points-at 02c026b03cd31dd3f867e5faeb7e104cce174c5f
[        ] 2.2.1
[   +6 ms] executing: [D:\flutter\flutter/] git rev-parse --abbrev-ref --symbolic @{u}
[  +73 ms] Exit code 0 from: git rev-parse --abbrev-ref --symbolic @{u}
[        ] origin/stable
[        ] executing: [D:\flutter\flutter/] git ls-remote --get-url origin
[  +72 ms] Exit code 0 from: git ls-remote --get-url origin
[        ] https://github.com/flutter/flutter.git
[ +163 ms] executing: [D:\flutter\flutter/] git rev-parse --abbrev-ref HEAD
[  +97 ms] Exit code 0 from: git rev-parse --abbrev-ref HEAD
[        ] stable
[ +101 ms] Artifact Instance of 'AndroidGenSnapshotArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'AndroidInternalBuildArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'IOSEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'FlutterWebSdk' is not required, skipping update.
[   +4 ms] Artifact Instance of 'WindowsEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'MacOSEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'LinuxEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'LinuxFuchsiaSDKArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'MacOSFuchsiaSDKArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'FlutterRunnerSDKArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'FlutterRunnerDebugSymbols' is not required, skipping update.
[  +63 ms] executing: C:\Users\hdarwish\AppData\Local\Android\sdk\platform-tools\adb.exe devices -l
[  +71 ms] List of devices attached
           R58NC4TZSJA            device product:a12nnxx model:SM_A125F device:a12 transport_id:1
[   +8 ms] C:\Users\hdarwish\AppData\Local\Android\sdk\platform-tools\adb.exe -s R58NC4TZSJA shell getprop
[ +113 ms] Artifact Instance of 'AndroidInternalBuildArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'IOSEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'FlutterWebSdk' is not required, skipping update.
[   +1 ms] Artifact Instance of 'WindowsEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'MacOSEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'LinuxEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'LinuxFuchsiaSDKArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'MacOSFuchsiaSDKArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'FlutterRunnerSDKArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'FlutterRunnerDebugSymbols' is not required, skipping update.
[  +48 ms] "flutter run" took 327ms.
[  +20 ms] Target file "run" not found.
[   +2 ms]
           #0      FlutterCommand.validateCommand (package:flutter_tools/src/runner/flutter_command.dart:1322:9)
           #1      RunCommand.validateCommand (package:flutter_tools/src/commands/run.dart:448:19)
           #2      FlutterCommand.verifyThenRunCommand (package:flutter_tools/src/runner/flutter_command.dart:1148:11)
           <asynchronous suspension>
           #3      FlutterCommand.run.<anonymous closure> (package:flutter_tools/src/runner/flutter_command.dart:1043:27)
           <asynchronous suspension>
           #4      AppContext.run.<anonymous closure> (package:flutter_tools/src/base/context.dart:150:19)
           <asynchronous suspension>
           #5      CommandRunner.runCommand (package:args/command_runner.dart:196:13)
           <asynchronous suspension>
           #6      FlutterCommandRunner.runCommand.<anonymous closure> (package:flutter_tools/src/runner/flutter_command_runner.dart:284:9)
           <asynchronous suspension>
           #7      AppContext.run.<anonymous closure> (package:flutter_tools/src/base/context.dart:150:19)
           <asynchronous suspension>
           #8      FlutterCommandRunner.runCommand (package:flutter_tools/src/runner/flutter_command_runner.dart:232:5)
           <asynchronous suspension>
           #9      run.<anonymous closure>.<anonymous closure> (package:flutter_tools/runner.dart:62:9)
           <asynchronous suspension>
           #10     AppContext.run.<anonymous closure> (package:flutter_tools/src/base/context.dart:150:19)
           <asynchronous suspension>
           #11     main (package:flutter_tools/executable.dart:91:3)
           <asynchronous suspension>

[ +253 ms] ensureAnalyticsSent: 251ms
[   +1 ms] Running shutdown hooks
[        ] Shutdown hooks complete
[        ] exiting with code 1


text:
Q: UIImage > NSData > NSString fail I know this question has been questioned many times, but my problem is a little different. I have an image (shared.image) and I want to upload the data to a server. This is the code (the img: bit is just a way to let the server know that is an image, not a string):
NSString *imageString = [NSString stringWithFormat:@"img:%@", UIImagePNGRepresentation(shared.image)];
NSData *imageData = [imageString dataUsingEncoding:NSUTF8StringEncoding];
[shared.outputStream write:[imageData bytes] maxLength:[imageData length]];

When the server responds back (as a string), this is the other code (shared.array is an array which groups all of the strings in case of packet fragmentation. The img: bit is deleted):
string = [shared.imageArray componentsJoinedByString:@""];
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
imageView.image = [UIImage imageWithData:data];

I nslogged [UIImage imageWithData:data] and it returns nil.
What am I doing wrong ?
Thanks

A: Why are you round-tripping to a NSString when you have binary data? If you want to load imageData with the contents of your image, you would bypass the NSString altogether:
NSData *imageData = UIImagePNGRepresentation(shared.image);

If your server accepts binary data, that's all you need.
If it needs text string, then your proposed code will not accomplish the job, but rather you should use something like Base64 to encode it (e.g. using Matt Gallager's NSData+Base64 category). For example:
NSData *imageData = UIImagePNGRepresentation(shared.image);
NSString *imageString = [NSString stringWithFormat:@"img:\"%@\"", [imageData base64EncodedString]];

Please note that in the response, I'd suggest enclosing the Base64 encoded string in quotes. That way, the recipient can detect the end of the Base64-encoded string. FYI, I've tried to respect your interface of img:, but you could also contemplate using the standard data URI scheme, perhaps something like:
NSString *imageString = [NSString stringWithFormat:@"img:\"data:image/png;base64,%@\"", [imageData base64EncodedString]];

It's up to you.
In terms of parsing the server response, again, it's a question of whether it is a string (in which case it should be a Base64 representation of the data), or whether it's binary data (in which case, you should just be appending the data to your NSMutableData and then just using imageWithData).

A: for IOS >= 7
- (NSString *)imageToNSString:(UIImage *)image
{
    NSData *imageData = UIImagePNGRepresentation(image);

    return [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}

- (UIImage *)stringToUIImage:(NSString *)string
{
    NSData *data = [[NSData alloc]initWithBase64EncodedString:string
                                                      options:NSDataBase64DecodingIgnoreUnknownCharacters];

    return [UIImage imageWithData:data];
}


text:
Q: List becomes String when Marshalling object to json I'm getting a pretty strange error when marshalling my object to json. My object is annotated like this.
My class:
@XmlRootElement(name = "myobject")
public class MyObject {

private List<String> contactPersonsForMyObject;

@javax.xml.bind.annotation.XmlElement()
public List<String> getContactPersonsForMyObject() {
    return contactPersonsForMyObject;
}

public void setContactPersonsForMyObject(List<String> contactPersonsForMyObject) {
    this.contactPersonsForMyObject = contactPersonsForMyObject;
   }
}

Everything works fine except for that if the List contactPersonsForMyObject contains only one value it get's marshalled to a string which ofcourse creates problems since the application consuming this expects a list.
The marshalled object:
[
        {
            "myobject": {
                "somethingcool": "amazing",
                "contactPersonsForMyObject": [
                    "test.test@gmail.com",
                    "test@test.se"
                ],
                "myObjectId": "c85e48730501bfae41e67714c6131b7d"
            }
        },
        {
            "myobject": {
                "somethingcool": "cool",
                "contactPersonsForMyObject":"test@test2.se",
                "myObjectId": "c85e48730501bfae41e67714cqwerty"
            }
        }
    ]

Why does this happen and how do I force it to create a list with one value?

A: Try using Jackson to handle processing your objects into JSON, it solved the same array problem for me in the past. If you are using RESTEasy (version 1.2 GA) with Maven, this link should help you get things setup to use Jackson to serialize objects to JSON.
This article also has some useful information for integrating Jackson with RESTEasy. Hope this helps!


text:
Q: CSS control for multiple div's with different results I'm trying to implement this
CSS rating widget
into my web app that takes data from a db and displays it to a table. One of the values in the table is the span that contains the rating system:

I programmatically create the span for each DB item:
            else if(dbArray[j].match('Rating')){
                var spanID = 'SPAN' + i;
                var ratingDiv = document.createElement(spanID);
                ratingDiv.setAttribute('class', 'starRating');
                var ratingContents = '<input id="rating5" type="radio" name="rating" value="5">5<input id="rating4" type="radio" name="rating" value="4">4<input id="rating3" type="radio" name="rating" value="3" checked>3<input id="rating2" type="radio" name="rating" value="2">2<input id="rating1" type="radio" name="rating" value="1">1';
                ratingDiv.innerHTML = ratingContents;
                cellName.appendChild(ratingDiv);
            }

The spans each have a unique id, however they all use the same css.  The issue is when the star ratings are created I can only save one rating.  Is there a way for me to have the rating be unique in each case without creating seperate css for each DB item? Here is a crude example of the problem:
JSfiddle showing what the issue is like

A: You have a couple of problems, but I think you're closer than you think. First you have non unique IDs, which is I think the main problem. IDs should always be unique.  I've made this jsfiddle, by just renaming id with letter prefix, and then a very small modification of your code made it work.
http://jsfiddle.net/v2575fg2/
For example:

    <input type="radio" name="rating" id="astr5" value="5">
    <input type="radio" name="rating" id="astr4" value="4">
    <input type="radio" name="rating" id="astr3" value="3">
    <input type="radio" name="rating" id="astr2" value="2">
    <input type="radio" name="rating" id="astr1" value="1">

Then simply remove your removeClass:
 //$(".rating span").removeClass('checked');

And the ratings stick. Also instead of input click, I put span, it doesn't change much and makes it leaner.
Now you'll have to figure out how to lower rating...
EDIT:
To lower rating:
add to click event:
$(this).siblings().removeClass('checked');
$(this).parent().addClass('rated');

And this in css:
.rating.rated:hover span:not(:hover) label {
    background:#CCC;
    color:#FFF;
}
.rating.rated:hover span:hover ~ span label,
.rating.rated:hover span:last-child label
{
    background:#F90;
    color:#FFF;
}

updated jsfiddle: http://jsfiddle.net/v2575fg2/9/

A: I apologise if I have the wrong end of the stick.
Could you not create a class based on the rating and add that to each one also. .rating5 { /* styles for 5 star rating */ } ? Assuming the ratings are similar in nature and resolve to a finite number of possible outcomes.

A: Here's my solution:
html

 ☆
 ☆
 ☆
 ☆
 ☆

js
$(document).ready(function () {
    //  Check Radio-box
    $('.rating .star').click(function (evt) {
        var $target = $(evt.currentTarget);
        $target.parent().find('.star').removeClass('selected');
        $target.addClass('selected');
        var userRating = this.data('value');
        alert(userRating);
    });
});

CSS
.rating {
    unicode-bidi: bidi-override;
    direction: rtl;
    text-align: left;
}
.rating > .star {
    cursor: pointer;
    display: inline-block;
    position: relative;
    width: 1.1em;
}
.rating > .star:hover,
.rating > .star:hover ~ .star,
.rating > .star.selected,
.rating > .star.selected ~ .star {
    color: transparent;
    2
}
.rating > .star:hover:before,
.rating > .star:hover ~ .star:before,
.rating > .star.selected:before,
.rating > .star.selected ~ .star:before {
    content:"\2605";
    position: absolute;
    left: 0;
    color: gold;
}

http://jsfiddle.net/bhpyk18w/122/
I'm using this pattern, which I think is a lot cleaner (https://css-tricks.com/star-ratings/).
Note that you're probably going to probably want to add something to click on to select 0 stars.
As stated above, you can't use the same id twice on the DOM.


text:
Q: google-picker image search 403,We're sorry, but you do not have access to this page google drive ImageSearchView is deprecated,how can i use the image search now?
var picker = new google.picker.PickerBuilder().
        addView(google.picker.ViewId.IMAGE_SEARCH).
        setLocale('fr').
        setDeveloperKey(developerKey).
        setCallback(pickerCallback).
        build();

A: Set the Mime Type
let view = new google.picker.View(google.picker.ViewId.DOCS);
view.setMimeTypes("image/png,image/jpeg,image/jpg");
let picker = new google.picker.PickerBuilder()
    .enableFeature(google.picker.Feature.NAV_HIDDEN)
    .enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
    .setAppId(appId)
    .setOAuthToken(token)
    .addView(view)
    .addView(new google.picker.DocsUploadView())
    .setDeveloperKey(API_KEY)
    .setCallback(handlePick)
    .build();
picker.setVisible(true);

For a full set up I would recommend looking at getting the quickstart working.
You can also see another answer of mine in which an example of using the picker to then call the Drive API to get the blob of an image.
Reference

*

*Picker Docs


text:
Q: Magento 2 - How to create a Block for back-end/adminhtml? I am using a module like this:
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <referenceContainer name="header.container">
        <container name="header.containertwo" as="header_containertwo" label="Page Header Container"  htmlTag="header" htmlClass="header-mini-container" after="header.panel.wrapper"/>
    </referenceContainer>
<referenceContainer name="header.containertwo">
    <block class="Magento\Framework\View\Element\Template" name="header.mini.container" template="Vendor_Module::test.phtml"/>
</referenceContainer>
</page>

At this point test.phtml is just hard coded content.
test.phtml:

Content is here but I need to content to be read from a Block created in the back-end instead

I want to create a block for my test.phtml where i able to read/use my custom block.
How can I create a block for test.phtml.?

A: You can create the adminhtml page with block by following below code
<referenceContainer name="header.containertwo">
    <block class="Vendor\Module\Block\Adminhtml\CustomBlock" name="Overview" template="Vendor_Module::test.phtml" />
</referenceContainer>

And create the block.
<?php
namespace Vendor\Module\Block\Adminhtml;
use Magento\Backend\Block\Template;

class CustomBlock extends Template
{

    public function greet()
    {
        return 'Hello world';
    }

}

in test.phtml you can access the block like.

 Hello i'm custom

<?php echo $block->greet(); ?>

Remove the cache and check.
Reference


text:
Q: How to ensure Excel calculation is completed from within a VBA procedure In an excel-spreadsheet user-defined functions are used to calculate basic results as spread-sheet matrices (cross-section values of composite elements).
Public Function XSValues(inputRange as Range) as variant
    [...]
    ' returns an array and used as matrix-formula (Ctrl-Shift-Enter)
End Function

These results are used within the spreadsheet on the one hand. Based on some values from these spreadsheet-results, on the other hand, a VBA-procedure is used to perform a relatively complex and time consuming calculation (static analysis of a structural model). This procedure is triggered by a button.
Public Sub Recalculate()
    [...]
    myValue = range("SomeXLResult").Value
    ' calculation
    ' notification updates
    ' drawing
    ' places different results into cells
End Sub

Now, my problems is, that the spread-sheet calculation is out of date, when the Sub Recalculate is triggered.
I found that in Excel 2016, the spread-sheet calculation is split into multliple threads. And experienced that user interaction sometimes is faster than spreadsheet calculation.
Therefore, I get depreciated values for further processing in the VBA-procedure.
My question is: How to guarantee for updated values from spread-sheet ranges?

A: If the solution as explained in your answer is working for you then great. I'm just wondering if you're aware of the application's AfterCalculate event (https://msdn.microsoft.com/en-us/vba/excel-vba/articles/application-aftercalculate-event-excel):

This event occurs whenever calculation is completed and there are no
  outstanding queries. It is mandatory for both conditions to be met
  before the event occurs. The event can be raised even when there is no
  sheet data in the workbook, such as whenever calculation finishes for
  the entire workbook and there are no queries running.
Add-in developers use the AfterCalculate event to know when all the
  data in the workbook has been fully updated by any queries and/or
  calculations that may have been in progress.
This event occurs after all Worksheet . Calculate , Chart . Calculate
  , AfterRefresh , and SheetChange events. It is the last event to occur
  after all refresh processing and all calc processing have completed,
  and it occurs after Application . CalculationState is set to xlDone .

It might be an easier implementation for you. The trick to access the application object's events is to declare it WithEvents in a class module. For the example, I've called the class clsAppEvents:
Option Explicit

Private WithEvents mApp As Application

Private Sub Class_Initialize()
    Set mApp = Application
End Sub

Private Sub mApp_AfterCalculate()
    Debug.Print "Calc ended at: " & Now
    ConsumeAfterCalculate
End Sub

In your module, you'd simply have the calling and event handling code:
Option Explicit

Private mAppEvents As clsAppEvents
Private mEnableConsume As Boolean

Public Sub RunMe()
    Set mAppEvents = New clsAppEvents
End Sub
Public Sub ConsumeAfterCalculate()
    If mEnableConsume Then
        Debug.Print "Sub called at: " & Now
        mEnableConsume = False
    End If
End Sub
Public Sub ConsumeButtonClick()
    Debug.Print "Button clicked at: " & Now
    mEnableConsume = True

    'For demo purposes I'm just forcing a calculation on existing data.
    Sheet1.EnableCalculation = False
    Sheet1.EnableCalculation = True
End Sub

FYI, the debug results were as follows:

Button clicked at: 25/10/2017 4:49:20 p.m.
Calc ended at: 25/10/2017 4:49:22 p.m.
Sub called at: 25/10/2017 4:49:22 p.m.

A: The following solution satisfies my needs:
When a button for recalculation is pressed, vba checks the current Excel calculation state. In case, calculation is done, the VBA-Procedure for calculation Recalculate is started directly. In case, calculation-mode is pending or calculating, then only the local worksheet-variable p_RecalcButtonClicked is set to true. When excel calculation is done, each worksheet fires the Worksheet_Calculate event after it was calculated. And so we can instruct Excel to Recalculate then.
As a safety measure, I kept the solution described in the related two questions from the above comment at the beginning of the sub Recalculate using the function waitForRecalculation. To avoid inactivity, I introduced a timer to tell the user, if calculation could not be finished within a given amount of time.
This is the code of the main worksheet:
' ##### Worksheet-Code

'''
' Private Worksheet-Variable to determine,
' if the button was pressed prior to worksheet calculated-event
'
Private p_RecalcButtonClicked As Boolean

'''
' Procedure to handle Button Clicked
' (either using a shape with a macro assigned or
'  an Active-X-Button with this procedure as event handler: best is to use {Button}_MouseUp as {Button}_clicked is fired occasionally by excel itself)
'
Public Sub ButtonClicked()
    '
    ' depending on the calculation state ...
    '
    Select Case Application.CalculationState
        Case xlDone
            '
            ' ... all done, fine ...
            ' ... directly call the calculation procedure sub Recalculate
            '
            p_RecalcButtonClicked = False
            Recalculate
        Case xlPending
            '
            ' ... pending ...
            ' ... set local worksheet variable true in order to call sub Recalculate
            '     later, when the calculated-event was raised
            '
            p_RecalcButtonClicked = True
            '
            ' instruct excel to recalculate
            '
            Application.CalculateFullRebuild
            '
            ' now let excel perform until worksheet calculated event is raised
            '
        Case xlCalculating
            '
            ' ... calculating ...
            ' ... set local worksheet variable true in order to call sub Recalculate
            '     later, when the calculated-event was raised
            '
            p_RecalcButtonClicked = True
            '
            ' let excel continue until worksheet calculated event is raised
            '
        Case Else
    End Select

End Sub

'''
' worksheet calculation finished
' this event is raised AFTER calculation was finished
' (shold actually be named Worksheet_Calculated)
'
Private Sub Worksheet_Calculate()
    ' check if the RecalcButton was clicked
    If p_RecalcButtonClicked Then
        p_RecalcButtonClicked = False
        Recalculate
    End If
End Sub

'''
' Recalculation
'
Public Sub wm_Recalculate()
        '
        ' wait for calculation to be done
        ' just in case...
        '
        If Not waitForRecalculation Then
            MsgBox "Press Ctrl+Alt+F9 for full recalculation", vbCritical + vbOKOnly, "Excel-calculation not done"
            Exit Sub
        End If

        ' [...] Your calculation here...
End Sub

'''
' Helper function to wait and do events until Excel-calculations are done
' returns true if calculation is done within the given time
'
Public Function waitForRecalculation() As Boolean

    Const MAXTIME_S = 10

    Dim t As Double
    t = Timer()

    ' in case of sql-async queries this might be required
    '
    ' Application.CalculateUntilAsyncQueriesDone

    '
    ' As a safety net,
    ' the second solution is to
    ' do System events until calculation is done
    '
    If Application.CalculationState <> xlDone Then
        Do
            DoEvents
            If Timer() - t > MAXTIME_S Then Exit Do
        Loop Until Application.CalculationState = xlDone
    End If

    '
    ' return true if calculations are done
    '
    waitForRecalculation = (Application.CalculationState = xlDone)

End Function


text:
Q: Kapow ManagementConsole could not start An error message pops out when I try to connect to the management console. The version is Kapow 10.1.0 master nightly 2370 x64.
The Error message is:

Unable to register to the default cluster: ManagementConsole failed to start: Spring subsystem failed to load.. Retrying

A: I had to delete the folder on Kapow Appdata User Profile folder, for example:
C:\users\<user>\appdata\local\Kapow

And then restart the RoboServer/Management Console.
This will create a new configuration and from there you can continue the installation (bring up the management console, enter the license, etc)

A: Please Delete Appdata and open localhost:50080 Management console and delete and then add Cluster settings again.
Now restart the Design studio and open it up again. Make sure you are using same objectdb.

A: You only need to rename the folder:
C:\Users\<user>\AppData\Local\Kapow\10.ur.version\Data

Then rerun the Management console as Administrator.
If you are still facing the same issue, please uninstall Kapow and install it again (also make sure you renamed the Data folder).


text:
Q: Circumscription to infinity: Is this infinite product convergent? A circle with radius $r_1=1$ is inscribed in an equilateral triangle. The triangle itself is inscribed in a larger circle and this larger circle is inscribed in a square. If we continue this process of alternatively circumscribing between a circle and a regular $n$-gon, theoretically, we will end up with a circle whose radius is $r_\infty$ and we cannot circumscribe that circle with any larger regular polygon (since regular $n$-gon will become a circle when $n$ tends toward infinity). Find the value of $r_\infty$.
I figure that because the relationship between the apothem $a$ and circumradius $r$ of a regular $n$-gon is: $r=\frac{a}{\cos\frac{\pi}{n}}$, I would have to calculate the infinite product: $$r_\infty=\prod_{n=3}^{\infty} \frac{1}{\cos(\frac{\pi}{n})}$$
Does this infinite product converge? If it is, what is the value of $r_\infty$ and how to compute it? Please help, thank you all in advance.

A: Since $\frac{1}{\cos(\frac{\pi}{n})} \geq 1$ the product $\prod_{n=3}^{\infty} \frac{1}{\cos(\frac{\pi}{n})}$ converges if and only if $\sum_{n=3}^{\infty}\left( \frac{1}{\cos(\frac{\pi}{n})}-1 \right)$ converges.
Now
$$\lim_{n\to \infty} \frac{\frac{1}{\cos(\frac{\pi}{n})}-1}{\frac{1}{n^2}}= \lim_{n\to \infty} \frac{1}{\cos(\frac{\pi}{n})}\frac{1-\cos(\frac{\pi}{n})}{\frac{1}{n^2}}= \lim_{n\to \infty} \frac{1-\cos(\frac{\pi}{n})}{\frac{1}{n^2}}\\=\pi^2\lim_{n\to \infty} \frac{1-\cos(\frac{\pi}{n})}{\frac{\pi^2}{n^2}}=\pi^2\lim_{x \to 0} \frac{1-\cos(x)}{x^2}=\frac{\pi^2}{2}$$
Since $\sum_{n=3}^\infty \frac{1}{n^2}$ converges, by the lmit comparison theorem  $\sum_{n=3}^{\infty}\left( \frac{1}{\cos(\frac{\pi}{n})}-1 \right)$ converges. Therefore, your product converges.

A: $r_\infty=8.7000366\dots$ is the polygon-circumscribing constant, OEIS A051762. So it does converge, though there is no closed form.


text:
Q: Test Kitchen with existing chef node If I already have a node provisioned using $ knife bootstrap... and in my list of servers $ knife list, can I just point kitchen to that node and have it converge so I can then run verify on it?

A: Kind of, but that's really not what Test Kitchen is for. What you probably want is to use the inspec CLI tool directly.


text:
Q: Neural network: Batch-version affine layer back-propagation weight matrix updation I'm trying to follow a book about deep learning but I found some part about affine layer of the network confusing. Say I have a network which accepts some handwriting number(0 ~ 9) images(mnist), which are flatten into one dimensional array, e.g. np.array([123, 255, 0, ...]) and it will output the scores for each possible output, e.g. np.array([0., 0., 0.3, 0., 0., 0.6, 0., 0., 0., 0.1])(So the image may be the number 5).
Here is my implementation of affine layer:
class AffineLayer(object):
    ...
    def backward(self, dy):
        dx = np.dot(dy, self._W.T)
        self._dW = np.dot(self._x.T, dy) # Question related part
        self._db = np.sum(dy, axis=0)
        dx = dx.reshape(self._original_x_shape)
        return dx
    ...

Here is some explanations:

*

*self._W is the weight matrix.

*The part of concern here is self._dW = np.dot(self._x.T, y) # Question related part.

*This line is derived from an equality:
X               *            W     +    B    =    Y
(N,2)     matrix product    (2,3)      (1,3)      (N,3).

*The notation (2,) comes from the X.shape of numpy.array, etc. To simplify my problem I choose these dimension numbers.
End of terminology, now here comes the question:

By some math(omitted), we can arrive the equality used in back-propagation,( so self._dW = np.dot(self._x.T, y) is used in the code):
d L         T         d L
---   ==   X     *    ---
d W                   d Y

(2,3)    (2,N)   *    (N,3).
Notice that no matter how I adjust N, which is the size of the batch, the dimension of dL/dW, the partial-derivative-of-L weight-matrix, won't change, and it's always (2,3).
Does this mean that the total effect of these N batches are combined/condensed into the dL/dW? This is related to how I would implement the output layer, e.g. softmax-cross-entropy layer as the final layer. My current conclusion for this is that N batch means doing the back-propagation N times and the division of the gradient dL/dW by N is needed to average/amortize the total effect of that batch. But now it seems like I only have to do it one time and the division should be "in the first step".

Edit:
I also find the version which seems to divide it at last step mnielsen/neural-networks-and-deep-learning - GitHub, for reference.
Since the softmax-cross-entropy layer class is the last layer of the net, in back-propagation it will becomes the "first step" as I mentioned above:
class SoftmaxCrossEntropy(object):
    ...
    def backward(self, dout=1):
        batch_size = self._t.shape[0]
        # one-hot
        if self._t.size == self._y.size:
            dx = (self._y - self._t) / batch_size # <-- why divided by N here?
        else: # not one-hot
            dx = self._y * 1
            dx[np.arange(batch_size), self._t] -= 1
            dx = dx / batch_size       #    <-- why divided by N here?
        return dx
    ...

A:
Does it means that the effect of these N batches of input are combined/condensed into the dW?

Since the i-th row of X is a 1-d array that is related to the i-th flatten image. If I transpose X into
     T
    X    , then it's columns to represent those flatten images. If N increase, although
the dimension of the result(dW) won't change, the intermediate steps of computing each element of
           T        d L
 dW   =   X    *    ---
                    d Y    , increase, which means
              N
 dW     =    Sum  (  pixel_info     *   class_scores_deriv.       )
   i,j       n=1               i,n                         n,j      , which N is the batch
size. Clearly each class_scores_derivative_(n,j) "join" the determination of dW_(i,j), but this implies that the division by batch_size = N is needed, because the summation above is not the average effect of that batch, but what I need is dW to represent the average impact of that batch. If I divide each element of class_scores_deriv., which is the line
dx = (self._y - self._t) / batch_size, then
    N                         1
   Sum  (  pixel_info     *  ---  class_scores_deriv.    )
   n=1               i,n      N                   n,j
        1    N
    =  ---  Sum  (  pixel_info     *   class_scores_deriv.       )
        N   n=1               i,n                         n,j
        1
    =  --- dW
        N       , which is the real dW I want.
So the answer (I hope) should be

The entire batch determine the dW, but to condense it, the divisions in SoftmaxCrossEntropy::backward(self, dout=1) is needed.


text:
Q: localization of big project I need to localize an asp.net webapp with lots of pages.
So far what i'm doing is replace all text with literals where needed and i'm adding <%$ Resources: restype, reskey %> tags wherever needed. All the strings come from my database.
The problem is putting all the text in the database it's just a huge time spender.
I really don't want to be putting all the text in the database manually because everytime i finish a new page i have to go over the same excercise again.
So i came up with an idea:
What if i extended the localization resource handler with a default value like this (pseude code):
<asp:literal runat="server" Text='<%$ Resources: restype, reskey, 'This was the hard coded text' %>' />

When the page was first loaded the string resource wouldnt be in the database, but having the default text i can add it with the known resource type and key to my database. I could prefix the default values with a question mark for example. This allows me to check my table with strings and everywhere i see a text with a question mark i know it needs translating.
This way i only have to add resource tags to my markup and i avoid inserting all the text in my database. I just have to make sure to load every page once, which i can do locally in debug and then send the non-translated labels to a translator.
Please advise on this approach.

A: What we do here where I work is to declare string resources using special helper class. When the application is run, new string resources defined in code are auto-inserted into the database with their default value. The application works without any preparation steps. Later you can change the strings.
But yes, it requires some wrapper code to write.

A: Sounds like a nice idea, especially if you can't go along with the standard resource files mechanism which is automatically generated by VS.
Rick Strahl has written a solution for localizing ASP.net webapps to the DB. He's written some kind of Ajax UI which would even allow your users to translate the Webapp. The source code is also open, so you may take a look at it when developing your own solution.
Here's the link: http://www.west-wind.com/WestWindWebToolkit/


text:
Q: Evento scroll no funciona en Firefox para Android Tengo una página con un menú con el efecto estilo sticky, pero tuve que hacerlo mediante JavaScript y posicionamiento fixed, ya que el menú estaba dentro de un contenedor y no me funcionaba el usar la propiedad sticky de CSS.
La cosa es que en mi código JavaScript, cuando el valor de scrolltop es diferente a cero se activa un evento y se agrega una clase CSS al menú, para que pase a estar fijo en pantalla y cambie de color.  Esto me funcionó perfectamente en Chrome y Firefox para escritorio.
Pero en Firefox para teléfonos Android no me funciona, el efecto se activa pero no me quita la clase, nuevamente cuando vuelvo a la posición inicial.
En el inspector de elementos me aparece este mensaje:

This site appears to use a scroll-linked positioning effect. This may
not work well with asynchronous panning; see
https://developer.mozilla.org/docs/Mozilla/Performance/ScrollLinkedEffects
for further details and to join the discussion on related tools and
features!

Intenté investigar por mi cuenta, pero no entendí mucho a que se refieren, si me pueden explicar a qué se refiere el mensaje y por qué me ocurre esto me ayudaría mucho.
Incluso la página web la pueden revisar si desean, es esta
Dejo acá el código JavaScript, es bastante corto y fácil de entender:
let header = document.getElementById("header");
let inicio  = document.getElementById("inicio");

let altoHeader = header.offsetHeight;

function activarPegajoso(){

    let bajada = document.documentElement.scrollTop;

    if(bajada !=0){

        header.classList.add("cambio");
        inicio.style.marginTop = altoHeader+"px";

    }else{

        header.classList.remove("cambio");
        inicio.style.marginTop = "0px";
    }

}

    window.addEventListener("scroll", activarPegajoso);


text:
Q: Side caption on subfigure I have problem: I would like to put a side caption on a subfigure.
Here is my actual code (that doesn't perform the side caption):
\begin{figure}[H]
\begin{center}
    \subfigure[\footnotesize{...}]{
        \label{...}
        \includegraphics[width=0.25\textwidth]{...}
    }
    \subfigure[\footnotesize{...}]{
        \label{...}
        \includegraphics[width=0.25\textwidth]{...}
    }\\
    \subfigure[\footnotesize{...}]{
        \label{...}
        \includegraphics[width=0.25\textwidth]{...}
    }
    \subfigure[\footnotesize{...}]{
        \label{...}
        \includegraphics[width=0.25\textwidth]{...}
    }\\
    \subfigure[\footnotesize{...}]{
        \label{...}
        \includegraphics[width=0.25\textwidth]{...}
    }
    \subfigure[\footnotesize{...}]{
        \label{...}
        \includegraphics[width=0.25\textwidth]{...}
    }\\
    \subfigure[\footnotesize{...}]{
        \label{...}
        \includegraphics[width=0.25\textwidth]{...}
    }
    \subfigure[\footnotesize{...}]{
        \label{...}
        \includegraphics[width=0.25\textwidth]{...}
    }\\
    \subfigure[\footnotesize{...}]{
        \label{...}
        \includegraphics[width=0.25\textwidth]{...}
    }
    \subfigure[\footnotesize{...}]{
        \label{...}
        \includegraphics[width=0.25\textwidth]{...}
    }\\
\end{center}
\caption{"I would like that this text is put on the side of the image"}
\label{...}
\end{figure}

Where I put "..." is text that I delete.
I tried with the sidecap package and edit the environment with SCfigure instead of figure, but this gives me a lot of errors.

A: This differs from sidecap in that it computes the width available for the caption and it aligns the tops using \raisebox.
The caption \label should go inside the minipage with the caption.
\documentclass{article}
\usepackage{subfigure}
\usepackage{graphicx}
\usepackage{varwidth}

\begin{document}
\begin{figure}[htp]
\sbox0{\begin{varwidth}{\textwidth}% get width of combined subfigures
    \subfigure[\footnotesize{...}]{
        \includegraphics[width=0.25\textwidth]{example-image}
    }
    \subfigure[\footnotesize{...}]{
        \includegraphics[width=0.25\textwidth]{example-image}
    }\\
    \subfigure[\footnotesize{...}]{
        \includegraphics[width=0.25\textwidth]{example-image}
    }
    \subfigure[\footnotesize{...}]{
        \includegraphics[width=0.25\textwidth]{example-image}
    }\\
    \subfigure[\footnotesize{...}]{
        \includegraphics[width=0.25\textwidth]{example-image}
    }
    \subfigure[\footnotesize{...}]{
        \includegraphics[width=0.25\textwidth]{example-image}
    }\\
    \subfigure[\footnotesize{...}]{
        \includegraphics[width=0.25\textwidth]{example-image}
    }
    \subfigure[\footnotesize{...}]{
        \includegraphics[width=0.25\textwidth]{example-image}
    }\\
    \subfigure[\footnotesize{...}]{
        \includegraphics[width=0.25\textwidth]{example-image}
    }
    \subfigure[\footnotesize{...}]{
        \includegraphics[width=0.25\textwidth]{example-image}
    }\\
\end{varwidth}}%
\raisebox{-\height}{\usebox0}% left
\hspace{\columnsep}% gap
\raisebox{-\height}{\begin{minipage}{\dimexpr \textwidth-\wd0-\columnsep}
\abovecaptionskip=0pt
\caption{"I would like that this text is put on the side of the image"}
\end{minipage}}
\end{figure}
\end{document}

A: Please, be aware that subfigure is obsolete. Either use subfig (and \subfloat instead of \subfigure) or the more recent and maintained subcaption package.
I guess that you want the caption to be next to the set of images because the caption text is long. Otherwise bottom placement would be much better.
Just use a tabular to align the images and a minipage to set the caption.
\documentclass{article}
\usepackage{subfig}
\usepackage{graphicx}

\usepackage{lipsum} % for mock caption text

\begin{document}

\begin{figure}
\begin{tabular}{@{}cc@{}}
    \subfloat[subfigure]{%
        \label{a}%
        \includegraphics[width=0.25\textwidth]{example-image}%
    }&
    \subfloat[subfigure]{%
        \label{b}%
        \includegraphics[width=0.25\textwidth]{example-image}%
    }\\
    \subfloat[subfigure]{%
        \label{c}%
        \includegraphics[width=0.25\textwidth]{example-image}%
    }&
    \subfloat[subfigure]{%
        \label{d}%
        \includegraphics[width=0.25\textwidth]{example-image}%
    }\\
    \subfloat[subfigure]{%
        \label{e}%
        \includegraphics[width=0.25\textwidth]{example-image}%
    }&
    \subfloat[subfigure]{%
        \label{f}%
        \includegraphics[width=0.25\textwidth]{example-image}%
    }\\
    \subfloat[subfigure]{%
        \label{g}%
        \includegraphics[width=0.25\textwidth]{example-image}%
    }&
    \subfloat[subfigure]{%
        \label{h}%
        \includegraphics[width=0.25\textwidth]{example-image}%
    }\\
    \subfloat[subfigure]{%
        \label{i}%
        \includegraphics[width=0.25\textwidth]{example-image}%
    }&
    \subfloat[subfigure]{%
        \label{j}%
        \includegraphics[width=0.25\textwidth]{example-image}%
    }\\
\end{tabular}\hfill
\begin{minipage}{0.4\textwidth}
\caption{\lipsum[2]}
\label{x}
\end{minipage}
\end{figure}

\end{document}

Using [H] as the placement specifier is generally wrong; even more in this case where the float is quite large.

With a couple of tricks you can get top alignment.

*

*change \begin{tabular}{@{}cc@{}} into
\begin{tabular}[t]{@{}cc@{}} \\[-\dp\strutbox]

*change \begin{minipage}[t]{0.4\textwidth} into
\begin{minipage}[t]{0.4\textwidth}

The rest remains unchanged.


text:
Q: Splash screen - AnimationController won't start before async call is done on initState I'm trying to make a splash screen for my Flutter application. I want my logo to rotate while checking if the user is logged on firebase authentifaction and then going to the views concerned depending of the return value.
The problem is that my application doesn't build properly before my async call (I see my backGround but not the AnimatedBuilder).
I tried running my CheckUser() using the after_layout package, or using this function :
WidgetsBinding.instance.addPostFrameCallback((_) => yourFunction(context));
but it always wait for the CheckUser() function to finish so I don't see the animation as it navigates directly to my other views.
Here's my code if you want to test it :
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:skull_mobile/connexion/login.dart';
import 'accueil.dart';

class SplashPage extends StatefulWidget {
  SplashPage({Key key}) : super(key: key);

  @override
  _SplashPage createState() => _SplashPage();
}

class _SplashPage extends State<SplashPage>
    with SingleTickerProviderStateMixin {

  AnimationController animationController;

  @override
  void initState() {
    super.initState();
    animationController = new AnimationController(
      vsync: this,
      duration: new Duration(seconds: 5),
    );
    animationController.repeat();
    checkUser();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[800],
      body: Center(
        child: Container(
          child: new AnimatedBuilder(
            animation: animationController,
            child: new Container(
              height: 150.0,
              width: 150.0,
              child: new Image.asset('assets/skull.png'),
            ),
            builder: (BuildContext context, Widget _widget) {
              return new Transform.rotate(
                angle: animationController.value * 6.3,
                child: _widget,
              );
            },
          ),
        ),
      ),
    );
  }

  void checkUser() async {
    FirebaseAuth.instance.currentUser().then((currentUser) => {
          if (currentUser == null)
            {Navigator.pushNamed(context, LoginPage.routeName)}
          else
            {Navigator.pushNamed(context, AccueilPage.routeName)}
        });
  }
}

A: Following on my comment I'm sharing here a snippet of my own code and how I handle a splash screen, here called "WaitingScreen", the device's Connection state and then send the user to different pages with different properties depending on the results:
@override
Widget build(BuildContext context) {
  switch (authStatus) {
    case AuthStatus.notDetermined:
      if(_connectionStatus == ConnectionStatus.connected){
        return _buildWaitingScreen();
      }else{
        return _buildNoConnectionScreen();
      }
      break;
    case AuthStatus.notSignedIn:
      return LoginPage(
        onSignedIn: _signedIn,
        setThemePreference: widget.setThemePreference,
      );
    case AuthStatus.signedIn:
      return MainPage(
        onSignedOut: _signedOut,
        setThemePreference: widget.setThemePreference,
        getThemePreference: widget.getThemePreference,
      );
  }
  return null;
}


text:
Q: copy files to specified dir with cmake I want to copy somefile.bmp to my "${PROJECT_BINARY_DIR}/bin/data" folder but it doesn´t work. However if I change the path to "${PROJECT_BINARY_DIR}/bin" it works fine. How can I fix this?
add_custom_command(TARGET Invaders POST_BUILD
           COMMAND ${CMAKE_COMMAND} -E copy_if_different
           "${PROJECT_SOURCE_DIR}/Game/data/somefile.bmp"
           "${PROJECT_BINARY_DIR}/bin/data")

A: The directory does not exist, I guess. You need to create it before copying:
add_custom_command(TARGET Invaders POST_BUILD
           COMMAND ${CMAKE_COMMAND} -E make_directory
           "${PROJECT_SOURCE_DIR}/Game/data"
           COMMAND ${CMAKE_COMMAND} -E copy_if_different
           "${PROJECT_SOURCE_DIR}/Game/data/somefile.bmp"
           "${PROJECT_BINARY_DIR}/bin/data")


text:
Q: After iframe, no div value showing in webpage My application is web based and developed by MVC3 razor. I wanna show SSRS report in my page. For that I have used iframe tag to show SSRS report and its working fine. After the iframe tag I have put a div and included content in that.

© 2012

Problem: I facing problem in div i.e. I'm unable to view values inside the div.
I'm using IE8

A: An iframe is not a self-closing tag. You should change from  to :

© 2012

iframe's can be self-closed with HTML5, but IE8 doesn't support this.

A: Your iframe code is missing the closing, you should change your code to

© 2012

© 2012


text:
Q: Zxing Barcode Scanner triggers OnSleep() - OnResume() Methods on start and on finish I'm developing a Xamarin.Forms app. I have a button which triggers the Scanner.
<Button VerticalOptions="Center"
        IsVisible="False"
        Text="Scan"
        CornerRadius="10"
        FontSize="Medium"
        FontAttributes="Bold"
        TextColor="White"
        Clicked="Scan"
        x:Name="btnScan"/>

My scanning function is:
private async void Scan(object sender, EventArgs e)
    {
        PermissionStatus granted = await Permissions.CheckStatusAsync<Permissions.Camera>();
        if (granted != PermissionStatus.Granted)
        {
            _ = await Permissions.RequestAsync<Permissions.Camera>();
        }
        if (granted == PermissionStatus.Granted)
        {
            try
            {
                MobileBarcodeScanningOptions optionsCustom = new MobileBarcodeScanningOptions();

                scanner = new MobileBarcodeScanner();
                scanner.TopText = "Insert";
                scanner.BottomText = "Align red line with Barcode";

                optionsCustom.DelayBetweenContinuousScans = 3000;
                scanner.ScanContinuously(optionsCustom, ScanResult);

            }
            catch (Exception)
            {
                scanner.Cancel();
                Device.BeginInvokeOnMainThread(async () =>
                {
                    await DisplayAlert("Problem", "Something went wrong.", "ΟΚ");
                });
            }
        }
    }

The problem is after the scanner is actually opened, the OnSleep() method in App.xaml.cs is triggered.
protected override void OnSleep()
{

}

protected override void OnResume()
{

}

And after the scanner is closed the OnResume() method is triggered.
Is this behavior expected? Am i doing something wrong with the scanner initialization?

A: Based on the comments, your question then becomes not to suppress the behaviour you're seeing but handle it. So you could put a static flag in the App class so you know the scanner is active and put your handler code inside this.
App.xaml.cs:
public static bool ScannerActive { get; set; }

protected override void OnSleep()
{
    if (!ScannerActive)
    {
        HandleOnSleep();
    }
}

protected override void OnResume()
{
    if (!ScannerActive)
    {
        HandleOnResume();
    }

    // Reset the flag if we are coming back from the scanner
    else App.ScannerActive = false;
}

Scanning function:
private async void Scan(object sender, EventArgs e)
{
    App.ScannerActive = true;

    try
    {
        // ... //
        scanner.ScanContinuously(optionsCustom, ScanResult);
    }
    catch (Exception)
    {
        // Reset flag if it crashed out
        App.ScannerActive = false;
    }
}