text:
Q: getting next() and prev() array elements not working as expected I have an array with all the results of a query search.
My problem is that i need to select one row from this array, and then be able to select the next and previous row.
here is my code
function getUserProf(array $data, $faceid)
{
    //make sure that all data is saved in an array
    $userprof = array();

    //makes the array with the info we need
    foreach ($data as $val)
        if ($val['faceid'] == $faceid){
            $userprof = array ("id" => $val["id"], "total" => $val["total"], "faceid" => $val["faceid"], "lname" => $val["lname"], "fname" => $val["fname"], "hand" => $val["hand"], "shot1" => $val["shot1"], "shot1" => $val["shot1"], "shot2" => $val["shot2"], "shot3" => $val["shot3"], "shot4" => $val["shot4"], "shot5" => $val["shot5"]);
        }
        $next = next($data);//to get the next profile
        $prev = prev($data);//to get the next profile
        $userprofinfo = array('userprof' => $userprof, 'next' => $next);//make a array with the profile and the next prof and the prev prof

    //we return an array with the info
    return $userprofinfo;
}

This works somehow, but it doesn't give me the correct next and previous row?

A: Your problem is that prev() moves the array pointer -1 and next() moves it +1 again, resulting in $next being the exact same row as the current one where you started before invoking prev().
Also, you get $prev and $next after the complete foreach() run, which leaves the array pointer at the end of the array. (so you will always get the last element)
Try this instead:
function getUserProf(array $data, $faceid) {
    foreach ($data as $key => $val) {
        if ($val['faceid'] == $faceid) {
            return array(
                'userprof' => $val,
                'prev'     => isset($data[$key-1]) ? $data[$key-1] : array(),
                'next'     => isset($data[$key+1]) ? $data[$key+1] : array()
            );
        }
    }
}


text:
Q: 2 Wordpress Installations serving specific areas of each on one URL I have 2 Wordpress installations on EC2 instances. Servers are running Bitnami Stacks on Ubuntu 18 and after a couple of days of trying to get this up and running I'm stuck.
Currently I have
 new.website.com (server 2)
 website.com (server 1)

website.com is the old website however it is still very much in use and has a huge amount of SEO value. new.website.com currently only has the homepage on. Due to the reletive instability of website.com we would like to simply display the new homepage of new.webiste.com when a user travels to website.com and, thereafter, display the backend of website.com. We want to do this to prevent any new code being merged with old etc.....
I'm aware that this can be achieved with simple redirects however we aren't wanting to display new.website.com to individuals whom visit the website and simple want them to see website.com.
I have explored multisite, network and reverse proxy options however cant manage to get this working and so any direction or help would be great.
In summary
Any traffic that hits - website.com - display new homepage from server 2
Thereafter - all other pages - display pages from website.com / server 1
The main element here is that whilst the user is accessing two servers we want them to see 1 URL of website.com

A: Just use a full screen iFrame to display the new website inside the old website.
<iframe src="https://www.google.com/" height="100vh" width="100vw" title="Iframe Example"></iframe>

redpajama_set_name: RedPajamaStackExchange


text:
Q: What wp_verify_nonce() means? I've read the reference of this function on Wordpress but i still don't understand what this function really does.
I'm reading a tutorial about creating a meta box in wordpress and I have this code inside the function which saves the data:
if ( !wp_verify_nonce( $_POST[$meta_box['name'].'_noncename'], plugin_basename(__FILE__) )) {
                return $post_id;
}

Can someone explain briefly what is the meaning of wp_verify_nonce() ?

A: The nonce is a 'number used once' - a code that WP uses to make sure that POST data is coming from a safe place. This is useful to make sure that your plugin does not end up digesting data from an unsafe source (see Cross-Site Request Forgery).
This blog post by Mark Jaquith is useful for understanding them.

[nonces] are unique to the WordPress install, to the WordPress user, to the action, to the object of the action, and to the time of the action (24 hour window). That means that if any of these things changes, the nonce is invalid. So if you (somehow) intercept a nonce being used by me, you would, first of all, only have 24 hours to use this key to attempt to trick me.

To create a nonce you must give wp_create_nonce a certain string, providing the 'context' for the nonce. It gives you back a string - the nonce itself. You then include this nonce as part of your POST request. The receiving page should then create a nonce of its own, using the same context, and see if they match up.
In this case, the context given is plugin_basename(__FILE__). This will generate the same string whenever it is called from within the same plugin (see here).
When your wp_verify_nonce recieves a nonce created under the same circumstances as specified by Mark, with the same context string, it returns true.
In short:
!wp_verify_nonce

returns true if wp_verify_nonce returns false.
($_POST[$meta_box['name'].'_noncename'],

First argument to wp_verify_nonce: the nonce to check. This code gets the nonce out of the post request, stored in the $_POST global.
plugin_basename(__FILE__) )

Second argument to wp_verify_nonce: the context for generating the new nonce against which the first will be checked.
{ return $post_id; }

If the nonce doesn't match, stop executing the current function, returning the variable $post_id.


text:
Q: How to use this javascript library in Dart? The problem
I tried to use the JS code below in Dart with "new JsObject(context["Delaunay"])", however, I get a message that: Exception: type JsObject is not a subtype of type JsFunction of constructor.
Questions
Does this means I have to use the JS function with "JsFunction"? I checked JsFunction class, but I don't know how to use the constructor.
Any ideas?
Thanks
Code:
var Delaunay;

(function() {
  "use strict";

  var EPSILON = 1.0 / 1048576.0;

  function supertriangle(vertices) {
    var xmin = Number.POSITIVE_INFINITY,
        ymin = Number.POSITIVE_INFINITY,
        xmax = Number.NEGATIVE_INFINITY,
        ymax = Number.NEGATIVE_INFINITY,
        i, dx, dy, dmax, xmid, ymid;

    for(i = vertices.length; i--; ) {
      if(vertices[i][0] < xmin) xmin = vertices[i][0];
      if(vertices[i][0] > xmax) xmax = vertices[i][0];
      if(vertices[i][1] < ymin) ymin = vertices[i][1];
      if(vertices[i][1] > ymax) ymax = vertices[i][1];
    }

    dx = xmax - xmin;
    dy = ymax - ymin;
    dmax = Math.max(dx, dy);
    xmid = xmin + dx * 0.5;
    ymid = ymin + dy * 0.5;

    return [
      [xmid - 20 * dmax, ymid -      dmax],
      [xmid            , ymid + 20 * dmax],
      [xmid + 20 * dmax, ymid -      dmax]
    ];
  }

  function circumcircle(vertices, i, j, k) {
    var x1 = vertices[i][0],
        y1 = vertices[i][1],
        x2 = vertices[j][0],
        y2 = vertices[j][1],
        x3 = vertices[k][0],
        y3 = vertices[k][1],
        fabsy1y2 = Math.abs(y1 - y2),
        fabsy2y3 = Math.abs(y2 - y3),
        xc, yc, m1, m2, mx1, mx2, my1, my2, dx, dy;

    /* Check for coincident points */
    if(fabsy1y2 < EPSILON && fabsy2y3 < EPSILON)
      throw new Error("Eek! Coincident points!");

    if(fabsy1y2 < EPSILON) {
      m2  = -((x3 - x2) / (y3 - y2));
      mx2 = (x2 + x3) / 2.0;
      my2 = (y2 + y3) / 2.0;
      xc  = (x2 + x1) / 2.0;
      yc  = m2 * (xc - mx2) + my2;
    }

    else if(fabsy2y3 < EPSILON) {
      m1  = -((x2 - x1) / (y2 - y1));
      mx1 = (x1 + x2) / 2.0;
      my1 = (y1 + y2) / 2.0;
      xc  = (x3 + x2) / 2.0;
      yc  = m1 * (xc - mx1) + my1;
    }

    else {
      m1  = -((x2 - x1) / (y2 - y1));
      m2  = -((x3 - x2) / (y3 - y2));
      mx1 = (x1 + x2) / 2.0;
      mx2 = (x2 + x3) / 2.0;
      my1 = (y1 + y2) / 2.0;
      my2 = (y2 + y3) / 2.0;
      xc  = (m1 * mx1 - m2 * mx2 + my2 - my1) / (m1 - m2);
      yc  = (fabsy1y2 > fabsy2y3) ?
        m1 * (xc - mx1) + my1 :
        m2 * (xc - mx2) + my2;
    }

    dx = x2 - xc;
    dy = y2 - yc;
    return {i: i, j: j, k: k, x: xc, y: yc, r: dx * dx + dy * dy};
  }

  function dedup(edges) {
    var i, j, a, b, m, n;

    for(j = edges.length; j; ) {
      b = edges[--j];
      a = edges[--j];

      for(i = j; i; ) {
        n = edges[--i];
        m = edges[--i];

        if((a === m && b === n) || (a === n && b === m)) {
          edges.splice(j, 2);
          edges.splice(i, 2);
          break;
        }
      }
    }
  }

  Delaunay = {
    triangulate: function(vertices, key) {
      var n = vertices.length,
          i, j, indices, st, open, closed, edges, dx, dy, a, b, c;

      /* Bail if there aren't enough vertices to form any triangles. */
      if(n < 3)
        return [];

      /* Slice out the actual vertices from the passed objects. (Duplicate the
       * array even if we don't, though, since we need to make a supertriangle
       * later on!) */
      vertices = vertices.slice(0);

      if(key)
        for(i = n; i--; )
          vertices[i] = vertices[i][key];

      /* Make an array of indices into the vertex array, sorted by the
       * vertices' x-position. */
      indices = new Array(n);

      for(i = n; i--; )
        indices[i] = i;

      indices.sort(function(i, j) {
        return vertices[j][0] - vertices[i][0];
      });

      /* Next, find the vertices of the supertriangle (which contains all other
       * triangles), and append them onto the end of a (copy of) the vertex
       * array. */
      st = supertriangle(vertices);
      vertices.push(st[0], st[1], st[2]);

      /* Initialize the open list (containing the supertriangle and nothing
       * else) and the closed list (which is empty since we havn't processed
       * any triangles yet). */
      open   = [circumcircle(vertices, n + 0, n + 1, n + 2)];
      closed = [];
      edges  = [];

      /* Incrementally add each vertex to the mesh. */
      for(i = indices.length; i--; edges.length = 0) {
        c = indices[i];

        /* For each open triangle, check to see if the current point is
         * inside it's circumcircle. If it is, remove the triangle and add
         * it's edges to an edge list. */
        for(j = open.length; j--; ) {
          /* If this point is to the right of this triangle's circumcircle,
           * then this triangle should never get checked again. Remove it
           * from the open list, add it to the closed list, and skip. */
          dx = vertices[c][0] - open[j].x;
          if(dx > 0.0 && dx * dx > open[j].r) {
            closed.push(open[j]);
            open.splice(j, 1);
            continue;
          }

          /* If we're outside the circumcircle, skip this triangle. */
          dy = vertices[c][1] - open[j].y;
          if(dx * dx + dy * dy - open[j].r > EPSILON)
            continue;

          /* Remove the triangle and add it's edges to the edge list. */
          edges.push(
            open[j].i, open[j].j,
            open[j].j, open[j].k,
            open[j].k, open[j].i
          );
          open.splice(j, 1);
        }

        /* Remove any doubled edges. */
        dedup(edges);

        /* Add a new triangle for each edge. */
        for(j = edges.length; j; ) {
          b = edges[--j];
          a = edges[--j];
          open.push(circumcircle(vertices, a, b, c));
        }
      }

      /* Copy any remaining open triangles to the closed list, and then
       * remove any triangles that share a vertex with the supertriangle,
       * building a list of triplets that represent triangles. */
      for(i = open.length; i--; )
        closed.push(open[i]);
      open.length = 0;

      for(i = closed.length; i--; )
        if(closed[i].i < n && closed[i].j < n && closed[i].k < n)
          open.push(closed[i].i, closed[i].j, closed[i].k);

      /* Yay, we're done! */
      return open;
    },
    contains: function(tri, p) {
      /* Bounding box test first, for quick rejections. */
      if((p[0] < tri[0][0] && p[0] < tri[1][0] && p[0] < tri[2][0]) ||
         (p[0] > tri[0][0] && p[0] > tri[1][0] && p[0] > tri[2][0]) ||
         (p[1] < tri[0][1] && p[1] < tri[1][1] && p[1] < tri[2][1]) ||
         (p[1] > tri[0][1] && p[1] > tri[1][1] && p[1] > tri[2][1]))
        return null;

      var a = tri[1][0] - tri[0][0],
          b = tri[2][0] - tri[0][0],
          c = tri[1][1] - tri[0][1],
          d = tri[2][1] - tri[0][1],
          i = a * d - b * c;

      /* Degenerate tri. */
      if(i === 0.0)
        return null;

      var u = (d * (p[0] - tri[0][0]) - b * (p[1] - tri[0][1])) / i,
          v = (a * (p[1] - tri[0][1]) - c * (p[0] - tri[0][0])) / i;

      /* If we're outside the tri, fail. */
      if(u < 0.0 || v < 0.0 || (u + v) > 1.0)
        return null;

      return [u, v];
    }
  };

  if(typeof module !== "undefined")
    module.exports = Delaunay;
})();

