text:
Q: Coldfusion - Form submission somehow different on mobile? So I have a very strange problem.  I have a simple form setup to collect email / password.  On the submission page I run these through a query to check if the user exists.  This all works fine on desktop, but using it on mobile results in the query always returning 0 for record count.
<form action="test2.cfm" method="post">
<input type="hidden" name="lang" value="EN">
Email Address :  <input type="text" name="strEmail" style="width: 200px;">
Password : <input type="password" name="strPassword" style="width: 200px;">

<input type="submit" value="LOGIN">
</form>

<cfquery name="getParticipant" datasource="#request.dbDSN#" username="#request.dbUsername#" password="#request.dbPassword#">
SELECT * FROM mytable
WHERE email = <cfqueryparam value="#FORM.strEmail#" cfsqltype="CF_SQL_VARCHAR">
AND password = <cfqueryparam value="#FORM.strPassword#" cfsqltype="CF_SQL_VARCHAR">
</cfquery>

<cfoutput>
    record count: #getParticipant.recordCount#
</cfoutput>

As I've stated this code works fine when an existing user attempts to login on a desktop computer.  The EXACT same code returns 0 when a login is attempted on mobile.
What is going on???


text:
Q: Gradle finish with 552 errors when i build the project i get this error "Gradle finish with 552 error " but there are no java code error app run perfectly
Please click the link for the error
Please see the link for the error

redpajama_set_name: RedPajamaStackExchange


text:
Q: Output a comma-separated list in a column in SQL Server
Possible Duplicate:
Simulating group_concat MySQL function in SQL Server 2005?

What's the best way to achieve this?  Edit: in MSSQL 2005
Table
a   |  b
------------
x   |  1
x   |  4
y   |  6
y   |  1

Query:
SELECT ? FROM Table

so that output is :
a   | ListOfB
------------
x   | 1, 4
y   | 6, 1

A: In SQL Server you can use FOR XML PATH:
select distinct a,
  stuff(
  (
    select ','+ cast(b as varchar(10))
    from table1 t2
    where t1.a = t2.a for XML path('')
  ),1,1,'') ListOfB
from table1 t1

See SQL Fiddle with Demo


text:
Q: Getting page source without opening the page I'm trying to get the source code of a specific webpage, then find a special
 in it.
I don't want to open the webpage in a browser, because what I'm doing is supposed to run on a mobile platform using React Native (which is not our concern here).
How can I get the page source without opening the webpage using vanilla JavaScript (no jQuery)?

A: With vanilla JS:
  var x = new XMLHttpRequest();

  x.onreadystatechange = function(){
    if( x.status === 200 && x.readyState === 4) {
      console.log(x.responseText);
    }
  }

  x.open('GET', '/my/file/at/address.html', true);
  x.send();

That will give you the raw text contents of address.html. However, due to its being just text, you won't be able to do things like document.querySelector('#mydiv'). I would once again recommend a headless browser, depending on what exactly you want to do.

A: Using jquery, you can get the data like this:
$.get("test.html",function(data){
  console.log(data);
});

A: I think you can use .load():
$("#dummy").load("link");

And make #dummy div hidden:

In this way you will have loaded HTML in div dummy and then you can directly work with it without parsing the result.


text:
Q: Do $\ell_{\infty}$ and $\ell_{2,1}$-norms give similar results? and why? I am aware that $ \ell_{2,1} $-norm is being used for inducing a structure in the sparse matrix. I was told by someone that $ \ell_{\infty} $ and $ \ell_{2,1} $-norms give similar results. But how and why is that?
What are the differences, similarities, or advantages of $ \ell_{\infty} $-norm versus $ \ell_{2,1} $-norm in the case of norm minimization algorithms?
More specifically this question is in the context of Robust PCA (low-rank and sparse decomposition of a two dimensional matrix) where the mentioned norms are used to induce structured sparsity in the sparse part.
Robust PCA solves the matrix decomposition problem
$$L^*, S^* = \arg \min_{L, S} \|L\|_* + \|S\|_1 \quad \text{s.t. } L + S = X$$
as a surrogate for the actual problem
$$L^*, S^* = \arg \min_{L, S} rank(L) + \|S\|_0 \quad \text{s.t. } L + S = X,$$
To induce structured-sparsity in $S$ we can use the $\ell_{2,1}$ or $\ell_{\infty}$-norm. So the problem becomes:
$$L^*, S^* = \arg \min_{L, S} \|L\|_* + \|S\|_{2,1} \quad \text{s.t. } L + S = X$$
or
$$L^*, S^* = \arg \min_{L, S} \|L\|_* + \|S\|_{\infty} \quad \text{s.t. } L + S = X$$


text:
Q: How to block access to a file to other functions within same process? I don't mean locking the file!
What I want to achieve is that all other threads should access the file without any problem, but in some circumstances I want to fail calls which are accessing that file through fd like dup2(2), ftruncate(2), etc. One option is to make a wrapper for all such functions like dup2(2), that will first check if to allow fd or no and then call the real dup2(2). But its a long task to do it with every sys call using fd.
Maybe if there is a solution to password protect a file so that it can only be accessed when specified password is given.
My library is being injected to anonymous process so I don't have control over the caller and I observe that anonymous process doesn't check fd before using it. It ends up using the fd my library is using.
Kindly don't complain about the design issues. Please just focus on problem.

A: It sounds like you're injecting a library into a process that has a different constrained memory model and your library is incompatible. You could try using dup2() to move your own handles to really high values and hope it works.

A: Through in a mutex lock and make it so that if a thread wants to access the file then it has to do so through that function?


text:
Q: Intuition for orientation of a simplex (in 3 dimensions) In trying to begin to learn basic homological algebra, i am confronted with orientation of simplices. The definition seems unmotivated and unintuitive: for $n$-simplices with $n \in \{-1,0,1,2\}$, it is intuitive to visualize: intuitively, given a 2-simplex, we can walk to the left or to the right. For $n=3$ and above, the definition seems arbitrary. Is there a "geometric intuition" for this?
Definition of orientation: two (ordered) simplices with same vertices have same orientation if one is the componentwise image of an even permutation of the other. Else they are said to have opposite orientation.


text:
Q: Sorting floating Pointer array We have:
 private void function(ptr* data, const int size_of_data){
       std::sort(std::begin(data), std::end(data), floatcomparer);

Is this actually possible? Is there another way? Cause I get here an error: no instance of overloaded function ""std::begin" matches the argument types are: (float *).
I know that we need the size for a fast sorting algorithm like std uses and ptr* doesn't deliver an included size. But shouldn't there be a way cause I know how big the array is I'm pointing on?

A: std::sort(arr, arr+ size, std::greater<float>());

where you can use pass float arr in this form
func(float[],int sz){...}

With this comparator you can sort it.

A: Your function signature is wrong and you're calling std::sort incorrectly, you want something more like:
void function(float* data, std::size_t size_of_data) {
    std::sort(data, data + size_of_size, std::less<float>());
}


text:
Q: Control Nesting Limits in WinForms I'm creating my form's controls in the runtime, and for some reason, I need the depth to be more than 49 nested controls (i.e. control is contained in another one).
but the following error appears:

How can I add more controls nested in each other ?
Here is a little piece of code that may reproduce the error:
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        Panel lastPanel = panel1;
        for (int i = 0; i < 49; i++)
        {
            Console.WriteLine(i);
            Panel newPanel = new Panel();
            lastPanel.Controls.Add(newPanel);
            lastPanel = newPanel;
        }
    }
}

A: According to Raymond Chen you cannot, it was a deliberate decision on the part of the windows executive developers.


text:
Q: ActiveX support for 64 bit application We are converting our 32 bit application(.Net Framework 1.1) to 64 bit(Framework 2.0).After the conversion the project is building and running successfully except in some places were we are using ActiveX control iPlotx and Slider . The converted application runs fine when the target platform is 32 bit but in 64 bit mode it is showing class not registered error. Please note that the machine on which i'm testing is 64 bit.

Error : Class not registered (Exception from HRESULT: 0x80040154
  (REGDB_E_CLASSNOTREG))

After some search what i understood is - Since my application is running as 64 bit and since ActiveX supports only 32 bit hence this error.
I would like to know if my understanding of the problem is correct and if there is a workaround for this problem other than letting the application run as 32 bit on a 64 bit machine.

A: Your understanding isn't quite correct. ActiveX is certainly supported for 64-bit applications, but only using 64-bit controls. 32-bit controls don't work in 64-bit applications (and vice versa). If you had 64-bit versions of the controls in question, it should run. Ask your supplier if they have a 64-bit version available.
The workaround if no such version is available is to host the control in a 32-bit process, and shuttle requests back and forth between that process and yours. This gets fairly involved if you have to integrate it into a GUI, however.


text:
Q: Cannot Install Older Version of Rake Gem in Rails I have rake version 0.9.2 installed, and I think I need to install 0.8.7 to solve some problems. However, after installing 0.8.7, 0.9.2 is still installed. Here is what I ran:
rake --version

rake, version 0.9.2
gem install rake -v 0.8.7

Successfully installed rake-0.8.7
1 gem installed
Installing ri documentation for rake-0.8.7...
Installing RDoc documentation for rake-0.8.7...
I then added this to my Gemfile:
gem 'rake', '0.8.7'

