text:
Q: How to evaluate $\int_0^{2\pi} \frac{d\theta}{A+B\cos\theta}$? I'm having a trouble with this integral expression:
$$\int_0^{2\pi} \frac{d\theta}{A+B \cos\theta}$$
I've done this substitution: $t= \tan(\theta/2)$
and get: $\displaystyle \cos\theta= \frac{1-t^2}{1+t^2}$ and $\displaystyle d\theta=\frac{2}{1+t^2}dt$ where $\displaystyle \cos^2\theta/2=\frac{1}{1+t^2}$
then the integral becomes:
$$\int\frac{2 \, dt}{(A-B)t^2+(A+B)}= \sqrt\frac{A+B}{A-B} \arctan \left(\left(\sqrt\frac{A+B}{A-B} \right) t\right)$$
However, I'm not sure about the new limits since $\tan$ has period $\pi$ so what I have to do at this point to decide the new limits? And of course if you find some mistake in what I've done before, please let me know!

A: Ideally, you want to do your substitution on a domain where it is defined, continuous, and invertible.
That's not quite true here, as this plot shows.
But we can carefully break the domain up into parts where the substitution behaves nicely, sort of, by splitting $\theta \in [0, 2 \pi]$ into two regions $\theta \in [0, \pi]$ and $\theta \in [\pi, 2 \pi]$. Note that we really should break the integral up into two integrals, one over each domain.
Over $\theta \in [0,\pi]$, $t$ varies from $0$ to $+\infty$; so the substitution is problematic! However, you can still set up the improper integral, and take care to show that it converges to the right thing.
You can treat $\theta \in [\pi, 2\pi]$ similarly.
Of course, once you've set that up, it's clear you can put the integrals back together, since $\int_0^{+\infty} f + \int_{-\infty}^0 f = \int_{-\infty}^{+\infty} f$. You could have observed this by changing the original limits of integration from $[0, 2\pi]$ to $[-\pi, \pi]$ because the integrand was periodic.
P.S. there's one extra problem with your integral: the integrand diverges at the $\theta$ where $A + B \cos \theta = 0$. Such solutions exist if $|A| \leq |B|$. So you have to handle the improperness of that as well. (notice that your solution method for the transformed integral assumes this, and possibly more)

A: To avoid confusion with limits, note that
$$\int_0^{\pi} \dfrac{dx}{a+b \cos(x)} = \int_{\pi}^{2\pi} \dfrac{dx}{a+b \cos(x)}$$
Hence, we have
$$I = \int_0^{2\pi} \dfrac{dx}{a+b \cos(x)} = 2\int_0^{\pi} \dfrac{dx}{a+b \cos(x)}$$
Now use your substitution $t = \tan(x/2)$ and note that $t$ goes from $0$ to $\infty$ as $x$ goes from $0$ to $\pi$.
EDIT
An easier way if you are familiar with a little bit of complex analysis is as follows.
Let $z = e^{ix}$. Then we have that $dz = iz dx$. Hence,
\begin{align}
I & = \int_0^{2 \pi} \dfrac{dx}{a+b \cos(x)} = \oint_{\vert z \vert = 1} \dfrac{dz}{iz \left( a + \dfrac{b}2 \left(z+ \dfrac1z \right)\right)}\\
& = \dfrac1i \oint_{\vert z \vert = 1} \dfrac{dz}{az + \dfrac{b}2 \left(z^2+1 \right)} = \dfrac2{ib} \oint_{\vert z \vert = 1}\dfrac{dz}{z^2 + \dfrac{2a}b z + 1}\\
& = \dfrac2{ib} \oint_{\vert z \vert = 1} \dfrac{dz}{\left(z + \dfrac{a}b \right)^2 + 1 - \dfrac{a^2}{b^2}} = \dfrac2{ib} \oint_{\vert z \vert = 1} \dfrac{dz}{\left(z + r + \sqrt{r^2-1} \right)\left(z + r - \sqrt{r^2-1} \right)}
\end{align}
where $r = \dfrac{a}b \in \mathbb{R}$.
First note that if $\vert r \vert \leq 1$, then $\left \vert r \pm \sqrt{r^2-1} \right \vert = 1$. Hence, the integral doesn't exist.
If $r > 1$, then $ \left \vert r + \sqrt{r^2 - 1} \right \vert > 1$ and $\left \vert r - \sqrt{r^2-1} \right \vert < 1$. Hence, by Cauchy integral formula, we have that
$$I = \dfrac{2}{ib} 2 \pi i \dfrac1{2 \sqrt{r^2-1}} = \dfrac{2 \pi \, \text{sign}(a)}{\sqrt{a^2 - b^2}}$$
If $r < -1$, then $\left \vert r - \sqrt{r^2 - 1} \right \vert > 1$ and $\left \vert r + \sqrt{r^2-1} \right \vert < 1$. Hence, by Cauchy integral formula, we have that
$$I = \dfrac{2}{ib} 2 \pi i \dfrac{-1}{2 \sqrt{r^2-1}} = \dfrac{2 \pi \, \text{sign}(a)}{\sqrt{a^2 - b^2}}$$
Hence, to summarize,
$$I = \begin{cases} \dfrac{2 \pi \, \text{sign}(a)}{\sqrt{a^2 - b^2}} & \text{if } \vert a \vert > \vert b\\ \text{Does not exists} & \text{if } \vert a \vert \leq \vert b\end{cases}$$

A: By periodicity and parity of $\cos$
$$
\int\limits_0^{2\pi} \dfrac{d\theta}{A+B\cos\theta}=\int\limits_{-\pi}^{\pi} \dfrac{d\theta}{A+B\cos\theta}=2\int\limits_0^{\pi} \dfrac{d\theta}{A+B\cos\theta}
$$

A: As $\theta$ goes from $0$ to $2\pi$, $\theta/2$ goes from $0$ to $\pi$, so $\tan(\theta/2)$ goes from $0$ up to $+\infty$ and then from $-\infty$ up to $0$.  Add the two together and you get $\displaystyle\int_{-\infty}^\infty$.


text:
Q: Presetting currentIndex in QML TreeView I'm using QML TreeView to list some categorized options for user to select.
Using property TreeView.selection I have assigned SlectionModel to the treeview.
I have a problem with preselecting the item. Using
treeView.selection.setCurrentIndex(idx,3)
I only set the properties of the selection model(the item gets correctly selected/higlighted), but treeView.currentIndex is still invalid. And when using key up/down, it will jump to the first item.
What am I missing?
 ItemSelectionModel {
        id: treeViewSelectionModel
        objectName: "treeViewSelectionModel"
        model: myModel
        onCurrentChanged:{console.log("Selectio - current changed from ",previous, " to ", current)}

    }

    TreeView {
        focus: true
        id: treeView
        objectName: "treeView"
        headerVisible: false    //to hide the header

        TableViewColumn {
            title: "Name"
            role: "name"
        }
        model: myModel

        selectionMode: SelectionMode.SingleSelection
        selection: treeViewSelectionModel

        Component.onCompleted: {
            var idx = treeView.model.getPreselected();
            console.log("preselected",idx);
          treeView.selection.setCurrentIndex(idx,ItemSelectionModel.Select);
            treeView.selection = treeView.selection
            //These logged current indexes does not match
            console.log("treeView.currentIndex",treeView.currentIndex);
            console.log("treeView.selection.currentIndex",treeView.selection.currentIndex);

            updateGuiSize();
            treeView.forceActiveFocus();
        }

    }

A: The problem is that the treeView.currentIndex and treeView.selection.currentIndex are not the same. If you go to set the value of the treeView.currentIndex, it is accessible only through the hidden variable __listView.
        __listView.currentIndex = idx.row

EDIT:
I found another option
         treeView.__currentRow = idx.row

redpajama_set_name: RedPajamaStackExchange


text:
Q: NullPointerException when forwarding a record in a Punctuator (kafka clients 2.5.0) I am working on a Kafka stream application based on spring-boot and java 8. We use Kafka clients version 2.5.0
I noticed that sometimes (not always) when forwarding a record from a punctuator, the operation fails with a null pointer exception. Here is the stack trace:
Caused by: org.apache.kafka.streams.errors.StreamsException: task [2_2] Abort sending since an error caught with a previous record (timestamp 1603721062667) to topic reply-reminder-push-sender due to java.lang.NullPointerException\tat
org.apache.kafka.streams.processor.internals.RecordCollectorImpl.send(RecordCollectorImpl.java:240)\tat
org.apache.kafka.streams.processor.internals.RecordCollectorImpl.send(RecordCollectorImpl.java:111)\tat org.apache.kafka.streams.processor.internals.SinkNode.process(SinkNode.java:89)\tat
org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:201)\tat
org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:180)\tat
org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:133)\t... 24 common frames omitted
Caused by: java.lang.NullPointerException: null\tat
org.apache.kafka.common.record.DefaultRecord.sizeOf(DefaultRecord.java:613)\tat
org.apache.kafka.common.record.DefaultRecord.recordSizeUpperBound(DefaultRecord.java:633)\tat org.apache.kafka.common.record.DefaultRecordBatch.estimateBatchSizeUpperBound(DefaultRecordBatch.java:534)\tat
org.apache.kafka.common.record.AbstractRecords.estimateSizeInBytesUpperBound(AbstractRecords.java:135)\tat
org.apache.kafka.common.record.AbstractRecords.estimateSizeInBytesUpperBound(AbstractRecords.java:125)\tat org.apache.kafka.clients.producer.KafkaProducer.doSend(KafkaProducer.java:914)\tat
org.apache.kafka.clients.producer.KafkaProducer.send(KafkaProducer.java:862)\tat org.apache.kafka.streams.processor.internals.RecordCollectorImpl.send(RecordCollectorImpl.java:181)\t... 29 common frames omitted

It looks like there is a null pointer exception in the library when calculating the size of record headers but I don´t think I am creating or updating them. Is there any way to fix it?
Thanks


text:
Q: Calculus remark I forgot. Suppose we have a set $X$. Let $a = \inf X$. then for all $n$,   $a + \frac{1}{n} \in X$.
maybe this is wrong anyway I am trying to show it. So, we know $a \leq x $ for all $x \in X$. By archimidean, can find $n$ such that $a + \frac{1}{n} \leq x$. Im stuck here. Any help would be greatly appreciated. thanks in advance
Suppose $X \neq \varnothing$ and $X \subseteq \mathbb{R}$

A: If $X$ is a nonempty set of real numbers with a lower bound, then $a=\inf X$ satisfies:

*

*For all $x\in X$, $a\leq x$.

*For each positive integer $n$, there exists $x\in X$ such that $x<a+\frac{1}{n}$.

However, you cannot conclude that $a+\frac{1}{n}$ is in $X$, only that it is not a lower bound for $X$, which follows from the definition of the infimum as the greatest lower bound of $X$.  For example, $X$ might only contain one element.

A: This is clearly false. Think of the set:
$$X = {1/3^n}$$
It's infimum is $0$, but $0+1/2 \notin X$.


text:
Q: PHP: preg_match & explode to get some random code from url I want to get some random code from URL beginning with some word (d_ and r_)
Example:
 1. domain.com/index/book-one-d_123456
 2. domain.com/index/book-one-r_123456