A: new JsObject(context["Delaunay"]) is the js equivalent of new Delaunay(). Basically when you call context["Delaunay"] you get a reference to the js object Delaunay.
To use the "triangulate function" simply use :
context["Delaunay"].callMethod('triangulate', [vertices, key]);

See Using JavaScript from Dart for more details.


text:
Q: Database Normalization vs dependencies I am developing 3-4 interdependent programs.  Call them foo bar baz and auth.  I want them to be independent of each other.  Imagine if I were to license out each program to other companies.  Some companies may want foo and bar, others may just want baz, etc.  It also seems like good practice to keep auth independent as well.
Context:
auth is taking care of authentication for all of the systems.  The main users table in auth has user_id, email, password, first, last
foo has a users table as well which has specific fields for the application:
user_id, role_id, etc.
Each system has its own database.  In the past I have created a foreign key from each application to the auth db.  I removed update permissions from the other dbs but granted select access to certain relevant fields.  This seems like a bad solution because it creates a tight dependency, but it allowed me to normalize the db so that I didn't have to store the users name and email in the foo, bar, or baz databases.
Would it be better to store the information in all of the databases?  Or would it be better to store the Auth Id in foo bar and baz and use an api to get the user info using the authId?
Similarly, I might have customers in all 3 systems.  Sure it seems bad to create a dependency into an auth db, but what about the customer dbs across all 3 of them?
Or is the best solution to have one central db.  One users table.

Other Suggestions?

A: If you have 4 independant services, then they have to independant. No data should be shared in common DBs or similar, as then you simply make them dependant!
Now while its OK to share a single DB in production, the services should use their own schemas as to DB is just there as a common container, similar to how a single Linux server can run all 4 services.
Each service should have its own API, and this is the only way to get data in and out of each. So your auth service will store users and perform authentication, but will return some token to identify a user. This token is what the other services use to remember which user is which - but otherwise they should have no knowledge of user authentication at all.
The easiest way to think of implementing these is to think what would you do if you decided to use a 3rd party service instead of the ones you're writing - if you used StackExchange's OpenID service for users instead of your own. If you can replace that into your architecture then you have a good, independent design.

A: Your example is a bit abstract, but let me run through my thoughts.
Option A : In my experience this is Always Bad regardless of your reasons. sure DBs like MSSQL can have friend databases etc, but if the data is linked, it should be in the same DB
Option B : Not sure whats going on in here, you are adding an API which queries all DBs and brings the results together? This is Better, but if you have Apps on top of that API then its part of the datalayer for them and they really only use one of the DBs, so why have they got the others in thier data layer?
Option C : Well this works, but its not good to have one big database with unrelated data in it. You want the programs to be independent of each other right? this dosnt help with that.
Option D
My suggestion is to abstract the authentication away form the concept of userId. your Auth App should be concerned with users and roles (or promises etc if your are going all modern) this data should exist in the Auth DB
Each App needs to have a userId to group data by user, with some related data to make the auth call and identify the user to humans. this would be userId (unique to the app), real name, authusername, auth service to use. This data should exist on the apps DB
The databases should have no connection between them, conceptually you should be able to use facebook as your auth service rather that your Auth App
You may need a Further User linking information if you want to relate a foo user with a bar user

A: I would recommend implementing Single Sign On (SSO), for example with LDAP. Your larger customers probably would have benefited from it as well, as they would be able to replace your built in auth app with their own existing user database. For your smaller customers that don't support SSO, you can simplify deployment by shipping your app with a default auth app.


text:
Q: Curve fiting of normal distribution in Python I want to calculate the percentiles of normal distribution data, so I first fit the data to the normal distribution, here is the example:
from scipy.stats import norm
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt

x = np.array([ 0.47712125,  0.5445641 ,  0.61193563,  0.67924615,  0.74671202,
    0.81404772,  0.88144172,  0.94885291,  1.01623919,  1.08361011,
    1.15100191,  1.21837793,  1.28578227,  1.3531658 ,  1.42054981,
    1.48794397,  1.55532424,  1.62272161,  1.69010744,  1.75749472,
    1.82488047,  1.89226717,  1.9596566 ,  2.02704774,  2.09443269,
    2.16182302,  2.2292107 ,  2.29659719,  2.36398595,  2.43137342,
    2.49876254,  2.56614983,  2.63353814,  2.700926  ,  2.76831392,
    2.83570198,  2.90308999,  2.97008999,  3.03708997,  3.10408999,
    3.17108999,  3.23808998,  3.30508998,  3.37208999,  3.43908999,
    3.50608998,  3.57308998,  3.64008999,  3.70708999,  3.77408999,
    3.84108999,  3.90808999])
y = array([  0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
     0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
     0.00000000e+00,   5.50000000e+01,   1.33500000e+02,
     2.49000000e+02,   4.40000000e+02,   7.27000000e+02,
     1.09000000e+03,   1.53000000e+03,   2.21500000e+03,
     3.13500000e+03,   4.44000000e+03,   5.57000000e+03,
     6.77000000e+03,   8.04500000e+03,   9.15500000e+03,
     1.00000000e+04,   1.06000000e+04,   1.06500000e+04,
     1.02000000e+04,   9.29000000e+03,   8.01500000e+03,
     6.50000000e+03,   5.24000000e+03,   4.11000000e+03,
     2.97000000e+03,   1.86000000e+03,   1.02000000e+03,
     5.26500000e+02,   2.49000000e+02,   1.11000000e+02,
     5.27000000e+01,   6.90825000e+00,   4.54329000e+00,
     3.63846500e+00,   3.58135000e+00,   2.37404000e+00,
     1.81840000e+00,   1.20159500e+00,   6.02470000e-01,
     3.43295000e-01,   1.62295000e-01,   7.99350000e-02,
     3.60750000e-02,   1.50000000e-02,   3.61500000e-03,
     8.00000000e-05])

def datafit(x,N,u,sig):
    y = N/(np.sqrt(2*np.pi)*sig)*np.exp(-(x-u)**2/2*sig**2)
    return y
popt,popc = curve_fit(datafit,x,y,p0=[np.max(y),2,2])
Normal_distribution = norm(loc = popt[-2],scale = popt[-1])

Then I checked if the plot of (x,y) and (x,popt[0]*Normal_distribution.pdf(x))are same, but the result shows they are  totally different....

