text:
Q: Access whole DOM in Angularl2 RC In an Angular 2 application I need to check whether or not a chrome extension is installed. To do so Google recommends here to check for a DOM element added by the extension. I'm implementing the extension as well so it's no problem to add that element when the extension loads.
But I'm struggling with the Angular side. I have a service that handles the  logic with the extension (install etc.), and I would like to implement the check there as well. Unfortunately I could not figure out how to get access to the whole DOM.
There is the injectable class ElementRef with the property nativeElement, but that only gives me access to the DOM element that belongs to the component. Since the element added by the extension is a direct child of body that does not work here.
Does anyone now how to get access to the whole DOM in an Angular 2 compliant way?

A: EDIT Please check the link provided by tschuege if tempted to used the solution below.
Import renderer:
import {Renderer} from '@angular/core';

Inject it:
constructor(private renderer: Renderer)

Then get the element reference by issuing:
renderer.selectRootElement(<elementID>)

A: I finaly solved it by getting @document injected into the constructor:
constructor(@Inject(DOCUMENT) private document: any) {}

and then query for the element
this.document.querySelector('#idToCheck');

This solution works fine in my case.


text:
Q: "command 'vscode.previewHtml' not found", cannot get preivew of latex I have this error flashing everytime I try to use VS for Latex. I have no idea how to proceed. One thing I noticed is that it can load pdf that already exists in the folder.
error:

command 'vscode.previewHtml' not found

using

Latex Workshop 8.0.5
Latex preview 0.5.1

os

mac

I am also very new into this, so apologies if this is some stupid question. I tried a  lot of googling, but couldn't understand any solution.
Looking for help. Thank you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Difference between ASP.Net Applications and ASP.Net Apps vSomething Performance Counter Sets On Microsoft Windows Server 2016 (and probably earlier versions) I see several Performance Monitor Counter sets/categories that have similar names and similar counters:
\ASP.NET Applications(*)\*
\ASP.NET Apps v2.0.50727(*)\*
\ASP.NET Apps v4.0.30319(*)\*

What is the relationship between these counter sets?  Will the results in \ASP.NET Applications(*)\* be some sort of aggregation of the other two?  Is usage of each based on the .Net CLR version of the app pool?  Has anyone seen an official explanation?  Google has not helped me.
thanks!
Martin

A: Per Microsoft Support:

\ASP.NET Applications(*)\* - These counters aggregate information from all ASP.NET applications on a Web server computer.
\ASP.NET Apps v2.0.50727(*)\* - These counters provide the information from all ASP.NET 2.0 based applications on a Web server computer.
\ASP.NET Apps v4.0.30319(*)\* - These counters provide the information from all ASP.NET 4.0 based applications on a Web server computer.

Hope this helps someone in the future.
Martin


text:
Q: How to get keys from nested objects in mongodb I'm working on a migration from mongodb to mysql. I have a sub document in one collection, I need to find the data using sub document.
The collection structures looks like this
{
        "_id" : ObjectId("578506a90420bec15ea33783"),
        "reselected" : "ABCDEFGH",
            "reskip" : [],
            "restatus" : "active",
            "reuser" : {
                "activeListings" : [
                    {
                        "subcategory" : "mobiles",
                        "title" : " Mobile 1",
                        "transactiontype" : "post"
                    },
                    {
                        "category" : "mobiles",
                        "title" : " Mobile 2",
                        "transactiontype" : "post"
                    } ],
            "reuserInput" : "2",
            "reussdsession" : "303757117"   }

I have tried with mapreduce code
mr = db.runCommand({
          "mapreduce" : "collection name",
          "map" : function() {     */map/
            for (var key in "this.reuser.activeListings") {
            for (var key1 in "this.reuser.activeListings"[key]) {
                emit(key1, null);
            }
            }
          },
          "reduce" : function(key, stuff) { return null; },  /*reducer/
          "out": "my_collection" + "_keys"
        })

I need output for activeListings
{subcategory,title,transactiontype,category}

A: You essentially need to iterate the array and then emit each key. The following mapReduce script will give you the desired key list:
mr = db.runCommand({
    "mapreduce": "collectionName",
    "map": function() { /* mapper */
        this.reuser.activeListings.forEach(function (obj){
            for (var key in obj) { emit(key, null); }
        });
    },
    "reduce": function() {}, /* reducer */
    "out": "my_collection" + "_keys"
})

To get a list of all the dynamic keys, run distinct on the resulting collection:
> db[mr.result].distinct("_id")
["subcategory", "title", "transactiontype", "category"]


text:
Q: Compute oracle not visible the compute functions results are not visible. only total and count are visible
BREAK ON PET_ID SKIP 5
COMPUTE COUNT LABEL 'No. of Visits' OF VISIT_DATE ON PET_ID
COMPUTE AVG LABEL 'Avg Cost' OF BASIC_COST ON PET_ID
COMPUTE MIN LABEL 'Min Cost' OF BASIC_COST ON PET_ID
COMPUTE MAX LABEL 'Max Cost' OF BASIC_COST ON PET_ID
COMPUTE SUM LABEL 'Total Cost' OF BASIC_COST ON PET_ID
/

A: Don't use COMPUTE as separate commands (because only the last takes effect); put all of them into the single line, separated by space.
SQL> break on pet_id
SQL> compute count label 'No. of visits' avg label 'avg cost' min label 'min cost' max label 'max cost' sum label 'total cost' of basic_cost on pet_id
SQL> select * from pets order by pet_id;

    PET_ID PET_NAME   BASIC_COST
---------- ---------- ----------
        10 CLARK            2450
           KING             5000
           MILLER           1300
**********            ----------
avg cost              2916,66667
No. of vis                     3
min cost                    1300
max cost                    5000
total cost                  8750
        20 JONES            2975
           FORD             3000

    PET_ID PET_NAME   BASIC_COST
---------- ---------- ----------
        20 ADAMS            1100
           SMITH             800
           SCOTT            3000
**********            ----------
avg cost                    2175
No. of vis                     5
min cost                     800
max cost                    3000
total cost                 10875
        30 WARD             1250
           TURNER           1500

    PET_ID PET_NAME   BASIC_COST
---------- ---------- ----------
        30 ALLEN            1600
           JAMES             950
           BLAKE            2850
           MARTIN           1250
**********            ----------
avg cost              1566,66667
No. of vis                     6
min cost                     950
max cost                    2850
total cost                  9400

14 rows selected.

SQL>