But 0.9.2 is still called:
rake --version

rake, version 0.9.2
How do I fix this?

A: Run this command on the bash:
gem uninstall rake

Then you will be asked which version you want to remove. You select 0.9.2 and then you run
bundle update rake

This should do it for you...

A: I had a similar problem (going back to a older version of rake in the Gemfile meant I got a "You have requested: rake = 10.3.2 ... The bundle currently has rake locked at 10.4.2." error). If "fixed" this by deleting the Gemfile.lock file and running bundle install like so:
rm Gemfile.lock
bundle

Now rake --version produces "rake, version 10.3.2"
This is an alternative to running bundle update rake.


text:
Q: Get all related Django model objects How can I get a list of all the model objects that have a ForeignKey pointing to an object?  (Something like the delete confirmation page in the Django admin before DELETE CASCADE).
I'm trying to come up with a generic way of merging duplicate objects in the database.  Basically I want all of the objects that have ForeignKeys points to object "B" to be updated to point to object "A" so I can then delete "B" without losing anything important.
Thanks for your help!

A: Django <= 1.7
This gives you the property names for all related objects:
links = [rel.get_accessor_name() for rel in a._meta.get_all_related_objects()]

You can then use something like this to get all related objects:
for link in links:
    objects = getattr(a, link).all()
    for object in objects:
        # do something with related object instance

I spent a while trying to figure this out so I could implement a kind of "Observer Pattern" on
one of my models. Hope it's helpful.
Django 1.8+
Use _meta.get_fields(): https://docs.djangoproject.com/en/1.10/ref/models/meta/#django.db.models.options.Options.get_fields (see reverse in the _get_fields() source also)

A: links = [rel.get_accessor_name() for rel in a._meta.get_all_related_objects()]
You can then use something like this to get all related objects:
for link in links:
    objects = getattr(a, link.name).all()
    for object in objects:
        # do something with related object instance

From Django 1.10 offical docs:

MyModel._meta.get_all_related_objects() becomes:

[
    f for f in MyModel._meta.get_fields()
    if (f.one_to_many or f.one_to_one)
    and f.auto_created and not f.concrete
]

So by taking the approved example we would use:
links = [
            f for f in MyModel._meta.get_fields()
            if (f.one_to_many or f.one_to_one)
            and f.auto_created and not f.concrete
        ]

for link in links:
    objects = getattr(a, link.name).all()
    for object in objects:
        # do something with related object instance

A: Give this a try.
class A(models.Model):
    def get_foreign_fields(self):
      return [getattr(self, f.name) for f in self._meta.fields if type(f) == models.fields.related.ForeignKey]

A: The following is what django uses to get all related objects
from django.db.models.deletion import Collector
collector = Collector(using="default")
collector.collect([a])

print collector.data

A: Django 1.9
get_all_related_objects() has been deprecated
#Example:
user = User.objects.get(id=1)
print(user._meta.get_fields())

Note:
RemovedInDjango110Warning: 'get_all_related_objects is an unofficial API that has been deprecated. You may be able to replace it with 'get_fields()'

A: for link in links:
    objects = getattr(a, link).all()

Works for related sets, but not for ForeignKeys. Since RelatedManagers are created dynamically, looking at the class name is easier than doing an isinstance()
objOrMgr = getattr(a, link)
 if objOrMgr.__class__.__name__ ==  'RelatedManager':
      objects = objOrMgr.all()
 else:
      objects = [ objOrMgr ]
 for object in objects:
      # Do Stuff

A: @digitalPBK was close... here is probably what you are looking for using Django's built-in stuff that is used in Django admin for displaying related objects during deletion
from django.contrib.admin.utils import NestedObjects
collector = NestedObjects(using="default") #database name
collector.collect([objective]) #list of objects. single one won't do
print(collector.data)

this allows you to create what the Django admin displays - the related objects to be deleted.

A: Unfortunately, user._meta.get_fields() returns only relations accessible from user, however, you may have some related object, which uses related_name='+'. In such case, the relation would not be returned by user._meta.get_fields(). Therefore, if You need generic and robust way to merge objects, I'd suggest to use the Collector mentioned above.

A: Here is another way to get a list of fields (names only) in related models.
def get_related_model_fields(model):
    fields=[]
    related_models = model._meta.get_all_related_objects()
    for r in related_models:
        fields.extend(r.opts.get_all_field_names())
    return fields


text:
Q: Shader Noise and CPU Noise I've come across an issue, where I am using a custom shader to offset the vertices of a (flat) mesh using noise. this is fine, and works well:

I also want to generate a collision mesh for this - which requires the use of CPU-based noise. I am usin "noiseSimplex.cginc" that can be found online, but want to implement a c# version that gives the same result. Is there a suggested way of approaching this problem?

A: If you need to calculate the mesh on the CPU anyways, there is no further advantage in having it calculated on the GPU.
Do your mesh transformation on the CPU and use that mesh for both the rendering and the collision.
Edit:
Assuming a case where you mostly need the mesh for rendering only, but sometimes you want to have it on the CPU for processing, you might consider having it generated on the GPU with the possibility to download it as required.
I'm not up to date on shader technology, but last time I looked (DirectX 10 times), you might have generated the mesh purely using a geometry shader into a buffer on the GPU. Then you can use that buffer to feed into your rendering as well as download it to the CPU if required.
It's quite possible that this is no longer the way to do it today, but it should work.


text:
Q: Guardar datos generado en un fichero C++ Soy un poco nuevo en esto.
Mi problema es el siguiente: He generado tres filas con números aleatorios y necesito que me guarde dichos datos en un archivo txt y no sé como realizarlo. Leyendo he visto que está la orden fopen pero no se como hacerlo.
Mi codigo es el siguiente:
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
   srand(time(NULL));
   int i, n, aleatorio, DESDE=1, HASTA=100;
   n=20;
   for (i = 1; i <= n; i ++)
   {
             aleatorio = rand()%(HASTA-DESDE+1)+DESDE;
             cout << aleatorio << " ";
   }
   cout << endl;

   int aleatorio1, DESDE1=1, HASTA1=10;
   for (int i = 1; i <= n; i ++)
   {
             aleatorio1 = rand()%(HASTA1-DESDE1+1)+DESDE1;
             cout << aleatorio1 << " ";
   }
   cout << endl;

   int suma=0;
   for (int i = 1; i <= n; i ++)
   {
             suma= suma+ aleatorio;
   }
   int aleatorio2, DESDE2=suma*(0.5-0.4), HASTA2=suma*(0.5+0.4);
   for (int i = 1; i <= n; i ++)
   {
             aleatorio2 = rand()%(HASTA2-DESDE2+1)+DESDE2;
             cout << aleatorio2 << " ";
   }
   cout << endl;

   system("pause");
}

De esta manera deseo que se me guarden en un fichero de .txt las tres filas de números aleatorios generados.
Muchas gracias a quien me pueda ayudar.

A: Puedes crear un archivo usando ofstream. Una vez que has creado el archivo, puedes escribir datos de forma similar a cómo se usa cout:
#include <iostream>
#include <ctime>
#include <fstream>
using namespace std;
int main()
{
   srand(time(NULL));
   int i, n, aleatorio, DESDE=1, HASTA=100;
   n=20;
   ofstream f("archivo.txt");
   for (i = 1; i <= n; i ++)
   {
             aleatorio = rand()%(HASTA-DESDE+1)+DESDE;
             cout << aleatorio << " ";
             f << aleatorio << " ";
   }
   cout << endl;
   f << endl;

   int aleatorio1, DESDE1=1, HASTA1=10;
   for (int i = 1; i <= n; i ++)
   {
             aleatorio1 = rand()%(HASTA1-DESDE1+1)+DESDE1;
             cout << aleatorio1 << " ";
             f << aleatorio1 << " ";
   }
   cout << endl;
   f << endl;

   int suma=0;
   for (int i = 1; i <= n; i ++)
   {
             suma= suma+ aleatorio;
   }
   int aleatorio2, DESDE2=suma*(0.5-0.4), HASTA2=suma*(0.5+0.4);
   for (int i = 1; i <= n; i ++)
   {
             aleatorio2 = rand()%(HASTA2-DESDE2+1)+DESDE2;
             cout << aleatorio2 << " ";
             f << aleatorio2 << " ";
   }
   cout << endl;
   f << endl;

   system("pause");
}

Saludos.


text:
Q: Stencil not working with a 500 server error Using stencil 3.0.3, node 12.21 cornerstone theme was working and suddenly stopped with a weird server error:
Debug: internal, implementation, error
    Error: The BigCommerce server responded with a 500 error
    at Object.internals.getResponse (/usr/local/lib/node_modules/@bigcommerce/stencil-cli/server/plugins/renderer/renderer.module.js:128:15)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async internals.implementation (/usr/local/lib/node_modules/@bigcommerce/stencil-cli/server/plugins/renderer/renderer.module.js:39:20)
    at async module.exports.internals.Manager.execute (/usr/local/lib/node_modules/@bigcommerce/stencil-cli/node_modules/@hapi/hapi/lib/toolkit.js:45:28)
    at async Object.internals.handler (/usr/local/lib/node_modules/@bigcommerce/stencil-cli/node_modules/@hapi/hapi/lib/handler.js:46:20)
    at async exports.execute (/usr/local/lib/node_modules/@bigcommerce/stencil-cli/node_modules/@hapi/hapi/lib/handler.js:31:20)
    at async Request._lifecycle (/usr/local/lib/node_modules/@bigcommerce/stencil-cli/node_modules/@hapi/hapi/lib/request.js:312:32)
    at async Request._execute (/usr/local/lib/node_modules/@bigcommerce/stencil-cli/node_modules/@hapi/hapi/lib/request.js:221:9)