The blue line is plot of (x,y), and the orange line is the plot of  (x,popt[0]*Normal_distribution.pdf(x).
Why this happen? Is there anything wrong in my code?

A: depends on what you plotted, these look OK to me:
plt.plot(x,y)
Out[3]: [<matplotlib.lines.Line2D at 0xb9cef98>]

popt,popc
Out[4]:
(array([  8.41765250e+04,   1.98651581e+00,   3.15537860e+00]),
 array([[  5.64670700e+05,   1.12782889e-05,   1.15455042e+01],
        [  1.12782889e-05,   2.91058556e-06,   2.73909077e-10],
        [  1.15455042e+01,   2.73909077e-10,   2.88523818e-04]]))

plt.plot(x,datafit(x,*popt))
Out[5]: [<matplotlib.lines.Line2D at 0xb990080>]

my guess is that you've got an error in sig, scale and *,/ in your datafit def vs norm()
I rewrote datafit to match the scipy norm.pdf
and still have a factor of ~pi issue which may be just definitional: https://en.wikipedia.org/wiki/Normal_distribution
oops, looks like the "factor of pi" was just coincidence of your particular data
rereading the norm.pdf def suggest the whole is rescaled by the 'scale" factor so now I think it should be:
'''
norm.pdf(x) = exp(-x**2/2)/sqrt(2*pi)
norm.pdf(x, loc, scale) == norm.pdf(y) / scale with y = (x - loc) / scale
'''
def datafit(x,N,u,sig):
#    y = N/(np.sqrt(2*np.pi)*sig)*np.exp(-(x-u)**2/2*sig**2)
    y = N*np.exp(-((x-u)/sig)**2/2)/(np.sqrt(2*np.pi))
    return y
popt,popc = curve_fit(datafit,x,y,p0=[np.max(y),2,2])

# scipy norm.pdf with scaling factors to match datafit()
Normal_distribution = popt[0]*popt[2]*norm.pdf(x, popt[1], popt[2])

plt.plot(x,y, 'b')
plt.plot(x, datafit(x+.1, *popt), 'g')
plt.plot(x, Normal_distribution, 'r')


text:
Q: Difference between init() and sync.Once in golang I saw two ways of using singleton pattern in Go.

*

*Using init() functions

*Using sync.Once in sync package

What's the difference, and which one is better with respect to thread safety?
If init() solves all problems then what is sync.Once used for?

A: Package init() functions are guaranteed by the spec to be called only once and all called from a single thread (not to say they couldn't start goroutines, but they're thread safe unless you make them multi-threaded).
The reason you'd use sync.Once is if you want to control if and when some code is executed. A package init() function will be called at application start, period. sync.Once allows you to do things like lazy initialization, for example creating a resource the first time it is requested (but only once, in case multiple "first" requests come in at the same time) rather than at application start; or to only initialize a resource if it is actually going to be needed.


text:
Q: How to compute a sum based on the 2 biggest values for each group (group by)? Let's say, I have this table below:
| Name     | Voters
| George   | 10
| Barack   | 20
| Barack   | 50
| Barack   | 40
| Donald   | 30
| Bill     | 20
| George   | 10
| Bill     | 30
| Bill     | 15
| Bill     | 10

I would like to get the sum of the 2 biggest numbers of Voters for each Name(or less)
| Name     | Sum2BiggestVoters
| George   | 20 (10 + 10)
| Donald   | 30 (30)
| Bill     | 20 (30 + 20; 10 and 15 are not considered not part of the 2 biggest numbers of voters for Bill)
| Barack   | 90 (50 + 40; 20 is not considered here for the same reason as above)

It looks a bit like this post: How to get summation with count larger than certain amount, except that I am using SQLite which lacks the row_number() over feature as well as the partition by.
Any idea?

A: This is a pain in SQLite, because it doesn't support variables and it doesn't support window functions.  Assuming you have no ties for a given name, you can do:
select t.name, sum(t.voters)
from t
where t.voters in (select t2.voters
                   from t t2
                   where t.name = t2.name
                   order by t2.voters desc
                   limit 2
                  )
group by t.name;


text:
Q: Error saving a file on server I am generating a Key and i need to record on server. When i tried locally, it Works ! The problem is when i try on the server...
The archive is generated but when ON THE SERVER the download finish,but i cannot open and cannot save. I don´t get an error...but i just cannot save...
The code:
                string fileNamePrivate = @"pasta1/archive.txt";
                Directory.CreateDirectory(Path.GetDirectoryName(fileNamePrivate));
                StreamWriter textWriterPriv = new StreamWriter(fileNamePrivate, true);
                var pemWriter = new PemWriter(textWriterPriv);
                pemWriter.WriteObject(keyPair.Private);
                pemWriter.Writer.Flush();
                textWriterPriv.Close();

A: Try to use
string fileNamePrivate = "~/PASTA1/archive.txt";
Directory.CreateDirectory(Path.GetDirectoryName(HostingEnvironment.MapPath(fileNamePrivate)));
StreamWriter textWriterPriv = new StreamWriter(fileNamePrivate, false);

How is a Server you have to use HostingEnvironment.MapPath and set "false" instead "true" on StreamWriter if you need to overwrite.


text:
Q: \indent and \par not providing indentation within proof environment I have a proof nested within an enumerate. I have set \parindent and \listparindent but still do not paragraphs indented inside proof environments. Code below
\documentclass[12pt]{article}
\pagestyle{empty}
\usepackage{amsmath, amsfonts, amsthm, amssymb, sgame, bbm, enumitem, verbatim}
\usepackage[all,cmtip]{xy}

\setlength{\parindent}{0.5 in}
\setlength{\listparindent}{0.5in}

\begin{document}

\begin{enumerate}

\item This is a question on hw

\begin{proof}
    This is my answer. First paragraph. Words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words\par

    Second paragraph should be indented.  words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words
\end{proof}
\end{enumerate}
\end{document}

A: This is the default behaviour; a list environment like enumerate clears the value of \parindent. The following minimal example demonstrates that:

\documentclass{article}

\usepackage{lipsum}

\setlength{\parindent}{0.5in}
\setlength{\listparindent}{0.5in}

\begin{document}
\lipsum[1-2]% 0.5in paragraph indent

\begin{enumerate}
  \item \lipsum[1-2]% No paragraph indent
\end{enumerate}

\end{document}

If you wish to restore \parindent inside a list, you'll have to update it within the list, like in the following example:

    \documentclass{article}
\usepackage{lipsum}

\begin{document}
\lipsum[1-2]

\begin{enumerate}
  \setlength{\parindent}{0.5in}
  \item \lipsum[1-2]
\end{enumerate}

\end{document}

The same holds for restoring \parindent within proof as part of an enumerate:

\documentclass{article}

\usepackage{amsthm,lipsum}

\begin{document}

\begin{enumerate}
  \setlength{\parindent}{0.5in}
  \item \lipsum[1-2]

  \begin{proof}
    \lipsum*[3]

    \lipsum*[4]
  \end{proof}
\end{enumerate}

\end{document}

If you want a \parindent to be active with all of your enumerate environments, you easily set this globally using enumitem:
\usepackage{enumitem}
\setlist[enumerate]{listparindent=0.5in}


text:
Q: What is the period of $(\sin x)^3 (\sin(3x))$? If I do it in the general way of L.CM I'm getting $2\pi$ as answer
I don't know where I'm making mistake because the answer is given as $\pi$

A: Hint:
Linearise first this trigonometric polynomial: as $\;\sin 3x=3\sin x -4\sin ^3x$, we deduce that $$\sin^3x=\frac14(3\sin x-\sin 3x),$$
whence, using the standard linearisation formulæ:
\begin{align}\sin^3x\sin 3x&=\frac14(3\sin x\sin 3x-\sin^2 3x)=\frac 38(\cos 2x-\cos 4x)-\frac18(1-\cos 6x)\\
&=\frac18(\cos 6x- 3\cos 4x+3\cos 2x-1).
\end{align}

A: Correct if wrong :
$\sin ^3 x( \sin2x \cos x +\cos 2x \sin x)=$
$(1/2)(\sin^2 x) \sin^2 2x +$
$ (\sin^4 x) \cos 2x.$
Left to do:
Find the basic periods of the individual functions above.
(What is the basic period of $\sin^2 x$, and of $\sin^4 x$ ?)
And then?

A: Your LCM method will give you a largest possible period but it could be shorter.  You need to examine the particular functions involved.  Consider the period of $sin^2(x)$.  Is it $2\pi$?  No, it is only $\pi$.  It can be rewritten in terms of $\sin(2x)$.  Here's an even simpler example.  If $f(x)$ and $g(x)$ both have period $2\pi$ then what is the period of $f(x) + g(x)$?  How about if $f(x) = \sin(x)$ and $g(x) = - \sin(x)$?


text:
Q: Firebase authWithOAuthPopup to log into Facebook gives warning Using this in my code:
ref.authWithOAuthPopup("facebook", function(error, authData) { ... });

I get the following warning in the bottom of the dialog that appears, for an app that hasn't previously gotten permission to run:

You are using a display type of 'popup' in a large browser window or
  tab. For a better user experience, show this dialog with our
  JavaScript SDK without specifying an explicit display type. The SDK
  will choose the best display type for each environment. Alternatively,
  set height and width on your window.open() call to properly size this
  dialog if you have special requirements precluding you from using the
  SDK. This message is only visible to developers of your application.

I'm assuming that this is a bug in Firebase.  Am I wrong?

A: [Engineer at Firebase] This is working-as-intended. The Firebase API manually configures the display parameters of the Facebook popup to best match the platform and environment that you're using. This warning is shown to the developers of the application, encouraging you to use the Facebook JavaScript SDK rather than the generic OAuth flow.
Note: This warning from Facebook is only shown to the developers listed on the Facebook application, and your end users won't see it.


text:
Q: Can logistic regression output a non linear curve? I have a doubt regarding logistic regression.I know that it separates the data into 2 parts.Is it possible that it leads to a curve as shown in the example of underfitting and overfitting
What i know is that adding more layers(Neural networks) of logistic regression can cause these curves .My question is can a standalone Logistic Regression without any layer lead these types of non linear curves.
And if NO,how can we define the case of overfitting and underfitting in that scenario visually.

A: "Standalone" logistic regression can indeed only draw a straight line, as it defines a linear relationship between the predictors and the log of the odds (our response).
Overfitting can occur in logistic regression in exactly the same way that it can occur for regular linear regression. The reason it's hard to picture it using those diagrams is that you're only visualizing two dimensions, where the idea of over fitting isn't as intuitive.
So linear model overfitting is difficult to visualize precisely because it occurs when you are working in too many dimensions. So this might be side stepping your question, but I think it's actually best to not try and directly visualize it, but just think through an example step by step. Imagine that we're trying to predict someone's weight. We can create a simple linear model that is a decent fit using just their height, and that should generalize fairly well. If we add gender, that should will improve the fit, and also generalize well. But if we also add 26 binary variables based on whether or not they have a given first letter in their last name ("A", "B", "C", etc), well, in a small data set we might improve our fit (maybe the lone "Quinn" in our data set is very heavy, and we capture that), but it probably won't generalize very well (as we don't think there's any real association there). Hence, we are overfitting.
While that was using binary variables (starting letter, gender), it's the exact same concept, and still a linear model (but binary variables can be a little easier to visualize). The fact is, linear models over fit when they involve too many dimensions, relative to the actual sources of variability you're trying to capture in the observed data set. The concept of overfitting in logistic regression is the exact same, the only difference is your target (the log of the odds, not just any continuous response variable).


text:
Q: T-SQL Move From Test To Production Dynamically (Part 2) Alright, since my previous post, I was able to make progress!! However, I've run into another problem...once again:
GOAL: Pass in two parameters (a task and a primary key) to generate a list of tables. Take the list, and then dynamically construct insert statements with the aim to copy data from a production environment to a test environment. In other words, do programmatically what 'EDIT TOP 200' does...but a lot faster.
PROBLEM (UPDATED): @tmpInserVars isn't updating with each iteration. It gets set the first time the code is entered, and never refreshes.
Thus far:
USE MAINDB
DECLARE @PK int = 1000,
 @TaskName nvarchar(50) = 'TASK',
 @curTable nvarchar(75),
 @curRow nvarchar(75),
 @tmpStatement nvarchar(500),
 @tmpInsert nvarchar(500)

RAISERROR('Retrieving Tables',0,1) WITH NOWAIT
 DECLARE TableCursor CURSOR LOCAL FOR

    SELECT DISTINCT TOP 2 PRMPTTBL.tTable as PromptTable
       FROM THING1 TK INNER JOIN THING2 SC ON TK.tkNo=SC.tkNo
              INNER JOIN Component EL on EL.scNo=SC.scNo
              LEFT OUTER JOIN Field FLD1 on FLD1.cfNo=EL.cfNoPrompt1
              LEFT OUTER JOIN MyTableTable MTTTBL on MTTTBL.tbNo=FLD1.tbNo

       WHERE EL.PK=@PK
              AND (MTTTBL.tTable is not NULL AND MTTTBL.tTable not in('OneTableIDontWant'))
              AND MTTTBL.tTable not like '%[_]d%' --eliminate any tables that are actually views
              AND EL.cfNo > 0
              AND TK.Description like @TaskName

RAISERROR('Table',0,1) WITH NOWAIT
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @curTable
WHILE @@FETCH_STATUS = 0
BEGIN
   SET @tmpStatement = 'SELECT TOP 5 * FROM [MYCONN].TEST_MYDB.dbo.' + @curTable + ' where PK=' + Cast(@PK as nvarchar(10))
   EXEC (@tmpStatement)
   RAISERROR(N'Table (outside): %s',0,1,@curTable) WITH NOWAIT

   IF @@ROWCOUNT = 0
   BEGIN
        --@tmpInsertVars isn't updating!!!
        RAISERROR(N'Initial Select: %s',0,1,@tmpStatement) WITH NOWAIT
        SELECT @tmpInsertVars = COALESCE(@tmpInsertVars + ',','') + COLUMN_NAME
        FROM PRODDB.INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_NAME = @curTable

        SET @tmpInsertStatement = 'INSERT INTO [MYCONN].TEST_MYDB.dbo.' + @curTable + ' (' + @tmpInsertVars + ')' +
                                  ' SELECT TOP 500 ' + @tmpInsertVars +
                                  ' FROM TEST_MYDB.' + @curTable +
                                  ' WHERE PK=' + Cast(@PK as nvarchar(10))

        RAISERROR(N'Insert Statement: %s',0,1,@tmpInsertStatement) WITH NOWAIT
   END

   FETCH NEXT FROM TableCursor INTO @curTable
END

CLOSE TableCursor
DEALLOCATE TableCursor

A: *

*Declare your @tmpInsertStatement and @tmpInsertVars variables.

*Reset @tmpInsertVars to NULL just before you populate it
USE MAINDB
DECLARE @PK int = 1000,
 @TaskName nvarchar(50) = 'TASK',
 @curTable nvarchar(75),
 @curRow nvarchar(75),
 @tmpStatement nvarchar(500),
 @tmpInsert nvarchar(500),
 @tmpInsertStatement nvarchar(500),
 @tmpInsertVars nvarchar(500)

RAISERROR('Retrieving Tables',0,1) WITH NOWAIT
 DECLARE TableCursor CURSOR LOCAL FOR

    SELECT DISTINCT TOP 2 PRMPTTBL.tTable as PromptTable
       FROM THING1 TK INNER JOIN THING2 SC ON TK.tkNo=SC.tkNo
              INNER JOIN Component EL on EL.scNo=SC.scNo
              LEFT OUTER JOIN Field FLD1 on FLD1.cfNo=EL.cfNoPrompt1
              LEFT OUTER JOIN MyTableTable MTTTBL on MTTTBL.tbNo=FLD1.tbNo

       WHERE EL.PK=@PK
              AND (MTTTBL.tTable is not NULL AND MTTTBL.tTable not in('OneTableIDontWant'))
              AND MTTTBL.tTable not like '%[_]d%' --eliminate any tables that are actually views
              AND EL.cfNo > 0
              AND TK.Description like @TaskName

RAISERROR('Table',0,1) WITH NOWAIT
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @curTable
WHILE @@FETCH_STATUS = 0
BEGIN
   SET @tmpStatement = 'SELECT TOP 5 * FROM [MYCONN].TEST_MYDB.dbo.' + @curTable + ' where PK=' + Cast(@PK as nvarchar(10))
   EXEC (@tmpStatement)
   RAISERROR(N'Table (outside): %s',0,1,@curTable) WITH NOWAIT

   IF @@ROWCOUNT = 0
   BEGIN
        --@tmpInsertVars isn't updating!!!
        SELECT @tmpInsertVars = NULL; -- RESET @tmpInsertVars
        RAISERROR(N'Initial Select: %s',0,1,@tmpStatement) WITH NOWAIT
        SELECT @tmpInsertVars = COALESCE(@tmpInsertVars + ',','') + COLUMN_NAME
        FROM PRODDB.INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_NAME = @curTable

        SET @tmpInsertStatement = 'INSERT INTO [MYCONN].TEST_MYDB.dbo.' + @curTable + ' (' + @tmpInsertVars + ')' +
                                  ' SELECT TOP 500 ' + @tmpInsertVars +
                                  ' FROM TEST_MYDB.' + @curTable +
                                  ' WHERE PK=' + Cast(@PK as nvarchar(10))

        RAISERROR(N'Insert Statement: %s',0,1,@tmpInsertStatement) WITH NOWAIT
   END

   FETCH NEXT FROM TableCursor INTO @curTable
END

CLOSE TableCursor
DEALLOCATE TableCursor


text:
Q: Round to 2 decimal places calling data from json - php foreach($arrayUsers as $user) {
echo '
'. $user['firstname'] .'	'. $user['lastname'] .'	'. $currencies[$user["currency"]] . $user['salary'].
    '
';
}
?>

Calling 'salary' from a JSON file, but need this to be rounded to 2 decimal places in the output table.

A: For rounding numbers you can use the round() and you can mention the precision as well.
round($user['salary'], 2)

You can find more information on round function Here
Hope this helps.


text:
Q: Error pushing React app to Heroku - "remote rejected main-> main (pre-reseive hook declined)" I'm gettig this very frustrating erro while trying to push my React app to Heroku. I was able to push it up with no problem in the application's earlier development, but for some reason it now gives me the same error message all the time:

 ! [remote rejected] main -> main (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/sapient-origin-alpha.git'
The only thing I can think of is that there is some issue with the version of react I'm using (I tried react 18 and 17, both gave the same results). But again, I was able to push it up before with no problem so I'm not sure. My other thought was that it's the client-side package.json since it's saying the build is failing.
Another thing worth mentioning is that I re-named the Heroku app, but afterwards I removed my local git remote and created a new git remote with the updated Heroku app name. So maybe this had something to do with it? This is basically what I did:
*rename heroku app*
$ git remote rm heroku
$ heroku git:remote -a sapient-origin-alpha

If anyone is able to help me on this I would very greatly appreciate it.

A: Nevermind I'm just dumb. It literally told me what was wrong in the error message slightly above the text in the image I provided.
The problem was in the client-side package.json because of some dependency I was using. Make sure to double check your package.json file for things that could be causing a similar error, and delete your package-lock.json then run npm i again to refresh the file.


text:
Q: Nutch Crawling Path - View Hops in solr Is there a possibility to track in which depth nutch found the link and what is the parent link of this one.
It would be very interesting for my project to see in solr where did the crawler came from and maybe as a result I can create a dependency tree in which the user can see where how this link is connected to the root.
Is the linked data an option in nutch or do I need another programm to manage this?

A: Nutch keeps the relations between pages in the linkdb, however it is not used by default when indexing. The easiest way to do this would be to write a custom plugin or hack the scoring-depth one so that it keeps the parent link.
The depth can be tracked by activating the scoring-depth plugin, you could combine it with the index-metadata plugin to store the metadata 'depth' into the index.
You might find it easier to do this with StormCrawler instead as it tracks the depth and the full path by default. Those can then be indexed into SOLR simply by specifying the key names in indexer.md.filter.


text:
Q: Get value of key from a mutable map I have a Map which looks as follows:
 val myMap = mutableMapOf<String,String>()

 myMap.put("A", "APPLE")
 myMap.put("B", "BALL")
 myMap.put("C", "CAT")
 myMap.put("D", "DOG")
 ...

When I print the map as follows, it prints it correctly:
println("MAP DATA -> $myMap")

//Output
MAP DATA -> [A = APPLE, B = BALL, C = CAT, D = DOG, ...]

But in my activity when I want to check if the value for a specific key is what it is, so that I can check a specific radio button, it doesn't work.
I tried the following:
 val option1 = myMap.get("A")

 if(option1 == "APPLE"){

    radioOption1.isChecked = true

  }

EDIT: The 2nd way I tried was this (in this case, the println text gets printed, but the radio button won't get checked.:
    if(myMap.getValue("A") == "APPLE"){
        println("getValue of MAP")
        radioOption1.isChecked = true
    }

When I try this it says : The key 'A' does not exist in the map.
I am struggling with it. How can I get the value of a specific key from the map so that I can check the relevant radioButton?
Any help or advice will be highly appreciated.


text:
Q: Can't install prebuilt gem I'm trying to install prebuilt binary of pg gem on windows (I don't want devkit):
>ruby -v
ruby 2.1.4p265 (2014-10-27 revision 48166) [x64-mingw32]

>gem install pg
Fetching: pg-0.17.1.gem (100%)
ERROR:  Error installing pg:
        The 'pg' native gem requires installed build tools.

>gem install pg -v 0.17.1 --platform=x64-mingw32
ERROR:  Error installing pg:
        The 'pg' native gem requires installed build tools.

even though the binary gem is published at https://rubygems.org/gems/pg/versions/0.17.1-x64-mingw32
What am I doing wrong ?
Same thing happens with 32-bit ruby.

A: So it turns out the gem was prebuilt for ruby 2.0.x which is not ABI compatible with ruby 2.1.x that I'm using. The error message could be more clear about that :(
Switched to the latest pre-release that contains needed binary and everything is fine now.


text:
Q: Counter-intuitive mixed strategy Nash eq question I'm currently in intro game theory, and am having trouble with understanding (conceptually) these two games:
$\begin{array}
{c|c|c} \ & L & R \\
\hline
T & 2, 6 & 2, 2 \\
\hline
B & 2, 2 & 2, 4
\end{array}$
$\begin{array}
{c|c|c} \ & L & R \\
\hline
T & 2, 6 & 2, 2 \\
\hline
B & 1, 2 & 2, 4
\end{array}$
We have two Nash equilibria in pure strategies, TL and BR. Mathematically, I understand that row player in both games plays top 1/3 of the time, bottom 2/3 of the time, and that in the second game the column player will always pick R; conceptually, however, I am having trouble understanding why on earth this would happen: it seems to me that in game 1, row player can play any probability, and column player should accordingly just play L always (6 > 4), and in game 2, row player should always play T (weakly dominating) and column player should always play L (knowing what player 1 will do). Why doesn't this happen?
Any assistance would be greatly appreciated!

A: Let $p \in [0, 1]$ denote the probability that row plays $T$ and $q \in [0, 1]$ that column plays $L$.
As every pure strategy equilibrium is a mixed strategy equilibrium we already figuerd that there exists two Nash equilibria for both games, namely $(p^*, q^*) \in \{(1, 1), (0,0)\}$.
Considering interior solutions, it is easy to show that the first game exihibts infinite equilibria $\{1/3\} \times [0, 1]$ and in the second game a single point $(1/3, 0)$.
The reason is, in order to motivate mixing each party needs to make the other party indifferent between playing one strategy or the other. While in the first game it does not matter what column does, as row always gets a payoff of 2 (and therefore $q^* \in [0, 1]$), row needs to play $T$ with probability $1/3$ as otherwise column would either play $L$ or $T$ with probability 100%. In the second game, column only can motivate mixing by playing $R$.
As far as I can tell you would like to add $[0,1] \times {1}$ for the first game and $(1,1)$ for the second game. As it was already mentioned above $(1, 1)$ is actually an equilibrium point. However, the set $[0,1) \times \{1\}$ does not contain any equilbrium, but $(1/3, 1)$ as otherwise column was not indifferent between playing $L$ and $R$ and therefore it would not be considered a (non-degenerate) mixed strategy equilibrium.


text:
Q: Слайд-шоу с jQuery Помогите создать слайд-шоу из 5-и картинок, с возможностью передвигать их вперед и назад.
A: А готовый не подойдет ?
Например jCarousel
A: В помощь Вам плагин Cycle. Картинки автоматически прокручиваются по одной. Пользователь может перейти на любую понравившуюся картинки сам.
Либо lightBox. Пользователь сам должен щелкать на кнопку далее (назад), чтобы картинки  менялись.


text:
Q: Draw order of point symbols in QGIS I have a point shapefile that is symbolized with an svg.  The shapefile has a attribute with Y values.  I would like the points with lower Y values to draw on top of points with higher Y values.  Below is a SE link with instructions for an earlier version of QGIS that has that feaure called Define Order.  I do not see that as an option in v2.8.  How to change feature draw order in QGIS?.
Is that feature still an option in QGIS?

A: If you read the answer clearly in the link you provided in your question, the answer says that this option is available from QGIS version 2.14 and above, and here is  screenshot from QGIS 2.14.11:

Here is a screenshot in 2.18.3:

You need to upgrade to the latest LTR of QGIS 2.14.12 or QGIS 2.18.3 to get this feature. It is not available in 2.8 version.


text:
Q: Change unix user environment Logged in as user1, I'd like to project to another unix user env, let's say user2, without type it's password.
By "project", I mean:
- change current $HOME
- call user2's bash startup scripts (to get it's prompt and global vars)
What I've written a little script switch_user_env.sh:
HOME="/usr/users/$1"
cd "$HOME"

bash

. /etc/profile

if [ -f "$HOME/.bash_profile" ]; then
    . "$HOME/.bash_profile"
fi

if [ -f "$HOME/.profile" ]; then
    . "$HOME/.profile"
fi

I call it like following: . ./switch_user_env.sh user2
Current shell get correctly change to bash but startup scripts are not called.
Can you help me to understand what is wrong ?
Thanks !
[EDIT]
switch_user_env.sh source code is available in GitHub: https://github.com/pierrefevrier/switch-user-env

A: Because remaining part your script (after bash call) will be executed after you exit from bash (type exit command or "Ctrl+d"). Calling bash in your script takes the control of futher execution.
Here is updated version:
HOME="/usr/users/$1"
cd "$HOME"

SOURCE_PROFILE=/etc/profile

if [ -f "$HOME/.bash_profile" ]; then
    SOURCE_PROFILE="$HOME/.bash_profile"
fi

if [ -f "$HOME/.profile" ]; then
    SOURCE_PROFILE="$HOME/.profile"
fi

bash --rcfile "$SOURCE_PROFILE"


text:
Q: document.write a new page with a unified font-size across the page I want to open a new page that has content identical to a div called Div1 in the old page.
In my JavaScript function I have a newWindow variable that is returned by a window.open command, and I write the inner HTML of Div1 into newWindow, and I want every single text within the new page has a font size of 7px. Here is what I wrote:
newWindow.document.write('<title>Hello World</title>');
        newWindow.document.write('');
        newWindow.document.write($('Div1').html());
        newWindow.document.write('');

The new page renders but since the content in Div1 are splited into 3 fieldsets, only the legends of those fieldsets have their font size changed to 7px, everything within the fieldsets still has default font size (which is approximately 11px). How to change every text in the new page to 7px? I can document.write a link to a new stylesheet for the new page but I prefer inline styling. Thanks.

Old page (ASP.net):

    <fieldset>
        <legend class="LLegends"> Header </legend>
            <asp:FormView ID="FormView1" runat="server">
                contents that I want to be 7px in the new page
            </asp:FormView>
     </fieldset>

Class LLegends (only class of elements that has CSS style)
.LLegends {font-size: large;}

A: You can try this snippet. Add your actual styles, then append them to the document with your other HTML.
SO is preventing the new window from opening, so try this url: http://output.jsbin.com/sobewavagi

    (function(undefined) {
      /**
       *
       */
      'use strict';

      function addStyleOnOpen() {
        var style,
          stylesheet,
          pageTitle = 'my title',

          prnt = open();

        style = document.createElement("style");

        style.setAttribute('media', 'all');
        style.setAttribute('type', 'text/css');
        style.setAttribute('rel', 'stylesheet');

        style.appendChild(document.createTextNode(""));
        prnt.document.head.appendChild(style);

        stylesheet = style.sheet;

        stylesheet.insertRule('body {width: 100% !important;margin: 0 !important;padding: 0 !important;line-height: 1.45;font-family: "Open Sans", sans-serif;color: #999;background: none;font-size: 14pt;}', 0);

        stylesheet.insertRule('#new-window {color: green;}', stylesheet.cssRules.length);

        stylesheet.insertRule('h1 {color: red;}', stylesheet.cssRules.length);

        prnt.document.title = pageTitle;
        prnt.document.body.insertAdjacentHTML('afterbegin', '\n
Heading
 \n
Hello World!
');
      }

      document.getElementById('new-window').addEventListener('click', addStyleOnOpen, false);

    }(undefined));
Open

A: Cannot do inline styling on the new page's body but I figure I can change
newWindow.document.write('');

To:
newWindow.document.write('');


text:
Q: Выборка из базы между интервалом времени В таблице в строках имеется поле varchar(10). В нем храню дату формата ДД.ММ.ГГГГ? Как выбрать строки в интервале от xx.yy.zzzz до aa.bb.cccc? При этом для каждой даты есть по 4 строки и пронумерованы 0-3 в отдельном поле. Нужно чтобы сортировка шла по датам от 0 до 3:
xx.yy.zzzz 0
xx.yy.zzzz 1
xx.yy.zzzz 2
xx.yy.zzzz 3
.....
aa.bb.cccc 0
aa.bb.cccc 1
aa.bb.cccc 2
aa.bb.cccc 3

ЗЫ. Таблица старая и структуру изменить никак. Записей дофига :D
A: Кто же так хранит даты в базах :)
Для даты и времени есть специальные типы данных DATE и DATETIME. А выбирать интервалы можно запросом типа:
SELECT * FROM tablename WHERE date_field BETWEEN "2012-01-01" AND "2012-01-31"

С сосртировкой:
SELECT *
FROM tablename
WHERE date_field BETWEEN "2012-01-01" AND "2012-01-31"
ORDER BY date_field, ind_field

Где date_field - дата, а ind_field - индекс 0-3


text:
Q: How to make app in background like chat head of messenger in flutter How to make app in background like  chat head of messenger when user but it in background and click on this bubble to open the app again .
I'm trying to use floaty_head package but it doesn't work .

A: I am assuming that you are referring to the Android Bubbles API documented here. If that's the case, at the time of this writing I don't believe there are ready to use 3rd party packages on pub.dev that allow you to achieve this. Your best option at the moment is to write that code natively yourself and integrate it with your Flutter application using channels.


text:
Q: Block additional Firestore triggers from executing in a Firestore trigger Is there any way to specify something like "FINAL" when you execute a Firestore trigger so an app with a lot of triggers doesn't create recursive updates?
For a simple example here is a trigger that adds the created_date field to every document that is created:
exports.setCreatedDate = functions.firestore
    .document('{collectionID}/{docID}')
    .onCreate((change, context) => {
        const patch = {created_at: Date.now()};
        return change.ref.set(patch, {merge: true});
    });

And another trigger that does the same when a document is updated:
exports.setUpdatedDate = functions.firestore
    .document('{collectionID}/{docID}')
    .onUpdate((change, context) => {
        const patch = {updated_at: Date.now()};
        return change.after.ref.set(patch, {merge: true});
    });

Is there any built in way (I have a couple hacky workarounds already) to block the update from firing after we set the created_at time?
We are moving as much of the application logic for an enterprise app that has to scale to 100 million+ records, and cascading triggers are causing huge spikes in Firestore requests.
One obvious solution is to use single triggers, then have a stack of functions that are called, but I love the simplicity of using strictly core functionality and being able to write as many isolated triggers as we like.

A:
Is there any way to specify something like "FINAL" when you execute a Firestore trigger so an app with a lot of triggers doesn't create recursive updates?

No.

Is there any built in way (I have a couple hacky workarounds already) to block the update from firing after we set the created_at time?

No.
You will have to write code in your function to determine if the invocation should not make any more changes, and just return early.  It's common to either check to see if the change has already been made by looking at existing fields in the document.


text:
Q: Javascript namespacing convention wI'm unsure which is the better namespace convention to use.
var App = {}; // global variable, the root of our namespace
(function() {

   App.something = function() {

   }

})();

or
(function() {

   window.App = {}; //global variable, the root of our namespace

   App.something = function() {

   }

})();

window.App and var App are both global variables so both conventions achieve the same outcome, but which is better?

A: The only difference is that in the first variant, App cannot be deleted from window, although it's accessible as a property of the global object. In the second case, delete window.App works. Also, note that you should be attaching your namespace to window, not Window, as JavaScript is case-sensitive, and Window is a constructor.
Other than that, both are basically the same, there is no "better".


text:
Q: Fail Sending Email Unable To Connect the Remote Server im facing error when sending email. here is the error

what is the actual error for this exception because i newbie in in this, by the way here is my code line:
 Try
                Dim SmtpServer As New SmtpClient()
                Dim mail As New MailMessage()

                SmtpServer.Credentials = New  _
                Net.NetworkCredential("test@gmail.com", "passwordexample")
                SmtpServer.EnableSsl = True
                SmtpServer.Port = 587
                SmtpServer.Host = "smtp.gmail.com"

                mail = New MailMessage()
                mail.From = New MailAddress("test@gmail.com")
                mail.To.Add("examplemail@gmail.com")
                mail.Subject = "Change Request Submitted"
                mail.Body = "Dear User, " & Environment.NewLine & Environment.NewLine & Environment.NewLine & Environment.NewLine & "One Notification have been submitted," & Environment.NewLine & "Please check the change request on the intranet application"

//ad this line the error SmtpServer.Send(mail)
                SmtpServer.EnableSsl = True
                MsgBox("Notification emailed successfully")
            Catch ex As Exception
                MsgBox(ex.ToString)
            End Try

A: Please see this answer...
Sending Email from Visual Basic
If you still can't send the email....
Have you enabled POP or IMAP in Gmail?
Sign in to the Gmail web interface.Open the 'Forwarding and POP/IMAP' tab on your 'Settings' page, and configure IMAP or POP. After enabling this in Gmail, make sure you click 'Save Changes' so Gmail can communicate with your mail client.
If you have 2 step verification..
Get an Application-Specific Password
Google will automatically generate a password that you will need only once, when you set up Google Mail on your mobile device or email software. You can easily generate a password for each device or email software you want to use.
Step 1:
At the bottom of the 2-step verification screen, next to Application-specific passwords, click Manage application-specific passwords. The Authorized Access to your Google Account screen will open.
Step 2:
On the Authorized Access to your Google Account screen, in the Name field, type in a name to help you remember what application you are using to access your account and click Generate password. You will then see a password which you will use to configure your mobile device or email software. Keep this screen open until you are ready to enter the password (see part 4, below). The password creation with the device name will show at the bottom.  When you are done using the password, click Done.
Step 3:
To set up a password for another device or email software, simply type in the name of it in the Name field and click Generate password. You will receive another password.
See more here...
http://www.oit.umass.edu/support/google-apps/configure-google-mail-email-software-mobile-devices

A:   Dim SmtpServer As New SmtpClient()
    SmtpServer.Credentials = New Net.NetworkCredential("EMAIL FROM@gmail.com", "YOUR PASSWORD")
    SmtpServer.Port = 25
    SmtpServer.Host = "smtp.gmail.com"
    SmtpServer.EnableSsl = True
    Dim omail As New MailMessage()

    omail.From = New MailAddress("FROM EMAIL @gmail.com", "Message", System.Text.Encoding.UTF8)

    omail.Subject = "test subject"
    omail.To.Add("test@gmail.com")

    SmtpServer.SendAsync(omail, Nothing)

Catch ex As Exception
    MsgBox(ex.ToString)
End Try

if that didn't work try
SmtpServer.Port = 587


text:
Q: F# Async hanging I have some fairly straightforward F# async code to download a hundred random articles off of Wikipedia (for research).
For some reason, the code hangs at arbitrary points in time during the download. Sometimes it's after 50, sometimes it's after 80.
The async code itself is fairly straightforward:
let parseWikiAsync(url:string, count:int ref) =
    async {
            use wc = new WebClientWithTimeout(Timeout = 5000)
            let! html = wc.AsyncDownloadString(Uri(url))
            let ret =
                try html |> parseDoc |> parseArticle
                with | ex -> printfn "%A" ex; None
            lock count (fun () ->
                if !count % 10 = 0 then
                    printfn "%d" !count
                count := !count + 1
            )
            return ret
    }

Because I couldn't figure out through fsi what the problem was, I made WebClientWithTimeout, a System.Net.WebClient wrapper that allows me to specify a timeout:
type WebClientWithTimeout() =
    inherit WebClient()
    member val Timeout = 60000 with get, set

    override x.GetWebRequest uri =
        let r = base.GetWebRequest(uri)
        r.Timeout <- x.Timeout
        r

And then I use the async combinators to retrieve just over a hundred pages, and weed out all the articles that return parseWikiAsync calls that return None (most of which are "disambiguation pages") until I have exactly 100 articles:
let en100 =
    let count = ref 0
    seq { for _ in 1..110 -> parseWikiAsync("http://en.wikipedia.org/wiki/Special:Random", count) }
    |> Async.Parallel
    |> Async.RunSynchronously
    |> Seq.choose id
    |> Seq.take 100

When I compile the code and run it in the debugger, there are only three threads, of which only one is running actual code -- the Async pipeline. The other two have "not available" for location, and nothing in the call stack.
Which I think means that it's not stuck in AsyncDownloadString or in anywhere in parseWikiAsync. What else could be causing this?
Oh, also, initially it takes about a full minute before the async code actually starts. After that it goes at a fairly reasonable pace until it hangs again indefinitely.
Here's the call stack for the main thread:
>   mscorlib.dll!System.Threading.WaitHandle.InternalWaitOne(System.Runtime.InteropServices.SafeHandle waitableSafeHandle, long millisecondsTimeout, bool hasThreadAffinity, bool exitContext) + 0x22 bytes
    mscorlib.dll!System.Threading.WaitHandle.WaitOne(int millisecondsTimeout, bool exitContext) + 0x28 bytes
    FSharp.Core.dll!Microsoft.FSharp.Control.AsyncImpl.ResultCell<Microsoft.FSharp.Control.AsyncBuilderImpl.Result<Microsoft.FSharp.Core.FSharpOption<Program.ArticleData>[]>>.TryWaitForResultSynchronously(Microsoft.FSharp.Core.FSharpOption<int> timeout) + 0x36 bytes
    FSharp.Core.dll!Microsoft.FSharp.Control.CancellationTokenOps.RunSynchronously<Microsoft.FSharp.Core.FSharpOption<Program.ArticleData>[]>(System.Threading.CancellationToken token, Microsoft.FSharp.Control.FSharpAsync<Microsoft.FSharp.Core.FSharpOption<Program.ArticleData>[]> computation, Microsoft.FSharp.Core.FSharpOption<int> timeout) + 0x1ba bytes
    FSharp.Core.dll!Microsoft.FSharp.Control.FSharpAsync.RunSynchronously<Microsoft.FSharp.Core.FSharpOption<Program.ArticleData>[]>(Microsoft.FSharp.Control.FSharpAsync<Microsoft.FSharp.Core.FSharpOption<Program.ArticleData>[]> computation, Microsoft.FSharp.Core.FSharpOption<int> timeout, Microsoft.FSharp.Core.FSharpOption<System.Threading.CancellationToken> cancellationToken) + 0xb9 bytes
    WikiSurvey.exe!<StartupCode$WikiSurvey>.$Program.main@() Line 97 + 0x55 bytes   F#

A: Wikipedia is not to blame here, it's a result of how Async.Parallel works internally. The type signature for Async.Parallel is seq<Async<'T>> -> Async<'T[]>. It returns a single Async value containing all of the results from the sequence -- so it doesn't return until all of the computations in the seq<Async<'T>> return.
To illustrate, I modified your code so it tracks the number of outstanding requests, i.e., requests which have been sent to the server, but have not yet received / parsed the response.
open Microsoft.FSharp.Control
open Microsoft.FSharp.Control.WebExtensions
open System
open System.Net
open System.Threading

type WebClientWithTimeout() =
    inherit WebClient()

    let mutable timeout = -1
    member __.Timeout
        with get () = timeout
        and set value = timeout <- value

    override x.GetWebRequest uri =
        let r = base.GetWebRequest(uri)
        r.Timeout <- x.Timeout
        r

type ParsedDoc = ParsedDoc
type ParsedArticle = ParsedArticle

let parseDoc (str : string) = ParsedDoc
let parseArticle (doc : ParsedDoc) = Some ParsedArticle

/// A synchronized wrapper around Console.Out so we don't
/// get garbled console output.
let synchedOut =
    System.Console.Out
    |> System.IO.TextWriter.Synchronized

let parseWikiAsync(url : string, outstandingRequestCount : int ref) =
    async {
    use wc = new WebClientWithTimeout(Timeout = 5000)
    wc.Headers.Add ("User-Agent", "Friendly Bot 1.0 (FriendlyBot@friendlybot.com)")

    // Increment the outstanding request count just before we send the request.
    do
        // NOTE : The message must be created THEN passed to synchedOut.WriteLine --
        // piping it (|>) into synchedOut.WriteLine or using fprintfn causes a closure
        // to be created which somehow defeats the synchronization and garbles the output.
        let msg =
            Interlocked.Increment outstandingRequestCount
            |> sprintf "Outstanding requests: %i"
        synchedOut.WriteLine msg

    let! html = wc.AsyncDownloadString(Uri(url))
    let ret =
        try html |> parseDoc |> parseArticle
        with ex ->
            let msg = sprintf "%A" ex
            synchedOut.WriteLine msg
            None

    // Decrement the outstanding request count now that we've
    // received a reponse and parsed it.
    do
        let msg =
            Interlocked.Decrement outstandingRequestCount
            |> sprintf "Outstanding requests: %i"
        synchedOut.WriteLine msg

    return ret
    }

/// Writes a message to the console, passing a value through
/// so it can be used within a function pipeline.
let inline passThruWithMessage (msg : string) value =
    Console.WriteLine msg
    value

let en100 =
    let outstandingRequestCount = ref 0
    seq { for _ in 1..120 ->
            parseWikiAsync("http://en.wikipedia.org/wiki/Special:Random", outstandingRequestCount) }
    |> Async.Parallel
    |> Async.RunSynchronously
    |> passThruWithMessage "Finished running all of the requests."
    |> Seq.choose id
    |> Seq.take 100

If you compile and run that code, you'll see output like this:
Outstanding requests: 4
Outstanding requests: 2
Outstanding requests: 1
Outstanding requests: 3
Outstanding requests: 5
Outstanding requests: 6
Outstanding requests: 7
Outstanding requests: 8
Outstanding requests: 9
Outstanding requests: 10
Outstanding requests: 12
Outstanding requests: 14
Outstanding requests: 15
Outstanding requests: 16
Outstanding requests: 17
Outstanding requests: 18
Outstanding requests: 13
Outstanding requests: 19
Outstanding requests: 20
Outstanding requests: 24
Outstanding requests: 22
Outstanding requests: 26
Outstanding requests: 27
Outstanding requests: 28
Outstanding requests: 29
Outstanding requests: 30
Outstanding requests: 25
Outstanding requests: 21
Outstanding requests: 23
Outstanding requests: 11
Outstanding requests: 29
Outstanding requests: 28
Outstanding requests: 27
Outstanding requests: 26
Outstanding requests: 25
Outstanding requests: 24
Outstanding requests: 23
Outstanding requests: 22
Outstanding requests: 21
Outstanding requests: 20
Outstanding requests: 19
Outstanding requests: 18
Outstanding requests: 17
Outstanding requests: 16
Outstanding requests: 15
Outstanding requests: 14
Outstanding requests: 13
Outstanding requests: 12
Outstanding requests: 11
Outstanding requests: 10
Outstanding requests: 9
Outstanding requests: 8
Outstanding requests: 7
Outstanding requests: 6
Outstanding requests: 5
Outstanding requests: 4
Outstanding requests: 3
Outstanding requests: 2
Outstanding requests: 1
Outstanding requests: 0
Finished running all of the requests.

As you can see, all of the requests are made before any of them are parsed -- so if you're on a slower connection, or you're trying to retrieve a large number of documents, the server could be dropping the connection because it may assume you're not retrieving the response it's trying to send. Another issue with the code is that you need to explicitly specify the number of elements to generate in the seq, which makes the code less reusable.
A better solution would be to retrieve and parse the pages as they're needed by some consuming code. (And if you think about it, that's exactly what an F# seq is good for.) We'll start by creating a function that takes a Uri and produces a seq<Async<'T>> -- i.e., it produces an infinite sequence of Async<'T> values, each of which will retrieve the content from the Uri, parse it, and return the result.
/// Given a Uri, creates an infinite sequence of whose elements are retrieved
/// from the Uri.
let createDocumentSeq (uri : System.Uri) =
    #if DEBUG
    let outstandingRequestCount = ref 0
    #endif

    Seq.initInfinite <| fun _ ->
        async {
        use wc = new WebClientWithTimeout(Timeout = 5000)
        wc.Headers.Add ("User-Agent", "Friendly Bot 1.0 (FriendlyBot@friendlybot.com)")

        #if DEBUG
        // Increment the outstanding request count just before we send the request.
        do
            // NOTE : The message must be created THEN passed to synchedOut.WriteLine --
            // piping it (|>) into synchedOut.WriteLine or using fprintfn causes a closure
            // to be created which somehow defeats the synchronization and garbles the output.
            let msg =
                Interlocked.Increment outstandingRequestCount
                |> sprintf "Outstanding requests: %i"
            synchedOut.WriteLine msg
        #endif

        let! html = wc.AsyncDownloadString uri
        let ret =
            try Some html
            with ex ->
                let msg = sprintf "%A" ex
                synchedOut.WriteLine msg
                None

        #if DEBUG
        // Decrement the outstanding request count now that we've
        // received a reponse and parsed it.
        do
            let msg =
                Interlocked.Decrement outstandingRequestCount
                |> sprintf "Outstanding requests: %i"
            synchedOut.WriteLine msg
        #endif

        return ret
        }

Now we use this function to retrieve the pages as a stream:
//
let en100_Streaming =
    #if DEBUG
    let documentCount = ref 0
    #endif

    Uri ("http://en.wikipedia.org/wiki/Special:Random")
    |> createDocumentSeq
    |> Seq.choose (fun asyncDoc ->
        Async.RunSynchronously asyncDoc
        |> Option.bind (parseDoc >> parseArticle))
    #if DEBUG
    |> Seq.map (fun x ->
        let msg =
            Interlocked.Increment documentCount
            |> sprintf "Parsed documents: %i"
        synchedOut.WriteLine msg
        x)
    #endif
    |> Seq.take 50
    // None of the computations actually take place until
    // this point, because Seq.toArray forces evaluation of the sequence.
    |> Seq.toArray

If you run that code, you'll see that it pulls the results one at a time from the server and doesn't leave outstanding requests hanging around. Also, it's very easy to change the number of results you want to retrieve -- all you need to do is change the value you pass to Seq.take.
Now while that streaming code works just fine, it doesn't execute the requests in parallel so it could be slow for large numbers of documents. This is an easy problem to fix, though the solution may be a little non-intuitive. Instead of trying to execute the entire sequence of requests in parallel -- which is the problem in the original code -- let's create a function which uses Async.Parallel to execute small batches of requests in parallel, then uses Seq.collect to combine the results back into a flat sequence.
/// Given a sequence of Async<'T>, creates a new sequence whose elements
/// are computed in batches of a specified size.
let parallelBatch batchSize (sequence : seq<Async<'T>>) =
    sequence
    |> Seq.windowed batchSize
    |> Seq.collect (fun batch ->
        batch
        |> Async.Parallel
        |> Async.RunSynchronously)

To utilize this function, we just need a few small tweaks to the code from the streaming version:
let en100_Batched =
    let batchSize = 10
    #if DEBUG
    let documentCount = ref 0
    #endif

    Uri ("http://en.wikipedia.org/wiki/Special:Random")
    |> createDocumentSeq
    // Execute batches in parallel
    |> parallelBatch batchSize
    |> Seq.choose (Option.bind (parseDoc >> parseArticle))
    #if DEBUG
    |> Seq.map (fun x ->
        let msg =
            Interlocked.Increment documentCount
            |> sprintf "Parsed documents: %i"
        synchedOut.WriteLine msg
        x)
    #endif
    |> Seq.take 50
    // None of the computations actually take place until
    // this point, because Seq.toArray forces evaluation of the sequence.
    |> Seq.toArray

Again, it's easy to change the number of documents you want to retrieve, and the batch size can easily be modified (again, I suggest you keep it reasonably small). If you wanted to, you could make a few tweaks to the 'streaming' and 'batching' code so you could switch between them at run-time.
One last thing -- with my code the requests shouldn't time-out, so you can probably get rid of the WebClientWithTimeout class and just use WebClient directly.

A: Your code doesn't seem to be doing anything particularly special so I am going to assume that Wikipedia is not liking your activity. Take a look at their bot policy. Digging a bit deeper they also seem to have a strict User-Agent policy

As of February 15, 2010, Wikimedia sites require a HTTP User-Agent
  header for all requests. This was an operative decision made by the
  technical staff and was announced and discussed on the technical
  mailing list.[1][2] The rationale is, that clients that do not send a
  User-Agent string are mostly ill behaved scripts that cause a lot of
  load on the servers, without benefiting the projects. Note that
  non-descriptive default values for the User-Agent string, such as used
  by Perl's libwww, may also be blocked from using Wikimedia web sites
  (or parts of the web sites, such as api.php).
User agents (browsers or scripts) that do not send a User-Agent header
  may now encounter an error message like this:
Scripts should use an informative User-Agent string with contact information, or they may be IP-blocked without notice.

So with all I've found they will probably not like what you are doing even if you add a proper user-agent but you might as well give it a try.
wc.Headers.Add ("User-Agent", "Friendly Bot 1.0 (FriendlyBot@friendlybot.com)")

It also wouldn't hurt to avoid making so many connections to their servers.


text:
Q: Positioning in a list I have the following list:
l={2 x, x, 4 x, x, x, 2 x, 4 x, x, x, 2 x}

I want to pick those elements that have coefficients bigger than 1, i.e. {2 x, 4 x, 2 x, 4 x, 2 x}
I tried
Select[CoefficientList[{2 x, x, 4 x, x, x, 2 x, 4 x, x, x, 2 x},
    x][[All, 2]], # > 1 &]*x

which return what I need but I believe there must be a much shorter and faster way? Also I would like to find the position of {2 x, 4 x, 2 x, 4 x, 2 x} in my original list so I did:
Position[{2 x, x, 4 x, x, x, 2 x, 4 x, x, x, 2 x}, {2 x, 4 x, 2 x,
  4 x, 2 x}]

which does not work so I must be wrong

A: You can try
Pick[l,Exponent[x,l],0]

{2 x, 4 x, 2 x, 4 x, 2 x}

or
Flatten[Take[l,#]&/@Position[Exponent[x,l],0]]

Also if you want the positions try
Position[Exponent[x, l], 0]

{{1}, {3}, {6}, {7}, {10}}

A: You might do like this:
l /. x -> 1 /. x_ /; x == 1 -> Nothing /. a_ -> a*x
(*   {2 x, 4 x, 2 x, 4 x, 2 x}   *)

Have fun!

A: l = {2 x, x, 4 x, x, x, 2 x, 4 x, x, x, 2 x};

s = Select[CoefficientList[l, x][[All, 2]], # > 1 &]*x

p = Position[l, Alternatives @@ Union[s]]

{{1}, {3}, {6}, {7}, {10}}

Extract[l, p]

A: l={2 x, x, 4 x, x, x, 2 x, 4 x, x, x, 2 x};
Pick[l, Unitize[D[l, x] - 1], 1]

{2 x, 4 x, 2 x, 4 x, 2 x}

  Flatten@Position[Unitize[D[l, x] - 1], 1]

{1, 3, 6, 7, 10}

A: l = {2 x, x, 4 x, -x, x, 2 x, 4 x, x, x, 2 x};
test = Clip[Coefficient[l, x], {1, 1}, {1, 0}]; (* 1 means coeffient <= 1, else 0 *)
l2 = Pick[l, test, 0]
pos = Ordering[test, Length[l2]]

{2 x, 4 x, 2 x, 4 x, 2 x}
  {1, 3, 6, 7, 10}


text:
Q: my images are coming out with bad quality after downloading when i set them to the image view the image quality in my listview is bad and keeps repeating the image in each list view.
this is my image loader class
package com.ghost.app;

public class ImageLoader {

MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections
        .synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;

public ImageLoader(Context context) {
    fileCache = new FileCache(context);
    executorService = Executors.newFixedThreadPool(5);
}

final int stub_id = R.drawable.ic_launchers;

public void DisplayImage(String url, ImageView imageView) {
    imageViews.put(imageView, url);
    Bitmap bitmap = memoryCache.get(url);
    if (bitmap != null)
        imageView.setImageBitmap(bitmap);
    else {
        queuePhoto(url, imageView);
        imageView.setImageResource(stub_id);
    }
}

private void queuePhoto(String url, ImageView imageView) {
    PhotoToLoad p = new PhotoToLoad(url, imageView);
    executorService.submit(new PhotosLoader(p));
}

private Bitmap getBitmap(String url) {
    File f = fileCache.getFile(url);

    // from SD cache
    Bitmap b = decodeFile(f);
    if (b != null)
        return b;

    // from web
    try {
        Bitmap bitmap = null;
        URL imageUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) imageUrl
                .openConnection();
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(30000);
        conn.setInstanceFollowRedirects(true);
        InputStream is = conn.getInputStream();
        OutputStream os = new FileOutputStream(f);
        Utils.CopyStream(is, os);
        os.close();
        bitmap = decodeFile(f);
        return bitmap;
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

// decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
    try {
        // decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(new FileInputStream(f), null, o);

        // Find the correct scale value. It should be the power of 2.
        final int REQUIRED_SIZE = 100;
        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        int scale = 1;
        while (true) {
            if (width_tmp / 2 < REQUIRED_SIZE
                    || height_tmp / 2 < REQUIRED_SIZE)
                break;
            width_tmp /= 2;
            height_tmp /= 2;
            scale *= 2;

        }

        // decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
    } catch (FileNotFoundException e) {
    }
    return null;
}

// Task for the queue
private class PhotoToLoad {
    public String url;
    public ImageView imageView;

    public PhotoToLoad(String u, ImageView i) {
        url = u;
        imageView = i;
    }
}

class PhotosLoader implements Runnable {
    PhotoToLoad photoToLoad;

    PhotosLoader(PhotoToLoad photoToLoad) {
        this.photoToLoad = photoToLoad;
    }

    @Override
    public void run() {
        if (imageViewReused(photoToLoad))
            return;
        Bitmap bmp = getBitmap(photoToLoad.url);
        memoryCache.put(photoToLoad.url, bmp);
        if (imageViewReused(photoToLoad))
            return;
        BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
        Activity a = (Activity) photoToLoad.imageView.getContext();
        a.runOnUiThread(bd);
    }
}

boolean imageViewReused(PhotoToLoad photoToLoad) {
    String tag = imageViews.get(photoToLoad.imageView);
    if (tag == null || !tag.equals(photoToLoad.url))
        return true;
    return false;
}

// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
    Bitmap bitmap;
    PhotoToLoad photoToLoad;

    public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
        bitmap = b;
        photoToLoad = p;
    }

    public void run() {
        if (imageViewReused(photoToLoad))
            return;
        if (bitmap != null)
            photoToLoad.imageView.setImageBitmap(bitmap);
        else
            photoToLoad.imageView.setImageResource(stub_id);
    }
}

public void clearCache() {
    memoryCache.clear();
    fileCache.clear();
}

}

and i need the images to have rounded corners
this is the lazy adapter
`public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;

public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
    activity = a;
    data=d;
    inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    imageLoader=new ImageLoader(activity.getApplicationContext());
}

public int getCount() {
    return data.size();
}

public Object getItem(int position) {
    return position;
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
    View vi=convertView;
    if(convertView==null)
        vi = inflater.inflate(R.layout.row, null);

    TextView title = (TextView)vi.findViewById(R.id.tvtitle); // username
    TextView desc = (TextView)vi.findViewById(R.id.tvdesc); // post
    TextView time = (TextView)vi.findViewById(R.id.tvdate); // time
    ImageView thumb_image=(ImageView)vi.findViewById(R.id.image); // thumb image

    HashMap<String, String> post = new HashMap<String, String>();
    post = data.get(position);

    // Setting all values in listview
    title.setText(post.get("username"));
    desc.setText(post.get("post"));
    time.setText(post.get("timestamp"));
    //imageLoader.DisplayImage(post.get(CustomizedListView.KEY_THUMB_URL), thumb_image);
    return vi;
}

}`

A: In your ImageLoader class , you have given 100 as required size. increase it for better image.
in this line
final int REQUIRED_SIZE = 100;

make it 320 or 480


text:
Q: How efficient is the MongoDB $in operator? Let's say I will have millions of comments that are cross-posted to multiple points of interest. Should I store each cross-posted comment multiple time:
{
  user_id: 1,
  text: "hello world",
  poi_id: some_id1
}
{
  user_id: 1,
  text: "hello world",
  poi_id: some_id2
}

or should I do it as an array
{
  user_id: 1,
  text: "hello world",
  poi_ids: [some_id1, some_id2]
}

The first can just use an index on poi_id and query with blazing speed, but stores a redundant copy of the comment. The second one makes more intuitive sense as a database structure, and saves space, but I'm worried about query efficiency of using $in if I want to, say, get all the comments associated with some_id1.


text:
Q: How Can I run/start json-server and live-server using NPM scripts start in package.json? I have a project which has html/css/javascript files, and I want to type the command npm start to run json-server and live-server.
I tried this command: "start": "json-server --watch db.json && live-server", but it starts the first command only, and not both.
package.json
{
  "name": "testa-npm-live-server",
  "version": "1.0.0",
  "description": "",
  "main": "",
  "dependencies": {},
  "devDependencies": {
    "json-server": "^0.16.1",
    "live-server": "^1.2.1"
  },
  "scripts": {
    "start": "json-server --watch db.json && live-server"
  },
  "author": "",
  "license": "ISC"
}

IDE: vscode
Node version: v12.18.1
NPM version: 6.14.5

A: Use concurrently to run commands in paralell. && runs in serial/sequential i.e. second command starts only after first command finishes running.
{
  "name": "testa-npm-live-server",
  "version": "1.0.0",
  "description": "",
  "main": "",
  "dependencies": {},
  "devDependencies": {
    "concurrently": "^5.2.0",
    "json-server": "^0.16.1",
    "live-server": "^1.2.1"
  },
  "scripts": {
    "start": "concurrently \"json-server --watch db.json\" \"live-server\""
  },
  "author": "",
  "license": "ISC"
}

Many Thanks to the community of NodeSchool Campinas for helping :)


text:
Q: JQuery Drop Down List select option by text I have a select statement and a bunch of options. How do I choose an option by text using jQuery and at the same time deselect the default one, I am using selenium webdriver with python but I want to be able to do this in jQuery, because it seems like a basic thing I should know in jQuery and I would be able to translate it to python selenium myself once I understand how the jQuery works.
<select id="DropDownList">
  <option selected="selected" value="2"> Test1</option>
  <option value="8"> Test2 </option>
</select>

This is close to what I want. I have tried multiple functions and selections, but they result in either an empty array, or when I loop them give me all a list of undefined, or a list of every possible attribute they can have. The site is also designed using jQuery mobile if that makes any big difference in selection. Please and thank you.

A: You mean select by text? This should work:
$("#DropDownList option:contains(" + 'Test2' + ")").attr('selected', true);

Update: to deselect previously selected value, you can do:
$("#DropDownList :selected").attr('selected', false);


text:
Q: Button Borders appear broken in Android 4.1.2 using Ionic framework I created a small app using following this tutorial.
App runs fine on Android but after running on 2 mobiles both running Android 4.1.2, I find that in one mobile the layout was broken. I mean button borders are broken.
Any suggestions on what is going wrong here ?
Using latest ionic framework and cordova.

A: This mostly happens because different mobile screen size.
You should create different layout files for different screen sizes
For more information go here:
http://developer.android.com/training/multiscreen/screensizes.html


text:
Q: Steps required to check app on simulator in IOS I just started development in IOS I want to check app on simulator (app which is app store ).
How to check this app on IOS simulator ?
Secondly If I am in window is it possible to check app which is app store ? mean is there any online simulator available on net ?

A: You cannot run apps from the app store on the iOS simulator. The reason for that is that the iOS simulator is not an emulator. The simulator runs on the Intel CPU in your Mac, while apps built for the app store (and for iOS devices in general) are compiled to run on the ARM processor that's in every iOS device. Put another way, the simulator is not binary compatible with iOS hardware.


text:
Q: How to Disable PHP Email How do I comprehensively disable all email sending capability from my site?
I do not want it to ever send any emails to anyone, ever.
I have a joomla site that's updated to the latest version, but my host constantly suspends my hosting because the site is sending spam emails.
User registration is disabled and there are no user forms open to any users.
My site doesn't need to send any emails, so I'm fine with just disallowing any php functions that can send them. The site is currently offline, and my host doesn't provide any usage information or analysis to help me out in any way. So... How do I comprehensively disable all email sending capability from my site?

A:
I have a joomla site that's updated to the latest version, but my host
  constantly suspends my hosting because the site is sending spam
  emails.

To be blunt: if you know your site is sending spam, then it is incredibly irresponsible for you to keep it online. Take the site down until you are able to locate the vulnerability.

How do I comprehensively disable all email sending capability from my
  site?

You don't do this with PHP, as there are a myriad of ways somone could get around an arbitrary fuction blacklist. Rather, you do it with iptables:
iptables -A OUTPUT -p tcp --dport 25 -j DROP
iptables -A OUTPUT -p tcp --dport 587 -j DROP
iptables -A OUTPUT -p tcp --dport 465 -j DROP


text:
Q: PHPMyAdmin and mySQL: Insert into existing database, not create new one. Error "Can't create database; database exists" I recently went to backup a database and got the following error "#1007 - Can't create database 'wordpress_8'; database exists".
I have the following line in the beginning of my sql file:
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

--
-- Database: 'wordpress_8'
--
CREATE DATABASE wordpress_8 DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
USE wordpress_8;

What do I need to change this to in order to insert the subsequent data into the existing "wordpress_8" database rather than create a new one?
Thanks!

A: To change which database you're using, you use the USE statement.  In this case, USE wordpress_8;.  Then the actual data needs to be inserted into the tables using INSERT statements.

A: To ensure a clean restore, I would add:
DROP DATABASE wordpress_8;

Else you're potentially merging two databases, which can get ugly.

A: Delete
CREATE DATABASE wordpress_8 DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

and Imropt again ))


text:
Q: How to convert .po to .mo files on mac? I have tried using poedit 1.4.6>save as, but .mo is not an option.

A: Install gettext, then run the msgfmt command on the files.
> brew install gettext
> msgfmt inputfile.po -o outputfile.mo

A: Ah, simple yet unclear, Whenever you save a file as .po using poedit, it automatically saves a .mo file aswell. (.mo being the compiled version of the languagefile)


text:
Q: How to escape reserved keywords in DynamoDB ExecuteStatementRequest? I'm trying to issue an update ExecuteStatementRequest using DynamoDB and Java SDK 2.0. I'm struggling to escape keywords that are columns in my table schema.
The following statement:
var response = client.executeStatement(ExecuteStatementRequest.builder()
                .statement("""
                    UPDATE "my-table"
                    SET value=12.5
                    WHERE assignmentId='item1#123#item2#456#item3#789'
                    RETURNING ALL NEW *
                    """)
                .build());

When I run the following statement (notice that value column is a reserved keyword) I get the following error:

Exception in thread "main"
software.amazon.awssdk.services.dynamodb.model.DynamoDbException:
Statement wasn't well formed, can't be processed: Expected identifier
for simple path (Service: DynamoDb, Status Code: 400, Request ID: XXX)

If instead of value I change the column name to val, the statement works fine. I know that in UdateItem operations I can pass in an array of expressionAttributeNames to replace keywords with aliases. Is there a similar primitive I can use for ExecuteStatementRequest?

A: The documentation you link explicitly says what you need to do:

You can use a reserved keyword as a quoted identifier with double
quotation marks (for example, "user").

That is the SQL standard way of escaping reserved words. In other words, use "value" (or possibly "VALUE") in your statement instead of value.


text:
Q: How do I find the area of a triangle formed by cevians? Given $\triangle ABC$, locate points $A_1$, $B_1$, $C_1$ on respective sides $BC$, $CA$, $AB$ such that
$$\frac{BA_1}{A_1C} =\frac{CB_1}{B_1A} = \frac{AC_1}{C_1B} = 2$$

How can I show that the area of the triangle formed by the intersections of $AA_1$, $BB_1$, and $CC_1$ is $1/7$ of the area of $\triangle ABC$?

A: Observe how this whole problem is invariant under affine transformation. And any triangle can be mapped to any other via affine transformation. So if you have demonstrated the claim for one triangle, it must be true for all. Pick a particularly simple one. The numbers $3$ and $7$ seem to play a major role, so I chose two edge lengths to be $21$ and it works out nicely: all points are at integer coordinates, making the computation really easy:

The corners of the inner triangle are at
$$A_2=(12,3)\qquad B_2=(6,12)\qquad C_2=(3,6)$$
so its area is
$$\frac12\begin{vmatrix}12&6&3\\3&12&6\\1&1&1\end{vmatrix}=\frac{63}{2}$$
Compare that to the area of the whole triangle, and you get
$$\frac{63}{21^2}=\frac{63}{441}=\frac17$$

A:
This layman proof depends on two relatively simple things:

*

*Area of a triangle = Half the base times its perpendicular height.
(An elementary school idea - but this also means that triangles on the same base with different heights, or vice-versa, have areas in proportion to their heights or bases. This can be handy sometimes.)

*Parallel projection of points on one line onto another line preserves the proportion of distances between adjacent points. That is, if $ a, b, c $ are points on one line $ L_1 $ which are projected via parallel lines to $a_1, b_1, c_1 $ onto another line $ L_2 $ then
$$ |ab|:|bc| = |a_1b_1|:|b_1c_1| $$ (This is about US school grade 8 level transformation geometry.)
Proof:
Take any of the cevian triangles, e.g. $\Delta AEC$.
As its base |EC| is one third of the full side of $|BC|$, then its area must also be one third that of $\Delta ABC$.
Likewise for the other two cevian triangles, $\Delta LBC $ and $\Delta ABI $.
So we now have:
$ Area \Delta AEC = Area \Delta LBC = Area \Delta ABI  = \frac{1}{3} Area \Delta ABC $ ................. (1)
From the diagram we see that each of the cevians $ \Delta AEC, \Delta MBC, \Delta ABI $ overlaps the other two at $ \Delta OEC, \Delta LBM, \Delta ANI $. So when we add the areas of the cevians together and subtract them from the area of the whole $ \Delta ABC $ to get the inner $ \Delta NMO $, we must realize that we are adding the areas of $ \Delta OEC, \Delta LBM $ and $ \Delta ANI $ twice unless we subtract them.
So
$ Area NMO = Area ABC - (Area AEC + Area LBC + Area ABI - Area OEC - Area LBM - Area ANI)   $
Applying relation (1) we get:
$  Area NMO = Area OEC + Area LBM + Area ANI $ ...............(2)
So to get the area of the inner triangle $ \Delta NMO $ we must find the areas of the small corner triangles. Let's take $ \Delta OEC $ to start with.
Points I and J are $ \frac{1}{3} $ and $ \frac{2}{3} $ along $ |AC| $. We can see that a line parallel to BI that passes through point J will intersect |BC| at its mid-point G since J is the mid-point of |IC| and parallel project preserves line segment ratio. Point J is mapped onto point O on the intersection of cevian lines AE and CL.
Since $ |AI| = |IJ| = |JC|  =>  |AN| = |NO| $
This same parallel projection also maps segment EON onto EGB. Since this results in a segment ratio of
$$|EG|:|GB| = (\frac{1}{2} - \frac{1}{3}):\frac{1}{2} = 3:1 $$
we can conclude that $|ON| = 3 |EO| $
Since $|ON| = |NA| $ this means $|OA| = 6 |EO|$  implying $ |EA| = 7 |EO|  $
Projecting parallel to |AB|:
Line segment EOA falls onto EPB which results in O being mapped to a point P such that
$$ |EP| = \frac{1}{7} |EB| = \frac{1}{7} \frac{2}{3} |BC| = \frac{2}{21} |BC| $$
Thus
$$ |CP| = (\frac{1}{3} + \frac{2}{21}) |BC| = \frac{3}{7} |BC| $$
and
$$ |OP| = \frac{3}{7} |LB|  $$
This is all the information we need to estimate the area of $ \Delta OEC $ which has the same height as the $ \Delta OPC $, the latter being a similar triangle to $ \Delta LBC $.
$$ Area OPC = \frac{|CP|}{|BC|} \frac{|OP|}{|LB|} Area LBC $$
$$      = \frac{3}{7} \frac{3}{7} \frac{1}{3} Area ABC  = \frac{3}{49} Area ABC $$
Since $\Delta OEC $ has the same height as $ \Delta OPC $, we can estimate its area via the ratio of the triangle bases:
$$ Area OEC = \frac{|CE|}{|CP|} Area OPC = \frac{\frac{|BC|}{3}}{\frac{3|BC|}{7}} Area OPC  = \frac{7}{9} \frac{3}{49} Area ABC  $$
$$ = \frac{1}{21} Area ABC  $$
Similar reasoning gives us
$$ Area LBM = Area ANI = Area OEC = \frac{1}{21} Area ABC  $$
Hence:
$$ Area NMO = Area OEC + Area LBM + Area ANI = \frac{1}{7} Area ABC  $$
This is the sort of insight that 'New Math' geometry can give you!
I was hoping that I could prove it simply by translating & folding the small triangles in the corners into the middle one. But the problem didn't oblige in this case due to overlaps. But Alex Chik has found a lovely graphical proof.
Thanks to Geobra for their free online sketching tool.

A: These are all excellent answers and I just want to add the general formula to the mix. There is a theorem known as Routh's theorem, which states that:

In geometry, Routh's theorem determines the ratio of areas between a given triangle and a triangle formed by the pairwise intersections of three cevians. The theorem states that if in triangle ${\displaystyle ABC}$ points ${\displaystyle D}$, ${\displaystyle E}$, and ${\displaystyle F}$ lie on segments ${\displaystyle BC}$, ${\displaystyle CA}$, and ${\displaystyle AB}$, then writing ${\displaystyle {\tfrac {CD}{BD}}}{\displaystyle =x}$, ${\displaystyle {\tfrac {AE}{CE}}}{\displaystyle =y}$, and ${\displaystyle {\tfrac {BF}{AF}}}{\displaystyle =z}$, the signed area of the triangle formed by the cevians $AD$, $BE$, and $CF$ is the area of triangle $ ABC$ times
$$\dfrac{(xyz-1)^2}{(xy+y+1)(yz+z+1)(zx+x+1)}$$
Plug $2$ into the above equation and you get the required answer immediately.
$\textbf{Hint}$: Use Menelaus Theorem to prove the above result.


text:
Q: Delete files in a directory only when cumulative sum of files size exceeds xGB I have a directory, with thousands of files.
I need to sort the files in descending order of creation date (to make sure that the newest files wont be deleted), and start summing the size of these files until the summation reaches a certain limit (example 10GB).
Once that is reached, I need to be able to delete all the files (that are already sorted in descending order), that come after those 10GB of files.
So, after the operation, the contents of my directory should not exceed 10GB in total size, but the newest files must remain.
I need to be able to accomplish this without the usage of GAWK since I don't have GNU system.
Is this doable with the find command only?

A: With zsh and on systems and filesystems where the st_blocks attribute returned by the lstat() system call is expressed in number of 512 byte units (most):
#! /usr/bin/env zsh
zmodload zsh/stat || exit
zmodload zsh/files || exit # for a builtin rm as well.

disk_usage=0 threshold=$(( 10 * 2**30 ))

set -- **/*(ND.om)
for f do
  stat -LA blocks +block -- $f &&
    (( (disk_usage += blocks * 512) > threshold )) &&
    break
  shift
done
(( $# == 0 )) || print -r rm -f -- "$@"

(remove the print -r to actually do it).
Note that in the cumulative disk usage, it only counts regular files and if there are several hard links to the same file, their size will all be counted.


text:
Q: equivalent of pgcc "-Minfo=" flag for gcc compiler? I just discovered the nice "-Minfo=" flag in pgcc, which outputs all the optimizations that the compiler is making.
IE:
pgcc -c -pg -O3 -Minfo=all -Minline    -c -o example.o example.c
run:
 55, Memory zero idiom, loop replaced by call to __c_mzero8
 91, Memory zero idiom, loop replaced by call to __c_mzero8
pgcc -c -pg -O3 -Minfo=all -Minline    -c -o controller.o controller.c
main:
 82, second inlined, size=4, file controller.c (113)
 84, second inlined, size=4, file controller.c (113)

is there an equivalent compiler flag for GCC?

A: Yes there is. -fopt-info is what you are looking for.
gcc -O3 -fopt-info example.c -o example

Or equivalently you can do
gcc -O3 -fopt-info-all=all.dat example.c -o example

Will output all the optimization information to file all.dat. You can also be specific about which optimization information you want by specifying -fopt-info-options like so:
-fopt-info-loop                 # info about all loop optimizations
-fopt-info-vec                  # info about auto-vectorization
-fopt-info-inline               # info about function inlining
-fopt-info-ipa                  # info about all interprocedural optimizations

You can get more specific if you want by telling gcc to dump information only about loops/inlinings/vectorizations that were optimized or were missed
-fopt-info-inline-optimized     # info only about functions that were inlined
-fopt-info-vec-missed           # info only about vectorizations that were missed
-fopt-info-loop-note            # verbose info about loop optimization

For more details look at the online documentation.