I want to show if the link is "d_123456" show content for "d_123456" and if "r_123456" show content for "r_123456". And explode random code after "d_" or "r_".
I have tried with:
if ($co){
$rand = explode('/',$co);

if (preg_match('/^.*([d_]).*?$/i', $rand[1]))
{
$res = explode("d_",$rand[1]);
some code..........
{
else if (preg_match('/^.*([r_]).*?$/i', $soid[1]))
{
$res = explode("r_",$rand[1]);
some code..........
}

I can get random code from "d_" but I can't get it working for "r_" or seems not detecting.

for I'm sorry I posted to early and Thanks for your help guys :D
already found a solution from this post : https://stackoverflow.com/a/4366744/5118751
I just change :
if ($co){
$rand = explode('/',$co);

if (preg_match('/d_/', $rand[1]))
{
$res = explode("d_",$rand[1]);
some code..........
{
else if (preg_match('/r_/', $soid[1]))
{
$res = explode("r_",$rand[1]);
some code..........
}

and now everthing working perfect ...

A: I'm not sure if this is what you are looking for - the regex is quite crude.
$urls=array(
    'domain.com/index/book-one-d_123456',
    'domain.com/index/book-one-r_123456'
);

$pttn='@(.*)(d_(\d+))|(.*)(r_(\d+))@i';
foreach( $urls as $url ){

    preg_match( $pttn, $url, $matches );
    $matches=array_filter( $matches );
    if( !empty( $matches ) )print_r( array_values( $matches ) );
}

Will output:
Array
(
    [0] => domain.com/index/book-one-d_123456
    [1] => domain.com/index/book-one-
    [2] => d_123456
    [3] => 123456
)
Array
(
    [0] => domain.com/index/book-one-r_123456
    [1] => domain.com/index/book-one-
    [2] => r_123456
    [3] => 123456
)

From the output you can decide which items you wish to process further...

A: Given your example URLs, $rand[1] is going to be index which is not the delimiter you're looking for. Use $rand[2] instead of $rand[1].

A: I personally hate regex, so I believe there is a lot simpler way of doing what you need to do!
<?php
$url='domain.com/index/book-one-r_123456';
$ex=explode('_',$url);
    if(substr($ex[0],-1)=='d') { //checking if last letter is d
        //do some code, random code is $ex[2];, letter is d
    } elseif(substr($ex[0],-1)=='r') { //checking if last letter is r
        //do some code, random code is $ex[2]; letter is r
    }
?>

Good luck!


text:
Q: Azure functions developing locally - cannot register EventHub triggered function

I want to develop locally my Azure Function App and later publish it to Azure Portal.
I am using Azure Functions Core Tools command line and all my functions are in Node.js
Currently, I managed to download my functions locally and fetch their settings with command:
func azure functionapp fetch-app-settings

So after that my local.settings.json has correct settings values. When I make any changes I am also able to publish them succesfully to Azure Portal.
The problem is now that I have two functions in my app, one is Http Triggered and the second is EventHub triggered.
When I try run locally host with:
func host start

I get the following output from console:
[10.12.2017 13:03:47] Found the following functions:
[10.12.2017 13:03:47] Host.Functions.HttpTriggerJS1
[10.12.2017 13:03:47]
[10.12.2017 13:03:47] Job host started
[10.12.2017 13:03:47] The following 1 functions are in error:
[10.12.2017 13:03:47] EventHubTriggerJS1: The binding type 'eventHubTrigger' is not registered. Please ensure the type is correct and the binding extension is installed.

And when I try to run locally this EventHubTriggerJS1 function with curl:
curl --request POST -H "Content-Type:application/json" --data '{"input":"sample queue data"}' http://localhost:7071/admin/functions/EventHubTriggerJS1

then nothing happens, so I guess this is a problem of this trigger registration.
The HttpTriggerJS1 runs perfectly, I can access it under
http://localhost:7071/api/HttpTriggerJS1

So, do you have any idea where might be a problem in configuring? BTW Is it possible to have locally function and connect to the remote EventHub in portal?

A: I was unable to reproduce your error on the Version 1.0 runtime.
I reproduced the error in 2.0.  I believe 2.0 does not support event hubs yet,
https://github.com/Azure/azure-webjobs-sdk-script/wiki/Azure-Functions-runtime-2.0-known-issues#functional-gaps
try installing the extensions
func extensions install --package Microsoft.Azure.WebJobs.Extensions.EventHubs -v 3.0.0-beta4
Can you provided more detail about your functions, and the steps you took to create them?
HttpTriggerJS1 was created locally and then published to the portal following the steps outlined in https://learn.microsoft.com/en-us/azure/azure-functions/functions-run-local ?
EventHubTriggerJS1 was created in the portal? in the same Function App?
Do not mix local development with portal development in the same function app. When you create and publish functions from a local project, you should not try to maintain or modify project code in the portal.


text:
Q: Usability of BoringLayout I'm writing a custom layout that will manage text.
Before I started implementing the ViewGroup#onMeasure() method I started to dig the EditText source code, specifically at the EditText#onMeasure() method. So I came across the  BoringLayout. I read the docs but I didn't find much explanation on it and how to use it in an actual custom implementation. Then my question is how can I use it the right way and when it is really needed.

A: BoringLayout is used to draw text on a view. It is called "boring" because it only handles a single line of left-to-right text without any interesting characters such as emoji. This simplification allows the class to override onDraw with more efficient logic than the default does. Here is the source code if you want to see for yourself.
Like StaticLayout and DynamicLayout, the BoringLayout is also a subclass of the abstract Layout class. As the documentation says, you probably wouldn't use these classes directly unless you are making your own text handling widget. How do you know if you should be using one of these classes? If you are thinking about using Canvas.drawText in your custom view, then you should probably think about using a Layout. They also eventually call Canvas.drawText, but they do a lot of other processing beforehand.
If you are making your own text widget, then you would only use the BoringLayout for single line, simple, left-to-right text. For multi-line and more complex text use a StaticLayout. And if you need to dynamically change the text after creation, then use a DynamicLayout.

A: Technically, you can draw text on the canvas with `canvas.drawText("text");
However, text is a very general term and can get extremely complicated : is it LeftToRight or RightToLeft ? is it Ellipsized ? is it single or multiLine ? ...
android.text.Layout is here to handle all this.
the typical way to use it is :
        BoringLayout.Metrics boring = BoringLayout.isBoring(mText, mPaint);
    if (boring != null) {
        // this is boring !
        if (mSavedLayout != null) {
            mLayout = mSavedLayout.replaceOrMake(mText,
                    mPaint,
                    availableWidth,
                    Layout.Alignment.ALIGN_NORMAL,
                    SPACING_MULT,
                    SPACING_ADD,
                    boring,
                    true,
                    TextUtils.TruncateAt.END,
                    availableWidth);
        } else {
            mLayout = BoringLayout.make(mText,
                    mPaint,
                    availableWidth,
                    Layout.Alignment.ALIGN_NORMAL,
                    SPACING_MULT,
                    SPACING_ADD,
                    boring,
                    true,
                    TextUtils.TruncateAt.END,
                    availableWidth);
        }
        mSavedLayout = (BoringLayout) mLayout;
    } else {
        mLayout = new StaticLayout(mText,
                0,
                mText.length(),
                mPaint,
                availableWidth,
                Layout.Alignment.ALIGN_NORMAL,
                SPACING_MULT,
                SPACING_ADD,
                true,
                TextUtils.TruncateAt.END,
                availableWidth);
    }


text:
Q: Determine if a number n is a power What would be an efficient algorithm to determine if $n \in \mathbb{N}$ can be written as $n = a^b$ for some $a,b \in \mathbb{N}, b>1$?
So far, I've tried:
def ispower(n):
    if n<=3:
        return False
    LIM = math.floor(math.log2(n))
    for b in range(2,LIM+1):
        a = math.pow(n, 1/b)
        a_floor = math.floor(a)
        print(a,a_floor)
        if a == a_floor:
            return True
    return False

That is, checking if the $b-th$ roots are integer, for $b$ from 2 to $LIM$, where $LIM$ stands for the ultimate limit of n being a power of 2.
Thanks for your comments.

A: If you restrict $b\geq 2$, then the most efficient way is probably simply testing each root $b = 2, 3, \ldots, \lfloor\log_2 n\rfloor$. This is of runtime $O(\log n)$ and can be implemented using the gmpy2 module efficiently:
import gmpy2

p = 197
e = 989
n = p ** e

b = 2
while 2 ** b <= n:
    root, exact = gmpy2.iroot(n, b)
    if exact:
        print(f"n is a {b}-th power")
        break
    b += 1
else:
    print(f"n is not a perfect power.")
```

A: Since $n = n^1$, every number can be written in the required form. Thus an efficient algorithm is to always answer yes.


text:
Q: Dockerfile COPY not overwriting Nginx configuration (or Nginx overwrites on container start) - why? I have a Dockerfile I use for containerizing Python Flask-based microservices that's based on this base Docker image: https://github.com/tiangolo/uwsgi-nginx-flask-docker
In my Dockerfile, I add a custom nginx.conf and overwrite Nginx's:
FROM tiangolo/uwsgi-nginx-flask:python3.6

ADD nginx.conf nginx.conf

COPY ./app /app
COPY ./data /app/data
COPY nginx.conf /etc/nginx/conf.d/

My custom nginx.conf includes only one change - a single server_name that I prepare with a custom domain name:
server {
    listen 80;
    location / {
        try_files $uri @app;
    }
    location @app {
        include uwsgi_params;
        uwsgi_pass unix:///tmp/uwsgi.sock;
    }
    location /static {
        alias /app/static;
    }
    server_name my-fully-qualified-domain-name.com;
}

The reason for this is that I want to run Let's Encrypt's certbot utility to force Nginx to be SSL-only within the container.
The problem: Docker refuses to overwrite nginx.conf. It pretty much refuses to put anything I try into /etc/nginx/conf.d/.
Or maybe Docker does overwrite it, but something within Nginx on start (at container start) overwrites my changes. I haven't figured it out, but I'd really like to clobber that nginx.conf with my own changes.
Even attaching to the container and manually overwriting Nginx's configuration - then committing those changes to the container using docker commit fails. I suspect there's just something I'm not understanding about how Docker's COPY command works or how docker commit works - any thoughts/suggestions?
Note #1 - I have not been able to get a custom server_name field working with certbot using separate Nginx configuration files (per these instructions). The only way I've been able to get certbot to pick up the right server_name has been by clobbering & overwriting the default nginx.conf, hence going this approach. Perhaps I'm simply using custom Nginx configuration files incorrectly - any suggestions on that note would be greatly appreciated - but I had gone down that road before and was not successful.
Note #2 - I am able to run certbot on a running container (after attaching & overwriting Nginx's configuration), and that works great - SSL on my container, awesome - until the container stops and restarts. Then it's all wiped away and I need to overwrite Nginx's configuration & run certbot again - not ideal at all.

A: You shouldn't overwrite the default nginx.conf file (see https://github.com/tiangolo/uwsgi-nginx-flask-docker#customizing-nginx-configurations).
However you can still add your own configuration in a separate file within /etc/nginx/conf.d/, which should be enough for most use cases.
Edit:
If that doesn't work you can modify entrypoint.sh to better suit your needs since nginx.conf is set there. This issue contains a bit more info: https://github.com/tiangolo/uwsgi-nginx-flask-docker/issues/39


text:
Q: Mongodb Query to CSV dump (mlab hosted mongodb) I am querying an already populated mlab MongoDB database, and I want to store the resulting multiple documents in one single CSV file.
EDIT: output format of CSV file I hope to get:
uniqueid        status    date
191b117fcf5c    0         2017-03-01 15:26:28.217000
191b117fcf5c    1         2017-03-01 18:26:28.217000

MongoDB database document format is
{
    "_id": {
        "$oid": "58b6bcc00bd666355805a3ee"
    },
    "sensordata": {
        "operation": "chgstatus",
        "user": {
            "status": "1",
            "uniqueid": "191b117fcf5c"
        }
    },
    "created_date": {
        "date": "2017-03-01 17:51:17.216000"
    }
}

Database name:mparking_sensor
collection name: demo
The python code to query is as follows:
    # -*- coding: utf-8 -*-
"""
Created on Wed Mar 01 18:55:18 2017

@author: Being_Rohit
"""

    import pymongo
    uri = 'mongodb://#####:*****@ds157529.mlab.com:57529/mparking_sensor'

    client = pymongo.MongoClient(uri)
    db = client.get_default_database().demo
    print db
    results = db.find()

    f = open("mytest.csv", "w")

    for record in results:
        query1 =  (record["sensordata"]["user"],record["created_date"])
        print query1
    print "done"
    client.close()

EDIT: output format of query1 I am getting is:
({u'status': u'0', u'uniqueid': u'191b117fcf5c'}, {u'date': u'2017-03-01 17:51:08.263000'})

Does someone know the correct way to dump this data in a .csv file (pandas/or any other means) or some other approach for further prediction based analysis to do on it in future like linear regression?

A: Mongoexport will do the job for you. It can, uniquely among native MongoDB tools, export in CSV format, limited to a specific set of fields.
Your mongoexport command would be something like this:
mongoexport.exe \
--db mparking_sensor \
--collection demo \
--type=csv \
--fields sensordata.user.uniqueid,sensordata.user.status,created_date

That will export something like the following:
sensordata.user.uniqueid,sensordata.user.status,created_date
191b117fcf5c,0,2017-03-01T15:26:28.217000Z
191b117fcf5c,1,2017-03-01T18:26:28.217000Z

A: I was trying to export a collection to csv using mlabs 'export collection' they make it harder than it needs to be. So i used https://studio3t.com and connected using the standard MongoDB URI


text:
Q: Application Gateway stops working when enabling web service authentication I have an WAF application gateway in Azure with a backend pool that points to my application. If I visit the gateway address it works and I get the application homepage.
However, if I go to that application and enable PaaS AAD Authentication, which should prompt me with an org login page before getting to my application home page, the gateway stops working and returns message:

502 - Web server received an invalid response while acting as a gateway or proxy server.
  There is a problem with the page you are looking for, and it cannot be displayed. When the Web server (while acting as a gateway or proxy) contacted the upstream content server, it received an invalid response from the content server.

When checking backend health I can now see that it is unhealthy, and gives me message:

Probe status code mismatch. Received status code is different from
  expected 100-999.

Note that I even changed the range to 100-999, just for testing this out. No idea what could be causing this or how to fix it.

A: I guess you can try disabling WAF as specified in the comments. Also, I would suggest you to go through this article. https://serverfault.com/questions/882931/azure-ssl-application-gateway-with-web-apps?rq=1


text:
Q: Only half of push notifications reach devices (APNS) $usersStmt = self::$db->query("SELECT `token` FROM `tokens`");
$users = $usersStmt->fetchAll(PDO::FETCH_COLUMN);

foreach ($users AS $userToken) {
    $apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $userToken)) . chr(0) . chr(strlen($payload)) . $payload;
    $result = fwrite($fp, $apnsMessage);
}

I have a table with 10 push notification tokens inside of it. Using PHP, I fetch these tokens and send a notification for each token to APNS.
The problem is, only half are actually getting the notifications. I have a feeling that this is because one of the tokens is invalid (or something along those lines) and it is stopping it from sending the rest of the tokens.
I have checked the value of $result and each one returns true. This means that all notifications are being successfully sent to APNS but not delivered to all devices.
Is it possible that an invalid token could disrupt the rest of the notifications from reaching devices? I'm not sure what's going on here but I know all the notifications are sent successfully to APNS but not reaching the devices.
Any ideas?

A: Invalid tokens will not disrupt the rest of the notifications from reaching devices.
I have the same issue before, the problem was with messages sent itself.
Check your messages length, the notification payload is 256 bytes ).
Check your messages encoding, use the escape sequence for none ASCII messages.
If you send to same device multiple times, Apple will send the last notification only.
Make sure your tokens is for the same working environment, sandbox tokens will not work with production server.
Check Apple technical notes for more info:
https://developer.apple.com/library/mac/technotes/tn2265/_index.html#//apple_ref/doc/uid/DTS40010376-CH1-TNTAG23

A: As stated in the Apple Documentation:
"Remember that delivery of notifications is "best effort" and is not guaranteed."
(Linked relevant question with the same answer - thanks to Joe)
Are APNS now guaranteed delivery given that passbook passes are guaranteed

A: The current adoption rate of iOS 7 to iOS 8 is 50/50. Have you made sure your apps register separately for each OS in your didFinishLaunching call in the AppDelegate? Does the data suggest it's working for one OS and not the other? example code in App Delegate:
if(iOS8){

    [self.application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
    [self.application registerForRemoteNotifications];
    NSLog(@"Register for iOS 8 Notifications %@", application);

}else{

    // iOS 7 Notifications
    [self.application registerForRemoteNotificationTypes:
     (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound)];
    NSLog(@"Register for iOS 7 Notifications %@", application);
}


text:
Q: SSH Forwarding of Mesosphere in ACS fails with "administratively prohibited" I just created a new Mesosphere Cluster in Azure Container Service following the steps described here using the default template. The cluster/resources have been created and I just wanted to connect to the cluster via ssh forwarding. The connection was established but when I try to open a page on the forwarded port 80 I get channel 2: open failed: administratively prohibited: open failed
Here is the verbose ssh log:
sudo ssh -v -i ~/.ssh/id_rsa -L 80:localhost:80 -f -N       azureuser@myservermgmt.northeurope.cloudapp.azure.com -p 2200
OpenSSH_6.9p1, LibreSSL 2.1.8
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 20: Applying options for *
debug1: /etc/ssh/ssh_config line 102: Applying options for *
debug1: Connecting to myservermgmt.northeurope.cloudapp.azure.com [52.178.215.121] port 2200.
debug1: Connection established.
debug1: permanently_set_uid: 0/0
debug1: identity file /Users/me/.ssh/id_rsa type 1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/me/.ssh/id_rsa-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_6.9
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.2p2 Ubuntu-4ubuntu1
debug1: match: OpenSSH_7.2p2 Ubuntu-4ubuntu1 pat OpenSSH* compat 0x04000000
debug1: Authenticating to myservermgmt.northeurope.cloudapp.azure.com:2200 as 'azureuser'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client chacha20-poly1305@openssh.com <implicit> none
debug1: kex: client->server chacha20-poly1305@openssh.com <implicit> none
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:ZMD6A/rz3qWsn2V6yQyeg3kG8vFtweDc72oAZCLo9xs
debug1: Host '[myservermgmt.northeurope.cloudapp.azure.com]:2200' is known and matches the ECDSA host key.
debug1: Found key in /var/root/.ssh/known_hosts:2
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,password
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /Users/me/.ssh/id_rsa
debug1: Server accepts key: pkalg ssh-rsa blen 279
debug1: Authentication succeeded (publickey).
Authenticated to myservicemgmt.northeurope.cloudapp.azure.com ([52.178.215.121]:2200).
debug1: Local connections to LOCALHOST:80 forwarded to remote address localhost:80
debug1: Local forwarding listening on ::1 port 80.
debug1: channel 0: new [port listener]
debug1: Local forwarding listening on 127.0.0.1 port 80.
debug1: channel 1: new [port listener]
debug1: Requesting no-more-sessions@openssh.com
debug1: forking to background
debug1: Entering interactive session.
debug1: client_input_global_request: rtype hostkeys-00@openssh.com want_reply 0
debug1: Connection to port 80 forwarding to localhost port 80 requested.
debug1: channel 2: new [direct-tcpip]
channel 2: open failed: administratively prohibited: open failed
debug1: channel 2: free: direct-tcpip: listening port 80 for localhost port 80, connect from 127.0.0.1 port 55718 to 127.0.0.1 port 80, nchannels 3
debug1: Connection to port 80 forwarding to localhost port 80 requested.

AFAIK this could mean PermitTunnel is not enabled on the server. Since ssh tunnels work on my machine for other purposes, I was wondering if there is anything in ACS I have to configure? I already tried to ssh directly into the DCOS master, but without success.
Any help is appreciated.

A:
AFAIK this could mean `PermitTunnel is not enabled on the server.

No, it is AllowTcpForwarding in /etc/ssh/sshd_config of the target server. Or PermitOpen directive.
Also note that you are unable to bind privileged ports on your system, if you are not running under root or have specific privileges.


text:
Q: AVAudioEngine: Playing a stream of Int16 PCM samples I'm receiving a stream of 16 bit / 48 kHz stereo PCM samples as Int16s and I'm trying to play them using AVAudioEngine, however I am not hearing anything at all. I'm thinking it either has something to do with the way I set up the player or maybe the way I'm pushing the data into the buffer.
I have read a lot about alternative solutions using Audio Queue Services, however all sample code I could find is either in Objective-C or iOS-only.
If I had any kind of frameSize issues or whatever, shouldn't I still be able to a least hear garbage coming out of my speakers?
This is my code:

import Foundation
import AVFoundation

class VoicePlayer {

    var engine: AVAudioEngine

    let format = AVAudioFormat(commonFormat: AVAudioCommonFormat.pcmFormatInt16, sampleRate: 48000.0, channels: 2, interleaved: true)!
    let playerNode: AVAudioPlayerNode!
    var audioSession: AVCaptureSession = AVCaptureSession()

    init() {

        self.audioSession = AVCaptureSession()

        self.engine = AVAudioEngine()
        self.playerNode = AVAudioPlayerNode()

        self.engine.attach(self.playerNode)
        //engine.connect(self.playerNode, to: engine.mainMixerNode, format:AVAudioFormat.init(standardFormatWithSampleRate: 48000, channels: 2))
        /* If I set my custom format here, AVFoundation complains about the format not being available */
        engine.connect(self.playerNode, to: engine.outputNode, format:AVAudioFormat.init(standardFormatWithSampleRate: 48000, channels: 2))
        engine.prepare()
        try! engine.start()
        self.playerNode.play()

    }

    func play(buffer: [Int16]) {
        let interleavedChannelCount = 2
        let frameLength = buffer.count / interleavedChannelCount
        let audioBuffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(frameLength))!
        print("audio buffer size in frames is \(AVAudioFrameCount(frameLength))")
        // buffer contains 2 channel interleaved data
        // audioBuffer contains 2 channel interleaved data
        var buf = buffer
        let size = MemoryLayout<Int16>.stride * interleavedChannelCount * frameLength

        memcpy(audioBuffer.mutableAudioBufferList.pointee.mBuffers.mData, &buf, size)
        audioBuffer.frameLength = AVAudioFrameCount(frameLength)

        /* Implemented an AVAudioConverter for testing
         Input: 16 bit PCM 48kHz stereo interleaved
         Output: whatever the standard format for the system is

         Maybe this is somehow needed as my audio interface doesn't directly support 16 bit audio and can only run at 24 bit?
         */
         let normalBuffer = AVAudioPCMBuffer(pcmFormat: AVAudioFormat.init(standardFormatWithSampleRate: 48000, channels: 2)!, frameCapacity: AVAudioFrameCount(frameLength))
         normalBuffer?.frameLength = AVAudioFrameCount(frameLength)
         let converter = AVAudioConverter(from: format, to: AVAudioFormat.init(standardFormatWithSampleRate: 48000, channels: 2)!)
         var gotData = false

         let inputBlock: AVAudioConverterInputBlock = { inNumPackets, outStatus in

         if gotData {
         outStatus.pointee = .noDataNow
         return nil
         }
         gotData = true
         outStatus.pointee = .haveData
         return audioBuffer
         }

         var error: NSError? = nil
         let status: AVAudioConverterOutputStatus = converter!.convert(to: normalBuffer!, error: &error, withInputFrom: inputBlock);

        // Play the output buffer, in this case the audioBuffer, otherwise the normalBuffer
        // Playing the raw audio buffer causes an EXEC_BAD_ACCESS on playback, playing back the buffer from the converter doesn't, but it still doesn't sound anything like a human voice
        self.playerNode.scheduleBuffer(audioBuffer) {
        print("Played")
        }

    }

}

Any help would be greatly appreciated.

A: Once you copy data into an AVAudioPCMBuffer you need to set its frameLength property to indicate how much valid audio it contains.
func play(buffer: [Int16]) {
    let interleavedChannelCount = 2
    let frameLength = buffer.count / interleavedChannelCount
    let audioBuffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(frameLength))!

    // buffer contains 2 channel interleaved data
    // audioBuffer contains 2 channel interleaved data

    var buf = buffer
    memcpy(audioBuffer.mutableAudioBufferList.pointee.mBuffers.mData, &buf, MemoryLayout<Int16>.stride * interleavedChannelCount * frameLength)

    audioBuffer.frameLength = AVAudioFrameCount(frameLength)

    self.playerNode.scheduleBuffer(audioBuffer) {
        print("Played")
    }
}

Edit: Updated for changes to the question. The old, (now) irrelevant portion:
Part of the problem is that there is an inconsistency in your formats. format is declared as non-interleaved but buffer is a single array of Int16 so presumably represents interleaved data. Copying one to another directly is probably not correct.

A: I had a very similar problem and I managed to solve it using this post as a starting point.
The differences: I'm using float instead of int data. I have some C code that receives the audio data from the network and writes it to the head of a circular buffer (I use TPCircularBuffer). My Swift code then reads the data from the tail of that same circular buffer and copies it to an AVMAudioPCMBuffer, which I then pass to playernode.schedulebuffer(). I use a function that grabs the next data in this way, calls schedulebuffer and passes itself as the schedulebuffer callback, so data keeps being scheduled continuously. I got the best result using two such scheduling threads.
Otherwise the situation is the same. My input data is interleaved, as in your case. It seems to me that interleaved audio is just not supported by AVAudioEngine. If you specify interleaved stereo as the input format in engine.connect() you'll get a crash pointing to setFormat(). If instead you specify a non-interleaved format, as you did above, you are basically misinforming the framework about the data it's supposed to process and you will get EXEC_BAD_ACCESS errors.
To fix this I first tried to copy the data from the circular buffer to an interleaved AVAudioPCMBuffer. Then I used AVAudioConverter to produce a new deinterleaved AVAudioPCMBuffer which I then scheduled for playback. Now I finally got audio. At first it was only a series of random distorted click noises, possibly similar to what you heard after conversion. In my case I tracked the problem down to a simple miscalculation: I had been dividing a sample count by numChannels and MemoryLayout<Float>.stride to calculate the byte count rather than multiplying the three. So I heard only a 64th of each packet.
After that was fixed I heard actual speech, but the code was too slow to keep up with realtime data arrival. I ended up copying and converting the data in one operation, throwing out AVAudioConverter and doing it manually instead. Check out my code below.
Two more points regarding your code:

*

*I find accessing the data in AVAudioPCMBuffer through buffer.floatChannelData (or in your case buffer.int16ChannelData) much more convenient than using buffer.mutableAudioBufferList.pointee.mBuffers.mData.

*I'm not sure why you used AVCaptureSession for your audio session. Maybe you had a sound reason but I personally use AVAudioSession.sharedInstance() and audioSession.setCategory(.playback, mode: .spokenAudio, policy: .longForm) for playing back speech and it works nicely.

Here's the relevant portion of working code:
    init() {
        do {
            if #available(iOS 11.0, *) {
                try audioSession.setCategory(.playback, mode: .spokenAudio, policy: .longForm)
            } else {
                try audioSession.setCategory(.playback, mode: .spokenAudio)
            }
        } catch {
            print("Failed to set audio session category. Error: \(error)")
        }
        engine = AVAudioEngine()
        playerNode = AVAudioPlayerNode()
        outputFormat = AVAudioFormat(standardFormatWithSampleRate: sampleRate, channels: numChannels)!
        circularBuffer = TPCircularBuffer()

        engine.attach(playerNode)
        engine.connect(playerNode, to: engine.outputNode, format: outputFormat)
        engine.prepare()
    }

    func start() {
        isPlayRequested = true
        _TPCircularBufferInit(&circularBuffer, bufferLength, MemoryLayout<TPCircularBuffer>.stride)
        networkStream_start(&circularBuffer) //this starts a loop in C code
        do {
            try audioSession.setActive(true)
        } catch {
            print("Failed to start audio session. Error: \(error)")
        }
        do {
            try engine.start()
        } catch {
            print("Failed to start audio engine. Error: \(error)")
        }

        for _ in 1...numSchedulers {
            scheduleNextData()
        }
        playerNode.play()
    }

    func getAndDeinterleaveNextData () -> AVAudioPCMBuffer {
        let inputBufferTail = TPCircularBufferTail(&circularBuffer, &availableBytes)
        let outputBuffer = AVAudioPCMBuffer(pcmFormat: outputFormat, frameCapacity: bufferLength)!
        if inputBufferTail != nil {
            let sampleCount = Int(availableBytes / numSchedulers / floatSize)
            let tailFloatPointer = inputBufferTail!.bindMemory(to: Float.self, capacity: sampleCount)
            for channel in 0..<Int(numChannels) {
                for sampleIndex in 0..<sampleCount {
                    outputBuffer.floatChannelData![channel][sampleIndex] = tailFloatPointer[sampleIndex * Int(numChannels) + channel]
                }
            }
            outputBuffer.frameLength = AVAudioFrameCount(sampleCount / Int(numChannels))
            TPCircularBufferConsume(&circularBuffer, outputBuffer.frameLength * numChannels * floatSize)
        }
        return outputBuffer
    }

    func scheduleNextData() {
        if isPlayRequested {
            let outputBuffer = getAndDeinterleaveNextData()
            playerNode.scheduleBuffer(outputBuffer, completionHandler: scheduleNextData)
        }
    }


text:
Q: How to filter records from DB based on user access rights I am building a REST service for an event management application.
The idea is that each user can see on the feed only events he has been invited to and events he created. One condition is that each user have multiple emails.
What would be the best way to retrieve events (through JpaRepository) for a specific (authenticated) user?
One possible solution I thought of is having a query like the following, where :auth_email and :auth_id is the email and id of authenticated user.
SELECT e.* FROM events e
  WHERE e.user_id = :auth_id OR
  EXISTS (
    SELECT id FROM invitations
      WHERE (e.id = invitations.event_id) AND
       (
        invitations.email = :auth_email
        OR EXISTS (
          SELECT id FROM user_emails WHERE
            (user_emails.user_id = :auth_id)
            AND (invitations.email = user_emails.email)
        )
      )
  )

I'm not sure if it's scalable and also I'm not sure how to "translate" it to JPQL...
Approximate models I have:

*

*USERS table used for authentification, contains primary email

@Data @Entity @Table(name = "users")
public class User {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(unique = true, nullable = false)
    private String email;
    // other columns
}

*USER_EMAILS - used to keep additional (personal) user emails:

@Data @Entity @Table(name = "user_emails")
public class UserEmails {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @ManyToOne
    private User user;

    @Column(unique = true, nullable = false)
    private String email;
}

*EVENTS

@Data @Entity @Table(name = "events")
public class Event {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @ManyToOne
    private User user;

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "event_id") @JsonIgnore
    private List<Invitation> invitations;

    private String title;
    // other columns
}

*INVITATIONS - users (emails) invited to an event - can be used primary email (users.email) or any personal email (from user_emails)

@Data @Entity @Table(name = "invitations")
public class Invitation {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String email;

    @ManyToOne @JsonIgnore
    private Event event;
}


text:
Q: evaluation of series Evaluate :
a.$$\frac{1}{2\cdot3}+\frac{1}{4\cdot5}+\frac{1}{6\cdot7}+\cdots$$
For this I looked at
$$x+x^3+x^5+\cdots=\frac{x}{1-x^2} \text{ for }|x|<1$$
Integrating the above series from $0$ to $t$ yields
$$\frac{t^2}{2}+\frac{t^4}{4}+\frac{t^6}{6}+\cdots=\int_{0}^{t}\frac{x}{1-x^2} \, dx$$
Again integrating the series from $0$ to $1$ will give
$$\frac{1}{2\cdot3}+\frac{1}{4\cdot5}+\frac{1}{6\cdot7}+\cdots=\int_{0}^{1}\left(\int_{0}^{t}\frac{x}{1-x^2} \, dx\right) \, dt$$
But upon integration $\log(1-t^2) $ comes which is not defined at $t=1$

A: Using $\displaystyle \frac1{n(n+1)}=\frac1n-\frac1{n+1}$
$$\frac1{2\cdot3}+\frac1{4\cdot5}+\frac1{6\cdot7}+\cdots=\frac12-\frac13+\frac14-\frac15+\frac16-\frac17+\cdots$$
Now use Convergence for log 2 or Taylor series for $\log(1+x)$ and its convergence


text:
Q: Any tips on localizing dates in .NET or in general? I understand different cultures specify dates differently.  Some put day before month (27/10/2009 vs. 10/27/2009) and others use dots instead of slashes (10.27.2009 vs. 10/27/2009).  However, is there anything special that needs to be done regarding the year?  Do non-Christian cultures refer to the same numeric year (2009) as Christian cultures?  I created a simple C# app and did a toString on the current date, changed the language/culture to Arabic and it displays the same thing.  Maybe the year is a globally accepted standard???

A: Use the ToString() overload which takes an IFormatProvider and pass in CultureInfo.CurrentCulture and the date will format appropriately.


text:
Q: How do I test jQuery code with MochaJS? I think, mocha does not recognise jQuery in the scope of my tests, because it tests plain JavaScript without a problem. I tried to require jQuery's full code in the beginning of the .js file with my tests, tried to manually define $ with
before(function() {/* some code */}), but I always get this ReferenceError: $ is not defined when I try to run my tests and there is jQuery code tested with some of them.
Any ideas of how do I fix this?

A: In docs:

Mocha runs in the browser. Every release of Mocha will have new builds
  of ./mocha.js and ./mocha.css for use in the browser. To setup Mocha
  for browser use all you have to do is include the script, stylesheet,
  tell Mocha which interface you wish to use, and then run the tests. A
  typical setup might look something like the following, where we call
  mocha.setup('bdd') to use the BDD interface before loading the test
  scripts, running them onload with mocha.run().

So you can include any scripts, but the first you include libs, like jQuery, then tests

  <meta charset="utf-8">
  <title>Mocha Tests</title>
  <link rel="stylesheet" href="mocha.css" />


text:
Q: Readability, why won't Coleman-Liau index formula work when I plugin words, letters, and sentences? whats wrong with my code? this is the part that doest work
float L = (letters / words) * 100; and float S = (sentences / words) * 100;

when I plug in letters, words, and sentences into the formula it gives the wrong answer.
#include <stdio.h>
#include <string.h>
#include <cs50.h>
#include <ctype.h>
#include <math.h>

int main(void)
{
char ch[500];

int i;
int ii;
int iii;

int LettersWspace = 0;
int letters = 0;
int words = 1;
int sentences = 0;
int index;

string text = get_string("Enter Text: ");

 for(i = 0; text[i] != '\0'; i++)
 {
LettersWspace++;
 }
for( i = 0; i < LettersWspace; i++)
 {
if (text[i] == 32)
    letters++;
  }
  letters = LettersWspace - letters;

  ii = 0;
{
  if (text[ii] == ' ')
{
    words++;
}
ii++;
}

while (ii <= text[ii]);

iii = 0;
do
    {
if (text[iii] == '?' || text[iii] == '!' || text[iii] == '.')
{
    sentences++;
}
iii++;
}

while (iii <= text[iii]);

float L = (letters / words) * 100;

float S = (sentences / words) * 100;

return (index = 0.0588 * L - 0.296 * S - 15.8);

printf("%i\n", (int) sentences);

return 0;

    }


text:
Q: Is $n^2>n^2/m + nm$ for $m$ taking some value between $1$ and $n$. This is not a homework question. I am working on this paper and I need to come up with a proof for this, I will not include this is in the paper but I need to be sure of this or I will end up looking like idiot :(
$1 < m < n$, m is a integer

A: This inequality is not true. Take $n=4$ and $m=3$ then the inequality gives $16 > 16/3 + 12$, which is not true since $16/3 > 4$.

A: Dividing by $n^2$ on both sides, this reduces to $1>\frac{1}{m}+\frac{m}{n}$. Letting $m=n-1$, then $\frac{1}{n-1}+\frac{n-1}{n}>\frac{1}{n}+\frac{n-1}{n}=1$. So for any $n$, this is false, except $n=2$.


text:
Q: Uncaught SyntaxError: Unexpected token U in JSON at position 0 at JSON.parse () at Response.Body.json I am working on an angular2 project. I am stuck with these errors. The error occured when I tried to send the JSON objects to the backend. It may be due the parsing of JSON objects. I am new to angualar, so please do help
Signup.service.ts
import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';
import 'rxjs/add/operator/map' ;
@Injectable()
    export class SignupService{
        constructor (private http: Http){}
        insertform(newreg: any ){
            console.log();
            var headers = new Headers ();
            headers.append('Content-Type','application/json');
            return this.http.post('http://localhost:3000/api/users', JSON.stringify(newreg),{headers: headers})
            .map(res=> res.json());
         }
     }

signup.component.ts
import { Component, AfterViewInit } from '@angular/core';
import {SignupService} from '../../services/signup.service';
import {Signup} from '../../../signup';
declare var $: any;
 @Component({
 moduleId: module.id,
 selector: 'signup',
 templateUrl: 'signup.component.html',
  providers: [SignupService]
 })
 export class SignupComponent {
 datas: Signup[];
 data: any;
 first_name: string;
 last_name: string;
 address: string;
 email: string;
 pwd:string;
 pwdcnf:string;
 phone:number;
 constructor(private signupService: SignupService){ };
 ngAfterViewInit() {
    $('#textarea1').trigger('autoresize');
   };
     regformSubmit(event: any){
    event.preventDefault();
    var newreg = {
     first_name: this.first_name,
      last_name: this.last_name,
     email: this.email,
     address: this.address,
     phone: this.phone,
    pwd:this.pwd,
    pwdcnf:this.pwdcnf
   };
    this.signupService.insertform(newreg)
      .subscribe (data => {
       this.datas.push(data);
        this.first_name='';
         this.last_name ='';
         this.email='';
        this.address='';
         this.phone=0;
    this.pwd='';
    this.pwdcnf='';
      });
  }
 }

signup.component.html

<form class="col s12" (ngSubmit)="regformSubmit($event)">

      <input  id="first_name" type="text" class="validate" [(ngModel)]="first_name" name="first_name" required>
      First Name

      <input id="last_name" type="text" class="validate" [(ngModel)]="last_name" name="last_name" required>
      Last Name

      <textarea id="textarea1" class="materialize-textarea" [(ngModel)]="address" name="address" required></textarea>
      Address

      <input id="password" type="password" class="validate" [(ngModel)]="pwd" name="pwd" required>
      Password

      <input id="password1" type="password" class="validate" [(ngModel)]="pwdcnf" name="pwdcnf" required>
      Confirm password

      <input id="email" type="email" class="validate" [(ngModel)]="email" name="email" required>
      Email

      <input id="password2" type="number" class="validate" [(ngModel)]="phone" name="number" required>
      Phone

         <button class="btn waves-effect waves-light" type="submit" name="action">Submit
            send
        </button>

</form>

The full error message is
EXCEPTION: Unexpected token U in JSON at position 0
ORIGINAL STACKTRACE:
yntaxError: Unexpected token U in JSON at position 0
at JSON.parse (<anonymous>)
at Response.Body.json (http.umd.js:777)
at MapSubscriber.eval [as project] (signup.service.ts:13)
at MapSubscriber._next (map.ts:75)
at MapSubscriber.Subscriber.next (Subscriber.ts:95)
at XMLHttpRequest.onLoad (http.umd.js:1180)
at ZoneDelegate.invokeTask (zone.js:275)
at Object.onInvokeTask (core.umd.js:3971)
at ZoneDelegate.invokeTask (zone.js:274)
at Zone.runTask (zone.js:151)
at XMLHttpRequest.ZoneTask.invoke (zone.js:345)
Uncaught SyntaxError: Unexpected token U in JSON at position 0
at JSON.parse (<anonymous>)
at Response.Body.json (http.umd.js:777)
at MapSubscriber.eval [as project] (signup.service.ts:13)
at MapSubscriber._next (map.ts:75)
at MapSubscriber.Subscriber.next (Subscriber.ts:95)
at XMLHttpRequest.onLoad (http.umd.js:1180)
at ZoneDelegate.invokeTask (zone.js:275)
at Object.onInvokeTask (core.umd.js:3971)
at ZoneDelegate.invokeTask (zone.js:274)
at Zone.runTask (zone.js:151)
at XMLHttpRequest.ZoneTask.invoke (zone.js:345)

A: Read the call stack closely; the crash is on this line:
        .map(res=> res.json());

The JSON parser is failing to understand the response from the server. See if you can figure out what response the server (the POST to http://localhost:3000/api/users) is sending back. The response supposedly starts with 'U', which cannot be valid JSON.

A: the "u" there is the first letter of undefined . This is happening as a json is expected and an undefined is obtained.

A: I normally see this when the server returns an error (e.g. a 500 server error). The problem is that the server is returning plain text or sometimes even HTML and then the client app is trying to parse JSON from it thus throwing the error. I would recommend opening the chrome dev tools, navigating to the network tab, refreshing the page, and then look for the request in question and see what is actually getting returned from the server.
It should look something like this. My guess is that the text on the right will not be JSON.

A: return this.http.post('http://localhost:3000/api/users', JSON.stringify(newreg),{headers: headers})
            .map(res=> res.json());

The backend API at http://localhost:3000/api/users has a return type that is not JSON, in your case String beginning with the letter 'U'. Make sure the back end returns json data by using res.json("Your text here"); This is because your map function .map(res=> res.json()); is expecting a json response

A: Thanks @Jacob Krall for pointing out the reason:
I was getting the same error for following code
this.http.post(URL, formData).map((res: Response) => res.json()).subscribe(
(success) => {
    alert(success);
},
(error) => alert(error))

Reason: I was not sending json data from server itself so it was crashing for line res.json()
Solution:
Return json response from server then it should work fine.
replaced the following
return res.send("Upload Completed for " + path);

with,
return res.json("Upload Completed for " + path);

A: Actually this is not a frontend problem this is the backend problem. The frontend is expecting a JSON type instead of normal string. For resolving this error, all you need to do is in your backend:
res.json("Whatever you want to send")

This will work :)

A: Normally it happens when you use arrow function for fetching data through API and in that you use 'this' keyword.
So, arrow function not have its own 'this' So, we got error.
This is not the main reason but it is one of them.
fetch.addEventListener('load',()=> {

const [delta] = JSON.parse(this.responseText);

console.log(delta);
//Uncaught SyntaxError: Unexpected token U in JSON at position 0 at JSON.parse (<anonymous>)


text:
Q: iOS - kill the app with a button? I have an app that runs for a while, but needs to be reset every day, because it's lifecycle is a bit different than most other apps. It seems that the easiest way to do this is to kill the app and re-launch it.
I found a solution that kills the app when the home button is tapped:

In your application's Info.plist, add a boolean key
  UIApplicationExitsOnSuspend with the value YES

This is not something that I want to do. I need to give the user an option to kill/reset the app before it is used. I can certainly ask the user to double tap the home key and kill the app with a long press>x. Yet this is too complex for some users.
Another simple solution would be to have a button do something crashworthy, like divide by 0, although I'm not sure if the app store would penalize my app for "crashing" every single day for all users.
Has anyone found a way to add an "exit" button to an iPhone app? In android, I could do system.exit(0), which worked. What's the iPhone alternative?

A: iOS Human Interface Guide says -
Don't Quit Programmatically

Never quit an iOS application programmatically because people tend to
  interpret this as a crash. However, if external circumstances prevent
  your application from functioning as intended, you need to tell your
  users about the situation and explain what they can do about it.
  Depending on how severe the application malfunction is, you have two
  choices. ...

exit(0); can terminate the application (0 is a normal code), but Apple don't like this approach, and the application would be rejected in review.


text:
Q: Open AutoCompleteBox in WPF on control focus I'm trying to open System.Windows.Controls.AutoCompleteBox on control focus. The event triggers but nothing happens:/ When I start entering some text, the autocomplete box works fine. What am I doing wrong?
AutoCompleteBox box = new AutoCompleteBox();
box.Text = textField.Value ?? "";
box.ItemsSource = textField.Proposals;
box.FilterMode = AutoCompleteFilterMode.Contains;
box.GotFocus += (sender, args) =>
    {
        box.IsDropDownOpen = true;
    };

A: I did a quick workaround as if this solution is satisfying for me in my program.
AutoCompleteBox box = new AutoCompleteBox();
box.Text = textField.Value ?? "";
if (textField.Proposals != null)
{
    box.ItemsSource = textField.Proposals;
    box.FilterMode = AutoCompleteFilterMode.None;
    box.GotFocus += (sender, args) =>
        {
            if (string.IsNullOrEmpty(box.Text))
            {
                box.Text = " "; // when empty, we put a space in the box to make the dropdown appear
            }
            box.Dispatcher.BeginInvoke(() => box.IsDropDownOpen = true);
        };
    box.LostFocus += (sender, args) =>
        {
            box.Text = box.Text.Trim();
        };
    box.TextChanged += (sender, args) =>
        {
            if (!string.IsNullOrWhiteSpace(box.Text) &&
                box.FilterMode != AutoCompleteFilterMode.Contains)
            {
                box.FilterMode = AutoCompleteFilterMode.Contains;
            }

            if (string.IsNullOrWhiteSpace(box.Text) &&
                box.FilterMode != AutoCompleteFilterMode.None)
            {
                box.FilterMode = AutoCompleteFilterMode.None;
            }
        };
}

A: The recommended solution from @elgonzo worked perfectly for me.
XAML:
<wpftk:AutoCompleteBox FilterMode="Contains"
                       ItemsSource="{Binding List}"
                       MinimumPrefixLength="0"
                       Text="{Binding Text}"
                       GotFocus="AutoCompleteBox_GotFocus"/>

with namespace
xmlns:wpftk="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input.Toolkit"

and Code-Behind:
private void AutoCompleteBox_GotFocus(object sender, System.Windows.RoutedEventArgs e)
{
    var _acb = sender as AutoCompleteBox;
    if(_acb != null && string.IsNullOrEmpty(_acb.Text))
    {
        _acb.Dispatcher.BeginInvoke((Action)(() => { _acb.IsDropDownOpen = true; }));
    }
}

The dropdown appears when there is no text entered yet and the AutoCompleteBox got focus.


text:
Q: Comparing an integer variable in the Bash shell I know I'm missing something very obvious, but I just can't see it. In the code below, new_i variable gets incremented properly, however, when I get to the if statement, I think my syntax is off. I looked at some examples, but none show variable set to zero when if statement is greater than (in this case 15) a number.
#!/bin/sh
i=$(cat /etc/hour.conf)
new_i=$((i+1))
if [[ "$new_i" -gt 15 ]]; then
 new_i=0
fi
echo "$new_i">/etc/hour.conf
echo "$new_i"

When I run this script I get the following error:
./loops: 3: ./loops: Illegal number: new_i

Thanks in advance for your help!

A: This works - the $ in front of the i in the new_i=$(( line and the removal of the quotes and one set of the brackets fixed the errors and now the scripts works as intended.  Thanks to everyone for their help!
#!/bin/sh
i=$(cat /etc/hour.conf)
new_i=$(($i+1))
if [ $new_i -gt 15 ]; then
 new_i=0
fi
echo "$new_i">/etc/hour.conf
echo "$new_i"

A: Try without the quotes:
if [ $new_i -gt 15 ]; then
    ...
fi

or, better yet, use arithmetic evaluation instead:
if (( $new_i > 15 )) ; then
    ...
fi


text:
Q: Javascript_ Error in user.js TypeError: Cannot read property 'value' of undefined Here is some problems with it.
I would like to ask you how to cope with this problem? Actually I'm new to Javascript.
Thank you in advance.
It looks like this on the console:

Javascript_ Error in user.js TypeError: Cannot read property 'value' of undefined

function checkPassword(form) {
  var password = checkPassword(password);
  var s_letters = "qwertyuiopasdfghjklzxcvbnm";
  var b_letters = "QWERTYUIOPLKJHGFDSAZXCVBNM";
  var digits = "0123456789";
  var specials = "!@#$%^&*()_-+=\|/.,:;[]{}";
  var is_s = false;
  var is_b = false;
  var is_d = false;
  var is_sp = false;

  for (var i = 0; i < password.length; i++) {
    if (!is_s && s_letters.indexOf(password[i]) != -1) is_s = true;
    else if (!is_b && b_letters.indexOf(password[i]) != -1) is_b = true;
    else if (!is_d && digits.indexOf(password[i]) != -1) is_d = true;
    else if (!is_sp && specials.indexOf(password[i]) != -1) is_sp = true;
  }

  var rating = 0;
  var text = "";
  if (is_s) rating++;
  if (is_b) rating++; //
  if (is_d) rating++; //
  if (is_sp) rating++; //
  if (password.length < 6 && rating < 3) text = "Bad";
  else if (password.length < 6 && rating >= 3) text = "Good";
  else if (password.length >= 8 && rating < 3) text = "Good";
  else if (password.length >= 8 && rating >= 3) text = "Excellent";
  else if (password.length >= 6 && rating == 1) text = "Bad";
  else if (password.length >= 6 && rating > 1 && rating < 4) text = "Good";
  else if (password.length >= 6 && rating == 4) text = "Excellent";
  console.log(text); // Alert will not work for us here. Console.log allows you to export data to the console for troubleshooting.
  return text;
}

var player = GetPlayer(); // Gets the player object.
var myPassword = player.GetVar("SystemDate"); // Gets the value for myPassword
console.log(myPassword);
var newValue = checkPassword(myPassword); // Run the function and return to newValue
player.SetVar("SystemDate",newValue); // Set the value of newValue back to Storyline

A: I've changed your function in a little, try that one (and show us SetValue function):
// @first error - password input, not the form
function checkPassword (password) {
    var expr,
        rating = 0,
        rules = {
            // Lower case
            '/[a-z]+/g': false,
            // Upper case
            '/[A-Z]+/g': false,
            // Numbers
            '/[0-9]+/g': false,
            // Special symbols
            '/[^\w\s]/gi': false
        };

    for (expr in rules) {
        if (password.match(expr)) {
            // rules[expr] = true; // - can be used to show the proper message of invalidation
            rating++;
        }
    }

    return
        || password.length >= 8 && rating >= 3 && "Excellent"
        || password.length < 6 && rating >= 3 && "Good"
        || password.length >= 8 && rating < 3 && "Good"
        || password.length >= 6 && rating > 1 && rating < 4 && "Good"
        || "Bad";
}

// Gets the player object.
var player = GetPlayer();
// Gets the value for myPassword
var myPassword = player.GetVar("SystemDate");
// Run the function and return to newValue
var newValue = checkPassword(myPassword);
// Set the value of newValue back to Storyline
// @second error seems to be in the function SetVar
player.SetVar("SystemDate",newValue);


text:
Q: How do I keep Google Analytics from corrupting query strings that contain %26? I have many links on my site that have query strings that contain %26 (which is a URL-encoded ampersand). For example:
?action=keyword_results&f=company&q=Bausch+%26+Lomb+Canada+Inc.

Apparently, Google Analytics is prematurely decoding the query string and it treats the text after the %26 as a separate parameter.
I use the Exclude URL Query Parameters option to exclude most query parameters (including action, f, and q) from our results. But I am getting stats for hundreds of pages with query strings like ?+Lomb+Canada+Inc. and I can't exclude them because they are all different.
I've tried a variety of Google searches to see if this is a known bug. But all I found was people having trouble because they weren't encoding the ampersand.
Am I doing something wrong? Is this a bug? Is there anything I can do to clean up my reports?

A: You could try creating a "search and replace" filter on Request URI and use regex to replace '%26' with '&'. Unfortunately, I'm not too experienced with regex, so I can't really help you there; you might have to ask someone else to write one for you (or figure it out yourself, of course).
https://support.google.com/analytics/answer/1034834
edit: I think it could something as easy as:
search string for: %26
replace it with: &
http://rubular.com/r/V7yrenW3tt
But just create a separate profile and test it, I guess.


text:
Q: React Testing Library: fireEvent change is not working When I tried to change DatePicker input I am getting error.
Here is my files for components and testcase:
datePicker.js
  const DatePicker = ({ value, onChange, name, locale }) => {
      const myVal = value ? value.locale(locale) : '';
      return (
       <TextInput
         value={myVal}
         onChange={onChange}
         name={name}
       />)
  };
export default DatePicker;

date.js
import React from 'react';
import DatePicker from './datepicker';
const Date = () => {
   const [dates, setDate] = useState('');
   return (
      <DatePicker
        name="date"
        value={dates}
        onChange={(_, value) => setDate(value)}
        locale="ja"
      />
 ); }

date.test.js
test('should render Date properly', () => {
const component = render(<Date />);

const date = component.container.querySelector(
  'input[name="date"]'
);
fireEvent.change(date, {
  target: {
    value: '10/1/2021',
  },
 });
});

Here is the error which I am getting :
 TypeError: value.locale is not a function
 fireEvent.change(date, {
           ^
     target: {
        value: '10/1/2021',
     },

A: I am personally have the issues with the change fire event however one thing I see that you have wrong is invalid formatting. React testing library specifically states that the target value for that event on a date input type has to be 00-00-000.
https://testing-library.com/docs/dom-testing-library/api-events/
// Invalid:
fireEvent.change(input, {target: {value: '24/05/2020'}})

// Valid:
fireEvent.change(input, {target: {value: '2020-05-24'}})


text:
Q: How can i apply callback to get the http response in a method I am attempting to write a method so that i pass the url and application name and it return the response. I read that I can apply callback to resolve this but I am not able to resolve the issue. Any help would be appreciated.
Please find below my code snippet.
var response = getResponse(url,applicationName)
console.log("response from getResponse \n" +response);

function getResponse(url,applicationName){
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
    "application": applicationName
}));
xhr.onload = function() {
  console.log(this.responseText);
}
return xhr.responseText;
}

A: You can use the onreadystatechange method to handle XHR responses, try this:

//XHR POST
const xhr = new XMLHttpRequest;                             // creates new object
const url = 'https://api-to-call.com/endpoint';
const data = JSON.stringify({"application": applicationName});              // converts data to a string

xhr.responseType = 'json';
xhr.onreadystatechange = () => {
  if(xhr.readyState === XMLHttpRequest.DONE) {
    return xhr.response;
  }
}
xhr.open('POST', url);      // opens request
xhr.send(data);                         // sends object

A: you should use promise instead of callback and do something like that.

const url = "https://httpbin.org/post";
const applicationName = "test";
getResponse(url, applicationName)
  .then(response => {
    //work here, not outside
    console.log(response);
  })
  .catch(error => {
    console.log(error);
  })

function getResponse(url, applicationName) {
  return new Promise((resolve, reject) => {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", url, true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.send(JSON.stringify({
      "application": applicationName
    }));
    xhr.onload = function() {
      // print JSON response
      if (xhr.status >= 200 && xhr.status < 300) { // if valid
        // work here
        const response = JSON.parse(xhr.response.replace(/"/g, '"'));
        const data = JSON.parse(response.data.replace(/"/g, '"'));
        resolve(data);
      }
      reject(xhr.response); // reject and return the response if not valid
    }
  })

}

If you want to learn more about asynchronous https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Concepts, I invite you to go to this website to learn a little more about the promise.
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Promises

A: The callback is executed after the code returned xhr.responseText. So that means xhr.responseText returns null.
I would recommend using the fetch API opposed to the older XMLHttpRequest you are using now. The fetch API is basically a Promise based XMLHttpRequest.
Your function would look something like:

async function getResponse( url, applicationName ) {
  const json = JSON.stringify({
    "application": applicationName
  });
  return fetch( url, {method: 'POST', headers: { 'Content-Type':'application/json'}, body: json} );
}

// access like this

getResponse( url, applicationName)
.then( response => { console.log(response) });

async function someFunction( url, applicationName ) {
  // or pause the code while the request is fetched by using await, note that you need to be in a function that is declared async to use this approach.
  const response = await getResponse( url, applicationName );
}

Fetch documentation can be found at MDN: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch


text:
Q: django-rest returning http 301 status code when calling http delete without trailing slash I recently experienced that on django rest framework a http 301 status code is returned when making a delete request, without including the trailing slash in the url when trailing_slash=True. While missing the trailing slash on a post request would return a runtime error. So my question is, is this a bug or is it expected behavior?

A: The 301 is expected because Django redirects you to the URL with the trailing slash since you have trailing_slash=True. See APPEND_SLASH settings if you want to change that.


text:
Q: JS export to excel is formatting numeric columns as text I am using a js function exporting few tables to tabs to a single Excel file, the problem is that the columns from the 2ed column and further, are numeric columns and they are exported as text, how can I set these columns data type to number by this code?
I have tried to render these columns but with no success.
Thanks in advance

var tablesToExcel = (function () {
    var uri = 'data:application/vnd.ms-excel;base64,'
        , tmplWorkbookXML = '<?xml version="1.0"?><?mso-application progid="Excel.Sheet"?><Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">'
            + '<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"><Author>Axel Richter</Author><Created>{created}</Created></DocumentProperties>'
            + ''
            + ''
            + '</Styles>'
            + '{worksheets}</Workbook>'
        , tmplWorksheetXML = '<Worksheet ss:Name="{nameWS}">
{rows}
</Worksheet>'
        , tmplCellXML = '<Cell{attributeStyleID}{attributeFormula}><Data ss:Type="{nameType}">{data}</Data></Cell>'
        , base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) }
        , format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) }
    return function (tables, wsnames, wbname, appname) {
        var ctx = "";
        var workbookXML = "";
        var worksheetsXML = "";
        var rowsXML = "";

        for (var i = 0; i < tables.length; i++) {
            if (!tables[i].nodeType) tables[i] = document.getElementById(tables[i]);
            for (var j = 0; j < tables[i].rows.length; j++) {
                rowsXML += '<Row>'
                for (var k = 0; k < tables[i].rows[j].cells.length; k++) {
                    var dataType = tables[i].rows[j].cells[k].getAttribute("data-type");
                    var dataStyle = tables[i].rows[j].cells[k].getAttribute("data-style");
                    var dataValue = tables[i].rows[j].cells[k].getAttribute("data-value");
                    dataValue = (dataValue) ? dataValue : tables[i].rows[j].cells[k].innerHTML;
                    var dataFormula = tables[i].rows[j].cells[k].getAttribute("data-formula");
                    dataFormula = (dataFormula) ? dataFormula : (appname == 'Calc' && dataType == 'DateTime') ? dataValue : null;
                    ctx = {
                        attributeStyleID: (dataStyle == 'Currency' || dataStyle == 'Date') ? ' ss:StyleID="' + dataStyle + '"' : ''
                        , nameType: (dataType == 'Number' || dataType == 'DateTime' || dataType == 'Boolean' || dataType == 'Error') ? dataType : 'String'
                        , data: (dataFormula) ? '' : dataValue
                        , attributeFormula: (dataFormula) ? ' ss:Formula="' + dataFormula + '"' : ''
                    };
                    rowsXML += format(tmplCellXML, ctx);
                }
                rowsXML += '</Row>'
            }
            ctx = { rows: rowsXML, nameWS: wsnames[i] || 'Sheet' + i };
            worksheetsXML += format(tmplWorksheetXML, ctx);
            rowsXML = "";
        }

        ctx = { created: (new Date()).getTime(), worksheets: worksheetsXML };
        workbookXML = format(tmplWorkbookXML, ctx);

        console.log(workbookXML);

        var link = document.createElement("A");
        link.href = uri + base64(workbookXML);
        link.download = wbname || 'Workbook.xls';
        link.target = '_blank';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
})();
<!DOCTYPE html>

    <meta charset=utf-8 />
    <title>DataTables - JS Bin</title>

            Product
            Price
            Available
            Count

            Bred

                1

                2

                3

            Butter

                4

                5

                6

            Product
            Price
            Available
            Count

            Bred

                7

                8

                9

            Butter

                14

                15

                16

    <button onclick="tablesToExcel(['tbl1','tbl2'], ['ProductDay1','ProductDay2'], 'TestBook.xls', 'Excel')">Export to Excel</button>

A: Check this: JsFiddle
Basically you must add this to every td
100.00

You can change the format...
Source


text:
Q: C: flip integer value as a boolean I'm looking a way to flip an integer value (8bits) using it as a boolean (0 -> False, 1 -> True).
On many languages you can do val = !val to change the value. The only thing I have done is val = (val == 1) ? 0 : 1. I don't know if in C can work with a bite value.
It is for an old hardware with a 8bit processor, so the idea of use boolean is not possible, and I can't install external libraries.

A: In C a value of 0 is considered "false", and any other (nonzero) value is considered "true".  So one, very explicit way to convert an arbitrary int value to an explicitly true-or-false Boolean value is to use the (C99 and later) bool type:
#include <stdbool.h>

int i;
bool b;

b = (i != 0) ? true : false;

But since the != operator essentially "returns" a Boolean value, you can also do
b = (i != 0);

And since the zero/nonzero definition is built in to the language, you can also just do
b = i;

But you don't have to use type bool.  If you have an arbitrary-value int and you want to force it to 0/1 "in place", you have the same sorts of options:
i = (i != 0) ? 1 : 0;

Or
i = (i != 0);

Or there's another common trick:
i = !!i;

This last is concise, popular, and somewhat obscure.  It changes zero/nonzero to 1/0 and then back to 0/1.
I've shown these examples using type int, but they would all work just as well with short int or char (i.e. byte).

One more thing.  In your question you wrote val = (val == 1) ? 0 : 1, but that's basically meaningless.  In C, at least, everything (everything!) follows from whether a value is zero or nonzero.  Explicit comparisons with 1 are almost always a bad idea, if not a downright error.

A: I posted one answer, but I may have misread the question.  If you have an integer variable -- it might be int, short int, or char -- and you want to have it cycle back and forth 0, 1, 0, 1 (which you can interpret as false, true, false, true), there are two about equally good ways to do it.  You could do:
i = !a;

This first way emphasize the "Boolean" nature of the variable.
Or, you could do:
i = 1 - i;

This second way is purely numeric.
But either way will work perfectly well.  In either case, i is guaranteed to alternate 0, 1, 0, 1, ...
You could also use
i = i ? 0 : 1;

or
i = (i == 0) ? 1 : 0;

Both of these will work, too, but they're basically equivalent to i = !i.
In your question you suggested
i = (i == 1) ? 0 : 1;

This would mostly work, but it looks weird to my eye.  Also it would do the wrong thing if i ever ended up containing 2 (or any value other than 0 or 1).

A: Adding to Summit's answer, you can also do this:
#define TRUE ~0U
#define FALSE 0U

#ifndef BOOL
#define BOOL unsigned int;
#endif

int main() {
    BOOL var = TRUE;
    var = ~var; //Negate var and set it to false.
    var = ~var; //Negate var again and set it to true.
    return EXIT_SUCCESS;
}

If you are using at least C99, then you can change
#ifndef BOOL
#define BOOL unsigned int;
#endif

to:
#include <stdint.h>

#ifndef BOOL
#define BOOL uint_fast8_t;
#endif


text:
Q: Overriding a @Path annotation in a class by method in JAX-RS I have a REST API service i maintain in java (over jersey, JAX-RS)
I want to support the following route in my service:
/api/v1/users/{userId}/cars

however, it concatinates to the class's @Path annotation. e.g.
/api/v1/cars/api/v1/users/{userId}/cars

This is my service class:
@Path("api/v1/cars")
public class CarsService {
    @GET
    @Path("/api/v1/users/{userId}/cars")
    public Response getUserCars(@PathParam("userId") Long userId) {
        // ...
    }

    @GET
    public Response getCars() {
        // ...
    }

}

Is there any way to override it?

A: Note the following:

*

*The @Path annotation in a class designates a root resource.

*The @Path annotation in a method designates a sub-resource of a root resource.

When placed on methods, the @Path annotation does not override the @Path annotation of the class. JAX-RS/Jersey performs a hierarchical matching using the @Path annotations.
So, you can try:
@Path("api/v1")
public class CarsService {

    @GET
    @Path("/cars")
    public Response getCars() {
        ...
    }

    @GET
    @Path("/users/{userId}/cars")
    public Response getUserCars(@PathParam("userId") Long userId) {
        ...
    }
}

However, have you considered using different resource classes?
@Path("api/v1/cars")
public class CarsService {

    @GET
    public Response getCars() {
        ...
    }
}

@Path("api/v1/users")
public class UsersService {

    @GET
    @Path("{userId}/cars")
    public Response getUserCars(@PathParam("userId") Long userId) {
        ...
    }
}

For more details on resources, have a look at the documentation.

A: You just should change the @Path annotation of the method to:
@Path("users/{userId}/cars")

In this way, the resulting path of concatenating the class and the method @Path annotations will produce your desired path.


text:
Q: How to safe a ObservableCollection within a ObservableCollection in xamarin.forms with Sqlite.net Last 3 days i tried to save my collection in my database.
I tried it in all sorts of ways... without success.
The last one i tried is to serialize my collection and save it to a byte[] everytime the collection changes.
And on appstart i tried to derserialize it in my collection.
I'm just trying to show the most important thing's.
I can save and reload this class without problems from my database.
[Serializable]
    public class MainElement : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public static int count = 0;
        [PrimaryKey]
        public int Id { get; set; }
        public string Name { get; set; }

        public byte[] _elements;

        private ObservableCollection<SecondElement> elements;

        [OneToMany]
        public ObservableCollection<SecondElement> Elements
        {
            get
            {
                return elements;
            }
            set
            {
                elements = value;
                this.SerializeElementsFromMainElement();
                //_elements = ExtensionAndDb.SerializeElementsFromMainElement(elements);
                OnPropertyChanged();
            }
        }

        public MainElement()
        {
            Id = count++;
            Elements = new ObservableCollection<SecondElement>();
            this.DeSerializeElementsFromMainElement();
            //Elements = ExtensionAndDb.DeSerializeElementsFromMainElement(_elements);
        }

        public void OnPropertyChanged([CallerMemberName] string propertyname = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyname));
        }
        public void DeSerializeElementsFromMainElement()
        {
            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream stream = new MemoryStream(_elements);
            using (stream)
            {
                Elements = bf.Deserialize(stream) as ObservableCollection<SecondElement>;
            }
        }
        public void SerializeElementsFromMainElement()
        {
            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream stream = new MemoryStream();
            using (stream)
            {
                bf.Serialize(stream, Elements);
                _elements = stream.ToArray();
            }
        }
    }

Every MainElement is stored in the MainList (ObservableCollection).
Everything is fine.
But i cant save or reload the public byte[] _elements; from/to the collection.
I know my code is not good, but if anyone has an idea or can show me how to save the public ObservableCollection<SecondElement> Elements with my class together in Sqlite, i would be really grateful.
I've been trying for 3 days
if you need more code, let me know.
Thank's in advance.

A: According to your description, you want to serialize and deserialie ObservableCollection, I suggest you ca use Newtonsoft.Json to do this.
Installing Newtonsoft.Json by Nuget package firstly.
For example, I do one esample:
public class person
{
    public string username { get; set; }
    public int age { get; set; }
}

public ObservableCollection<person> persons { get; set; }
private string list;
    public Page13()
    {
        InitializeComponent();
        persons = new ObservableCollection<person>()
        {
            new person(){username="cherry",age=12},
            new person(){username="barry",age=14}
        };

    }

Btn1.clicked is to serialize data, Btn2.clicked is to deserialize data.
 private void Btn1_Clicked(object sender, EventArgs e)
    {
         list = Newtonsoft.Json.JsonConvert.SerializeObject(persons);

    }

    private void Btn2_Clicked(object sender, EventArgs e)
    {
        var myValue = Newtonsoft.Json.JsonConvert.DeserializeObject<ObservableCollection<person>>(list) ;
    }

If the Observablecollection changed, you can query this data by Id or other, then update this data.
Here is the article about Update, insert and save data in sqlite, you can take a look:
https://dzone.com/articles/register-and-login-using-sqlite-in-xamarinforms


text:
Q: Lighttpd redirect I am re-jigging my website and would like to redirect (not rewrite but not hang up on this) the majority of requests to *.php files to their equivalent *.html files.
I have placed all the files I do not want redirected in one folder aptly named excluded, so I can filter the redirect rule on that folder. Here's what I have in my lighttpd.conf file:
$HTTP["url"] !~ "^/excluded/" {
  $HTTP["url"] =~ "^(.*)\.php(.*)" {
    # this is where I want the redirect rule
  }
}

EDIT: I am not sure whether I am missing a $ at the end of the second conditional rule (or whether the ending (.*) is necessary), but I suppose that is where I'd like help with.

A: $HTTP["url"] !~ "^/excluded/" {
  url.redirect = ( "^(.*)\.php(.*)" => "$1.html$2" )
}

A: OK, the above marked answer did help, however the one that worked, having added another directory to exclude was a little different.
$HTTP["url"] !~ "/(excluded|otherfolder)/" {
   url.redirect = ( "^(.*)\.php(.*)" => "$1.html$2" )
}


text:
Q: JList append row at top instead at bottom I was searching on web regarding this but could not find any relevant answer. Actually, my JList currently appends new row at the bottom of list. What my problem case needs is I want to add or prepend new row added to my JList model (at the top). How can I achieve this?

A: Had you visited the java docs, you would have known of a certain method add(int index, Object element)  for the listModel which in case should be used to insert the element at the index you desire.
EXAMPLE:
DefaultListModel myListModel = (DefaultListModel) myList.getModel();
myListModel.add(0, "new row added at top");


text:
Q: How to make DAO thread safe JPA? I am new to JPA and Java. I understood how EntityManager and EMF works a littel bit. I have JPAUtill from where I get EntityManager, which is using ThreadLocal variable, which makes EntityManager thread safe. I have DAO where in I am persisting new users when having 10 thousand thread accesses simultaneously.
I get to see following exception:
javax.persistence.PersistenceException: org.hibernate.SessionException: Session is closed!
        at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:614)

Here is my DAO code
try{
    entityManager = JPAUtil.getEntityManager();
    user.setArea(getArea());
    user.setCity(getCity());
    user.setPassword("xxxxx");
    user.setEmail_Id(getEmail_Id());
    user.setMobile_Num(TempMobile_Num);
    user.setFirst_Name(getFirst_Name());
    user.setSession_Id("0");
    user.setEmail_Verification_Status("NOT VERIFIED");
    user.setBalance(new BigDecimal(0.00));
    if (!entityManager.getTransaction().isActive()){
        entityManager.getTransaction().begin();
    }
    entityManager.persist(user);
    JPAUtil.commit();
} catch (Exception e) {
    logger.info(e);
    e.printStackTrace();
} finally{
    if(entityManager.isOpen())
    JPAUtil.closeEntityManager();
}

JPAUtil:
public class JPAUtil {

    private static Logger logger = Logger.getLogger(JPAUtil.class);
    private static EntityManager entityManager = null;
    private static final ThreadLocal<EntityManager> threadLocal;

    private static EntityManagerFactory emf = null;

    static {
        try {
            emf = Persistence.createEntityManagerFactory("XYZDB");
            threadLocal = new ThreadLocal<EntityManager>();
        } catch (Throwable ex) {
            logger.info("JPAUtil Exception", ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static EntityManager getEntityManager() {
        try {
            entityManager = threadLocal.get();

            if (entityManager == null || !entityManager.isOpen()) {

                JPAUtil.entityManager = emf.createEntityManager();
                threadLocal.set(entityManager);

            } else if (!emf.isOpen()) {
                entityManager = threadLocal.get();
                emf = Persistence.createEntityManagerFactory("XYZDB");
                JPAUtil.entityManager = emf.createEntityManager();
                threadLocal.set(entityManager);
            }
        } catch (Throwable ex) {
            logger.info("JPAUtil Exception", ex);
            throw new ExceptionInInitializerError(ex);
        }
        return JPAUtil.entityManager;
    }

    public static void closeEntityManager() {
        EntityManager entityManager = threadLocal.get();
        if (entityManager != null) {
            entityManager.close();
            threadLocal.set(null);
        }
    }

    public static void closeEntityManagerFactory() {
        emf.close();
    }

    public static void commit() {
        if (!entityManager.getTransaction().isActive()) {
            entityManager.getTransaction().begin();
        }
        entityManager.getTransaction().commit();
    }

    public static void rollback() {
        if (!entityManager.getTransaction().isActive()) {
            entityManager.getTransaction().begin();
        }
        entityManager.getTransaction().rollback();
    }
}

Can someone please help me understand the issue and how to resolve it?

A: Remove this static variable form JPAUtil:
private static EntityManager entityManager = null;

You were still using a static variable; you didn't really use the ThreadLocal.
Change your getEntityManager to this:
public static EntityManager getEntityManager() {
    EntityManager entityManager;
    try {
        entityManager = threadLocal.get();

        if (entityManager == null || !entityManager.isOpen()) {
            entityManager = emf.createEntityManager();
            threadLocal.set(entityManager);

        }
    } catch (Throwable ex) {
        logger.info("JPAUtil Exception", ex);
        throw new ExceptionInInitializerError(ex);
    }
    return entityManager;
}


text:
Q: Aspnet identity: manage users using a generic class I have defined 3 classes that inherit from IdentityUser since I want to store different properties for each type of user but have the common ones in one class.
My question is how can i have a generic usermanager class that loads the correct membership type
A simple example
public class MembershipUser : IdentityUser
{
    public DateTime? Birthdate { get; set; }
    .
    .
    .
}

public class Membership1 : MembershipUser
{
    public int? Level_ID { get; set; }
    .
    .
    .
}

public class Membership2 : MembershipUser
{
    public int? Count { get; set; }
    .
    .
    .
}

I want to have a generic usermanager class
like this
public class UserManager<T> : UserManager<T>  where T: IUser
{
public UserManager()
                : base(new UserStore<T>(new MembershipManagementContext()))
{
}

but i get an error "Error   1   'object' does not contain a constructor that takes 1 arguments"

A: In order to use generics UserManager** the classes you want to use have to have a parameterless constructor. So forexample the MembershipUser must contain:
public MembershipUser()
{
  // Initialization
}


text:
Q: Popen xauth list I am trying to run a wxpython script via VNC. When i try to open it i get the error:
X11 connection rejected because of wrong authentication.
Unable to access the X Display, is $DISPLAY set properly?
I solve it via:
xauth list
sudo xauth add raspberrypi/unix:10 MIT-MAGIC-COOKIE-1

and then the corresponding cookie. Thing is i wanted to automate this in the init of the script, so that the user would not need to do it every time. i have written the following script:
import subprocess
import string

p=subprocess.Popen(['xauth','list'],stdout=subprocess.PIPE)
(out,err)=p.communicate()
out1=out.split('\n')
for line in out1:
 t=line.split()
 y=subprocess.Popen(['sudo','xauth','add',t[0],t[1],t[2]],stdout=subprocess.PIPE)

which works fine but i am still not able to get the program to run. Checking the output i realize that i am not getting the same output if i run xauth list from shell and if i run it with Popen.
Any help would be much appreciated!


text:
Q: Merge two objects without override I have a defaultObject like that:
var default = {
    abc: "123",
    def: "456",
    ghi: {
       jkl: "789",
       mno: "012"
    }
};

And I have another like:
var values = {
    abc: "zzz",
    ghi: {
       jkl: "yyy",
    }
};

How can I merge those 2 objects with the following result (no override)?
var values = {
    abc: "zzz",
    def: "456",
    ghi: {
       jkl: "yyy",
       mno: "012"
    }
};

(I don't want to change the default object!)

A: Also if you are happy with ES6:
Object.assign({}, default, values)

A: Another way would be to simply extend value by default (instead of the other way around which would override default)
Object.assign(value, default) // values of default overrides value
default = value // reset default to value

The caveat here is that the content of value is changed as well. Upside is no library is required and easier than the plain vanilla solution above.

A: My version based on Oriol's answer adds a check for arrays, so that arrays don't get transformed into funny {'0': ..., '1': ...} thingys
function extend (target) {
  for(var i=1; i<arguments.length; ++i) {
    var from = arguments[i];
    if(typeof from !== 'object') continue;
    for(var j in from) {
      if(from.hasOwnProperty(j)) {
        target[j] = typeof from[j]==='object' && !Array.isArray(from[j])
          ? extend({}, target[j], from[j])
          : from[j];
      }
    }
  }
  return target;
}

A: For those who don't use jQuery, here comes a vanilla-js solution.
Solution:
function extend (target) {
    for(var i=1; i<arguments.length; ++i) {
        var from = arguments[i];
        if(typeof from !== 'object') continue;
        for(var j in from) {
            if(from.hasOwnProperty(j)) {
                target[j] = typeof from[j]==='object'
                ? extend({}, target[j], from[j])
                : from[j];
            }
        }
    }
    return target;
}

Compressed (with Closure Compiler):
Only 199 characters!
var extend=function e(c){for(var d=1;d<arguments.length;++d){var a=arguments[d];if("object"===typeof a)for(var b in a)a.hasOwnProperty(b)&&(c[b]="object"===typeof a[b]?e({},c[b],a[b]):a[b])}return c}

How to use:
extend(target, obj1, obj2); // returns target

If you only want to merge, use
var merged = extend({}, obj1, obj2);

Features:

*

*It doesn't look at objects' prototype.

*Ignores non-objects.

*It is recursive in order to merge properties which are objects.

*Objects referenced in target's properties, if extended,  are replaced by new ones, and the original ones are not modified.

*In case of same property names, the merged value will be the merging of the objects after the last (in the order of arguments) non-object value. Or, if the last isn't an object, itself.

Examples:
extend({}, {a:1}, {a:2});            // {a:2}
extend({}, {a:1}, {b:2});            // {a:1, b:2}
extend({}, {a: {b:1}}, {a: {b:2}});  // {a: {b:2}}
extend({}, {a: {b:1}}, {a: {c:2}});  // {a: {b:2, c:2}}
extend({}, {a: {a:1}}, {a: {b:2}}, {a: 'whatever non object'});
    // {a: "whatever non object"}
extend({}, {a: {a:1}}, {a: {b:2}}, {a: 'whatever non object'}, {a: {c:3}},{a: {d:4}});
    // {a: {c:3, d:4}}

Warning:
Be aware that if browser is not clever enough, it could be trapped in an infinite loop:
var obj1={},
    obj2={};
obj1.me=obj1;
obj2.me=obj2;
extend({},obj1,obj2);

If the browser is clever enough, it can throw an error, or return {me: undefined}, or whatever.
Note that this warning also applies if you use jQuery's $.extend.

A: With ES2015 now being supported in all modern browsers, the native Object.assign can be used to extend objects
Object.assign({}, _default, values)

Object.assign
Note that default is a reserved keyword, and can't be used as a variable name

The original answer, written in 2013 :
Since this is tagged with jQuery, you could use $.extend for a simple cross-browser solution
var temp = {};
$.extend(true, temp, _default, values);
values = temp;

A: I found that the easiest way to to this is to use mergeWith() from lodash ( https://lodash.com/docs/4.17.15#mergeWith ) which accepts a customizer function that decides what to do with every property merge. Here is one that is recursive :
const mergeFunction = (objValue, srcValue) => {
  if (typeof srcValue === 'object') {
    _.mergeWith(objValue, srcValue, mergeFunction)
  } else if (objValue) {
    return objValue
  } else {
    return srcValue
  }
}