I have tried to re-install big commerce stencil, clean build and still get the same error.... at this point I have no idea what could be causing this issue.
Importantly, there was no code changes in between the day where everything was working and the day where it stopped.

A: Are you using CloudFlare for a CDN? I've ran into this issue and have had to edit my hosts file
I add the following 3 lines.
The first one is for the Store Domain, i.e. if you have MyShoeStore.com
The second 2 contain the auto-generated store-hash for a BigCommerce store that should be visible in your URL bar if you are on the BigCommerce control panel (Logged into the admin view - that's the easiest way to get it, there are some others)
35.186.223.98 mystoredomain.com
35.186.223.98 store-abcdefg[store-hash].mybigcommerce.com
35.186.223.98 www.store-abcdefg[store-hash].mybigcommerce.com

For some reason, Stencil-CLI gets thrown for a loop when trying to connect to a BigCommerce store that is running behind CloudFlare CDN. This has caused 500 errors in the Stencil-CLI, and a failure to render, during local development, but the store is able to be uploaded and hosted in production without a problem.
I'm not sure if this is the actual issue that you had which caused your 500 error, (It can be due to an error in the syntax of one of the HandleBars templates, but usually Stencil-CLI will output an informative error for that reason.)
The other situation I have seen this in is if you are trying to run Cornerstone on a very old BigCommerce store which is still running their old template framework (Blueprint) - in that situation, certain pages will 500, but others will work.
This may be helpful for others who are running into this.

A: I installed a proxy tool to capture traffic between stencil and BigCommerce in order to perhaps find more details on this error.
Unfortunately, as soon as I did that, the site worked again...


text:
Q: Spanning Tree, Network Modelling I'm developing some software at the moment for voip communications (broadcast style comms, think ventrilo or teamspeak) between multiple users without a central server (send voice to server, server sends too all clients). I'm looking at adding some intelligence to the way it sends voice packets around, to find the best route depending on link latency, a user's free bandwidth etc.
Hopefully this will behave so that in a particular network, each node is aware of the overall network and can decide on how best to send voice packets to minimize the net total delay for all nodes to receive the packet. So for a user with a very limited, slow internet connection, the best route may be to send the packet to a user with a high capacity, fast connection and have him forward the packets on. For average users, perhaps the best route is a mix of sending directly to nodes and having some forwarded on. Forwarding on packets adds a 'hop', and increases delay so the optimum solution will look to minimise this, but not violate bandwidth limits.
I am trying to model this as a spanning tree, where all vertices are connected to each other with a weight associated to each edge that represents network latency (and other factors). The weight needs to be different depending on direction. In addition to this, there is a bandwidth limit (or flow limit) on each vertex which limits the number of edges you can use from a single vertex. Broadcast will be one node sending packets to every other node, which essentially creates a minimum spanning tree.
My first thoughts are to model it on a simple spanning tree diagram, and use a well established algorithm to find a near optimum solution. However, I'm a bit confused as my network has different weights for different directions, flow limits through a node and weights added by the fact you are repeating through another node. I'm not really sure where to start with this. Are there algorithms designed to find solutions to a problem like this, if not how would I go about finding a solution?
EDIT: I think the main problem I have at the moment is working out how to classify the problem. It's like a minimum spanning tree, but there is a maximum number of edges to each vertex. It's like a flow network, but it has weights on the edges and the flow capacity is through a vertex not along an edge. Is there a classification for this kind of problem?

A: After spending some more time on this, I tried to work out how I intuitively find the best route and turn it into an algorithm. I eventually came up with a greedy algorithm, that by no means finds perfect results, but runs very quickly and serves as a starting point.
I wrote it myself, however it probably belongs to someone else (or adaptation of someone else's) so I'm not asserting any kind of ownership. I probably read it, forgot I read it, then re-invented it.
Its written as pseudo-code.
Start the avenues list, set to the starting vertex.

Start the remaining vertices list (all except starting vertex)

Start list of all edges, set to the entire edge list

Loop while remaining vertices list is NOT empty
{
   Set current vertex to top of avenues list

   Loop while vertex has unused edges and edge limit has not been reached
   {
      Find cheapest edge, add to the edge spanning tree

      Remove cheapest edge from edges list

      Add the vertex connected to the cheapest edge to the avenues list
   }

  Vertex has no more available edges, remove from avenues list
}

Done, return spanning tree

I welcome comments on it, or improvements. I have an implementation in python that runs pretty quickly. A fully connected network of 100 nodes takes around 77ms (2.6Ghz, i5, 8GB RAM) on a fairly standard machine. That's running with debug printing and python interpreter delays etc. I need to add some more code to analyse how good the resulting spanning tree is, and see if it varies much.

A: I think you have two different problems, First, you need to solve a Flow Network problem.
Then you should somehow create a minimum spanning tree from the solution you previously obtained.
I think you are not the first to stumble with this problem, a little serch might help you start familiarizing with this problem.
Good luck with the program!


text:
Q: Foreach file in directory jQuery How can I do a foreach(File file in Directory) kind of thing in jQuery.
Thank you!

A: Javascript does not have access to the local file system for obvious security reasons. This is not possible.
Unless you are trying to loop through files on your server, in which case you wouldn't want to use jQuery anyway but something like ASP.NET or PHP or whatever framework you are using.

A: $('selector').each(function(idx, elm){
    //some code
});

Will allow you to iterate over a list, applying the same function to each.  However, accessing the filesystem is not possible.

A: It is not possible with javascript/jquery to read contents of a directory for security reasons. Imagine you are trying to read the file system of client machine. You can use FSO (File System Object) but that works only in IE. You can use server-side languages such as PHP, ASP.Net for accessing the file system.
If you meant a loop with each, consider the each method of though. Example:
$('selector').each(function(){
  // your code.....
});

A: If the files are on the client you can't access them for security reasons.
If the files are on the server and you want process the list sever-side you wouldn't use JQuery as it's for client-side scripting.
If the files are on the server and you want to process the list client-side, you could generate the list in the server code and send it down as xml, json, etc.
If the files are on somebody else's server your only options is to recursivly follow links on their site, which is not really something you'd want to be doing with Javascript from a client's browser.


text:
Q: More efficient way to mean center a sub-set of columns in a pandas dataframe and retain column names I have a dataframe that has about 370 columns. I'm testing a series of hypothesis that require me to use subsets of the model to fit a cubic regression model. I'm planning on using statsmodels to model this data.
Part of the process for polynomial regression involves mean centering variables (subtracting the mean from every case for a particular feature).
I can do this with 3 lines of code but it seems inefficient, given that I need to replicate this process for half a dozen hypothesis. Keep in mind that I need to data at the coefficient level from the statsmodel output so I need to retain the column names.
Here's a peek at the data.
It's the sub-set of columns I need for one of my hypothesis tests.
      i  we  you  shehe  they  ipron
0  0.51   0    0   0.26  0.00   1.02
1  1.24   0    0   0.00  0.00   1.66
2  0.00   0    0   0.00  0.72   1.45
3  0.00   0    0   0.00  0.00   0.53

Here is the code that mean centers and keeps the column names.
from sklearn import preprocessing
#create df of features for hypothesis, from full dataframe
h2 = df[['i', 'we', 'you', 'shehe', 'they', 'ipron']]

#center the variables
x_centered = preprocessing.scale(h2, with_mean='True', with_std='False')

#convert back into a Pandas dataframe and add column names
x_centered_df = pd.DataFrame(x_centered, columns=h2.columns)

Any recommendations on how to make this more efficient / faster would be awesome!

A: df.apply(lambda x: x-x.mean())

%timeit df.apply(lambda x: x-x.mean())
1000 loops, best of 3: 2.09 ms per loop

df.subtract(df.mean())

%timeit df.subtract(df.mean())
1000 loops, best of 3: 902 µs per loop

both yielding:
        i  we  you  shehe  they  ipron
0  0.0725   0    0  0.195 -0.18 -0.145
1  0.8025   0    0 -0.065 -0.18  0.495
2 -0.4375   0    0 -0.065  0.54  0.285
3 -0.4375   0    0 -0.065 -0.18 -0.635

A: I know this question is a little old, but by now Scikit is the fastest solution. Plus, you can condense the code in one line:
pd.DataFrame(preprocessing.scale(df, with_mean=True, with_std=False),columns = df.columns)

%timeit pd.DataFrame(preprocessing.scale(df, with_mean=True, with_std=False),columns = df.columns)
684 µs ± 30.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

test.subtract(df.mean())

%timeit df.subtract(df.mean())
1.63 ms ± 107 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

df I used for testing:
df = pd.DataFrame(np.random.randint(low=1, high=10, size=(20,5)),columns = list('abcde'))


text:
Q: GNU Parallel fundamentals: how can I feed some parameter that is not in the last position? How can I parallelize ping operations like these below using GNU Parallel?
ping -c 5 -S ${AdapterIP[1]} 8.8.8.8
ping -c 5 -S ${AdapterIP[2]} 8.8.8.8
ping -c 5 -S ${AdapterIP[3]} 8.8.8.8

Problem: I am using FreeBSD, so this change is not allowed (note the host parameter to ping must be the last one) on the syntax:
ping -c 5 8.8.8.8 -S ${AdapterIP[1]}

On Linux systems I just do:
parallel ping -c 5 8.8.8.8 -S ::: "${AdapterIP[@]}"

I have tested this method on FreeBSD:
    luis@Balanceador:~$ parallel ping -c 5 -S ::: "${AdapterIP[@]}" 8.8.8.8
usage: ping [-AaDdfnoQqRrv] [-c count] [-G sweepmaxsize] [-g sweepminsize]
            [-h sweepincrsize] [-i wait] [-l preload] [-M mask | time] [-m ttl]
            [-P policy] [-p pattern] [-S src_addr] [-s packetsize] [-t timeout]
            [-W waittime] [-z tos] host
       ping [-AaDdfLnoQqRrv] [-c count] [-I iface] [-i wait] [-l preload]
            [-M mask | time] [-m ttl] [-P policy] [-p pattern] [-S src_addr]
            [-s packetsize] [-T ttl] [-t timeout] [-W waittime]
            [-z tos] mcast-group
usage: ping [-AaDdfnoQqRrv] [-c count] [-G sweepmaxsize] [-g sweepminsize]
            [-h sweepincrsize] [-i wait] [-l preload] [-M mask | time] [-m ttl]
            [-P policy] [-p pattern] [-S src_addr] [-s packetsize] [-t timeout]
            [-W waittime] [-z tos] host
       ping [-AaDdfLnoQqRrv] [-c count] [-I iface] [-i wait] [-l preload]
            [-M mask | time] [-m ttl] [-P policy] [-p pattern] [-S src_addr]
            [-s packetsize] [-T ttl] [-t timeout] [-W waittime]
            [-z tos] mcast-group
usage: ping [-AaDdfnoQqRrv] [-c count] [-G sweepmaxsize] [-g sweepminsize]
            [-h sweepincrsize] [-i wait] [-l preload] [-M mask | time] [-m ttl]
            [-P policy] [-p pattern] [-S src_addr] [-s packetsize] [-t timeout]
            [-W waittime] [-z tos] host
       ping [-AaDdfLnoQqRrv] [-c count] [-I iface] [-i wait] [-l preload]
            [-M mask | time] [-m ttl] [-P policy] [-p pattern] [-S src_addr]
            [-s packetsize] [-T ttl] [-t timeout] [-W waittime]
            [-z tos] mcast-group

... with no luck, as can be seen.
This is probably a dumb question, but I am new to GNU Parallel. Some help, please?
For those interested, this is a possible value of the array that will feed GNU Parallel:
luis@Balanceador:~$ echo ${AdapterIP[@]}
192.168.1.254 192.168.2.254 192.168.3.254

A: This is the way I have found to specify the parameter when not in the last position (the --dry-run flag is to not execute, just test):
luis@Balanceador:~$ parallel --dry-run sudo ping -c 5 -S {1} 8.8.8.8 ::: "${AdapterIP[@]}"
sudo ping -c 5 -S 192.168.1.254 8.8.8.8
sudo ping -c 5 -S 192.168.2.254 8.8.8.8
sudo ping -c 5 -S 192.168.3.254 8.8.8.8

Note the {1}.
It can be used with multiple parameters. Example for {2}:
luis@Balanceador:~$ parallel --dry-run sudo ping -c 5 -S {1} {2} ::: "${AdapterIP[@]}" ::: 8.8.8.8 8.8.4.4
sudo ping -c 5 -S 192.168.1.254 8.8.8.8
sudo ping -c 5 -S 192.168.1.254 8.8.4.4
sudo ping -c 5 -S 192.168.2.254 8.8.8.8
sudo ping -c 5 -S 192.168.2.254 8.8.4.4
sudo ping -c 5 -S 192.168.3.254 8.8.8.8
sudo ping -c 5 -S 192.168.3.254 8.8.4.4


text:
Q: JENKINSFILE - MSBUILD - System.ArgumentException contains an invalid character "." I am working on building the project via jenkinsfile. Earlier we were using different platform for build but now need to have a pipeline stuff to build and deploy the project/binaries to the hosts.
I am a beginner and tried almost everything
Currently we have one common solution file for web and wcf. Separate project files for web and wcf respectively.
Solution file - path\\solutionfilename.sln
Web project file – web.project.csproj
Wcf project file - wcf.project.csproj

Stage 1 -  restoring (nuget Restore) : i am passing the solutions file name here and it is success
Output- Restoring is success
stage 2 - Build the project -  Passing commands -
bat(script: '"%ProgramFiles(x86)%\\Microsoft Visual
Studio\\2017\\BuildTools\\MSBuild\\15.0\\Bin\\msbuild.exe" path\\solutionfilename.sln /t:web.project')

in building the project I am getting the error of
18:46:41  MSBUILD : error MSB1025: An internal failure occurred while running MSBuild.
18:46:41  System.ArgumentException: The name "Service\xyz:xyz" contains an invalid character ".".

And this is failing the project build.
In older environment – existing framework – 4.5.2 VS – 2015 (works well)
New – VS 2017 – as developer mentioned that this will work fine with visual studio 2017 as this was working fine in the local system.
Target framework is already mentioned as v4.5.2 with tools version 15.0 (updated to 15.0 when moved to vs2017 in csproj, earlier was 14.0 )
Requirement is to build the clean package for web component
Please help as I am stuck since 3 days.


text:
Q: How to make a POST request to a page that may redirect to a login page I am using a macro in Outlook VBA to submit a file via POST to a URL:
Set http = New WinHttp.WinHttpRequest
http.Open "POST", UrlToPostTo, False    'True                                          '
http.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
http.setRequestHeader "Content-Type", "multipart/form-data; "
http.Send data

My problem is the page that will accept the request (a file upload page, in this case) is protected by authentication - the initial request for it above will return a login page instead of the page itself.
I have tried to detect if the login page appears and if so, post the username and password as form variables (I'm hoping this is equivalent to a human typing said username and password into a page in the web browser).
So the steps are:
* request URL (include file with post).
* Check if the reponse is the login page.
* If so, then in the same http session, submit the username and password to the URL.
* If the server now processes the original post, good, otherwise I can post it again.
The code looks like:
' if the login page comes back, send credentials                                     '
If (InStr(http.ResponseText, "j_password") > 0) Then

    Dim loginData As String
    loginData = "j_username=theusername&j_password=thepassword"

    http.Open "POST", UrlToPostTo, False
    http.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
    http.setRequestHeader "Content-Type", "multipart/form-data; "
    http.Send loginData
End If

But when I do this, The http.Responsetext is just the login page still (or again?).
Any idea what I'm doing wrong? Is my plan even valid?
(This is related to trying to solve this problem )

A: I know this thread is ancient and I realize the OP most definitely moved on long ago.  I just spent the better part of 3 evenings being humbled by this exact same problem, and this thread kept coming up when I would stop to research more so I thought I would contribute for the next guy who comes along.
The trick is:

*

*Disable redirects using using the Option property, to stop it from
moving on without you. (see comments below)

*Capture the redirect on the output of the Status property, and
handle from there.

I'm sure there's other ways, but this seemed pretty elegant to me, and I found lots of other ways to use it.
To use the OPs code example, you could make your request as planned with one exception: The EnableRedirects var, which must come after opening the connection (didn't read that anywhere, just couldn't get it to stick to a closed connection).
Good luck "next guy"!
    Dim http As WinHttp.WinHttpRequest
    Dim UrlToPostTo As String, UrlRedirectedTo As String

    'Your initial request (assuming lots here)
    Set http = New WinHttp.WinHttpRequest
    http.Open "POST", UrlToPostTo, False
    'Stop it from redirecting automatically, so you can capture it
    http.Option(WinHttpRequestOption_EnableRedirects) = False 'You can also use the collection index instead of the pretty name
    http.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
    http.setRequestHeader "Content-Type", "multipart/form-data; "
    http.Send

    'Now if you have an active session, you should get your desired content
    'If it redirected you, you'll have a different status, header etc...

    If http.status = "302" Then
        Dim loginData As String
        'Now lets find out where we're being pointed and POST there
        'This may not be the same url you see in your address bar
        UrlRedirectedTo = http.GetResponseHeader("Location")
        'Also, you may have to do this again to arrive back at the intended resource
        loginData = "j_username=theusername&j_password=thepassword"
        http.Open "POST", UrlRedirectedTo, False
        http.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
        http.setRequestHeader "Content-Type", "multipart/form-data; "
        http.Send loginData
    End If

Some info I found useful in the MSDN maze.
WinHttpRequest Options (MSDN)
WinHttpRequest Object (MSDN)
Cookie Handling WinHttp (MSDN)

A: Is the logon page at the same URL as the page you originally submitted to? I don't see any code that changes urlToPostTo
After your first send, you might want to look at the Status property of your request. See the RFC for what each status code means. It could also help to use the GetAllResponseHeaders method to work out exactly what's going on. See MSDN for more on that

A: It might be possible for you to store the username and password in cookies which would allow you to access your page directly.
    Dim doc As WinHttp.WinHttpRequest
    Set doc = New WinHttpRequest

    doc.Open "POST", url, False

    doc.SetRequestHeader "Cookie", "UserID=" & username
    doc.SetRequestHeader "Cookie", "Password=" & password

You need to confirm the variable names on your server.  You can use a tool like ieHTTPHeaders to inspect the headers when you access the page from the browser to see what you need to do.

A: Try SetCredentials -- it may work for you, e.g.:
http.Open "POST", UrlToPostTo, False
http.SetCredentials "YourUsername", "YourPassword", 0
http.Send

Source: http://www.automateexcel.com/2005/02/11/excel_vba_winhttprequest_with_login_and/


text:
Q: Error - firestore is not defined (Only after "then") I have a problem : When I want to create fake users in my database, everything work like a charm until I start the loop 'for'.
At this point, I have this error :

Error adding document:  TypeError: Cannot read property 'firestore' of
  undefined

I've try multiple things but nothing work ... Do you have an idea ?
Thank you all !
create_NewUser(data:any){
        this.firestore.collection('Users-test').add({
          name:data.name,
          town:data.town,
          gender:data.gender,
          email:data.email,
          picture:data.picture,
          birthdate:data.birthdate
        })
        .then(function(docRef) {
          // console.log("Document written with ID: ", docRef.id);
          let nbInterest:any = data.interests.length;
          // let nbAvailaibilities:any = data.interests.length;
          for (let index = 0; index < nbInterest; index++) {
            this.firestore.collection('Users-test').doc("/" + docRef.id + "/interests/" + index).add({
              interest:data.interests[index]
            })
          }
        })
        .catch(function(error) {
            console.error("Error adding document: ", error);
        });
      }

A: Taken from here:

In classic function expressions, the this keyword is bound to different values based on the context in which it is called. With arrow functions however, this is lexically bound. It means that it usesthis from the code that contains the arrow function.

This means: in the function that you pass as an argument to then this is not defined.
Arrow function
You can use an arrow-function that binds to the "surrounding" this.
.then((docRef) => {
    // process this here
})

Bind this to the function
You can explicitly bind an object to a function that is treated as this within the function
.then(function(docRef) {
     // process this here
}.bind(this))

A: Do this:
In your create_NewUser:
const that = this;

Inside for loop use
that.firestore
.collection('Users-test').doc("/" + docRef.id + "/interests/" + index).add({
......
});

This is because this in not in the scope of then and is not referable.
Complete:
create_NewUser(data:any){
        const that = this;
        this.firestore.collection('Users-test').add({
          name:data.name,
          town:data.town,
          gender:data.gender,
          email:data.email,
          picture:data.picture,
          birthdate:data.birthdate
        })
        .then(function(docRef) {
          // console.log("Document written with ID: ", docRef.id);
          let nbInterest:any = data.interests.length;
          // let nbAvailaibilities:any = data.interests.length;
          for (let index = 0; index < nbInterest; index++) {
            that.firestore.collection('Users-test').doc("/" + docRef.id + "/interests/" + index).add({
              interest:data.interests[index]
            })
          }
        })
        .catch(function(error) {
            console.error("Error adding document: ", error);
        });
      }

Binding is also a way suggested by scorpioo590


text:
Q: How can I do Join in codeigniter? How can I do JOIN in codeigniter? Im just a newbie in programming using codeigniter.
I have 2 tables an item_db table and a mob_db table.
item_db table:
+-----+---------------+
| id  | name          |
+-----+---------------+
| 501 | Red Potion    |
+-----+---------------+
| 502 | Orange Potion |
+-----+---------------+
| 503 | Green Potion  |
+-----+---------------+

mob_db table:
+------+---------+----------+---------+----------+
| ID   | Drop1id | Drop1per | Drop2id | Drop2per |
+------+---------+----------+---------+----------+
| 1001 | 501     | 7000     |         |          |
+------+---------+----------+---------+----------+
| 1002 | 502     | 500      | 503     | 2500     |
+------+---------+----------+---------+----------+
| 1003 | 501     | 7000     | 502     | 500      |
+------+---------+----------+---------+----------+

how can I change the variable into the name that is match in item_db?
If I got the variable 501 from mob_db, how can I change it into a name that match in item_db table as well as the percentage which is the Drop1per or Drop2per or Drop3per?
Example:
501 - 1000%
502 - 500%
503 - 2500%
Result must be:
Red Potion - 10%
Orage Potion - 5%
Green Potion - 25%
I hope you understood my issue. Thanks


text:
Q: Given $u'(t)\leq au(t)$, $u(0)\leq b$. Find an upper bound on $u(t)$. Let $a$ and $b$ be positive constants, and let $u(t)$ be a differentiable function on $[0,\infty)$ satisfying the inequality
$u'(t)\leq au(t)$, $u(0)\leq b$.
Find an upper bound on $u(t)$ and prove that it is the best possible.
My attempt: Using separation of variables, we can see that $u\leq Ce^{at}$ for some constant $C$. I'm not sure how this could possibly bound $u(t)$ given that $a>0$. Am I making a mistake?
Any help appreciated!
Side note: I realize there is a similar question asked, but the answers don't seem to actually answer the question, at least not as far as I can understand.

A: Use the appropriate integrating factor and integrate
$$
(e^{-at}u(t))'=e^{-at}(u'-au)\le 0
$$
from $0$ to $t$.


text:
Q: Writing output in multiple files in Hadoop
Possible Duplicate:
MultipleOutputFormat in hadoop

I want to write the files according to months using map-reduce in hadoop. If data is from January month then the data should be wriiten in jan-file and likewise for each month there should be seperate file.
How Can I create such file in hadoop mapredude. I am trying for recursive map-reduce but not getting how to implement it?
Pls suggest me some solution.
Thanks.

A: Use the MultipleOutputFormat class, the output file name can be deduced from the key and the reducer output value from the reducer. MultipleOutputFormat#generateFileNameForKeyValue has to be implemented in the user defined OutputFormat class.
static class MyMultipleOutputFormat extends MultipleOutputFormat<Text, Text> {
    protected String generateFileNameForKeyValue(Text key, Text value, String name) {
        String keyString = key.toString();
        String valueString = value.toString();
        #return a combination of keyString and valueString
    }
}


text:
Q: War depl Tomcat server JDBC& Mysql err--I copied my driver to Tomcat/lib and build war file by making my dependency as provided. Getting error still -May-2019 18:29:47.938 WARNING [http-nio-8080-exec-24] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesJdbc
The web application [SampleTest] registered the JDBC driver [com.mysql.cj.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.

16-May-2019 18:29:47.939 WARNING [http-nio-8080-exec-24]

org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesThreads The web application [SampleTest] appears to have started a thread named [mysql-cj-abandoned-connection-cleanup] but has failed to stop it.

This is very likely to create a memory leak. Stack trace of thread:
I copied my driver to Tomcat/lib and build war file by making my dependency as provided. Getting error still
SEVERE [http-nio-8080-exec-6]
org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks

The web application [enimmPartner] created a ThreadLocal with key of
type
[org.springframework.boot.SpringBootExceptionHandler.LoggedExceptionHandlerThreadLocal] (value [org.springframework.boot.SpringBootExceptionHandler$LoggedExceptionHandlerThreadLocal@11550dfc]) and a value of type [org.springframework.boot.SpringBootExceptionHandler] (value
[org.springframework.boot.SpringBootExceptionHandler@8864e34]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory
leak.


text:
Q: disable video autoplay in twitter bootrap and stop video when modal is closed I'm embedding a local video to my page using Bootstrap 3
I use this code inside the modal

How can I prevent this video from autoplay? I also want the video to stop when the modal window is closed.

A: I was having issues with this and found a workaround. Drop the iframe in the html, for example:
(Note: I wanted video on the left so i put it in a row in the first 7 columns, also the "class = left_vid" is defined in my "override" custom linked style sheet)

           <video controls class= left_vid> <source src="vid.mp4" type="video/mp4">
        This browser does not display this video type </video>

 Text stuff

In the style.css
.left_vid {
    display:block;
    margin-left:auto;
    margin-right:auto;
    width: 80%;
    height:auto;
 }

A: Is it necessary to use an iframe for this? If not have look at the HTML5 video-tag:
http://www.w3schools.com/html/html5_video.asp
You are using iframe, you can not stop playing, you can only remove element like this
$('#myModal').on('hidden.bs.modal', function () {
  $( ".embed-responsive-16" ).remove();
})

This is just example, we dont have all you code :(


text:
Q: Post ajax request with link_to doesn't work I have a view with link_to method like this :
= link_to "Add Friend", friendships_path(:id => @user), :method => :post, :remote => true

As you can see I want to send a post request with link_to using ajax (remote: true).
This request go to the create method in friendships controller and it work fine (it create a relationship) but it render anything (firebug show me: 500 Internal Server Error).
views/friendships/create.js.erb
$("#my_selector").html("<%= escape_javascript(render('users/cancel_invitation')) %>")

views/users/cancel_invitation
= link_to "Cancel request", { :controller => "friendships", :action => "cancel", :id => @user }, data: { confirm: "Cancel friendship request?" }

I can't find the error.

A: = link_to "Cancel request", { :controller => "friendships", :action => "cancel", :id => @user }, data: { confirm: "Cancel friendship request?" }, :remote => true
The :remote => true bit is important for ajaxy stuff.


text:
Q: best way to parse google custom search engine results I need to parse through the results of google custom search engine. My first issue is that it is all in javascript. below page loads the results to be parsed, which opens in a js popup.

What I have already tried with no success.
Selenium
Jsoup
HtmlUnit
they never load the results. I know if I put waits in, it will load the JS but that is not the case with google custom search engine. The data in div id=results never loads in any of the above. Data such as css, js page calls load but not the actual results. I need to do this in java. Is there a better way to do this?
Is it possible to force the page to load directly with html without any javascript loads? If this was in html, of course, it would be much easier. Maybe there is a way to convert to html after javascript load?
Selenium Example
package raTesting;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

public class Testing {

    public static void main(String[] args)
    {
        WebDriver driver = new HtmlUnitDriver(BrowserVersion.CHROME);

        driver.get("https://www.google.com/cse/publicurl?q=breaking&cx=005766509181136893168:j_finnh-2pi");

        System.out.println(driver.getPageSource());

          }

when the url loads it displays all the results that need to be scanned. but the source never comes back with any results.

A: for anyone still looking. Alter the code below to fit your needs. You put your procedure into method(s) and run that in function check(). Anything inside the function will be looped until it has looped the array.
*Known issue: * capserjs runs faster than google js. The result is duplicate links. I haven't been able to tell casperjs to wait for google js popup to close first.
var casper = require("casper").create({
    verbose: true
});
url = casper.cli.get(0)
// The base links array
var links = [
    url
];

// If we don't set a limit, it could go on forever
var upTo = ~~casper.cli.get(0) || 10;

var currentLink = 0;

// Get the links, and add them to the links array
// (It could be done all in one step, but it is intentionally splitted)
function addLinks(link) {
    this.then(function() {
        var found = this.evaluate(searchLinks);
        this.echo(found.length + " links found on " + link);
        links = links.concat(found);
    });
}

// Fetch all  elements from the page and return
// the ones which contains a href starting with 'http://'
function searchLinks() {
    var filter, map;
    filter = Array.prototype.filter;
    map = Array.prototype.map;
    return map.call(filter.call(document.querySelectorAll("a"), function(a) {
        return (/^http:\/\/.*/i).test(a.getAttribute("href"));
    }), function(a) {
        return a.getAttribute("href");
    });
}

// Just opens the page and prints the title
function start(link) {
    this.start(link, function() {
        this.echo('Page title: ' + this.getTitle());
    });
}

// As long as it has a next link, and is under the maximum limit, will keep running
function check() {
    if (links[currentLink] && currentLink < upTo) {
        this.echo('--- Link ' + currentLink + ' ---');
        start.call(this, links[currentLink]);
        addLinks.call(this, links[currentLink]);
        currentLink++;
        this.run(check);
    } else {
        this.echo("All done.");
        this.exit();
    }
}

casper.start().then(function() {
    this.echo("Starting");
});

casper.run(check);

src: http://code.ohloh.net/file?fid=VzTcq4GkQhozuKWkprFfBghgXy4&cid=ZDmcCGgIq6k&s=&fp=513476&mp&projSelected=true#L0


text:
Q: Se puede eliminar el trail de la bola? Ansi.clearScreen();
        printFrame(' ', COL, ROW, NUM_COLS, NUM_ROWS, Ansi.Color.NONE, Ansi.Color.YELLOW);

        while(true) {
        Ansi.printTo('O', ballX, ballY, false, Ansi.Color.NONE, Ansi.Color.NONE);

            ballX += dirX;
            ballY += dirY;
            Util.wait(delay);

        }
    }

    public static void printFrame(char c, int xPos, int yPos, int width, int height, Ansi.Color fg, Ansi.Color bg)  {
        for(int x = xPos; x <= xPos + width - 1; x++) {
            Ansi.printTo(c, x, yPos, false, fg, bg);
            Ansi.printTo(c, x, yPos + height - 1, false, fg, bg);
        }

        for(int y = yPos; y <= yPos + height - 1; y++) {
            Ansi.printTo(c, xPos, y, false, fg, bg);
            Ansi.printTo(c, xPos + width - 1, y, false, fg, bg);
        }
    }
}

He hecho este programa que imprime una bola 'O' dento de un cuadrado acotado, y mi duda consiste en si es posible eliminar el rastro que deja dicha bola al volver a imprimirse por el bucle while.


text:
Q: Special characters as argument in bash Im making a small calculator that takes 3 command line argument like sh programname operand1 operator operand2 and compute its value. I want the user to only enter 3 arguments and an operator which can only be one +,-,x,/,%,^. The problem Im having is when the user enters # or /* the program doesn't output the right error message.
My code:
#!/bin/sh

if [ ! $# == 3 ]
    then
    echo "Usage: sh $0 operand1 operator operand2 "
    exit 1
fi

n1=$1 op=$2 n2=$3
if [ $2 == "+" ]; then
        ans=`expr $n1 + $n2`
        echo "$ans"
elif [ $2 == "-" ]; then
    ans=`expr $n1 - $n2`
    echo "$ans"
elif [ $2 == "x" ]; then
    ans=`expr $n1 \* $n2`
    echo "$ans"
elif [ $2 == "/" ]; then
    ans=`expr $n1 / $n2`
    echo "$ans"
elif [ $2 == "%" ]; then
    ans=`expr $n1 % $n2`
    echo "$ans"
elif [ $2 == "^" ]; then
    echo $((n1**n2))
else
    echo "Error: invalid operator"
    exit 1
fi

When the user 2 /* 3 or 2 # 4 the program doesn't recognizes thats its 3 arguments and output the first error message when it really should output the last else statement.

A: That's because * (glob expanding everything) and # (comment) have different meanings in shell.
Run your script with single quote around your operator such as:
# 2 '*' 3
# 2 '#' 4

Your program doesn't really handle /* case. So I am assuming it's *.

A: This is out of your control.
The user enters the command string in their shell, which interprets # as "the rest of this line is a comment" and /* as "everything in the / directory".
Demonstration:
~$ echo hello # there
hello
~$ echo /*
/bin /boot /cdrom /dev /etc /home /initrd.img /initrd.img.old /lib /lib32 /lib64 /libx32 /lost+found /media /mnt /opt /proc /root /run /sbin /srv /sys /tmp /usr /var /vmlinuz /vmlinuz.old

You can also see the exact arguments passed from the shell into your script by doing echo "$@".


text:
Q: libtorch 1.6 gives me different results on each run I traced a model and I am using it within libtorch, but for some bizarre reason, I notice that the results are different at each run :( I am totally baffled by this.
So, I load the model like so:
  torch::jit::script::Module module_af;
  module_af = torch::jit::load(af_model_path);
  module_af.eval();
  // std::cout << "Model Load ok\n";
  filelog.get()->info("Model Load ok");

and I run the inference like so:
    Mat img4encodingRGB = imread(align_filename, cv::COLOR_BGR2RGB);
    auto img2encode = torch::from_blob(img4encodingRGB.data, {img4encodingRGB.rows, img4encodingRGB.cols, img4encodingRGB.channels()}, at::kByte);

    img2encode = img2encode.to(at::kFloat).div(255).unsqueeze(0);
    img2encode = img2encode.permute({ 0, 3, 1, 2 });
    img2encode.sub_(0.5).div_(0.5);

I run the forward like so:
    std::vector<torch::jit::IValue> arcface_inputs;
    arcface_inputs.push_back(img2encode);
    at::Tensor embeds0 = module_af.forward(arcface_inputs).toTensor();

    std::cout << embeds0; // GIves different output on each run.

I am really baffled by this. The problem seems to be even worse - on two machines, they seem to produce identical results on concecutive runs, but on two other machines they dont. All packages are EXACTLY the same - libtorch 1.6 and the above code compiled using cmake.
It kinda reminds me of undefined behaviour, but I am totally lost because on two machines (a server and a vm) they seem to produce identical results - but they dont on other two.
I have triple checked everything to see if I am doing something stupid, but it does not seem like it - and hence my post.
Hope someone can point me to clues as to what I could be doing wrong :sob:
Example output run:1:
Columns 1 to 10-0.1005 -0.1768 -0.2082  0.1240  0.1185  0.3801  0.1378  0.1269 -0.3572 -1.1453

run:2:
Columns 1 to 10-0.1861 -0.3326 -0.3739  0.2302  0.1730  0.5391  0.1965  0.1972 -0.5481 -1.7317


text:
Q: How to use the server stored socket I'd on Cross domain client socket? I'm using socket.io for sending the data to cross domain, but the cross domain socket.id gives the unique id for the socket(client) , I want to use the particular server socket I'd on client side at cross domain.
I try this method
server side
io.emit('sendsocketid', id);

Crossdomain clientside
var socket = io('https://localhost:3000/', { transports: ['websocket'] });

socket.on('sendsocketid', function (id) {
    console.log(id);

})

I've successfully emit the server socket.id on Crossdomain client, but
I want only use the server_socket.id on cross domain client.
How to customize the client's_socket.id at cross domain?
Thanks!


text:
Q: Does a targets-permutation test prove that regression find a real pattern? I need to solve a standard ("vanilla") regression problem meaning that I have a 2D array of real-valued features (X) and 1D array of real-valued targets (Y). I use this data to train a simple regression model (let say a linear model or a simple decision tree).
Since my data are very noisy, I am not sure that there is any pattern in the data at all. In other words, it might be the case, that what I have is only noise and there is absolutely no dependency of my targets on my features. To exclude this possibility, I came up with the idea of the following test:

*

*I randomly permute all my targets so that, per construction, I destroy any possible relation between features and targets. For example, the first features-vector gets 137-th target, the second features-vector gets 34-th target and so on.

*I use these (fake, synthetic) data to fit my model again and I record its accuracy (for example squared deviation).

*Then I permute my targets again and run a fit again. I do it 10 000 times and check how often my accuracy on "fake" (synthetic) data is as good as, or even better, than accuracy achieved on real (original) data.

I was happy with this test. I said that, if accuracies obtained on the "fake" data is almost never better than accuracy achieved on the "real" data, then we can say that there is some dependency of targets on features in my data set. So, my model does something meaningful and not just overfitting by finding some "fake" patterns in pure noise.
However, I am not sure anymore about my interpretation. I guess that the only thing that I prove, is that the distribution of targets depends on features and it does not necessarily mean that the mean of this features-dependent distribution depends on features!
By minimising squared deviation I search dependency of mean on targets but my test probably does not guaranty that the found dependency of mean on features makes any sense. Maybe mean is not features dependent but standard deviation (or kurtosis, or skewness or other property of distribution) is and, this is why accuracy achieved on the real data is almost always better than accuracy achieved on the fake data.
Are my concerns valid?

A: Your idea does work.
This can be viewed as a type of Monte Carlo simulation where you randomly pick a set of points from the target distribution and regress to them, and you get a distribution of MSE. you can then check if the MSE you get for the real target distribution is significantly lower than from a randomly assigned distribution.
The common way of doing it is called "permutation feature importance" where you shuffle a feature instead of the target, and it's used mainly for nonlinear estimators like trees, random forests, etc.
It would be better though to actually randomly assign targets from the distribution of targets and not just permuting them.
But I'm not sure why you would do this instead of just checking that the regression coefficients you get are significantly greater than zero for linear regression.

A: There are some issues with the type of used cost functions. For these issues see a previous second version of this answer. The current question is edited.
Your first fit already determined an effect that the mean is dependent on the features. Or at least expressing the mean as a linear function of the regressors gives a lower mean squared error than expressing the mean as a constant (and this indicates that a linear function is closer to the true mean of the population and a zero effect is not the true model).
The question that the permutations answer is not whether there is an effect and what the effect is (whether it is a difference in the mean or another difference in the distribution) but whether the observed effect is statistically significant. Statistically significant means that the observed effect in unlikely occuring in repeated experiments with different samples/data. These repeated experiments is what you simulated with the permutations.
If there is anything wrong with your method then it is not that the effect is not about the mean but that the significance might not be well approximated by permutations.

*

*For instance: is your data a collection of independent samples? If you have for example only two types of data points (say you measure a lot of people, but they are all from only two villages or other categories) and these are repeated many times, then your sample is effectively very small (it may not need to be about the number of observed people but instead about the number of observed villages). The same datapoints repeated many times in slightly different form makes you overestimate the sample size and you can easily get a false idea of a significant effect


text:
Q: I want to refresh or reload the $scope evey 60 secs Hi I am learning angularjs.
The main idea is to "refesh" or "reload" the $scope.
I was able to refresh the page with this ```location.reload();````.
But i was recomended to refresh the $scope, not the hole page.
I reserached about this, I reckon I should use apply or digest.
As so far the code is like this:

refresh.component.js
    myApp.component('refreshComponent', {
        template:"<button class='btn btn-lg btn-info text-uppercase' ng-click='vm.refresh()'Refresh </button>",
        controllerAs: 'vm',
        controller: function RefreshController($scope, $element, $attrs) {
           vm = this;

          vm.refresh = function(){
            location.reload();
          }
        }
      });

As I understand this should change:(this are assumptions, I dont know, if I sould keep the component or refactor into a controller or somthing else, it is not clear to me)

*

*The button should not longer exist, so it will be automatically
refreshing avery 60 secs.

*The component should not longer exist.

*I have an utils.js, where I suppose I should place the next code:

setTimeout($scope.apply(), 60000);
setTimeout($scope.digest(), 60000);

I dont know, if I am using apply or diggest in the correct way


text:
Q: copy blob data into on-premise sql table My problem statement is that I have a csv blob and I need to import that blob into a sql table. Is there an utility to do that?
I was thinking of one approach, that first to copy blob to on-premise sql server using AzCopy utility and then import that file in sql table using bcp utility. Is this the right approach? and I am looking for 1-step solution to copy blob to sql table.

A: Regarding your question about the availability of a utility which will import data from blob storage to a SQL Server, AFAIK there's none. You would need to write one.
Your approach seems OK to me. Though you may want to write a batch file or something like that to automate the whole process. In this batch file, you would first download the file on your computer and the run the BCP utility to import the CSV in SQL Server. Other alternatives to writing batch file are:

*

*Do this thing completely in PowerShell.

*Write some C# code which makes use of storage client library to download the blob and once the blob is downloaded, start the BCP process in your code.

A: To pull a blob file into an Azure SQL Server, you can use this example syntax (this actually works, I use it):
BULK INSERT MyTable
FROM 'container/folder/folder/file'
WITH ( DATA_SOURCE = 'ds_blob',BATCHSIZE=10000,FIRSTROW=2);

*

*MyTable has to have identical columns (or it can be a view against a table that yields identical columns)

*In this example, ds_blob is an external data source which needs to be created beforehand (https://learn.microsoft.com/en-us/sql/t-sql/statements/create-external-data-source-transact-sql)

*The external data source needs to use a database contained credential, which uses an SAS key which you need to generate beforehand from blob storage https://learn.microsoft.com/en-us/sql/t-sql/statements/create-database-scoped-credential-transact-sql)

The only downside to this mehod is that you have to know the filename beforehand - there's no way to enumerate them from inside SQL Server.
I get around this by running powershell inside Azure Automation that enumerates blobds and writes them into a queue table beforehand


text:
Q: How to fix this CSS-based vertical menu with relative positioned second level? I've got this simple CSS ul li menu with a second level to it, which should pop up below its parent and push down the rest.
Like this:
Option 1 <---- no positioning on UL
  Sub 1  <----- relative positioned UL
  Sub 2
Option 2
Option 3

For some reason, the relative positioned UL doesn't affect Option 2 as it should.
My try to put this in jsFiddle. http://jsfiddle.net/hxQRt/
My HTML

Miljörivning

Rivning av väggar och mattor

Rivning och borttagning av golvbeläggning

Brokkar med bilningshammare

Rivning av stora byggnader

Miljösanering

Håltagning

Stambyten

Golvslipning

Ventilationsrengöring

My CSS
/* Level 1 */

.sidemeny_undersida,
.sidemeny_undersida li,
.sidemeny_undersida li a { margin: 0; padding: 0; float: none;  }

.sidemeny_undersida { display: block; width:200px; min-height:33px; margin: 20px 0 0 20px; float:left; }

.sidemeny_undersida li { display: block; width: 200px; padding: 4px 0 6px 0; margin: 0 0 5px 0; background: url(../images/sub_nav_bg.png) no-repeat bottom left; }

.sidemeny_undersida li a { color: #000; padding: 0 0 0 10px; }

.sidemeny_undersida li a:hover,
.sidemeny_undersida li.current a  { color: #25a8de; }

.sidemeny_undersida li:last-child { background: none; }

/* Level 2 */

.sidemeny_undersida li.current ul { display: block; position: relative !important; width: 250px; min-height: 150px; margin: 0 0 0 0; padding: 0;   }

.sidemeny_undersida li li { width: inherit; height: 15px; margin-left: 10px; background: none; padding: 2px 0 0 0;  }

.sidemeny_undersida li li a,
.sidemeny_undersida li.current li a { font-size: 12px; color: #000; text-transform: none; padding: 0; }

A: You didn't add the second level ul tag. Your html should be as follows:

One

OneDotOne

OneDotTwo

Two

Three

Other than that your CSS is fine for basic functionality. Your basic example here: http://jsfiddle.net/DANqg/1/
And your initial menu example: http://jsfiddle.net/hxQRt/2/


text:
Q: Restricting Age without using TRIGGER constraint MySQL Requirement: A doctor should have age over 24
Env: MySQL 5.6
Someone says: "You do not need Trigger for this. Solution is very simple"
Options tried: CHECK does not work with this version of MySQL. Also I cannot use fuctions like Curdate() for CHECK constraints. I ended up using trigger and it works. but I want to know what is that SIMPLE SOLUTION is
What I have now is a Trigger:
BEGIN
IF NEW.DateofBirth > date_add(CURDATE(),interval -24 year)
       then SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Should be over 24 years old';
    END IF;
END

So far I have used DateOfBirth becuase Age column does not make sense in real life.
I am lost after googling for Generated column, ENUM, etc.


text:
Q: Recursion, iteration, and ...? Here are three common code structures that apply a function multiple times:
foo(x) {
    if basecase(x) return k else return foo(g(x))
}

uses recursion.
for i in 0..10 {
    n *= bar(i)
}

uses iteration.
baz(baz(baz(baz(quux))))

uses...?
In mathematics it'd be considered iteration, but mathematics doesn't generally concern itself with for and while loops, which are what people associate with the term in programming. How do programmers tersely and unambiguously refer to the third construct?

A: The term you're looking is for is function composition, although I'm not sure if there's a more specific term for the special case of a function composed with itself.


text:
Q: How can I prevent a mat-expansion-panel from opening when clicked? I want to control my mat-expansion-panel solely with the panel's [expanded] input property. I am using NGRX as state management.
Therefore, I don't want the panel to open when clicked. Instead, I have my own click listener that will dispatch the right action that will lead to the panel to open.
How can I prevent it from opening when clicked? I tried (click)="$event.stopImmediatePropagation(); but it does not do the trick.
<mat-accordion [multi]="true">
  <mat-expansion-panel [expanded]="item.isOpen">
    <mat-expansion-panel-header (click)="togglePanel($event, item)">
        <!-- Header Content-->
    </mat-expansion-panel-header>

    <ng-template matExpansionPanelContent>
        <!-- Panel Content -->
    </ng-template>
  </mat-expansion-panel>
</mat-accordion>

Any ideas?

A: There is not (from what I know) built in way to disable the click of the panels, thought there's a simple trick using only CSS to accomplish what you want.
You can set the style to pointer-events: none; to the <mat-expansion-panel> and it won't listen to any click events, and then you toggle it your way using your custom logic.
I made a StackBlitz example to demonstrate it.


text:
Q: Why these two Cypher queries return different result? I'm trying to learn Cypher and I have the data of a trust network, I wanted to query people who trust "15 most trusted people", so I wrote this query, QUERY1:
QUERY1:

MATCH (u1:USER)-[:TRUST]->(u2:USER)
with u2.Id as id, COUNT(u2) AS score
order by score desc
limit 15
match p=(w1:USER)-[:TRUST]->(w2:USER {Id: id})
return w1.Id as user1, w2.Id as user2

after that I wanted to change the last 2 lines of query to this:
QUERY2:

MATCH (u1:USER)-[:TRUST]->(u2:USER)
with u2.Id as id, COUNT(u2) AS score
order by score desc
limit 15
match p=(w1:USER)-[:TRUST]->(w2:USER {Id: id})-[:TRUST]->(w3:USER)
return w1.Id as user1,w2.Id as user2, w3.Id as user3

and after analyzing the result, I've guess that something is wrong!
so I hard coded id to specific value, for example 575, then count(p) is equal to 1937520, BUT if I run the last line of query with hardcoded Id, as a separate query:
QUERY3:

MATCH r=(u1:USER)-[:TRUST]->(u2:USER {Id: "575"})-[:TRUST]->(u3:USER)
return count(r)

the count(r) is equal to 129168!
I checked that the User "575" trust 207 people and is trusted by 624 people, so QUERY3 result seems correct: 207*624=129168. and my question is why?!
I can't understand what is wrong with the QUERY2, and the second question is does it mean that QUERY1 result is wrong too?
EDIT1:
thanks for answers, but I still had problem with this, so I checked another scenario and I've got the following result:
If I write a query like this:
QUERY4:
MATCH (n) WITH n limit 15 return "1"

I'll get 15 "1"s printed in the output, so it means the last part of QUERY2 executes 15 times, no matter if I hard code the Id or not, like it's in a for loop. so the problem here was that I thought the WHIT X LIMIT N doSomeThing would execute like a foreach(x : X) loop, if I use x, and would not, if I don't use x. stupid assumption...

A: In QUERY3, you are matching u2 to a single user (user 575). QUERY 3 is correct.
However, in QUERY2, that WITH (line 3) matches 15 different u1-u2 combinations. The MATCH (line 1) returns a "row" for each u1 and u2 that..well, matches that pattern. Then you are returning just the first 15 results, which I guess are 15 different u1 for u2=user{Id:575} That´s what give 1937520 results, which is exactly 15 * 129168.
The problem in the with appears because you are not aggregating (not getting just 1 row for each u2). You 'return' (using WITH) one id variable for each u2 user, so count(u2) will always be 1. Maybe you wanted to write u1.Id or count(u1) ? Anyway, WITHing u2.Id or u1.Id will return 15 results because of the LIMIT 15 (line 4). LIMIT 1 would do the trick, but we can also do this:
MATCH (u1:User)-[:TRUST]-(u2:User)
WITH DISTINCT(u2.Id) AS id
LIMIT 15

And then the rest of the QUERY2 (or QUERY1, for that matter). I eliminated the score variable, but if it´s meant to be count(u1), it can be readded with no problem.

A: This query might do what you intended.
MATCH (:USER)-[r:TRUST]->(u2:USER)
WITH u2, COUNT(r) AS score
ORDER BY score DESC
LIMIT 15
MATCH (w1:USER)-[:TRUST]->(u2)-[:TRUST]->(w3:USER)
RETURN w1.Id AS user1, u2.Id AS user2, w3.Id AS user3;

It first finds the 15 most-trusted users, then finds all the 2-level trust paths that those users are in the middle of, and finally returns the ids of the users in those paths.
Also, the second MATCH reuses the u2 nodes already found by the first MATCH, to speed up the processing of the second MATCH.

A: I'll just break down Query 2 and the rest should make sense.
QUERY2:

MATCH (u1:USER)-[:TRUST]->(u2:USER)
with u2.Id as id, COUNT(u2) AS score
order by score desc
limit 15
match p=(w1:USER)-[:TRUST]->(w2:USER {Id: id})-[:TRUST]->(w3:USER)
return w1.Id as user1,w2.Id as user2, w3.Id as user3

Starting with
MATCH (u1:USER)-[:TRUST]->(u2:USER)
with u2.Id as id, COUNT(u2) AS score
order by score desc
limit 15

You are basically creating a list of all u1 trusts u2; And COUNT(u2) = # of u2 matched. So assuming u1 trusts u2 has 100 matches, COUNT(u2) would put '100' in that column for each row. (and then you order on what is now a constant, which does nothing, and limit 15, so you now have an arbitrary list of 15 u1 trusts u2.
So that just leaves
match p=(w1:USER)-[:TRUST]->(w2:USER {Id: id})-[:TRUST]->(w3:USER)

So that is match each path p where a user w1 trusts user w2 (with for-each id from first part) who trusts a user w3.
So, fixing the first part, to get 'top 15 trusted users you need to count the number of incoming trusts
MATCH (u1:USER)-[trusts:TRUST]->(u2:USER)
with u2, COUNT(trusts) AS score
order by score desc
limit 15

So now you have 15 most trusted users and you can verify this with return u2.id, score. To get people who trust these people you would than just need to ask like...
MATCH (u3:USER)-[:TRUST]->(u2)

and u3 will then be all users who trust someone from top 15 trusted people (u2).
As an additional note, if you are using the neo4j web browser, try pre-pending the PROFILE keyword to your cypher for some insight into what the cypher query actually does.
Edit 1:
Now to explain what query 4 does MATCH (n) WITH n limit 15 return "1". As I am sure you guessed, MATCH (n) WITH n limit 15 matches all nodes but limits results to first 15. On the RETURN part, you are saying "For each row, return the constant '1'.", Which give you 15 distinct rows internally, but the returned rows are not distinct. This is what the DISTINCT keyword is for. Using RETURN DISTINCT "1" says "For each row, return the constant '1', but filter the result set to only have distinct rows." aka, no 2 columns will have the same value. The non-distinct result is useful if you know there will be some duplicate rows, but you want to see them anyways (maybe for a weight reference, or knowing that they are from 2 separate fields).

A: As I mentioned in the EDIT1, the problem here was that I thought the WHIT X LIMIT N doSomeThing would execute like a foreach(x : X) loop, if I use x, and would not, if I don't use x. stupid assumption...


text:
Q: How to access global scope variables in callback functions? [JS] For my user registration I have
const express = require ('express');
const userRouter = express.Router ();

userRouter.get ('/', function getUserList (req, res) {
    let User = require ('../models').User;
    User.find ({}, function (err, list) {
        res.json (list);
    });
});

userRouter.post ('/', function createUser (req, res) {
    let User = require ('../models').User;
    if (req.body.username && req.body.password)
        User.create (req.body, function (err, user) {
            res.json (user);
        });
});

... 3 more functions with the same `let User` ...

module.exports = userRouter;

Here, I have to require the module models twice. I tried setting the User variable as a global variable up at the top of the program, like
const express = ..., userRouter = ...
var User = ...

However this User variable is still not accessible inside my callback functions.
Is requiring the User module multiple times the correct way to do this or am I missing something?
edit: Inside the callback functions, the User variable is undefined.

A: As @Doug mentioned, you should pass global to the user variable like this:
global.user = ...

This process essentially turns user into a globally accessible variable. You can read more about Node's global here to understand what it does as well as understand what it's implications are too: http://stackabuse.com/using-global-variables-in-node-js/

A: To @charloetfl 's point if it is just within the file, declaring it outside the callback or on top of the file should do. If we are talking about access across all modules and files within the project then adding it to the global object is the way to go about it in node as @doug and @andrewl mentioned.