text:
Q: Under weak convergence, is the limit's moment infinite if the sequence's moments are infinite? If a sequence of random variables $X_n$ converges in distribution to some r.v. $X$, the convergence of moments doesn't immediately follow. However, if the sequence is uniformly integrable, then we have the convergence of moments.
Thus, for example, if $X_n\Rightarrow X$ and $\sup \mathbb{E}[|X_n|^{1+\varepsilon}]&lt\infty$ for some $\varepsilon >0$ (a sufficient condition for uniform integrability), then $\mathbb{E}[|X|]&lt\infty$ and $\mathbb{E}[X_n]→\mathbb{E}[X]$. (See for example Theorem 25.12 and Corollary in Billingsley's Probability and Measure).
My situation however is this: $X_n\Rightarrow X$, and $\mathbb{E}[X_n]=\infty$.
QUESTION: Does it follow that $\mathbb{E}[X]=\infty$ too?
Let me add that all the $X_n$ and $X$ are nonnegative so their moments are defined ($\mathbb{R}_+ \cup \infty$).
The moment convergence results I've seen all invoke uniform integrability and finiteness of moments, which doesn't apply here. Is it even possible to have $\mathbb{E}[X]&lt\infty$ (a counterexample would be instructive)? Or might anyone be able to suggest other additional conditions so that $\mathbb{E}[X]=\infty$?

A: Let $X_n$ of density $f_n(x):=\frac{2n}{\pi(1+nx^2)}\chi_{(0,+\infty)}$; if $g$ is a continuous bounded function then
$$\int_0^{+\infty}(f_n(x)g(x)-f_n(x)g(0))dx\leq 2\int_0^{+\infty}\frac{|g(tn^{-1})-g(0)|}{\pi(1+t^2)}dt$$
and by the dominated convergence theorem it converges to $0$. So $X_n$ converges in distribution to $\delta_0$ which have moments of each orders.


text:
Q: Why does $.load( handler(eventObject) ) not work for data returned from server after Ajax request, trying to make it wait for all images to load I need to keep displaying the loading gif until all images
in the returned data (html) have been finished loading.
The data and everything is returned properly, but the .live('load', function() {})
is never executed, have tried without the .live as well. The contents of #ContentBody
just get replaced with the returned html data (#LoadingLayer disappears too of course) and I can see images loading as usual.

HTML layout:

... Main contents, lots of images here

A: Why don't you just hide #LoadingLayer directly?
$('#ContentBody').html(data);
$("#LoadingLayer").hide();

Edit:
I misread your question, I don't think there is an easy way to detect that all images have been loaded. I suggest you try the waitForImages plugin.

A: Try changing the contents of the "success" function to this...
$('#ContentBody').html(data).live('load', function () {
    var imgcount = $(this).find("img").length;
    $(this).find("img").one("load", function() {
        imgcount--;
        if (imgcount == 0) {
            $("#LoadingLayer").hide();
        }
    }).each(function() {
        if (this.complete) $(this).load();
    });
});

It waits till html(data) is loaded and then gets an image count.  It then adds an event handler to each of the images to decrement the image count when the image is loaded.  The one("load" code means only allows the following code to run once, and the each code basically says "if it's already loaded (as per cached images) then run the load event".
Once the image count is 0 it hides the loading layer.
Without a URL where I can run this through the console I can't be 100% sure it's accurate, so it may need a fiddle about.  If you get stuck give us a shout.

A: Try binding the load event to the images.  Keep track of how many have loaded, and remove the loading layer only after they've all loaded.  This is untested code but should give you an idea:
success:function(data){
    // Set the content
    $('#ContentBody').html(data);

    // How many images do we have?
    var images = $('#ContentBody img'),
        leftToLoad = images.size();

    // Listen for load event *FOR IMAGES*
    images.bind('load', function (){
        // Hey look we loaded one, was that the last one?
        if(--leftToLoad === 0){
            // Yep, we're done
            $("#LoadingLayer").hide();
        }
    });
}

If you'd rather use live than handling in the ajax callback, do this in your $(document).ready callback:
$('#ContentBody img').live('load', function(){...});

Should do the trick.
Cheers


text:
Q: TextChange event loose focus in asp.net I am trying a very simple thing. I have 3 textboxes and 3 labels. On text change i am setting the content of label.
The issue is when i insert some value in 1st textbox(e.g 50) change the focus to another textbox the values in label is reflected perfectly.
But the focus which i setted on 2nd textbox is lost. And the focus is lost somewhere.
I need to click again on 2nd textbox to get focus.
The same issue is reproduced if TAB is clicked to change focus.
I have made a small demo project for the same and attached. You can avail that from the below link
https://skydrive.live.com/redir?resid=A716D678775EEF95!115&authkey=!ABp6kAon_ZNDLBU
Please someone help me...what am i doing wrong??
Thanks in advance...

A: This is a rather common issue in ASP.NET, as described here: http://www.codeproject.com/Articles/17571/Maintain-focus-between-postbacks-in-ASP-NET-2-0-al or here: How do I maintain focus position in UpdatePanel after page partial post back. Those links also contain some suggestion on how to solve this issue.
One of the possible solutions is to keep track of control with focus, put information about it into a hidden field and manually restore the focus after postback. This method is described in the first link mentioned.


text:
Q: In AWS, How to specify region in describe-image api to get AMI Id for that region I am finding it too hard to specify the region in the describe-image api of AWS java SDK.
I am filtering out the result using Filter() but there is no way (or I can't find one) to specify a particular region to get AMI ids of that particular region and hence, it always results in "The image id '[ami-xxxxxxxxxxxxxx]' does not exist".
How can I get AMI ids for a particular region.
Following is the Code I am using currently
final AmazonEC2 ec2 = AmazonEC2ClientBuilder.standard().withRegion('us-east-1').build();

DescribeImagesRequest request = new DescribeImagesRequest().withOwners("amazon");
request.getFilters().add(new Filter().withName("name").withValues("*centos*7*"));
request.getFilters().add(new Filter().withName("is-public").withValues("true"));
request.getFilters().add(new Filter().withName("manifest-location").withValues(""));

DescribeImagesResult result = ec2.describeImages(request);

I am using the first Image returned after sorting by recent images and I was assuming I have specified the region in ec2Client it should return AMIs of that region but it always throws the error.
How, Can I get the AMI ids for a particular region?

A: With the exception of AWS IAM and AWS CloudFront, all AWS services are regional.
Therefore, information returned will always be limited to resources in the region requested.
You are correct that it will only return values for AMIs in the region specified in the ec2Client.
Here is an equivalent query for the AWS CLI:
aws ec2 describe-images --owners amazon --filters 'Name=name,Values=*centos*7' --query 'Images[].[ImageId,Name]' --region us-east-1

I realize that you are seeking a Centos image, but it is worth mentioning that the latest Amazon Linux and Windows AMIs can be obtained from the Parameter Store: Query for the latest Amazon Linux AMI IDs using AWS Systems Manager Parameter Store | AWS Compute Blog


text:
Q: How to change client ip address using php How to change client ip address using php. Is it Possible to change client ip address if they visit our site. i'm trying to stream video which is not works in my country without vpn. So is there any way to play video without using vpn. Like using proxy in php. please help me with that i'm new in php. Thanks for your your time.

A: I'm not sure I understand your question 100%, but if it's what I think you're asking then no. PHP is a server-side language that cannot have any effect on the client.
You can change various things on the server though, but it's not recommended that a webserver can have that much control of the host OS if the server is public.


text:
Q: Load node modules from virtual file system I'm trying to load some node modules from a virtual file system
but I can't make it work
var request = require('request')
  , AdmZip = require('adm-zip')
  , fs = require('fs')
  , unionfs = require('unionfs')
  , memfs = require('memfs')
  , mem = new memfs.Volume
  , data = []

unionfs.use(fs).use(mem)
unionfs.replace(fs)

var req = request({
    method: 'GET',
    uri: 'https://firebasestorage.googleapis.com/v0/b/****.appspot.com/o/node_modules.zip',
    headers: {
        "encoding": "binary"
    }
})

req.on('data', function(chunk) {
    data.push(chunk)
}).on('end', function() {
    var binary = Buffer.concat(data)
    mem.mountSync('./', {
        "node_modules.zip": binary
    })

    var zip = new AdmZip("./node_modules.zip")
    var files = {}
    zip.getEntries().forEach(function(entry) {
        if (entry.isDirectory)
            console.log(entry.entryName)
        files[entry.entryName] = entry.getData()
    });
    mem.mountSync('./node_modules', files)

    //need to get these modules dynamically
    var async = require("async")
})

The error I get is: Error: Cannot find module 'async'
now I was trying to use this module https://www.npmjs.com/package/app-module-path to add my virtual path but it only gets physical paths.
Can anybody help me with this pleas?
Don't worry about security I'm going to use encryption with this.

A: The author of unionfs writes that the require does not work in new versions of the node.js:
// NOTE: This does not work in new Node.js
// Now you can also do:
// require('/usr/mem/dir/hello.js');
// Hello world!
// require('/project/hello.js');
// Hello world!

https://github.com/streamich/unionfs/blob/master/examples/example.js#L41


text:
Q: Formula for inner and outer tessellation factors given number of triangles I am trying to use tessellation to make all triangles on a mesh with varying sizes of triangles to be roughly the same size. I am doing this in unity. For simplicity we can assume that both inner and outer tessellation factors are the same.
In another question someone gave this recursive alorithm as an example of how to calculate the number of triangles that will result from any tessellation factor.
int calculateTriangles(int n) {
    if(n < 0)   return 1;
    if(n == 0)  return 0;
    return ((2*n -2) *3) + calculateTriangles(n-2);
}

So one solution could be to reverse that recursion and use the area of each triangle as the desired number of triangles. But this is to be used in a shader and would therefore much rather have a formula that directly gives the tessellation factor, even if it is an approximation.
The closest I have gotten so far is log2(area + 1) but no dice it seems. I have also tried smaller and bigger logarithms but they all start behaving badly when the triangles are very small or very big.

A: calculateTriangles function gives sequence that is sum of arithmetic progression, so calculateTriangles(n)value is about 3/2 * n^2
Seems you need some kind of reverse function A*Sqrt(x)


text:
Q: Trouble with sorting array #include "stdafx.h"
#include <iostream>
#include <math.h>
#include <time.h>
#include<iomanip>
#include<array>
#include <algorithm>

using namespace std;
const int AS = 6;
void FillingRandomly(int [AS][AS]);
void printing(int[AS][AS]);
void forsorting(int[][AS], int);
int c;

int main()

{
    int funny = 0;
    int timpa = 0;
    int counter = 0;
    int Array[AS][AS];
    srand(time(0));

    FillingRandomly(Array);

    cout << "The unsorted array is" << endl << endl;

    printing(Array);

    cout << "The sorted array is" << endl << endl;

    forsorting(Array, funny);
    printing(Array);

    system("PAUSE");

    return 0;

}

void FillingRandomly(int Array[AS][AS])
{
    for (int i = 0; i<AS; i++)
    {
        for (int j = 0; j<AS; j++)
            Array[i][j] = rand()%87 +12;
    }
}

void printing(int Array[AS][AS])
{
    int counter = 0;
    for (int i = 0; i<AS; i++)
    {
        for (int j = 0; j<AS; j++)
        {
            cout << setw(5) << Array[i][j];
            counter++;
            if (counter%AS == 0)
                cout << endl << endl;
        }
    }
}

void forsorting(int Array[AS][AS], int funny)
{

    int w=0;
    int dice = 0;
    int Brray[AS*AS];
    int super = 0;
    int space=0;

    //Transofrming Array[][] into Brray[]
    for (int i = 0; i < AS; i++)
    {
        for (int k = 0; k < AS; k++)
        {
            Brray[space] = Array[k][i];
            space++;
        }
    }

    //Bubble sorting in Brray[]

    for (int passer = 0; passer < AS-1; passer++)
    {
        for (int timpa = 0; timpa < AS-1; timpa++)
        {
            if (Brray[timpa]>Brray[timpa + 1])
            {
                super = Brray[timpa];
                Brray[timpa] = Brray[timpa + 1];
                Brray[timpa + 1] = super;
            }
        }
    }

    //Transforming Brray[] into sorted Array[][]

    for (int j=0;j<AS;j++)
        for (int i=0;i<AS;i++)
        {
            Brray[w]=Array[i][j];
        }

    w++;

}

Ok so here's my code. All I need done is the sorting part, Ive written the bubble sorting technique, and i double checked my course and it was the same logic. So what I would like to know is why is my array not sorted when I print it out on the screen.
Thank you for your help

A: This
Brray[w]=Array[i][j];
is the wrong way around.
You never actually write into Array.

A: One of the issues you have is that you assumed a total size of AS when implementing the bubble sort algorithm, instead of AS*AS. In addition, your implementation does not even check for when the array is already sorted, leading to unnecessary comparison operaations. Try this:
//Bubble sorting in Brray[]
bool sorted;
int len = AS*AS-1;
do
{
    sorted = true;
    for (int timpa = 0; timpa < len; timpa++)
    {
        if (Brray[timpa]>Brray[timpa + 1])
        {
            super = Brray[timpa];
            Brray[timpa] = Brray[timpa + 1];
            Brray[timpa + 1] = super;
            sorted = false;
        }
    }
    len--;
} while (!sorted);

Furthermore, you have switched the order of the assignment operations, when moving the contents back to the 2D array:
int w = 0;
for (int j=0;j<AS;j++) {
    for (int i=0;i<AS;i++)
    {
      Array[i][j] = Brray[w];
    }
    w++;
}

I would also advise you to split the program's logic into more generic and manageable pieces: two functions to reinterpret a 2D array into a 1D array (and vice-versa), and another for the actual sorting. Both could accept arrays of variable sizes, making it applicable to more problems in the same program. This also applies to the function that fills the array with random numbers.
Another useful piece of advice in the case of C++ is to declare variables about where you need them, rather than stacking them up at the beginning of the function. See the w variable in the code above.

A: There are so many things wrong with this code...
Firstly, your sorting is wrong. This will work
for (int i = 1; i <= AS*AS; i++)
    for (int j = 0; j < (AS*AS - 1); j++)
        if (Brray[j + 1] > Brray[j])  {
            int temp = Brray[j];
            Brray[j] = Brray[j + 1];
            Brray[j + 1] = temp;
        }

Secondly, as others have mentioned, you're not actually updating your 2D array.
for (int j = 0; j < AS; j++)
    for (int i = 0; i < AS; i++)
        Array[j][i] = Brray[w++];

Thirdly, you could have just used std::sort, it's faster than bubble sort, safer, more reliable etc:
std::sort(std::begin(Brray), std::end(Brray));

Fourthly, there are much better alternatives than raw arrays. Use std::vector for example. One of the benefits is that you can have access to .size().
Fifthly, don't use system("pause");. Use std::cin.get(); instead.
Sixthly, rand() is not an accurate way to get uniformly distributed random numbers. Here's a better alternative:
#include <random>

// both min and max inclusive
int rnd(int min, int max) {

    std::random_device rand_dev;                        // create a random device
    std::mt19937 mt(rand_dev());                        // create a mersenne_twister
    std::uniform_int_distribution<int> dist(min, max);  // uniformly distribute between min and max

    return dist(mt);

}

Seventhly, using namespace std; is bad. I will let you do the research to find out why.
There are a few more improvements, but I think there's plenty of work for you already.


text:
Q: Is it possible to have a peer to peer communication using nothing but PHP Is it possible to implement a p2p using just PHP? Without Flash or Java and obviously without installing some sort of agent/client on one's computer.
so even though it might not be "true" p2p, but it'd use server to establish connection of some sort, but rest of communication must be done using p2p
i apologize for little miscommunication, by "php" i meant not a php binary, but a php script that hosted on web server remote from both peers, so each peer have nothing but a browser.

A:
without installing some sort of
  agent/client on one's computer

Each computer would have to have the PHP binaries installed.
EDIT
I see in a different post you mentioned browser based.  Security restrictions in javascript would prohibit this type of interaction

A: No.
You could write a P2P client / server in PHP — but it would have to be installed on the participating computers.
You can't have PHP running on a webserver cause two other computers to communicate with each other without having P2P software installed.
You can't even use JavaScript to help — the same origin policy would prevent it.
JavaScript running a browser could use a PHP based server as a middleman so that two clients could communicate — but you aren't going to achieve P2P.

Since 2009 (when this answer was originally written), the WebRTC protocol was written and achieved widespread support among browsers.
This allows you to perform peer-to-peer between web browsers but you need to write the code in JavaScript (WebAssembly might also be an option and one that would let you write PHP.)
You also need a bunch of non-peer server code to support WebRTC (e.g. for allow peer discovery and proxy data around firewalls) which you could write in PHP.

A: It is non-theoretical because server side application(PHP) does not have peer's system access which is required to define ports, IP addresses, etc in order to establish a socket connection.
ADDITION:
But if you were to go with PHP in each peer's web servers, that may give you what you're looking for.

A: No, not really. PHP scripts are meant to run only for very small amount of time. Usually the default maximum runtime is two minutes which will be normally not enough for p2p communication. After this the script will be canceled though the server administrator can deactivate that. But even then the whole downloading time the http connection between the server and the client must be hold. The client's browser will show in this time its page loading indicator. If the connection breakes most web servers will kill the php script so the p2p download is canceled.
So it may be possible to implement the p2p protocol, but in a client/server scenario you run into problems with the execution model of php scripts.

A: both parties would need to be running a server such as apache although for demonstration purposes you could get away with just using the inbuilt php test server. Next you are going to have to research firewall hole punching in php  I saw a script i think on github but was long time ago . Yes it can be done , if your client is not a savvy programmer type you would probably need to  ensure that they have php installed and running. The path variable may not work unless you add it to the system registry in windows so make sure you provide a bat file that both would ensure the path is in the system registry so windows can find it .Sorry I am not a linux user.
Next  you have to develop the code. There are instrucions for how hole punching works and it does require a server on the public domain which is required to allow 2 computers to find each others ip address. Maybe you could rig up something on a free website such as www.000.webhost.com alternatively you could use some kind of a built in mechanism such as using the persons email address. To report the current ip.
The biggest problem is routers and firewalls but packets even if they are directed at a public ip still need to know the destination on a lan so the information on how to write the packet should be straight forwards. With any luck you might find a  script that has done most of the work for you.

A: Doesn't peer-to-peer communication imply that communication is going directly from one client to another, without any servers in the middle?  Since PHP is a server-based software, I don't think any program you write on it can be considered true p2p.
However, if you want to enable client to client communications with a php server as the middle man, that's definitely possible.

A: Depends on if you want the browser to be sending data to this PHP application.
I've made IRC bots entirely in PHP though, which showed their status and output in my web browser in a fashion much like mIRC. I just set the timeout limit to infinite and connected to the IRC server using sockets. You could connect to anything though. You can even make it listen for incoming connections and handle them.
What you can't do is to get a browser to keep a two-way connection without breaking off requests (not yet anyways...)

A: Yes, but its not what's generally called p2p, since there is a server in between. I have a feeling though that what you want to do is to have your peers communicate with each other, rather than have a direct connection between them with no 'middleman' server (which is what is normally meant by p2p)
Depending on the scalability requirements, implementing this kind of communication can be trivial (simple polling script on clients), or demanding (asynchronous comet server).

A: In case someone comes here seeing if you can write P2P software in PHP, the answer is yes, in this case, Quentin's answer to the original question is correct, PHP would have to be installed on the computer.
You can do whatever you want to do in PHP, including writing true p2p software. To create a true P2P program in PHP, you would use PHP as an interpreted language WITHOUT a web server, and you would use sockets - just like you would in c/c++. The original accepted answer is right and wrong, unless however the original poster was asking if PHP running on a webserver could be a p2p client - which would of course be no.
Basically to do this, you'd basically write a php script that:

*

*Opens a server socket connection (stream_socket_server/socket_create)

*Find a list of peer IP's

*Open a client connection to each peer

*...

*Prove everyone wrong.


text:
Q: Cron Expression not working correctly I've .net windows service which schedules Quartz jobs, I've the following code to start my job at 4 AM every day and repeat every 12 hours. Start time below will be different for each job. The problem here is it is not starting at 4 AM when I say, but it is only running at 12 AM and 12 PM every day. How can I ensure that it starts exactly at the time that I asked it to StartAtTime? If I reduce the value in my cron expression to either 1/2 and change the start time to some 2 PM or 3 PM whatever, it works as expected.
var startAtTime = DateTime.Today.AddHours(localTime[Key]);

if (startAtTime.ToUniversalTime() < DateTime.UtcNow)
{
    startAtTime = startAtTime.AddDays(1);
}

ITrigger objESLJobTrigger = TriggerBuilder.Create()
                           .WithIdentity("ESLTrigger-",             AuditType.ESL.ToString())
                           .StartAt(new DateTimeOffset(startAtTime))
                           .WithCronSchedule("0 0 0/12 ? * SUN-SAT", x => x.WithMisfireHandlingInstructionIgnoreMisfires())
                           .Build();

A: It works as should. See

*

*.StartAt() method defines when start the trigger, not job.

*and your cron expression 0 0 0/12 ? * SUN-SAT means exactly "run job at at 12 AM and 12 PM every day" (you may use cronmaker to check).

Cron Scheduler is not helpful in your case, as it works with intervals in different way that you expect:

/ - used to specify increments. For example, "0/15" in the seconds field means "the seconds 0, 15, 30, and 45". And "5/15" in the seconds field means "the seconds 5, 20, 35, and 50". You can also specify '/' after the '' character - in this case '' is equivalent to having '0' before the '/'. '1/3' in the day-of-month field means "fire every 3 days starting on the first day of the month".

So expression like 0 0 4/12 ? * SUN-SAT will run every 12 hours at 4AM and 4PM. And 0 0 5/12 ? * SUN-SAT will run every 12 hours at 5AM and 5PM. And StartAt() method only define when first job will be triggered (at 4AM or 4PM), it does not do offset for cron expression.
Just use SimpleSchedule instead:
ITrigger objESLJobTrigger = TriggerBuilder.Create()
                           .WithIdentity("ESLTrigger-", AuditType.ESL.ToString())
                           .StartAt(new DateTimeOffset(startAtTime))
                           .WithSimpleSchedule(x => x
                               .WithIntervalInHours(12)
                               .RepeatForever())
                           .Build();


text:
Q: C++ - Sending "Email Attachments" over network I am working on an application that, among other applications, allows users to send emails. It works by writing everything onto an SQL server, so you can have multiple instances of an application.
The email sending currently works with an "Outbox" table on the SQL server, to which application instances directly write the data with SQL statements. I have, however, hit an issue, that a requirement for attachments on the emails has arisen.
My thinking is that if I can send the attached files to a directory on which the SQL server resides (possibly the TEMP directory?), and then store the path to that file (or a UUID, if the file is constant) in the table. The issue is I have no idea particularly where to start with sending the file, as I am still vaguely new to C++.
One term I have come across is sending it with sockets, but am struggling with where to start with it and do not know if it is indeed the best option. Could anyone provide some advice on this matter?
Thanks in advance.

A: If I correctly understand the way it works (applications save the emails to SQL then another application takes them out and sends them) you have two choices:

*

*Save the attachment as binary in the SQL and have the mailer application do the rest.

*Use sockets to transfer the file to the SQL server and save the path to it just as you said.

I'd say option 1 would be the best option if I understood correctly the way its currently working. And as for option 2, there are probably other ways to transfer the file but sockets would be the easily cross-platform option.
Its not hard to get started with sockets, there are a lot of examples all over the internet.

*

*winsock

*more winsock

*sys/socket.h

*more sys/socket.h


text:
Q: No constituent of type 'true | CallableFunction' is callable The full error:
This expression is not callable.
  No constituent of type 'true | CallableFunction' is callable

This is the code that was triggering the error:
public static base(
    text,
    callB: boolean | CallableFunction = false,

  ) {
    const sw = Swal.fire({
      text,
      });

    if (callB) {
      sw.then(callB());
    }
  }

I changed the type of callB to :
 callB: (param: any) => void |boolean = false

and when I remove the callB type definition:
callB= false

I get this error:
This expression is not callable.
  Type 'Boolean' has no call signatures

A: This is what you are looking for:
function base(text: string, callB: false | CallableFunction = false) {
  console.log(text);
  if (callB) {
    callB();
  }
}

Essentially, you want to pass a function or false. When it is truthy you want to call the function.
But as per your definition
function base(text: string, callB: boolean | CallableFunction = false) {
  console.log(text);
  if (callB) {
    callB();
  }
}

this would be a valid call base('some str', true) where callB is true and not a function that it will try to execute using callB(). Not boolean is not callable, it is? Hence the error.
TS Playground link: https://tsplay.dev/m056qW

A: The type
boolean | Function

is equivalent to
true | false | Function

Now because a value of type Function is truthy, your check
if (callB)

narrows the type of callB to
true | Function

and true is not callable, hence the error.
It's not clear how your base method is meant to be used so I've outlined two solutions:
If true isn't a valid input, adjust your parameter type accordingly
static base(
    text,
    callB: false | CallableFunction = false
) {
    if (callB) {
        callB();
    }
}

If true is a case you must handle, use a more precise conditional check such as
if (typeof callB === 'function') {
    callB() // OK
}

A: If you use false | Callablefunction (or boolean | CallableFunction) , you can coerce type by using typeof:
static base(
    text,
    callB: false | CallableFunction = false
) {
    if (typeof callB === "function") {
        callB()
    }
}


text:
Q: this keyword inside addEventListener callback I read some other answer about this topic but I'm not sure I understand how this keyword works inside addEventListener.
const button = document.querySelector('button');

function foo() { console.log(this) }

button.addEventListener('click', foo);

foo is a regular function inside addEventListener, it's not a method on button object. When foo is called should be executed in the context of the global object, therefore this should be equal to window and not to button.
Looks like a situation similar to this example:
const obj = {
  method: function (cb) {
    console.log('method', this); // `this` === `obj`

    return cb();
  }
};

obj.method(function() {
  console.log('cb', this); // `this` === `window`
});

Where obj could be considered as button, method could be addEventListener and cb the callback inside addEventListener.
I know I can use bind to change the context of this but I want to understand more in depth why it works like that.
Why this inside addEventListener callback is invoked on the context of the current element instead of the global object?

A: While we know that event listeners are executed with 'this' set to the event target, the below lines of code inside the EventTarget.prototype.dispatchEvent method in the EventTarget link that you found will answer your question as to how it is implemented.
for (var i = 0, l = stack.length; i < l; i++) {
    stack[i].call(this, event);
}

The 'stack' array has the callback functions and they are invoked using .call by passing in the event target instance (this) and event as arguments.

A: As event handler is a type of callback, they are passed as a parameter to the function. Let's create a simple function and passed one callback as a parameter to it and see how it actually works.
    function testCallBack(fn){
       console.log('inside testCallBack');
       fn('Hello I am a callBack')
    }

    testCallBack(foo);

    function foo(param){
      console.log(param);
    }

// Outputs:
inside testCallBack
Hello I am a callBack

Every scope in JavaScript has a this object that represents the calling object for the function.

That's the reason why this inside addEventListener callback is invoked on the context of the current element instead of the global object.
Refer below code for more clear understanding:
   function sayNameForAll() {
        console.log(this.name);
    }

    var person1 = {
        name: "Rajat",
        sayName: sayNameForAll
    };

    var person2 = {
        name: "pldg",
        sayName: sayNameForAll
    };

    var name = "Sidd";

    person1.sayName();      // outputs "Rajat" here calling object is person1, so this represents person 1
    person2.sayName();      // outputs "pldg"

    sayNameForAll();        // outputs "Sidd"

So when you call button.addEventListner('click',foo), your calling object is button.

A: If we are using functions which have been defined using function keyword as an event handler, then that event handler function executes in the context of the element on which event was binded
button.addEventListener('click', foo);

so, in this case, this value inside foo will be button element.
If we use arrow functions instead of them then this value will be the window object
The reason is this in an arrow function has the same value as the context in which the arrow function was created
button.addEventListener('click', () => { console.log(this) // window } );

More about lexical this
What is lexical 'this'?

A: Event listeners are executed with this set to the object that triggered the event, as one listener can listen to events of many objects.
A regular function invocation however does not set this if the invocation expression does not contain a member access via .. In those cases, without "use strict" active, this will become the global context, which is window in the browser.
If you want this for cb to be obj, you could replace cb() with cb.apply(this), which would set cb's this to that of the enclosing function.
A final warning: these this mechanics only work for functions defined with the function keyword (and similar mechanics). The this inside of an arrow function becomes locked to that of the enclosing scope at the time of definition.

A: Just like you can use bind or call to set this to whatever you want, the browser APIs can also call your functions with any value set to this. It's used in a bunch of weird ways and isn't very consistent. Outside of classes and methods, this is more like a secret extra argument to a function. In this case you could avoid needing it by getting the button element from event.target.


text:
Q: handling ORDER BY and unique attributes in Neo4j I am trying to use the ORDER BY clause and DISTINCT which is not handling well so far
MATCH (p:Project {projectName: "Digital Lab"})
MATCH (p)<-[:PART_OF]-(d)
RETURN d.date, d.prop1, d.prop2, d.prop3 ORDER BY d.date DESC LIMIT 10

Ofcourse this gives me a order by date table. BUT I have 3 unique property values for d.prop1 which repeats
d.date    d.prop1    d.prop2    d.prop3
123       a          123123     c54655
111       a          454565     b75655
110       b          456464     d46546
103       c          454211     e45645
100       c          465562     f45646

Now i would like to get a table which has the newest data according to date and unique prop1 value, which means
d.date    d.prop1    d.prop2    d.prop3
123       a          123123     c54655
110       b          456464     d46546
103       c          454211     e45645

I used this after, but as usual spent many hours with no progess...
MATCH (p:Project {projectName: "Digital Lab"})
MATCH (p)<-[:PART_OF]-(d) WITH DISTINCT d.prop1 AS pro
RETURN d.date, pro, d.prop2, d.prop3 ORDER BY d.date DESC LIMIT 10

I would appreciate help and really looking forward to a solution from this helpful community :)

A: Here a sample data for test purposes:
CREATE (p:Project {projectName : "Digital Lab"})
CREATE (d1 {date: 123, prop1: 'a', prop2: 123123, prop3 : 'c54655'})
CREATE (d2 {date: 111, prop1: 'a', prop2: 454565, prop3 : 'b75655'})
CREATE (d3 {date: 110, prop1: 'b', prop2: 456464, prop3 : 'd46546'})
CREATE (d4 {date: 103, prop1: 'c', prop2: 454211, prop3 : 'e45645'})
CREATE (d5 {date: 100, prop1: 'c', prop2: 465562, prop3 : 'f45646'})
CREATE (p)<-[:PART_OF]-(d1)
CREATE (p)<-[:PART_OF]-(d2)
CREATE (p)<-[:PART_OF]-(d3)
CREATE (p)<-[:PART_OF]-(d4)
CREATE (p)<-[:PART_OF]-(d5)

Tris query should work:
MATCH (p:Project {projectName: "Digital Lab"})<-[:PART_OF]-(d)
WITH d as d ORDER BY d.prop1, d.date DESC
WITH d.prop1 as prop1, collect(d) as items
ORDER BY prop1
RETURN items[0]

The output:
╒════════════════════════════════════════════════════════╕
│"items[0]"                                              │
╞════════════════════════════════════════════════════════╡
│{"prop2":123123,"date":123,"prop1":"a","prop3":"c54655"}│
├────────────────────────────────────────────────────────┤
│{"prop2":456464,"date":110,"prop1":"b","prop3":"d46546"}│
├────────────────────────────────────────────────────────┤
│{"prop2":454211,"date":103,"prop1":"c","prop3":"e45645"}│
└────────────────────────────────────────────────────────┘

A: Can you try this query :
MATCH (p)<-[:PART_OF]-(d)
WITH d.prop1 AS pro,d.date AS date, d
ORDER BY pro, date DESC
WITH collect(d) AS items
WITH items[0] AS d
RETURN d.date, d.prop1, d.prop2, d.prop3 ORDER BY d.date DESC LIMIT 10

Cheers


text:
Q: What happens when the swap folder on your harddrive is full? So this is an "what if" question. It may not happen that often, but I am just curious what happens if it would exactly happen. So in short a computer needs space somewhere to store different thinks before or after an calculation. So you have the cache on the CPU (L1,L2,L3) and then the memory and the last is the HDD/SSD swap folder. So let's say your CPU is full the memory is full then the OS will decide to use the SSD/HDD.
Question: But what will happen when the SSD/HDD is full too?
Where will the OS store it? Is this different in OS'es (like Windows, MAC and linux)? Will the PC/MAC reboot?

A: The OOM killer (http://linux-mm.org/OOM_Killer) will start killing processes. If there are no more processes to be killed, the server simply crashes.


text:
Q: iOS 5: Strange Behaviour of addSubview I'm trying to create an activity indicator in my app. I'm using a storyboard and I have created a button which is pushing another view.
Here is how I open another view:
- (IBAction)openView {
    NSLog(@"View is loading");
    @try {
        UINavigationController *nav = [storyboard instantiateViewControllerWithIdentifier:@"viewOpenSegue"];
        [nav setModalPresentationStyle:UIModalPresentationFullScreen];
        [self presentModalViewController:nav animated:YES];
    }
    @catch (NSException *exception) {
        NSLog(@"Error");
    }
    @finally {
        NSLog(@"View loaded");
    }
}

Everythings good so far. I got the log before view gets opened, and the 2nd log after it is fully loaded.
But when I want to use addSubview method, I am having a weird behavior.
NSArray *subviewArray2 = [[NSBundle mainBundle] loadNibNamed:@"View" owner:self options:nil];
loadingView = [subviewArray2 objectAtIndex:0];

That's how I load my view. And I add/remove like this:
[self.view addSubview:loadingView];
//@try block
//@catch block
//@finally
{
[loadingView removeFromSuperview];
}

I expect the view appear and disappear on screen. But it appears for like 1 millisecond right before pushed view appears then disappear suddenly.
If I add this way under viewDidLoad, it appears.
I have seen similar questions but they didn't help me out. Anyone has a clue? Should I try something else?
Thanks in advance.

A: Does this nib file View.xib have file owner?

A: it happen because first viewdidload execute than viewdidapper method. viewdidappear load every time u push or pop the view so write your code in viewdidload if you want to execute it very first of your view load.

A: It was because I wasn't using a selector. Please refer this question.
Here's the optimized code:
[self.view addSubview:loadingView];
[self performSelector:@selector(openView) withObject:nil afterDelay:0];


text:
Q: Server terminating the process before complete the full execution in PHP I am trying to run a php file through cron job. It starts the running well but after a certain time period,the server is terminating it's execution.
So that I can't get my desired output. I am taking the output in a text file. After start the cron, it store some output into the text file but before completing full execution, it is terminating the process.
I also called mail function at beginning and ending of the file. But I only got the beginning message.
I set the max_time, max_memory to the infinite and also checked the settings from php_info().
Everything is ok there but file is not completing its execution successfully. I am able to run the file through browser but it requires a very long time.
So I must do it with others way like cron. If any one provide me a better solution in this regard, I will be grateful.

A: Turn off safe_mode in php.ini and change maximum execution time by adding

set_time_limit(0)

At the beginning of your script
php set_time_limit function


text:
Q: how to setup dns nameserver in docker permanently in user-defined network? I need define nameserver in /etc/resolv.conf user defined network.
I know that directive --dns is working in default bridge of docker engine.
But I created user defined network.

A: There are two documentation pages describing the different modes
for the bridge mode:
https://docs.docker.com/engine/userguide/networking/default_network/configure-dns/
for the user defined network:
https://docs.docker.com/engine/userguide/networking/configure-dns/
The documentation for user defined network states:
The exact details of how Docker manages the DNS configurations inside the container can change from one Docker version to the next. So you should not assume the way the files such as /etc/hosts, /etc/resolv.conf are managed inside the containers and leave the files alone and use the following Docker options instead.
If you now look at the details of the documentation you'll find out that
--dns will also work in the user defined network mode but that there are more options available and certain default behavior applies.


text:
Q: Error 'integrand() takes 3 positional argumanets, but 4 were given', but I don't see how. Using scipy integration nquad I apologise if this is only a quick answer bug-fix question; hopefully instead I am having a conceptual error from which I can learn.
I am attempting to do an optimization on an integral, so have quite a few functions in my code. When I run it, I get an error

TypeError: integrand() takes 3 positional arguments but 4 were given

corresponding to line 53 of my code:

return integrate.nquad(integrand, [bounds_a(), bounds_x()], args = (t_est))[0]

But from what I understand of the documentation on nquad, what I have written in this line corresponds exactly to 3 arguments: a and x, implicit in giving their limits, and t_est, a vector. Dos it not like the fact that t_est is a  vector?
Code:
#!/usr/bin/env python3

from scipy.optimize import minimize
import numpy as np
from scipy import integrate

#0)Number of covariates:
p=5

#2)Obtain data y (use a mdified algorithm that takes as input the covariate distributions))
def g(z):
    g = np.power((1+np.exp(-z)),-1)
    return g

#betatrue for the values of y and how they depend on the coavriates x
betatrue = [1.3,3.5,2.6,0.9,2.1,1.1]

#)Z distribution
means=0
sigmas=1

#)Function as integral
def integrand(a, x, t_est):
    t0 = t_est[0]
    t1 = t_est[1]
    Z = np.power(a,2)/np.sqrt(2*np.pi*np.power(sigmas,2)) * np.exp(-np.power((a-t0-t1*np.sum(x)),2)/(2*sigmas*sigmas))
    xint = np.append([1.0],x)
    h = g(xint.dot(betatrue))
    px = np.divide(np.exp(-np.divide(np.power((x-means),2),(2*np.power(sigmas,2)))), np.sqrt(2*np.pi*np.power(sigmas)))
    Px = np.multiply(px)
    YV = Px*h
    return YV * Z

#Integration limits

def bounds_x():
    return [-np.inf,np.inf]

def bounds_a():
    return [0,np.inf]

#integration function. If the control is set to 0, gets the integrand. If control is set to 1
#gets the jacobian. Control set to 2, gets the Hessian.
def integration(t_est):
        return integrate.nquad(integrand, [bounds_a(), bounds_x()], args = (t_est))[0]

def integration_jac(t_est):

    def jacobian_integrand(a,x,t_est):
        t0=t_est[0]
        t1=t_est[1]
        j0 = (t0 + t1 * np.sum(x))/np.power(sigmas,2)
        j1 = np.sum(x)*(t0 + t1 * np.sum(x))/np.power(sigmas,2)
        jacintegrands = [integrand(a,x,t_est) * j0, integrand(a,x,t_est) * j1]
        return jacintegrands

    jac0 = integrate.nquad(jacobian_integrand[0], [bounds_a(), bounds_x()], args = (t_est))[0]
    jac1 = integrate.nquad(jacobian_integrand[1], [bounds_a(), bounds_x()], args = (t_est))[0]
    output = [jac0,jac1]
    return output

def integration_hessian(t_est):
    t0=t_est[0]
    t1=t_est[1]

    def hessian_integrand(a,x,t_est):

        h00 = (1 + np.power((t0+t1*np.sum(x)),2))/sigmas*sigmas
        h01 = np.sum(x)*( + np.power((t0+t1*np.sum(x)),2))/sigmas*sigmas
        h11 = np.power(np.sum(x),2)*( + np.power((t0+t1*np.sum(x)),2))/sigmas*sigmas
        Hint = [[integrand(a,x,t_est)*h00,integrand(a,x,t_est)*h01],[integrand(a,x,t_est)*h01,integrand(a,x,t_est)*h11]]
        return Hint

    entry00 = integrand.nquad(hessian_integrand(0,0), [bounds_a(), bounds_x()], args = (t_est))[0]
    entry01 = integrand.nquad(hessian_integrand(0,1), [bounds_a(), bounds_x()], args = (t_est))[0]
    entry11 = integrand.nquad(hessian_integrand(1,1), [bounds_a(), bounds_x()], args = (t_est))[0]
    output = [[entry00,entry01],[entry01,entry11]]

    return output

##And then a maximisation here!
t_est = [0,0]
res = minimize(integration, t_est, method='Newton-CG', jac=integration_jac, hess=integration_hessian, options={'xtol': 1e-8, 'disp': True})

A: Add a trailing comma to make args a one-element tuple: args = (t_est,)


text:
Q: command line; delete static file in a folders who begins with certain character I have hundreds of folders like
170102texta
170204textb
180306textc
180408textd
these folders and many subfolder is the file test.txt present.
I would like to to delete all the "test.txt" files but only in the folders who begins with "17.."
every advice is appreciated :)

A: you just have to run rm -rf {pattern}*
C02XF0N6JG5M:test kkadam$ ls -lrt
total 0
drwxr-xr-x 2 kkadam staff 64 Feb 13 21:00 11test
drwxr-xr-x 2 kkadam staff 64 Feb 13 21:00 11b
drwxr-xr-x 2 kkadam staff 64 Feb 13 21:00 11c
C02XF0N6JG5M:test kkadam$ rm -rf 11*
C02XF0N6JG5M:test kkadam$ ls -lrt
total 0


text:
Q: Electrical issue with USB ? Hi-speed device not working on own design Disclaimer, I'm a SW guy, so please don't take anything for granted, and I would appreciate explanations in layman's terms :)
We have a custom design based on Freescale's i.mx233, and as a reference, we used a board from Olimex called Olinuxino.
On the Olinuxino, they have a dual functioning LAN-USB chip that is unnecessary for our design (we only need 1 USB port for a WiFi dongle), so we figured we can just remove it, and connect a USB device directly to the processors D+ and D- lines.
Because of a separate layout mistake, the USB connector we selected cannot be used in this HW revision. I thought I could verify the design by just cutting a USB extension cable, and soldering it in connectors place, so currently it looks like this:

Now when I connect the WiFi module to the connector, it seems to start enumerating properly, and looking at the signaling, it looks decent as well (I compared to the reference board, and it look very much the same):

However, on the software side, the driver for WiFi is complaining that it is misreading the chipset ID, and refuses to load:
[    2.390000] ieee80211 phy0: rt2x00usb_vendor_request: Error - Vendor Request 0x07 failed for offset 0x1000 with error -
[    2.400000] ieee80211 phy0: rt2800_probe_rt: Error - Invalid RT chipset 0xc37b, rev 5108 detected
[    2.410000] ieee80211 phy0: rt2x00lib_probe_dev: Error - Failed to allocate device

The schematic part for the (original) USB port:

And the actual layout for that part is simple as well (In the picture only top layer, I have hidden all other layers for clarity. I drew the D- signal trace from the bottom layer by hand, please note that in the real picture above the is rotated 180degrees):

The exact same software package and same dongle on our reference board works, and the driver loads..
I started reading the USB2.0 Specification, and in chapter 7, they talk about the electrical signaling, and this part caught my eye:

High-speed operation supports signaling at 480 Mb/s. To achieve reliable signaling at this rate, the cable is
  terminated at each end with a resistance from each wire to ground. The value of this resistance (on each wire) is
  nominally set to 1/2 the specified differential impedance of the cable, or 45 Ω. This presents a differential
  termination of 90 Ω.

Have I screwed up the signaling now with my USB port ? What does this differential impedance mean ? Also, would I have had exact same problem also with the original port since we were planning just to connect the 5V, GND, D+ and D- lines to the connector?
Or is this resistor supposed to be inside each end of the connection inside the silicon ? What could be wrong here ?
Thanks for any advice!
Edit: Added layout and schematic picture for more clarity
Edit 2: I have thrown away my clipped extension cable, and bent the original USB connector and I was able to place it on the board in an bit funny angle.
I also added the necessary drivers to the kernel for USB memories, and I have now verified that my 16GB HighSpeed USB memory works. During boot it is detected:
[    2.240000] usb 1-1: new high-speed USB device number 2 using ci_hdrc
[    2.430000] usb-storage 1-1:1.0: USB Mass Storage device detected
[    2.440000] scsi0 : usb-storage 1-1:1.0
[    3.460000] scsi 0:0:0:0: Direct-Access     UFD 2.0  Silicon-Power16G PMAP PQ: 0 ANSI: 4
[    3.500000] sd 0:0:0:0: [sda] 30283008 512-byte logical blocks: (15.5 GB/14.4 GiB)
[    3.520000] sd 0:0:0:0: [sda] Write Protect is off
<snip>

The flash on the board is very small, but on the USB drive I can copy a 1GB file to another directory, and the speed is around 360KB/sec. The MD5 sum matches, and I dont see any problems using the memory stick.
So, I guess this means that something is now just going wrong with only the WiFi dongle.. it's strange.. If there was corruption on the DP and DM lines, wouldn't I also see corruption during the data transfers ?
Final edit While we haven't been able to pinpoint the problem with 100% certainty, when forcing the controller through registry to only work in 1.1 mode, all USB devices work without any issues, including the WLAN module.
In our next layout we have followed strict differential routing rules, and hopefully this will be the end of our problems :)

A: It's a hard question to answer as this is more of a debugging thing. But I can contribute some ideas as to what you could try.
The first thing I thought was that your pigtail connections (the 1-2cm loose wires coming out of the cable and onto your board) might be too long for 480 MBps operation. Ideas to try:

*

*Force your host to run as USB 1.1 (1.5 or 12 MBps). Maybe you can run it through a USB powered hub or something to force it to the lower speed.

*Use a real USB connector, glue it upside down or something, and make really tight short connections from connector pins to the PCB.

*Maybe you can find a way to cut the cable pigtails length to 1/5 or something in that order.

*Make sure you are not testing with the oscilloscope probe attached.

*Maybe try really short and really long USB cable.

*Maybe try changing temperature (warmer makes the edges slower and colder makes the edges faster).

A note to some comments here: Don't worry about number of vias and the length matching of those PCB traces. Done right, vias and a small bit of length mismatch have never been a problem for USB 2.0. And this is insignificant compared to what you do with the cable pigtails.
Some typical general errors to check for include:

*

*Clocking. Verify clock frequency and jitter is within spec - including any PLL's.

*Power. Verify (with 1-2 GHz BW oscilloscope) that your Vcc ripple is within spec etc.

Also I would not rule out software just yet. Look for differences - like in the config data etc.
And don't be too proud to ask an experienced hardware guy for help :-)
Update - Note on measuring Vcc ripple:
Taken from my answer to this question: How do I verify that my 3.3v power rail meets the requirements for an Ember EM357 SoC?
The best paper I know of that describes how to do this measurement is this one: http://www.electrical-integrity.com/Quietpower_files/Quietpower-21.pdf
In short: Use a coax cable soldered directly to your board. Run the 50R coax into your oscilloscope set to 50R input impedance. Select AC-coupling. A bandwidth that is adequate (minimum 500 MHz). And infinite persistence.
If you make the measurement using a high impedance probe with a long "pig-tail" for ground - you may have extra noise not related to your Vcc noise picked up. When in doubt, always do the null-experiement: touch the probe tip to the ground point, so both tip and ground of the probe touches the same point on the board. If you don't get a flat line, something is being picked up by inductive coupling into the loop formed by probe and ground lead.
So do you have too much noise? Suppose the datasheet of this device calls for 3.3V +/-5% for the Vcc supply. That means you have +/-165mV as the limit. Let's assume you have a 2% accuracy of your 3.3V DC regulator. And let's assume you have a 0-1% distribution drop in the connections between the regulator and the device (cables, connectors, traces, filters etc.). That leaves 2% to the AC-noise/ripple or +/-66mV (132mVpp).

A: You could try tacking the USB cable shield to the USB ground and see if that improves the situation. High speed USB is touchy about things like cable impedance.

A: Hi Regarding your question "What does this differential impedance mean ?"
The differential impedance of the line is actually the resistance of the PCB trace up to the connector, since USB is differential it will be a differential impedance. So a single track impedance of for example D+ will be 45 Ohms and the combined impedance of D+ & D- will be 90Ohm, now just real quick you can't measure this with a simple digital voltmeter (DMV) so you probably won't be able to check this unless you have a TDR somewhere near you.
Regarding your issue, it is not likely to be caused by an impedance mismatch a first sight look at you signal it doesn't seem to be very bad.
If you have questions about electrical testing and problems you can always take a look at http://www.testusb.com/ this is a website me and some of my colleagues wrote.
Could you maybe share a screenshot of your schematic ? So we can take a deeper look here.


text:
Q: Reading in multiple integers from the scanner and assigning each integer to a different variable? I have to read in integers and the scanner has to continue to scan them in until 0 is entered. Then all of those numbers have to be saved to different variables. Then the variables have to be compared and the following has to occur:

*

*Find the smallest integer

*Find how many integers are even

*Find the sum of the negative integers

I have this so far:
public static void main (String[] args)
{
    Scanner in = new Scanner(System.in);
    System.out.println("Enter integers");
    do
    {

    }
    while (in.nextInt() !=0);
}

I am lost on what to do next.

A: There are quite a few issues here, which would be solved if you read the docs for Scanner. Please don't expect people here to simply write your code for you. I'm doing this as an exception.
Your goal is to get the smallest integer, the number of even integers, and the sum of the negative integers. The code will stop running once the number 0 is entered.
public static void main (String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.println("Enter integers");
    int min = Integer.MAX_VALUE; // init to max possible
    int numEven = 0;
    int sumNeg = 0;
    while (true) {
        int val = in.nextInt();
        if(val == 0) // stop if 0 is entered
            break;

        // check small
        min = Math.min(val, min);

        // check even
        if(val % 2 == 0)
            evenNum++;

        // sum negatives
        if(val < 0)
            sumNeg += val;
    }
}


text:
Q: Overlay multiple JSliders in Swing Is it possible to overlay multiple JSliders so I can see the "thumbs" on both (I've tried disabling the painting of the track and setting opacity to false but one still hides the other)? Basically I'd like to create a component that allows the user to define a range (and I didn't really want to write a custom one since it has most of the attributes of a slider). If there is another way I could do that with a slider, that would work too.
thanks,
Jeff

A: Ah, I found it (i must not have been seraching on the right terms). Swing labs as a JXMultiThumbSlider that I think will do the trick.
http://swinglabs.org/hudson/job/SwingX%20Weekly%20Build/javadoc/org/jdesktop/swingx/JXMultiThumbSlider.html

A: I recently had the same problem, I wanted a slider with two thumbs. I didn't get into it too much, and what I ended up doing to get the range is simply putting two sliders and in the "onSliderChange" event listener prevented one beeing smaller than the other and the other bigger than the one. I don't beleive Swing has a two-thumb-Slider, although it might be a cool new feature to add, so I think this is your best bet.

A: JIDE has a RangeSlider with 2 thumbs (and a nice extra one on top to move both thumbs at once (e.g. drag the range around) in their open source common layer: http://www.jidesoft.com/products/oss.htm


text:
Q: How To Measure The Performance Of Map Function In Tensorflow's New DataSet API? I've been using Tensorflow version 1.12 in my GPU instance, I have around 130 TfRecords file containing the ImageNet data which is  1.2 million. First I apply a map function and then flat_map to augment the dataset, which will ultimately be 1.2 million x 2048 images.
self.filenames = tf.placeholder(tf.string, shape=[None])
self.eval_filenames = tf.placeholder(tf.string, shape = [None])
dataset = tf.data.TFRecordDataset(self.filenames)
eval_dataset = tf.data.TFRecordDataset(self.eval_filenames)
print("inside dataset ", dataset.output_shapes)
dataset = dataset.map(self.decode, num_parallel_calls=10)
dataset = dataset.flat_map(self.apply_flip_crop)
dataset = dataset.batch(self.config["batch_size"])
dataset = dataset.prefetch(2)
iterator = dataset.make_initializable_iterator()

Here decode function returns the flattened array of the image and the one-hot encoded label. However, the function passed in flat_map does quite a heavy thing, which is like: two loops to create the slices and reverse of them each producing 1024 tensors. The final output for a single image would be the [2048, 224, 224, 3] tensor. The function looks like this:
   def apply_flip_crop(self, tf_example, lable):
        """
        Calls a helper function random_crop flips which randomly crops and flips
        the images, and returns the agumented tensors.

        Parameters
        ----------
        :param tf_example: A tensor of shape [batchsize, flattedimageshape]
        :type tf_example: Tensors [batchsize, flattedimageshape]
        :param lable: A Constant integer representing the class_id of the image.
        :type lable: tf.int32
        :return: Tensors of shape [flattedimageshape], label of image tf.int32
        :rtype: Tensors

        """

        data = tf.reshape(tf_example, [256, 256, 3])
        data = self.random_crop_flip(data)
        lables = [lable for i in range(2048)]
        return tf.data.Dataset.from_tensor_slices((data, lables))

    def random_crop_flip(self, image):
        """
        Apply random crop and random flip to the image tensor.

        Parameters
        ----------
        :param image: A tensor representing a flattened image array.
        :type image: Tensor of shape [imageflattenedarray]
        :return: List of 2048 tensors of shape [imageflattenedarray]
        :rtype: List

        """
        crops = []

        for i in range(256 - 224):
            for j in range(256 - 224):
                crop = tf.slice(image, [i, j, 0], [224, 224, 3])
                crop2 = tf.reverse(crop, axis=[1])
                crops.append(crop)
                crops.append(crop2)
        return crops

Now the problem is that the training process is very slow. I've read that dataset.from_tensor_slices is quite bad with this kind of need. But I think there are lots of things which can be improved here. For that I need to visualize the performance of each of this operation. Mainly of the flat_map function.
I'm using RunTime Statistic of tensorflow like this:
sess.run(iterator.initializer, feed_dict={data_gen.filenames:
                                                      training_filenames},
                 options=run_options, run_metadata=run_metadata)
next_element = iterator.get_next()
for i in range(1):

     datapoint = sess.run(next_element, options=run_options,
                run_metadata=run_metadata)

      summary_writer.add_run_metadata(run_metadata, 'step%d' % i)

Which does logs the time taken to prepare the dataset, however it doesn't log the time taken to perform the flat_map operation, which is my concern here as I suspect, that is the place where the performance is lagging.

I would appreciate your help regarding both the Performance suggessation as well as the measurement of the time taken in flat_map function.
Thanks in advance.

A: Try to use the TensorFlow's timeline: HowTo profile TensorFlow


text:
Q: What's the redundant data in TCP packet? I am reading "Unix Network Programming" and tcpdump the packet generate by the example. The example is just send out a packet contain string "liha".
I read the TCP/IP RFC and found normal IP header is 20B. and normal TCP header except data is 24B.
So, there are 8B before string "liha" in the captured packet. Are "0121 3d2a 0120 b43e" useless?
11:00:51.690949 IP localhost.40163 > localhost.9877: Flags [P.], seq 94:99, ack 95, win 513, options [nop,nop,TS val 18955562 ecr 18920510], length 5
         0x0000:  4500 0039 ddc6 4000 4006 5ef6 7f00 0001  E..9..@.@.^.....
         0x0010:  7f00 0001 9ce3 2695 8465 e35c 8466 58ca  ......&..e.\.fX.
         0x0020:  8018 0201 fe2d 0000 0101 080a 0121 3d2a  .....-.......!=*
         0x0030:  0120 b43e 6c69 6861 0a                   ...>liha.

A: Those are the TCP options. And your analyzer already parsed them for you:
options [nop,nop,TS val 18955562 ecr 18920510],

They are generally important and used by communication sides to negotiate which extra enhancements can be used for the TCP connection.


text:
Q: A question regarding linear transformation to null space Suppose that $T: \mathbb{R}^3 \to \mathbb{R}^7$ is a linear transformation, and $\begin{bmatrix}3\\-2\\1\end{bmatrix} \in \mathrm{ker}(T)$.
    Show that there is a non-zero linear map $S : \mathbb{R^2} \to \mathbb{R^3}$ so that $T(S(\vec{x})) = \vec{0}$ for all $\vec{x} \in \mathbb{R}^2$.
Thank you very much in advance! I was a little confused about this question. As I know the aim is to find a linear map S with an output $\begin{bmatrix}3\\-2\\1\end{bmatrix}$. But I don't know how to find such specific S or any matrix that can transform any $\vec{x} \in \mathbb{R}^2$ to $\begin{bmatrix}3\\-2\\1\end{bmatrix}$.

A: You could take
$$S=\pmatrix{3 & 0\\-2 & 0\\1& 0}$$


text:
Q: JSSOR - Is it possible to fade in/out bullets/thumbnails when sliding? Like the title says is it possible to fade out bullets or thumbnails when starting to slide and fade in when its stopping with the slide animation? I looked into the development section but can't seem to find anything about it.
At the moment I just always show the thumbnails but it looks weird when the sliding animation is running. It would be great if there's a way to do this without to much custom code.

A: Given you have a bullet navigator element as follows,
<div u="navigator" class="jssorb03" ...>
...
</div>

You can make it fade out while swipe start, and fade in while swipe end.
function SwipeStartEventHandler(position) {
    if(Math.floor(position) == position)
        $(".jssorb03").fadeOut();
}

function SwipeEndEventHandler(position) {
    if(Math.floor(position) == position)
        $(".jssorb03").fadeIn();
}

jssor_slider1.$On($JssorSlider$.$EVT_SWIPE_START, SwipeStartEventHandler);
jssor_slider1.$On($JssorSlider$.$EVT_SWIPE_END, SwipeEndEventHandler);


text:
Q: Is it possible this way? Letting computer to guess my number I want pc to find the number in my mind with random function "every time"
so i tried something but not sure this is the correct direction and its not working as intended
how am i supposed to tell pc to guess higher than the previous guess
ps:code is not complete just wondering is it possible to do this way
def computer_guess():
myguess = int(input("Please enter your guess: "))
pcguess = randint(1, 10)
feedback = ""
print(pcguess)
while myguess != pcguess:
    if myguess > pcguess:
        feedback = input("was i close?: ")
        return feedback, myguess
while feedback == "go higher":
    x = pcguess
    pcguess2 = randint(x, myguess)
    print(pcguess2)

A: I wrote this a few years ago and it's similar to what you're trying to do except this only asks for user input once then calls random and shrinks the range for the next guess until the computer guess is equal to the user input.
import random
low = 0
high = 100
n = int(input(f'Chose a number between {low} and {high}:'))
count = 0
guess = random.randint(0,100)
lower_guess = low
upper_guess = high
while n != "guess":

    count +=1

    if guess < n:
        lower_guess = guess+1
        print(guess)
        print("is low")
        next_guess = random.randint(lower_guess , upper_guess)
        guess = next_guess

    elif guess > n:
        upper_guess = guess-1
        print(guess)
        print("is high")
        next_guess = random.randint(lower_guess , upper_guess)
        guess = next_guess

    else:
        print("it is " + str(guess) + '. I guessed it in ' + str(count) + ' attempts')

        break


text:
Q: What's the best distro/shell-agnostic way to set environment variables? The question says it all. I currently use Arch Linux and the zsh, but I'd like a solution that (at minimum) works both on VTs and in xterms and also (hopefully, preferably) will continue to work if I switch distros or shells.
I've heard wildly disparate answers to this question in different distros' docs. Ubuntu says "use .pam_environment". I think in Arch what they recommend depends on your shell. Currently I put everything in .profile and if a shell doesn't source that for some reason (e.g. bash if .bash_profile exists), I override that by manually sourcing it. But it seems like there must be a better way.

A: As far as I know there exists no distro and shell agnostic standard how to set environment variables.
The most common and de facto standard seems to be /etc/profile and ~/.profile. The second most common seems to be /etc/environment and ~/.pam_environment.
It seems to me that all documentation that I found you also already found. I list them here anyway for the other readers.

*

*Debian recommends /etc/profile and ~/.profile (link).

*Ubuntu recommends /etc/environment and ~/.pam_environment (link).

*Arch Linux mentions, among others, /etc/profile and /etc/environment (link).

Bonus: a text questioning the use and/or misuse of /etc/environment in debian (link, last update 2008).

A: There is unfortunately no fully portable location to set environment variables. The two files that come closest are ~/.profile, which is the traditional location and works out of the box on many setups, and ~/.pam_environment, a modern, commonplace but limited alternative.
What to put in ~/.pam_environment
The file ~/.pam_environment is read by all login methods that use PAM and that have this file enabled. This covers most Linux systems nowadays.
The major advantage of ~/.pam_environment is that (when enabled) it is read before the user's shell starts, so it works regardless of the session type, login shell and other complexities. It even works for non-interactive logins such as su -c somecommand and ssh somecommand.
The major limitation of ~/.pam_environment is that you can only put simple assignments there, not complex shell syntax. The syntax of this file is as follows.

*

*Files are parsed line by line.

*Each line must have the form VAR=VALUE where VAR consists of letters, digits and underscores. The alternative form VAR DEFAULT=value allows expansions of environment variables using ${VAR} syntax and the special variables @{HOME} and @{SHELL}.

*# starts a comment, it cannot appear in a value.

*If VALUE is surrounded by ", then VAR is set to the string between the quotes.

*\$ or \@ insert a literal $ or @ and long lines can be split by escaping the newline with a \.

*If there is a syntax error such as no = or unquoted whitespace, the variable is removed from the environment.

So on the upside, ~/.pam_environment works in a large array of circumstances. On the downside, you cannot use the output of a command (e.g. test if a directory or program is present), and some characters (#", newline) are impossible or troublesome to put in the value.
What to put in ~/.profile
This file should have portable (POSIX) sh syntax. Only use ksh or bash extensions (arrays, [[ … ]], etc.) if you know that your system has these shells as /bin/sh.
This file may be read by scripts in automated applications, so it should not call programs that produce any output or call exec. If you want to do that on text-mode logins, do it only for interactive shells. Example:
case $- in *i*)
  # Display a message if I have new mail
  if mail -e; then echo 'You have new mail'; fi
  # If zsh is available, and this looks like a text-mode login, run zsh
  case "`ps $PPID` " in
    *" login "*)
      if type zsh >/dev/null 2>/dev/null; then exec zsh; fi;;
  esac
esac

This is an example of using /bin/sh as your login shell and switching to your favorite shell. See also how can I use bash as my login shell when my sysadmin refuses to let me change it
When is ~/.profile not read on non-graphical login?
Different login shells read different files.
If your login shell is bash
Bash reads ~/.bash_login or ~/.bash_profile if they exist instead of ~/.profile. Also bash does not read ~/.bashrc in a login shell even if it is interactive. To never have to remember these quirks again, create a ~/.bash_profile with the following two lines:
. ~/.profile
case $- in *i*) . ~/.bashrc;; esac

See also Which setup files should be used for setting up environment variables with bash?
If your login shell is zsh
Zsh reads ~/.zprofile and ~/.zlogin, but not ~/.profile. Zsh has a different syntax from sh, but can read ~/.profile in sh emulation mode. You can use this for your ~/.zprofile:
emulate sh -c '. ~/.profile'

See also Zsh not hitting ~/.profile
If your login shell is some other shell
There's not much you can do there, short of using /bin/sh as your login shell and your favorite shell (such as fish) as an interactive shell only. That's what I do with zsh. See above for an example of invoking another shell from ~/.profile.
Remote commands
When invoking a remote command without going through an interactive shell, not all shells read a startup file.
Ksh reads the file specified by the ENV variable, if you manage to pass it.
Bash reads ~/.bashrc if it is not interactive (!) and its parent process is called rshd or sshd. So you can start your ~/.bashrc with
if [[ $- != *i* ]]; then
  . ~/.profile
  return
fi

Zsh always reads ~/.zshenv when it starts. Use with caution, since this is read by every single instance of zsh, even when it is a subshell where you've set other variables. If zsh is your login shell and you want to use it to set variables only for remote commands, use a guard: set some variable in ~/.profile, such as MY_ENVIRONMENT_HAS_BEEN_SET=yes, and check this guard before reading ~/.profile.
if [[ -z $MY_ENVIRONMENT_HAS_BEEN_SET ]]; then emulate sh -c '~/.profile'; fi

The case of graphical logins
Many distributions, display managers and desktop environments arrange to run ~/.profile, either by explicitly sourcing it from the startup scripts or by running a login shell.
Unfortunately, there is no general method to handle distro/DM/DE combinations where ~/.profile is not read.
If you use a traditional session started by ~/.xsession, this is the place where you should set your environment variables; do it by sourcing ~/.profile (i.e. . ~/.profile). Note that in some setups, the desktop environment startup scripts will source ~/.profile again.

A: I added the following script ~/bin/agnostic_setenv:
#!/bin/csh -f
set args = ($*)
if ($#args == 1) then
   echo "export $args[1]="
   exit 0
endif

if ($#args == 2) then
   if ("$args[1]" =~ *csh*) then
      echo "setenv $args[2]"
      exit 0
   else
      echo "export $args[1]=$args[2]"
      exit 0
   endif
endif

echo "setenv $args[2] $args[3]"

And in ~/.perl-homedir I use:
eval `${HOME}/bin/agnostic_setenv $shell PERL_HOMEDIR 0`

A Similiar script for agnostic_unsetenv:
#!/bin/csh -f
set args = ($*)
if ($#args == 1) then
   echo "export $args[1]"
   exit 0
endif

echo "unsetenv $args[2]"
exit 0

A: If you use systemd-homed, you should be able to use homectl to set environment variables for your user account regardless of your shell.
The following command sets the EDITOR environment variable this way.
homectl update username --setenv=EDITOR=/usr/bin/vim


text:
Q: How to create node js https (Windows) I want to create API call by HTTPS and binding port with IIS (not sure to related?)
I've to try like:
var pk = fs.readFileSync('privatekey.pem');
var pc = fs.readFileSync('cert.crt');
var opts = { key: pk, cert: pc };

var serv = https.createServer(opts, function(req, res) {
  console.log(req);
});
serv.listen(5000, "hostname.com", () => console.log("run server"));

or
var httpOptions = {
  key: fs.readFileSync("privatekey.pem"),
  cert: fs.readFileSync("cert.crt")
};

https.createServer(httpOptions, function (req, res) {
  res.writeHead(200);
  res.end("run server");
}).listen(5000, "hostname.com");

but I have an error:
Error: listen EADDRNOTAVAIL: address not available **hostname:port**

How can I do?

A: Try this:
server.listen(5000, '127.0.0.1');

The server.listen() is an inbuilt application programming interface of class Socket within tls module which is used to start the server to listen the encrypted connection.
host: It's the unspecified IPv4 address.


text:
Q: Is it possible to warp the underlying image with OpenGL ES 2.0? I have an Android 4.0 application that uses the GL_OES_EGL_image_external method of rendering video as an OpenGL surface. That works great. In addition, I would like to stretch/warp a few patches on top of that. I'm currently shading those areas I would like to warp with some additional shaders on some quads on top of those areas. I'm stuck on how to get the underlying color. How does the shader on my quad on top of the video quad warp the underlying image? Is it possible?

A: I'm on iOS, but my app does something very similar.
How I've achieved it is based on some sample code from Apple (look at the RippleModel.m in particular). How it works is that it places the video texture video not on a quad, but on a highly tessellated grid, so you've got a ton of triangles with a ton of texture coordinates. It creates the vertices of this grid programmatically -- and more importantly, it creates the texture coordinates programmatically as well -- and holds them in an array.
For each frame, it iterates through all the vertices and updates the texture coordinates for each, 'warping' them in a ripple pattern, based on where the user has touched, and based on how much texture offset the surrounding vertices have. So the geometry isn't changed at all, and they don't perform the warp in the shader, it's all done in the texture coordinates; the shader is then just doing the straight texture lookup on the coordinates it has received.
So it's hard to say if this approach will work for your needs, but if your warps only happen in 2d, and if you can figure out how to define your warp as texture coordinate adjustments, this may help.


text:
Q: JQuery Load not able to pass value to the controller I am trying to pass a complex object to the controller through ajax Load(), however im getting a null object on the controller.
Ive seen some questions on this however they are on codeIgniter, I am using MVC.NET
Here's my code :
$('#btnLoadMore').on('click', function () {
        dataObject.PageIndex = dataObject.PageIndex + 1;
        $("#viewPlaceHolder").load("/home/GetPagedData",
       { data: JSON.stringify(dataObject), contentType: 'application/json', type: 'post' });
    });

and this code below which is on the search click button is working fine.
$('#btnSubmit').on('click', function () {
        var startDate = $('#StartDate').val();
        var endDate = $('#EndDate').val();
        dataObject= {
            'UserId': 1,
            'PageIndex': pageIndex,
            'PageSize': pageSize,
            'StartDate': startDate,
            'EndDate': endDate
        };
        $.ajax({
            url: '@Url.Action("GetPagedData", "Home")',
            contentType: 'application/json',
    type: 'post',
    cache: false,
    async: true,

    data: JSON.stringify(dataObject)
    ,
    success: function (result) {
        $('#pricing-table').html(result);
        window.location = "#pricing";

    }
    });
    });

A: From jQuery Load article:

The POST method is used if data is provided as an object; otherwise,
  GET is assumed.

You can provide in load method only url, data, complete callback parameters.
So your code should looks like this:
$('#btnLoadMore').on('click', function () {
    dataObject.PageIndex = dataObject.PageIndex + 1;
    $("#viewPlaceHolder").load("@Url.Action("GetPagedData","Home")",
    dataObject);
});


text:
Q: Whats wrong in given caml query? I am trying to get the data based on some datetime string using CAML query.
Here is my CAML query:
<View>
    <Query>
        <Where>
            <And>
                <Le>
                    <FieldRef Name='StartDateTime'/>
                    <Value Type='DateTime' IncludeTimeValue='TRUE'>2017-03-23T05:20:00.000Z</Value>
                </Le>
                <Ge>
                    <FieldRef Name='EndDateTime'/>
                    <Value Type='DateTime' IncludeTimeValue='TRUE'>2017-03-23T05:20:00.000Z</Value>
                </Ge>
            </And>
        </Where>
    </Query>
</View>

When I am passing the value of date-time in ISO string it gives me error "500 (Internal Server Error)"
If I pass date without converting to ISO string it gives no result.
I am using SharePoint Online, my current timezone in regional setting is set to India.

A: It works for my list. You just check the internal name of the fields StartDateTime and EndDateTime and date format mention in the value section in query 2017-03-23T12:00:00Z
I think you mention Le instead of Lt(less than)/Leq(less than or equal) and Ge instead of Gt(greater than)/Geq(greater than or equal) and . in this 2017-03-23T05:20:00.000Z
see below my example.
<View>
    <Query>
        <Where>
            <And>
                <Lt>
                    <FieldRef Name='StartDateTime' />
                    <Value Type='DateTime' IncludeTimeValue='TRUE'>2017-03-23T12:00:00Z</Value>
                </Lt>
                <Gt>
                    <FieldRef Name='EndDateTime' />
                    <Value Type='DateTime' IncludeTimeValue='TRUE'>2017-03-23T12:00:00Z</Value>
                </Gt>
            </And>
        </Where>
    </Query>
    <ViewFields>
        <FieldRef Name='StartDateTime' />
        <FieldRef Name='EndDateTime' />
    </ViewFields>
</View>

A: The operators "Le" & "Ge" are not valid. It needs to either "Lt"/"Gt" (Less than/Greater than) OR "Leq"/"Geq" (Less than or Equal/Greater than or equal").
Also, it may be that, one would use "Geq"/"Gt" with Start Date and "Leq"/"Lt" with End date.


text:
Q: What is the best way to auto generate getters and setters for a class in php? I regularly create a class that has a few private variables.
When an instance of this class is set, it should be possible to fill all variables of the class with getters and setters.
Is there an easy way to do this without having to type all these setters and getters for each variable on creation of the class?
now i have to type this for each var in the class
public function setVar($var){
$this->var = $var;
}

and
public function getVar(){
return $this->var;
}

We now use RegExp, but i don't know if this is the easiest way...
We use Eclipse as environment, so perhaps there are some usefull plugins?

A: With Eclipse go to Preferences -> PHP -> Editor -> Templates -> New and use something like this:
/**
 * Method to get the ${PropertyName}
 *
 * @return  ${ReturnType}  return the ${PropertyName}.
 *
 * @since   __DEPLOY_VERSION__
*/
public function get${MethodName}() {
  return $$this->${PropertyName};
}

/**
 * Method to set the ${PropertyName}
 *
 * @return  boolean  True on success and false on failed case
 *
 * @since   __DEPLOY_VERSION__
*/
public function set${MethodName}($$value) {
  $$this->${PropertyName} = $$value;
}

To use the template type its name and press ctrl+space - a context menu should also automatically appear when you type the name.

A: Have you looked at the __set and __get methods? Don't know if this is what you mean but the are automatically called whenever a class member is SET or Retrieved/Fetched/Accessed.

A: Zend Studio has a feature of automatic getter/setter generation.

A: I think the best way is to use the __set and __get with some string functions, Here let me show you.
class UserProfile
{
    public function __get($key)
    {
        if(isset($this->$key))
        {
            return $this->$key;
        }
    }

    public function __set($key,$val)
    {
        $this->cahnge($key,$val);
    }

    public function __call($key,$params)
    {
        if(substr("set",$key))
        {
            //Update
        }elseif(substr("get",$key))
        {
            //return
        }

        //Else Blah
    }

    private function change($key,$val)
    {
        if(isset($this->$key))
        {
            $this->$key = $val;
        }
    }
}

the __call() method will allow you to set with functions such as
$profile->setUsername('Robert Pitt'); as long as you substr the set/get and check for the rest of the string as a value of the class :)
another example
public function __call($method,$params = array())
{

    if(isset($params[0]) && is_string($params[0]))
    {
        $this->$method = $params[0];
    }
}

//....

$profile->username('Robert Pitt');

Theres more work to be done here

A: Maybe better sollution:
class base {

    protected $_vars = array();

    public function setVar($name, $value = null) {
        $this->_vars[$name] = $value;
    }

    public function getVar($name) {
        return isset($this->_vars[$name]) ? $this->_vars[$name] : null;
    }
}

And simply extend this class. Or also you can use __set and __get methods, but they are quite slower.


text:
Q: arm-none-eabi-gcc "is not implemented and will always fail" messages I have two stm32 projects (one with stm32f103rb and the other with stm32f103re). Both projects are built using cmake and make based on stm32-cmake template and also use cubeMX HAL libraries. For both projects I use this printf library and overall structure of the source code and implemented functions are similar.
When I build the projects, I get these linker messages, but only in the 103re project and not the other one (both project build completely):
usr/lib/gcc/arm-none-eabi/12.2.0/../../../../arm-none-eabi/bin/ld: /usr/lib/gcc/arm-none-eabi/12.2.0/../../../../arm-none-eabi/lib/thumb/v7-m/nofp/libc_nano.a(libc_a-closer.o): in function `_close_r':
/build/arm-none-eabi-newlib/src/build-nano/arm-none-eabi/thumb/v7-m/nofp/newlib/../../../../../../newlib-4.3.0.20230120/newlib/libc/reent/closer.c:47: warning: _close is not implemented and will always fail
/usr/lib/gcc/arm-none-eabi/12.2.0/../../../../arm-none-eabi/bin/ld: /usr/lib/gcc/arm-none-eabi/12.2.0/../../../../arm-none-eabi/lib/thumb/v7-m/nofp/libc_nano.a(libc_a-lseekr.o): in function `_lseek_r':
/build/arm-none-eabi-newlib/src/build-nano/arm-none-eabi/thumb/v7-m/nofp/newlib/../../../../../../newlib-4.3.0.20230120/newlib/libc/reent/lseekr.c:49: warning: _lseek is not implemented and will always fail
/usr/lib/gcc/arm-none-eabi/12.2.0/../../../../arm-none-eabi/bin/ld: /usr/lib/gcc/arm-none-eabi/12.2.0/../../../../arm-none-eabi/lib/thumb/v7-m/nofp/libc_nano.a(libc_a-readr.o): in function `_read_r':
/build/arm-none-eabi-newlib/src/build-nano/arm-none-eabi/thumb/v7-m/nofp/newlib/../../../../../../newlib-4.3.0.20230120/newlib/libc/reent/readr.c:49: warning: _read is not implemented and will always fail
/usr/lib/gcc/arm-none-eabi/12.2.0/../../../../arm-none-eabi/bin/ld: /usr/lib/gcc/arm-none-eabi/12.2.0/../../../../arm-none-eabi/lib/thumb/v7-m/nofp/libc_nano.a(libc_a-writer.o): in function `_write_r':
/build/arm-none-eabi-newlib/src/build-nano/arm-none-eabi/thumb/v7-m/nofp/newlib/../../../../../../newlib-4.3.0.20230120/newlib/libc/reent/writer.c:49: warning: _write is not implemented and will always fail

What's the reason for these messages? and why the compiler behavior is different in two project?
PS: this wasn't the case couple of weeks ago and it happens recently probably after an update or something.
❮ pacman -Q | grep arm-none-eabi
arm-none-eabi-binutils 2.39-2
arm-none-eabi-gcc 12.2.0-1
arm-none-eabi-gdb 13.1-1
arm-none-eabi-newlib 4.3.0.20230120-1

Edit 1:
build flags, in gcc-arm-none-eabi.cmake module:
set(CMAKE_C_FLAGS_INIT
    "-fdata-sections -ffunction-sections --specs=nano.specs --specs=nosys.specs -Wl,--gc-sections")

compile options in CMakeLists.txt:
target_compile_options(${EXECUTABLE} PRIVATE
    ${CPU_PARAMETERS}
    -Wall
    -Wextra
    -Wpedantic
    -Wshadow
    -Wdouble-promotion
    -Wformat=2 -Wformat-truncation
    -Wundef
    -fno-common
    -Wno-unused-parameter
    $<$<COMPILE_LANGUAGE:CXX>:
        -Wconversion
        -Wno-volatile
        -Wold-style-cast
        -Wuseless-cast
        -Wsuggest-override>
    $<$<CONFIG:Debug>:-Og -g3 -ggdb>
    $<$<CONFIG:Release>:-Og -g0>)

and linker flags in CMakeLists.txt file:
target_link_options(${EXECUTABLE} PRIVATE
    -T${MCU_LINKER_SCRIPT}
    ${CPU_PARAMETERS}
    -Wl,-Map=${CMAKE_PROJECT_NAME}.map
    -Wl,--start-group
    -lc
    -lm
    -lnosys
    -lstdc++
    -Wl,--end-group
    -Wl,--print-memory-usage)

All these options are identical in both files
Edit 2:
Output of make VERBOSE=1 for one of the source files in both projects. I checked with vimdiff and they are identical (except -DSTM32F103xE which is -DSTM32F103xB on the other project:
[  3%] Building C object CMakeFiles/ap-v0.2-22-gd2cd.dir/Core/Src/dma.c.obj
/usr/bin/arm-none-eabi-gcc -DSTM32F103xE -DUSE_HAL_DRIVER -I/home/mehdi/wrk/code/ap -isystem /home/mehdi/wrk/code/ap/Core/Inc -isystem /home/mehdi/wrk/code/ap/Drivers/STM32F1xx_HAL_Driver/Inc -isystem /home/mehdi/wrk/code/ap/Drivers/STM32F1xx_HAL_Driver/Inc/Legacy -isystem /home/mehdi/wrk/code/ap/
Drivers/CMSIS/Device/ST/STM32F1xx/Include -isystem /home/mehdi/wrk/code/ap/Drivers/CMSIS/Include -fdata-sections -ffunction-sections --specs=nano.specs --specs=nosys.specs -Wl,--gc-sections -g -mcpu=cortex-m3 -mthumb -Wall -Wextra -Wpedantic -Wshadow -Wdouble-promotion -Wformat=2 -Wformat-truncati
on -Wundef -fno-common -Wno-unused-parameter -Og -g3 -ggdb -std=gnu11 -MD -MT CMakeFiles/ap-v0.2-22-gd2cd.dir/Core/Src/dma.c.obj -MF CMakeFiles/ap-v0.2-22-gd2cd.dir/Core/Src/dma.c.obj.d -o CMakeFiles/ap-v0.2-22-gd2cd.dir/Core/Src/dma.c.obj -c /home/mehdi/wrk/code/ap/Core/Src/dma.c

link command:
[100%] Linking C executable ap-v0.2-22-gd2cd.elf
/usr/bin/cmake -E cmake_link_script CMakeFiles/ap-v0.2-22-gd2cd.dir/link.txt --verbose=1
/usr/bin/arm-none-eabi-gcc -fdata-sections -ffunction-sections --specs=nano.specs --specs=nosys.specs -Wl,--gc-sections -g -T/home/mehdi/wrk/code/ap/CubeMX/STM32F103RETx_FLASH.ld -mcpu=cortex-m3 -mthumb -Wl,-Map=ap.map -Wl,--start-group -lc -lm -lnosys -lstdc++ -Wl,--end-group -Wl,--print-memory-u
sage "CMakeFiles/ap-v0.2-22-gd2cd.dir/Core/Src/dma.c.obj" ... all other sources

search results for _write_r in .map file:
in stm32f103rb project:
/usr/lib/gcc/arm-none-eabi/12.2.0/../../../../arm-none-eabi/lib/thumb/v7-m/nofp/libc_nano.a(libc_a-writer.o)
                              /usr/lib/gcc/arm-none-eabi/12.2.0/../../../../arm-none-eabi/lib/thumb/v7-m/nofp/libc_nano.a(libc_a-stdio.o) (_write_r)

 .text._write_r
                0x0000000008008c8c       0x24 /usr/lib/gcc/arm-none-eabi/12.2.0/../../../../arm-none-eabi/lib/thumb/v7-m/nofp/libc_nano.a(libc_a-writer.o)
                0x0000000008008c8c                _write_r

in stm32f103re project:
/usr/lib/gcc/arm-none-eabi/12.2.0/../../../../arm-none-eabi/lib/thumb/v7-m/nofp/libc_nano.a(libc_a-writer.o)
                              /usr/lib/gcc/arm-none-eabi/12.2.0/../../../../arm-none-eabi/lib/thumb/v7-m/nofp/libc_nano.a(libc_a-stdio.o) (_write_r)

 .text          0x0000000000000000        0x0 /usr/lib/gcc/arm-none-eabi/12.2.0/../../../../arm-none-eabi/lib/thumb/v7-m/nofp/libc_nano.a(libc_a-writer.o)
 .data          0x0000000000000000        0x0 /usr/lib/gcc/arm-none-eabi/12.2.0/../../../../arm-none-eabi/lib/thumb/v7-m/nofp/libc_nano.a(libc_a-writer.o)
 .bss           0x0000000000000000        0x0 /usr/lib/gcc/arm-none-eabi/12.2.0/../../../../arm-none-eabi/lib/thumb/v7-m/nofp/libc_nano.a(libc_a-writer.o)
 .text._write_r