text:
Q: Triple integral bounds
*

*Let $W$ be the region bounded by the planes
$x = 0$, $y = 0$, $z = 0$, $x + y = 1$, and $z = x + y$.

*$(x^2 + y^2 + z^2)\, \mathrm dx\, \mathrm dy\, \mathrm dz$; $W$ is the region bounded by $x + y + z = a$ (where $a > 0$), $x = 0$, $y = 0$, and $z = 0$.
$x,y,z$ being $0$ is throwing me off because I'm not sure how to graph it and get a bounded area; it seems like it would be infinite to me. What would the bounds for the triple integrals be?

A: 1)

$$\int_{x=0}^{x=1}\int_{y=0}^{y=1-x}\int_{z=0}^{z=x+y}\ dzdydx $$
2)

$$\int_0^{x=a}\int_0^{y=a-x}\int_0^{a-x-y} (x^2 + y^2 + z^2) \;dz\;dy\;dx$$

A: 1) give you nothing to integrate.  But we can still find the limits
$z = 0$ lower limit for $z$
$z = x+y$ upper limit for $z$
$y = 0$ lower limit for $y$
$y = 1-x$ upper limit for $y$
$x = 0$ lower limit for $x$
$x = 1$ upper limit for $x$
For the last one, because that is where $y = 0$ intersects $x+y = 1$
2)
$\int_0^a\int_0^{a-x}\int_0^{a-x-y} x^2 + y^2 + z^2 \;dz\;dy\;dx$


text:
Q: Displaying data from mysql into android studio using JSON i want to display data from mysql into android using textview,, but when im running the app, its goes force stop itself,
can someone help me how to fix it,,
any idea would be nice
dbconfig.php
<?php

//This script is designed by Android-Examples.com
//Define your host here.
$servername = "localhost";
//Define your database username here.
$username = "root";
//Define your database password here.
$password = "";
//Define your database name here.
$dbname = "u727224026_demo";

?>

send-data.php
<?php
include 'dbconfig.php';

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM TextViewTable";
$result = $conn->query($sql);

if ($result->num_rows > 0) {

    // output data of each row
    while($row[] = $result->fetch_assoc()) {

       $json = json_encode($row);

    }
} else {
    echo "0 results";
}
echo $json;
$conn->close();
?>

MainActivity.java
package flix.yudi.kuesioner2;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends Activity {

    TextView textview;
    JSONObject json = null;
    String str = "";
    HttpResponse response;
    Context context;
    ProgressBar progressbar;
    Button button;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        progressbar = (ProgressBar)findViewById(R.id.progressBar1);
        textview = (TextView)findViewById(R.id.textView1);
        button = (Button)findViewById(R.id.button1);

        progressbar.setVisibility(View.GONE);

        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                progressbar.setVisibility(View.VISIBLE);

                new GetTextViewData(context).execute();

            }
        });
    }

    private class GetTextViewData extends AsyncTask<Void, Void, Void>
    {
        public Context context;

        public GetTextViewData(Context context)
        {
            this.context = context;
        }

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... arg0)
        {

            HttpClient myClient = new DefaultHttpClient();
            HttpPost myConnection = new HttpPost("192.168.1.139/a_test/send-data.php");

            try {
                response = myClient.execute(myConnection);
                str = EntityUtils.toString(response.getEntity(), "UTF-8");

            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try{
                JSONArray jArray = new JSONArray(str);
                json = jArray.getJSONObject(0);

            } catch ( JSONException e) {
                e.printStackTrace();
            }

            catch (Exception e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }
        protected void onPostExecute(Void result)
        {
            try {
                textview.setText(json.getString("ServerData"));

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            //Hiding progress bar after done loading TextView.
            progressbar.setVisibility(View.GONE);

        }
    }

}

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.jsonparsingfromurltextview_android_examples.com.MainActivity" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:text="TextView Static Text Before Load"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:gravity="center"/>

<ProgressBar
    android:id="@+id/progressBar1"
    style="?android:attr/progressBarStyleLarge"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView1"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="17dp" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="150dp"
    android:text="Click Here to Load TextView data dynamically from MySQL Database Online Using JSON Parsing" />

logcat error notif
10-03 08:35:35.486 1754-2070/flix.yudi.kuesioner2 E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
                                                                Process: flix.yudi.kuesioner2, PID: 1754
                                                                java.lang.RuntimeException: An error occured while executing doInBackground()
                                                                    at android.os.AsyncTask$3.done(AsyncTask.java:300)
                                                                    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
                                                                    at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
                                                                    at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                                                                    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
                                                                    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                                    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                                    at java.lang.Thread.run(Thread.java:841)
                                                                 Caused by: java.lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=192.168.1.139/a_test/send-data.php
                                                                    at org.apache.http.impl.client.DefaultRequestDirector.determineRoute(DefaultRequestDirector.java:591)
                                                                    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:293)
                                                                    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
                                                                    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
                                                                    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
                                                                    at flix.yudi.kuesioner2.MainActivity$GetTextViewData.doInBackground(MainActivity.java:84)
                                                                    at flix.yudi.kuesioner2.MainActivity$GetTextViewData.doInBackground(MainActivity.java:60)
                                                                    at android.os.AsyncTask$2.call(AsyncTask.java:288)
                                                                    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
                                                                    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                                    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                                    at java.lang.Thread.run(Thread.java:841)

i tried to find how to fix it, but still nothing,
please help me,
ADDITIONAL INFO RESPONSE

A: Try adding some scheme like http or https to the URL:
http://192.168.1.139/a_test/send-data.php

A: First of all try ur service call in postman ... check whether you r getting right response from 192.168.1.139/a_test/send-data.php
follow her to get postman plugin
Check give code below
 private String makeRESTService(String methodNameWithUrl) throws JSONException {
        final String KEY_USER_NAME = "username";
        final String KEY_PASSWORD = "password";
        System.out.println("url" + methodNameWithUrl);
        String jsonResult = null;
        String jsonObj = null;

        //create a json string
        JSONObject parent = new JSONObject();
        parent.put(KEY_USER_NAME, "manu");
        parent.put(KEY_PASSWORD, "1234");
        Log.e("To json", jsonObj);

        URL url = null;

        HttpURLConnection urlConnection = null;
        try {
            url = new URL("your url"); //place your url
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(10000);
            urlConnection.setConnectTimeout(15000);

            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("Content-Type", "application/json");
            OutputStream os = urlConnection.getOutputStream();

            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(jsonObj);
            writer.flush();
            writer.close();
            os.close();

            urlConnection.connect();
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            jsonResult = inputStreamToString(in)
                    .toString();
            Log.e("jsonResult", jsonResult);

            //   readStream(in);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            urlConnection.disconnect();
        }
        return jsonResult;

    }

    private StringBuilder inputStreamToString(InputStream is) {
        String rLine = "";
        StringBuilder answer = new StringBuilder();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader rd = new BufferedReader(isr);
        try {
            while ((rLine = rd.readLine()) != null) {
                answer.append(rLine);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return answer;
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mongo java maching two or more values in mongo array I am new to mongodb.I am trying to match username and password in collection array. My sample doc is
{
    "_id" : ObjectId("51f20148a85e39af87510305"),
    "group_name" : "sai",
    "users" : [
            {
                "full_name" : "sumit",
                "user_name" : "sumitdesh",
                "password" : "mggg",
                "status" : "Active"
            },
            {
                "full_name" : "ad",
                "user_name" : "asd",
                "password" : "asdf",
                "status" : "Active"
            },
}

I am trying to match user name and password enter by user in above array.If user name and password match with our data,user will get login.  My java code is
BasicDBObject u = new BasicDBObject("users.user_name", uname);
 BasicDBObject p = new BasicDBObject("users.password", password);
 f=con.coll.find(u,p);

A: Your document structure might get in the way here. How do you distinguish the user logging in? If you get a match, it will return the whole document, with all users.
Anyhow, to query with multiple comparisons:
BasicDBObject query = new BasicDBObject();
List<BasicDBObject> parts = new ArrayList<BasicDBObject>();
parts.add(new BasicDBObject("users.user_name", uname));
parts.add(new BasicDBObject("users.password", password));
query.put("$and", parts);

DBCursor cursor = collection.find(query);
while (cursor.hasNext()) {
    System.out.println(cursor.next());
}

A: You need to use the $elemMatch query operator.
Something like this should work:
BasicDBObject elementQuery = new BasicDBObject("user_name", uname);
element.put("password", password);

BasicDBObject query = new BasicDBObject("users",
                         new BasicDBObject("$elemMatch", elementQuery);

f=con.coll.find(query);

Rob.
P.S. On a side note - having all of the users in a single document is probably not optimal.  Have you considered having a separate document for each user with the user name and password?
An example of a schema that might perform better is to divide the groups and users into two collections.  Each user will have a document like:
{
    "_id" : "sumitdesh",
    "full_name" : "sumit",
    "password" : "mggg",
    "status" : "Active"
    "groups" : [ "sai", "admin" ],
}

You will probably want to index the 'groups' if you query for all of the members of a group often.
The groups document will then look like:
{
    "_id" : "sai",
    "permissions" : [ "read", "write_secrets" ]
}

Index permissions.
A check for read permission for the sumitdesh user is then:
db.groups.findOne(
    {
         _id : { "$in" : [ "sai", "admin" ] } ,
         "permissions" : "read"
    }
);

Note that the array for the '$in' same as the array of groups from 'sumitdesh' user document.
P.P.S. ...and when you say password you mean a hash (SHA-2?) of the salted password? Right?


text:
Q: Session data is not saving to memory while using express-session I am encountering a problem when I try the following example using different express-session versions.
Using express-session 1.0.2:
var connect = require('express'),
    cookieParser = require('cookie-parser'),
    session = require('express-session');

var app = connect();
app.use(cookieParser())
.use(session({secret:'sessionsecret',cookie:{maxAge:60000}}))
.use(function(req,res,next){
    if(req.session.views){
        res.setHeader('Content-Type','text/html');
        res.write('
views ' + req.session.views + '
');
        //Here
        res.end();
        req.session.views++;
    }
    else {
        req.session.views = 1;
        res.end('welcome to the demoe. Try refresh this page');
    }

})
.listen(3000);

This works; the view counter keeps increasing when I refresh the page.
However, when I change express-session to 1.8.2 (the latest), that code ceases to work and the view counter stays at 1. But after I modify the code into following, it works again:
var connect = require('express'),
cookieParser = require('cookie-parser'),
session = require('express-session');

var app = connect();
app.use(cookieParser())
.use(session({secret:'sessionsecret',cookie:{maxAge:60000}}))
.use(function(req,res,next){
    if(req.session.views){
        res.setHeader('Content-Type','text/html');
        res.write('
views ' + req.session.views + '
');
        //Here
        req.session.views++;
        res.end();
    }
    else {
        req.session.views = 1;
        res.end('welcome to the demoe. Try refresh this page');
    }

})
.listen(3000);

It seems the session data is saving before the response is sent in the new express-session. Can someone explain this?

A: Yes, ExpressJS sessions cannot save the req.session object after res.end() is called - or any content data is sent.
The reason it does this is because cookies can only be set (therefor the session can only be saved) when the headers are being sent; after the headers are sent (and content is sent), the cookie cannot be reset and the session cannot be saved.
You can see the code in action here.


text:
Q: Call powershell replace from batch file with variables I need to replace a string by a user input in a xml file from a batch file, I made it working by using powershell "replace" command and calling it from the batch but I can't figure how to use batch variable inside the powershell command.
Working :
powershell -Command "(gc personalWifiProfile.xml) -replace 'password','somePassword' | Out-File -encoding ASCII tempProfile.xml"

Not working :
set /p pwd="Enter pwd: "
powershell -Command "(gc personalWifiProfile.xml) -replace 'password','%pwd%' | Out-File -encoding ASCII tempProfile.xml"

Info : I'm on Windows 7
Edit :
With simpler script, it work so the problem seems to come from elsewhere in my script (the brightness part is working fine).
for /f "tokens=3" %%i in ('netsh wlan show interface ^| findstr /i "SSID"') do set "myssid=%%i" & goto next
:next
set "myssid=%myssid: =%"
if /i "%myssid%"=="someSSID" (
set "brightness=80"
 ) ELSE (
set "brightness=30"
set /p pwd="Enter pwd: "
powershell -Command "(gc personalWifiProfile.xml) -replace 'password','%pwd%' | Out-File -encoding ASCII tempProfile.xml"
pause
)
CALL "brightness.bat" "%brightness%"

The execution order between the test and real script seems different. Here is the working test script :
set /p pwd="Enter pwd: "
echo %pwd%
powershell -Command "(gc personalWifiProfile.xml) -replace 'password','%pwd%' | Out-File -encoding ASCII tempProfile.xml"
pause

With it's output :
>set /p pwd="Enter pwd: "
Enter pwd: hell
>echo hell
hell
>powershell -Command "(gc personalWifiProfile.xml) -replace 'password','hell' | Out-File -encoding ASCII tempProfile.xml"
>pause
Appuyez sur une touche pour continuer...

And the output of the full script :
>for /F "tokens=3" %i in ('netsh wlan show interface | findstr /i "SSID"') do set "myssid=%i"   & goto next
>set "myssid=mySSID"   & goto next
>set "myssid=mySSID"
>if /I "mySSID" == "SomeSSID" (set "brightness=80" )  ELSE (
set "brightness=30"
 set /p pwd="Enter pwd: "
 powershell -Command "(gc personalWifiProfile.xml) -replace 'password','' | Out-File -encoding ASCII tempProfile.xml"
 pause
)
Enter pwd: 123
Appuyez sur une touche pour continuer...

A: You require delayedexpansion, note the replacement of % with ! in the variable as well !pwd!:

setlocal enabledelayedexpansion
if /I "mySSID" == "SomeSSID" (
      set "brightness=80"
   )  ELSE (
      set "brightness=30"
      set /p pwd="Enter pwd: "
      powershell -Command "(gc personalWifiProfile.xml) -replace 'password','!pwd!' | Out-File -encoding ASCII tempProfile.xml"
      pause
)

I only show part of the code relevant to your issue, so be sure you place setlocal enabledelayedexpansion` in the correct position, should you have other code blocks setting and using variables.


text:
Q: How do I install GCC 4.5.2 in Ubuntu 10.10? I have Ubuntu 10.10. The command: g++ -v evokes the response
gcc version 4.4.5 (Ubuntu/Linaro 4.4.4-14ubuntu5)
And the command sudo apt-get install g++ evokes the response
g++ is already the newest version.
However, the following site tells me that the latest version of GNU is 4.5.2:
   http://gcc.gnu.org/
How do I upgrade my GCC compiler to the latest 4.5.2?

A: The apt-get install command tells you that this is the latest version depending on the Ubuntu repositories.
The GCC website tells you the latest version developed by GCC project. That is it.
So, you need to install the package from source if you want to run the latest version or wait until Ubuntu guys releases a new version to catch the current release. This is general and not related to GCC project only.

A: I did the following, and it works:
On the Ubuntu 10.10 menu:
System -> Admin -> Synaptic Package Manager -> search for g++-4.5 and mark all for install.
Ensure you mark the dependencies as well.
Go to folder   /usr/bin
and give the commands
ls -l g*
sudo rm g++ gcc
sudo ln -s g++ g++-4.5
sudo ln -s gcc gcc-4.5

Now to compile any C++0x programs you need to give the command
g++ -std=c++0x <source_file_name>.cpp


text:
Q: Access parent node from virtualDOM before it renders | ReactJS I need to set component dimensions depending on parent element. Is it possible to get width and height of parent by ref from virtualDOM before it renders?
Parent

export default class App extends React.Component {
  render() {

    return (

 { this.container = container; }}>
          <Resizer parent={this} scrollAxis={'y'}>
          </Resizer>

    );
  }
}

I need to get the dimensions in constructor of child.
Is is possible with something like this.refs.container.offsetWidth ?

A: No. Layout dimensions are calculated by the browser, not the Virtual DOM. Either set the dimensions by hand, or use CSS to make your child component fill width and height. You can also read the width and height from the rendered component in componentDidMount and call setState in there, which isn't ideal and will cause a second render, but sometimes needs to be done.


text:
Q: Non-Dimensionalizing Separation of Variables PDE I have a problem where I'm considering a cylinder with a closed end at the bottom (x = 0) and open end at the top (x = L).
The problem is looking at pressure disturbances throughout the air column.
The governing PDE is: $$\frac{∂^2p}{∂t^2}− C^2∇^2p = 0$$
where p is pressure (p(x,r,t)) and the laplace operator is defined as $$∇^2(.) = \frac{∂^2}{∂x^2}(.) + \frac{1}{r}\frac{∂}{∂r}{r\frac{∂}{∂r} (.)}$$
The boundary conditions are:
$$\frac{∂p}{∂x}(x = 0, r, t) = 0$$; $$p(x = L, r, t) = 0$$
$$\frac{∂p}{∂r} (x, r = a, t) = 0$$ $$p(x, r → 0, t)\, is\, finite$$
My strategy is Separation of Variables. This type of problem is very well-documented for p(x,t), but adding the radial coordinate confuses me a bit.
I'm trying to non-dimensionalize the problem, but I'm having issue choosing scaling variables that are significant.
The ones that I chose now are:
$$ l = \frac{x}{l}$$
$$\alpha= \frac{r}{a}$$
$$ s = \frac{Ct}{a}$$
I'm not sure if these are even correct for this type of problem, but even if, I'm not sure how to go about substituting into the PDE to make the PDE or boundary conditions non-dimensional.
Any insight into the non-dimensional process in general and as it pertains to this problem would be greatly appreciated!


text:
Q: How to add an additional custom column with select * all in Google Sheet Query How would you do this query in Google Sheet? I have 24 columns in my data so I would not like to enter all column names into the query.
If this is not possible for QUERY, then what is the alternative?
I want something like this:
select *, 'ICS'
label 'ICS' 'Type'

But I get an error doing so:
> Error In ARRAY_LITERAL, an Array Literal was missing values for one or
> more rows.

This is the result I want to display:
Expected output

A: ={QUERY(IMPORTRANGE('Static Data'!$B$2,"MASTERFILE!A:AC"),"select * where Col"& 'Static Data'!$B$19 &" is not null",1) ,{"TYPE";TRANSPOSE(SPLIT(REPT("ICS;",COUNT(IMPORTRANGE('Static Data'!$B$2,"MASTERFILE!B:B"))),";"))}}


text:
Q: MySQL get percentage from day I have a query which looks like this
select *
 from (

      select
        user_id,
        created_at,
        event_name,
        count(*) as num_of_events,
        (count(*)/SUM(count(*)) OVER (PARTITION BY created_at))*100 AS pct_of_daily_total
      from events
      where event_name = 'post_submit' or event_name = 'post_cancel'
      group by event_name, created_at ) sub

This yields a result that looks like this
user_id, created_at,    event_name,    num_of_event,    pct_of_daily_total
123      2019-01-01     post_submit    1                100.000
456      2019-01-02     post_cancel    1                25.000
456      2019-01-02     post_submit    3                75.000
456      2019-01-03     post_cancel    1                100.000

I am looking to have a final output which shows the success rate of each day regardless of user id. Each event type of post submit is a success, and post cancel is unsuccessful. The final result should be
dt             success_rate%
2019-01-01     100
2019-01-02     75
2019-01-03     0


text:
Q: Does anybody know the view plugin that appears on the mid-click. I remember it was a circle with some useful buttons I had this plugin 3 or 4 years ago and found it on omgubuntu. It looked like the circle panel that appears where you click. Just like the compass.
So many years past I wonder if it has support for 14.04 or 15.04.

A: Check Gnome-Pie
sudo apt-add-repository ppa:simonschneegans/testing
sudo apt-get update
sudo apt-get install gnome-pie

Start with gnome-pie via Dash or Activities

If you don't like Gnome-Pie, simply remove via
sudo purge-ppa ppa:simonschneegans/testing


text:
Q: When is a matrix-valued function the Hessian of some function? What are necessary and sufficient conditions for a matrix valued function $H: \mathbb{R}^d \rightarrow \mathbb{R}^{d\times{}d}$ to be the Hessian of a convex scalar function $F:\mathbb{R}^d \rightarrow \mathbb{R}$, i.e. $H(x) = \nabla^2 F(x)$.
I have heard informally that the following are necessary and sufficient:
1) $H(x)$ is symmetric and positive semi-definite
2) $\frac{\partial}{\partial x_k} H_{ij}(x) = \frac{\partial}{\partial x_j} H_{ik}(x)$ for all $i,j,k$
however, I have not been able to find any rigorous statement.


text:
Q: How can I detect how many capture groups are in a Perl Regexp? I have a bunch of perl regexps in a script. I would like to know how many capture groups are in them. More precisely I'd like to know how many items would be added to the @- and @+ arrays if they matched before actually use them in a real match op.
An example:
'XXAB(CD)DE\FG\XX' =~ /(?i)x(ab)\(cd\)(?:de)\\(fg\\)x/
    and print "'@-', '@+'\n";

In this case the output is:
'1 2 11', '15 4 14'

So after matching I know that the 0th item is the matched part of the string, and there are two capture group expressions. Would it be possible to know right before the actual match?
I tried to concentrate onto the opening brackets. So I removed the '\\' patterns first to make easier to detect the escaped brackets. Then I removed '\(' strings. Then came '(?'. Now I can count the remaining opening brackets.
my $re = '(?i)x(ab)\(cd\)(?:de)\\\\(fg\\\\)x'; print "ORIG: '$re'\n";
'XXAB(CD)DE\FG\XX' =~ /$re/ and print "RE: '@-', '@+'\n";
$re =~ s/\\\\//g; print "\\\\: '$re'\n";
$re =~ s/\\\(//g; print "\\(: '$re'\n";
$re =~ s/\(\?//g; print "\\?: '$re'\n";
my $n = ($re =~ s/\(//g); print "n=$n\n";

Output:
ORIG: '(?i)x(ab)\(cd\)(?:de)\\(fg\\)x'
RE: '1 2 11', '15 4 14'
\\: '(?i)x(ab)\(cd\)(?:de)(fg)x'
\(: '(?i)x(ab)cd\)(?:de)(fg)x'
\?: 'i)x(ab)cd\):de)(fg)x'
n=2

So here I know that 2 capture groups are in this regexp. But maybe there is an easier way and this is definitely not complete (e.g. this treats (?<foo>...) and (?'foo'...) as a non-caputre groups).
Another way would be to dump the internal data structures of regcomp function. Maybe the package Regexp::Debugger could solve the issue, but I have no right to install packages in my environment.
Actually the regexps are keys to some ARRAY refs and I'd like to check if the referenced ARRAY contains the proper amount of values before actually applying the regexps. Of course this checking can be done right after the pattern matching, but it would be nicer if I could do it in the loading stage of the script.
Thank you for your help and comments in advance!

A: Regex:
\\.(*SKIP)(?!)|\((?(?=\?)\?(P?['<]\w+['>]))

Explanation:
\\.                     # Match any escaped character
(*SKIP)(?!)             # Discard it
|                       # OR
\(                      # Match a single `(`
(?(?=\?)                # Which if is followed by `?`
    \?                      # Match `?`
    P?['<]\w+['>]           # Next characters should be matched as ?P'name', ?<name> or ?'name'
)                       # End of conditional statement

Perl:
my @offsets = ();
while ('XXAB(CD)DE\FG\X(X)' =~ /\\.(*SKIP)(?!)|\((?(?=\?)\?(P?['<]\w+['>]))/g){
    push @offsets, "$-[0]";
}
print join(", ", @offsets);

Output:
4, 15

Which represents existence of two capturing groups in input string.

A: Without any limiting requirements for the occuring regexes, there is no definitive answer to the number of capture groups, I think. Just think of alternatives with a differing capture group count and the possibility of this occuring again in each branch:
my $re = qr/ A(B)C | A(D|(E(G+|H))F /x;

This regex can obviously have up to 3 capture groups. You could recursively parse each branch, and take the highest number as your result - but I honestly cannot come up with a practical way to do this in a short time. For 'linear' regexes not using alternatives or non-basic regex features, the task of determining the count of capture groups is possible, but I don't think it's feasible with more advanced ones.

A: As Mr. Obama said: "Yes We Can!"
I found a solution which does not require additional module and handles all the possible capturing group events (as I know). As ikegami mentioned it needs reparsing of the regexp, but perl does it for us.
During digging in the haystack of Perl modules on CPAN I found a very interesting one called warnings::regex::recompile. It generates a warning message each time a regexp is re-compiled. Analyzing the source I found the solution of my problem.
Using use re qw/Debug DUMP/; Perl returns the parsed regex to STDERR. In the original module result is dumped to a real file and then reread to process. I modified the code to use in-memory file.
My solution is:
sub dumpre {
  use re qw(eval Debug DUMP);
  my $buf = '';

  open OLDERR, '>&', STDERR or die "$!";
  close STDERR or die "$!";
  open STDERR, '>', \$buf or die "$!";

  my $re = qr/$_[0]/;

  close STDERR or die "$!";
  open STDERR, '>&', OLDERR or die "$!";
  close OLDERR or die "$!";

  no re 'debug'; # Needed because of split

  return [ split '\n', $buf ];
}

This function turns on DUMP when compiling a regexp. Enables eval to be able to handle (?{...}) and (??{...}) expressions.
my $re = 'aa(?:(a\d)+x)?((b\d)*d)*c*(d\d)?(e*)((f)+)(g)+';
my $r = dumpre $re;
print join "\n", @$r;

The result is:
Compiling REx "aa(?:(a\d)+x)?((b\d)*d)*c*(d\d)?(e*)((f)+)(g)+"
Final program:
   1: EXACT <aa> (3)
   3: CURLYX[0] {0,1} (19)
   5:   CURLYM[1] {1,32767} (16)
   9:     EXACT <a> (11)
  11:     POSIXU[\d] (14)
  14:     SUCCEED (0)
  15:   NOTHING (16)
  16:   EXACT <x> (18)
  18: WHILEM (0)
  19: NOTHING (20)
  20: CURLYX[1] {0,32767} (40)
  22:   OPEN2 (24)
  24:     CURLYM[3] {0,32767} (35)
  28:       EXACT <b> (30)
  30:       POSIXU[\d] (33)
  33:       SUCCEED (0)
  34:     NOTHING (35)
  35:     EXACT <d> (37)
  37:   CLOSE2 (39)
  39: WHILEM[1/7] (0)
  40: NOTHING (41)
  41: STAR (44)
  42:   EXACT <c> (0)
  44: CURLYM[4] {0,1} (55)
  48:   EXACT <d> (50)
  50:   POSIXU[\d] (53)
  53:   SUCCEED (0)
  54: NOTHING (55)
  55: OPEN5 (57)
  57:   STAR (60)
  58:     EXACT <e> (0)
  60: CLOSE5 (62)
  62: OPEN6 (64)
  64:   CURLYN[7] {1,32767} (74)
  66:     NOTHING (68)
  68:     EXACT <f> (0)
  72:   WHILEM (0)
  73:   NOTHING (74)
  74: CLOSE6 (76)
  76: CURLYN[8] {1,32767} (86)
  78:   NOTHING (80)
  80:   EXACT <g> (0)
  84: WHILEM (0)
  85: NOTHING (86)
  86: END (0)
anchored "aa" at 0 floating "fg" at 2..9223372036854775807 (checking floating) minlen 4

So the lines with OPEN\d+, CURLYM[\d+], CURLYN[\d+] shows capturing bracket expressions (Line syntax: segment_no: regex command (next segment)). (Note: CURLYX is a non-capturing bracket expression like (?:...)+). The number after OPEN/CURLY[MN} shows the ordinal number of capturing group. The last has to be found. Which is 8 in this case.
Unfortunately it does not handle if the (??{...}) returns a bracket expression, but this is not really needed for me now.
I suppose the format is not fixed, so it can differ from version to version. But it is ok for me.


text:
Q: Too many Close_wait in jetty 9.0.3 We have an application REST gateway deployed over jetty 9.0.3 server.For authentication and authorization of services deployed in jetty is taken care by apache commons-httpclient3.1.
when there are huge number of concurrent threads hitting Rest gateway, lot of CLOSE_WAIT are piling up in REST gateway machine.
Http connections which are opened for sending request to enabler(END POINT)are closed properly by calling releaseConnections method of apache commons.
Please let me know how to handle these CLOSE_WAIT or any clues why connections are ending up in CLOSE_WAIT.

A: The close_wait connections vanished when closeIdleConnections(0) provided by Apache commons http Client 3.1. But now too many TIME_WAIT are getting established and back end i am getting errors like "Address already in use" :(
Finally CLOSE_WAIT connections were not seen after using closeIdleConnections(0). Hope this solution might help others :)

A: CLOSE_WAIT means that TCP is waiting for the local application to close its end of the connection, which has already been closed by the peer.
Ergo you aren't closing them.


text:
Q: Is it kosher to create an activity inside another using new instead of an intent? I'm working with Android code that I've inherited. In the application's main activity, it's creating a new activity using new:
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    downloadActivity = new DownloadActivity(this);
}

Is this kosher? It doesn't feel right to me as I've always thought the best way to create an Activity is through an Intent.

A: Smells like ham to me. Why would you want to do that? I'm assuming the dev wants to use the methods and fields defined in the activity... But it's more Kosher (glatt) to create a different class and do everything there

A: Starting a new Activity is usually done via Intents. I can't see any reason for you to try doing it the other way.


text:
Q: Save a ListView into Settings.settings? How can I save a ListView with multicolumns into Settings.settings and load them upon running?
I'm trying to save a ListView with 3 columns. How can I do that?

A: *

*Bind the listview to some data structure.

*Serialize is using xmlseriualizer - then you can save the result into the Settings.

Restoring is done using deserialize.
StringWriter output = new StringWriter(new StringBuilder());
XmlSerializer s = new XmlSerializer(this.GetType());
s.Serialize(output,this);
var result = output.ToString()


text:
Q: Cross Origin Issue AngularJS's Directives in Eclipse Hello I have problem when use Angular JS in Eclipse.
I try to use Directives.
But when i access the index.html file i get the Cors Origin Issue when load Directives template.
XMLHttpRequest cannot load file:///Users/fanjavaid/Documents/Research%20and%20Development/workspaces_angularjs/usedirectives/app/js/directives/ArticleInfo.html. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

Here is my directive's javascript :
app.directive('articleInfo', function() {
    return {
        restrict: 'E',
        scope: {
            info : '='
        },
        templateUrl: 'js/directives/ArticleInfo.html'
    }
});

And this is my Directive's template :

{{ article.title }}

{{ article.meta }}, Comments : {{ article.comments }}

{{ article.content }}

How to handle that?
Thank you

A: Looks like you are directly opening the static file index.html in your browser and on load, your directive is making a call to get the template using templateUrl and it always appends the path to current path in your browser which is file://. That is the reason your request is failing.
If you're using Java, You can deploy your application on any server like Jetty or TomCat and access your index.html and it will work.


text:
Q: Subsets and combinatorics Let $A = \{1,\ldots,n\}$. Also, consider $y$, a subset of $A$ with the size of $k$.
What is the number of subsets, such that $x \subset y$ ($x\ne y$).
I know the answer is $2^k-1$, but cannot see why.

A: Let $y = \{ y_{1},\ldots,y_{k} \}$, then for all $y_{i} \in y$: either $y_{i} \in x$ or not, i.e. we have $2^{k}$ options. However, you assme $x \neq y$, hence one option is deleted and this results in $2^{k} - 1$.

A: You are simply asking for the number of (proper) subsets of a set $B$  with $k$ elements. A handy way to see the formula is to note that there is a bijective correspondence between subsets of $B$ and functions $B \to \{ 0, 1 \}$. Clearly there are $\lvert \{ 0, 1 \} \rvert^{\lvert B \rvert} = 2^{k}$ such functions.
The correspondence sends a subset $C \subseteq B$ to its characteristic function $f$, that is, the function such that $f(x) = 1$ if and only if $x \in C$. Conversely, to a function $f : B \to \{ 0, 1 \}$ you associate the subset $C = \{ x \in B : f(x) = 1 \}$.

A: You might as well take $k=n, y=A$, because the question of the number of subsets does not depend on what the elements are.  So let.  We want all the subsets of $A$, less the one that is all of $A$.  If we include that one (which we will subtract off later) you can independently choose to have $1, 2, 3, \dots, n$, so there are $n$ binary choices, giving $2^n$ subsets.  Now subtract the one subset that is all of $A$ and you are done.

A: There are ${n \choose k}$ subsets of size $k$ taken from the elements of a set of size $n$.
So the total is
$$S(n,k) = \sum_0^{n-1} {n \choose k} = \sum_0^n {n \choose k} - 1 = 2^n - 1.$$


text:
Q: Is it possible to force case-sensitivity in MATLAB for file operations like LOAD? MATLAB is case-sensitive for calling functions, even on Windows:
>> edit Untitled
>> untitled
Cannot find an exact (case-sensitive) match for 'untitled'

Is there a way to enforce case sensitivity on Windows for other functions, like load?
>> a = 3;
>> save a a
>> load A

The problem is that this code will run fine on Windows, but will error if I send it to a friend on Unix.

A: One way to enforce case-sensitivity for functions dealing with files, regardless of the platform you are running, is to write a wrapper for such functions.
For example, in the case of load, I came up with the following drop-in replacement:
function varargout = myload(fname, varargin)
    % make sure filename ends with MAT extension
    [~,~,ext] = fileparts(fname);
    if isempty(ext), fname = [fname '.mat']; end

    % open file (searching entire MATLAB path)
    fid = fopen(fname,'r');
    if fid < 0, error('file not found'); end

    % get fullpath to opened file, and close file handle
    filename = fopen(fid);
    fclose(fid);

    % extract the filename
    [~,name,ext] = fileparts(filename);
    filename = [name ext];

    % compare against original name (case-sensitive)
    if ~strcmp(fname,filename)
        error('Cannot find an exact (case-sensitive) match for file');
    end

    % load the MAT-file
    S = load(fname, varargin{:});

    % assign output
    if nargout > 0
        varargout{1} = S;
    else
        fn = fieldnames(S);
        for i=1:numel(fn)
            assignin('caller', fn{i}, S.(fn{i}))
        end
    end
end

I may have missed a few cases in the above implementation, but you get the idea..


text:
Q: Authentication failed (Bad Credentuals) in Spring Security with hibernate for REST I've created a spring boot app with spring-data-rest.
My Rest API is working just fine. Then I imported the spring security. I've also done configurations after referring to a number of Web resources.
However, each time I send a request, I get Bad Credential Error  The below are my codes
User.java
package com.innaun.model;

import org.springframework.data.rest.core.annotation.RestResource;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.HashSet;
import java.util.Set;

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long userId;

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

    @NotNull
    @RestResource(exported = false  )
    private String password;

    @NotNull
    private boolean enabled;

    @OneToMany
    private Set<UserRole> userRoles = new HashSet<UserRole>(0);

    public User() {
    }

    public User(String username, String password, boolean enabled) {
        this.username = username;
        this.password = password;
        this.enabled = enabled;
    }

    public Set<UserRole> getUserRoles() {
        return userRoles;
    }

    public void setUserRoles(Set<UserRole> userRoles) {
        this.userRoles = userRoles;
    }

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }
}

UserRole.java
package com.innaun.model;

import javax.persistence.*;
import javax.validation.constraints.NotNull;

@Entity
public class UserRole {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long userRoleId;

    @NotNull
    private String userRole;

    @ManyToOne
    private User user;

    public UserRole() {
    }

    public UserRole(String userRole, User user) {
        this.userRole = userRole;
        this.user = user;
    }

    public Long getUserRoleId() {
        return userRoleId;
    }

    public void setUserRoleId(Long userRoleId) {
        this.userRoleId = userRoleId;
    }

    public String getUserRole() {
        return userRole;
    }

    public void setUserRole(String userRole) {
        this.userRole = userRole;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

UserRepository.java
package com.innaun.model;

import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource
public interface UserRepository extends CrudRepository<User, Long>{
    User findByUsername(@Param("user") String user);
}

UserRoleRepository.java
package com.innaun.model;

import org.springframework.data.repository.CrudRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource
public interface UserRoleRepository extends CrudRepository<UserRole, Long> {
}

AppUserDetailsService.java
package com.innaun.model;

import com.innaun.model.UserRepository;
import com.innaun.model.UserRole;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service("appUserDetailsService")
public class AppUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Transactional
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        com.innaun.model.User user = userRepository.findByUsername(s);

        List<GrantedAuthority> authorities = buildUserAuthority(user.getUserRoles());

        return buildUserForAuthentication(user, authorities);
    }

    private User buildUserForAuthentication(com.innaun.model.User user, List<GrantedAuthority> authorities){
                return new User(user.getUsername(), user.getPassword(), user.isEnabled(), true, true, true, authorities);
    }

    private List<GrantedAuthority> buildUserAuthority(Set<UserRole> userRoles){
        Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();

        for (UserRole userRole : userRoles){
            setAuths.add(new SimpleGrantedAuthority(userRole.getUserRole()));
        }

        List<GrantedAuthority> result = new ArrayList<GrantedAuthority>(setAuths);

        return result;
    }

}

ApplicationRESTSecurity.java
package com.innaun;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class ApplicationRESTSecurity extends WebSecurityConfigurerAdapter {

    @Qualifier("appUserDetailsService")
    @Autowired
    UserDetailsService userDetailsService;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        return encoder;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .anyRequest().fullyAuthenticated()
                .and().httpBasic()
                .and().csrf()
                .disable();
    }
}

Also, I've added the below to add a test user to the database
package com.innaun;

import com.innaun.model.User;
import com.innaun.model.UserRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class PitchuApplication {

    public static void main(String[] args) {
        SpringApplication.run(PitchuApplication.class, args);
    }

    @Bean
    CommandLineRunner init(UserRepository userRepository) {

        return (args) -> {
            userRepository.save(new User("myuser", "mypassword", true));
        };
    }

}

Just as I thought, the database now has the above user and the user is enabled.
Screenshot of the User data table
All the other tables are blank.
However when I tried the curl
curl -u myuser:mypassword localhost:8080

it returned
{"timestamp":1489090315435,"status":401,"error":"Unauthorized","message":"Bad credentials","path":"/"}

Can anyone explain where did I went wrong.

A: Your configuration looks fine to me. So, my best guess is that your password column in your database has length less than 60 which is the length of the hash BCrypt will produce.

A: I figured it out. And this was so simple mistake. the password I used to save a new user in the userRepository is raw instead of encrypted. I figured it out by:
//Create a new password encoder
private PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

//Encode the password
String password = "mypassword";
String hashedPassword = passwordEncoder.encode(password);

//Create the user with the encoded password
User user = new User(myuser, hashedPassword, true);

//then persist
userRepository.save(user);


text:
Q: Managing process artifacts in a Mercurial release I am wondering what the best way might be to use Mercurial to create a release revision that includes artifacts that provide evidence of process execution.  For example, we'd like to attach system test results, check lists, release notes, etc. so that if we are audited by a customer we can easily show that we performed our process.  This is important to us due to the safety aspects of our product.
Our release management process will go something like the drawing below.  All developers are developing in local repos and periodically pushing to main.  Main is the latest and greatest but not necessarily safe for even internal engineering purposes outside of the dev team.
When we want to create a release for the customer or for other internal engineering departments, we start with a release candidate branch (e.g. RC1).  If any fixes are required, we commit to the RC branch.  Testing occurs on this branch.  When the RC is determined to be good, the changes are merged back to main.
We think that what we would like to do is merge into a Releases branch.  However, we have a chicken and an egg problem related to the artifacts: The artifacts that we would like include in the release revision contain, among other things, the hash for the revision.  This provides clear traceability that the testing and other process steps were performed on this precise revision.  But, to add these items, I need to create a new revision and I obviously can't know what the hash for that revision will be before I create it.  I am wondering if there is some way to "amend" a revision without changing the hash?
The only way to do this, that I can think of, would be, for example, in the drawing below, to create a revision RC2.3 that contains the necessary process artifacts but actually merge RC2.2 to Releases.
Then, of course, I have another problem and that is that the merge of RC2.2 into Releases will generate a new hash.  So, my artifacts are out of date again.  So the next question is whether there is some way to have the Release branch "point to" RC2.2.
BTW, we're open to changing this process if necessary.  Our reasons for using this methodology are:

*

*CI system is monitoring main and kicks off a series of builds and performs automated unit testing on each push.  There are frequent changes to main and we don't want people using it.

*Development can continue on main with no impact to the release.

*Any revision on the Releases branch kicks off a different set of tasks on our CI platform, including the creation of a distribution of a field flash utility and the required images (we're developing firmware).  This is how we provide releases to outside entities.

Main         A--B--C--D--E--F--G--H--I--J--K--L---------M-------------N
                       \            /          \                     /
RC1                     RC1.0--RC1.1            \                   /
                         \                       \                 /
RC2                       \                        RC2.0--RC2.1--RC2.2
                           \                                       \
                            \                                       \
Releases                    ER1.0-----------------------------------PR1.0

A: To answer your question:

I am wondering if there is some way to "amend" a revision without changing the hash?

No, that's impossible by design. The changeset hash is a cryptographic checksum derived from the content of the commit — this is why the changeset hash uniquely identifies the content of all the files in the changeset.
The Mercurial wiki has a page with a standard branch setup. I'll describe how it works with pictures below.
What people normally do in your situation is to create a branch for release candidates like you suggest. If you're about to release version 2.0 of your firmware, then I would call the branch 2.x. The commits on the branch are release candidates for your version 2.0:
Main      A--B--C--D--E--F--G--H--I--J--K--L---------M-------------N
                 \                /
2.x               2.0-RC1--2.0-RC2

Bugfixes are committed on the branch as needed and merged back into Main regularly. You should always be able to merge the bugfixes back since they are by their nature bugfixes and stability improvements that you want to have on Main too. In other words, commit I above has the bugfixes in 2.0-RC2 plus the new features in D to H.
You can work on the release candidate branch as much as you want and keep fixing bugs:
Main      A--B--C--D--E--F--G--H--I--J--K--L-------M-------------N
                 \            /                   /
2.x               2.0-RC1--2.0RC2 -- ... --2.0-RC8

All bugfixes are merged back since the rule is that you can only do fixes on the release candidate branch that are safe. Here you had 8 release candidates on the release branch.
When you like the status of the release candidate, you can tag it and run the more comprehensive tests on the revision you tagged. The output of a succesfull test is committed on the branch and you then tag that commit as the final released version:
Main      A--B--C--D--E--F--G--H--I--J--K--L-------M-----------N
                 \            /                   /           /
2.x               2.0-RC1--2.0RC2 -- ... --2.0-RC8 -- T -- 2.0

Here T has the test output for 2.0-RC8 included. Commit T is the one you tag as version 2.0 of your software and the one you package and ship to your customers.
Should you need to create a version 2.1 with a bugfix to 2.0 (but no new features), then you continue with the same scheme:
Main      A--B--C--D--E--F--G--H--I--J--K--L-------M-----------N
                 \            /                   /           /
2.x               2.0-RC1--2.0RC2 -- ... --2.0-RC8 -- T -- 2.0 -- 2.1-RC1

That is why I called the branch 2.x.

A: Your usage of mercurial seems a bit complicated with all those merges all over the place and will be painful to handle.
You are using the branches feature of mercurial, but seems to overlook 2 other important features:

*

*Tags

*Cherry Pick

I'll describe below our general usage of mercurial to highlight those features:
Note that the following only applies to projects for which different versions need to be maintained over time.
The main branch (called default in mercurial) is dedicated as you to the current development of the application.
Every time a developer complete the development/modification/update of a functionality, he/she pushes their change into default, which is then available to everybody and to our CI (jenkins) which will ensure nothing is broken.
When we reach a stage where a new version is about to be released a branch is created. In reference to your schema, the branch could be named MY_PRODUCT_1_0
Developers will continue to work on the default branch, and any time a commit need to be in the coming release, the related changeset will be copied to the MY_PRODUCT_1_0 branch via the command hg graft REV_CHANGESET (cherry pick) (note you can also copy from MY_PRODUCT_1_0 branch to default).
So you basically select which changesets from the default branch will make it to the current release, without having to merge the 2 branches.
This requires developers to push clean and atomic changesets, which is how things should be done in mercurial in the first place.
As your commits evolve in the MY_PRODUCT_1_0 you can tag it multiple times along the way as your schema from MY_PRODUCT_1_0_RC_1, MY_PRODUCT_1_0_RC_2,...
When the final changeset is made on this branch you just need to tag it MY_PRODUCT_1_0_PR_1_0
You then get only 2 branches at first, default (the dev branch) and MY_PRODUCT_1_0 (your first release), and as time goes on when you need to release a new version of your product, you create a new branch MY_PRODUCT_2_0 and restart the cycle as described above.
With this approach you are sure that you only have the required changes in your releases, and not extra ones that you would get when merging branches.
I hope I was clear enought, if not let me know.


text:
Q: Easier / better way to convert hexadecimal string to list of numbers in Python? My goal is to  get a 64 characters long hex number from a user (which represent a serial number) and convert to c_type 32bytes number.
Serial Number is defined like this:
_sn =  c_ubyte * 32

I accept SN string from user into args.sn variable. Here's how I managed to solve it. I'm sure there is an easier and more elegant way, would appreciate your help.
SN_List= []
for i in range(0,len(args.sn),2):
    myByte = args.sn[i: i+2]
    num = int("0x" + myByte,16)
    SN_List.append(num)

if(len(SN_List) != 32):
    print("S/N is not valid, it should be 64 hex characters long")
    return 1
_sn = (c_ubyte * 32)(*SN_List)

A: The very easy way, using binascii (Python 3):
import binascii

print(list(binascii.unhexlify(args.sn)))

Example:
>>> list(binascii.unhexlify('09F911029D74E35BD84156C5635688C0'))
[9, 249, 17, 2, 157, 116, 227, 91, 216, 65, 86, 197, 99, 86, 136, 192]

In Python 2, you would use
print map(ord, args.sn.decode('hex'))

Example:
>>> sn = '09F911029D74E35BD84156C5635688C0'
>>> print map(ord, sn.decode('hex'))
[9, 249, 17, 2, 157, 116, 227, 91, 216, 65, 86, 197, 99, 86, 136, 192]

A: Expanding on @nneonneo's comment (binascii.unhexlify is equivelent to binascii.a2b_hex):
_sn = (c_ubyte * 32)(*binascii.unhexlify("ffaabb"))

Example (with the hex ffaabb):
>>> binascii.unhexlify("ffaabb")
b'\xff\xaa\xbb'
>>> _sn = (c_ubyte * 32)(*binascii.unhexlify("ffaabb"))
>>> _sn
<__main__.c_ubyte_Array_32 object at 0x7fe14fee8bf8>
>>> for i in _sn:
...     print(i)
...
255
170
187
0
0
<27 more zeros>

A: First, you can use a list comprehension to eliminate most of the overhead code. Second, it's not necessary to prepend 0x to the string when you convert to int, as long as you've specified the second parameter. Third, if you need to validate the string to make sure it contains the correct number of digits, that should be a separate step. Or perhaps you can just rely on a raised exception when things go wrong.
SN_List = [int(args.sn[i: i+2], 16) for i in range(0, 64, 2)]


text:
Q: Format numbers in XML using XSLT I have one number in my input xml file like this 0.20 but I want to change to 0,20(comma instead of dot) in my output xml file through xslt.  How can I format this number? I don't want to use any templates for it.

A: Use format-number($x, '0.00', 'european')
in conjuction with
<xsl:decimal-format name="european" decimal-separator="," grouping-separator="."/>

A: Why not you give us the example of input like where is the number and which template you use for this? show the XML and XSLT it will easy to understand your problem:
you can normally use replace () if its coming in a tag like: <tag>0.20</tag>
<xsl:value-of select="replace(tag,'\.',','"/>

A: There are different approaches based on which XSLT version you are using.
Assuming you have the value 0.20 in an element as below
<element>0.20</element>

XSLT 1.0 provides a translate() function which allows replacement of the character from within a string using the following statement.
<xsl:value-of select="translate(element,'.',',')" />

XSLT 2.0 provides a replace() function to do the same. However when using XSLT 2.0, it is better to escape the period/dot since dot signifies value of current node and could lead to incorrect interpretations.
<xsl:value-of select="replace(element,'\.',',')" />


text:
Q: In-Memory SQL-CE Is there a way to connect to a SQL-CE database as a stream?
Specifically, our ASP.Net application builds small SDF at runtime for off-line needs.  When the user is done with his off-line duties, he uploads the SDF and the application imports the new and updated data.  No problems there.
Currently, we're saving the uploaded SDF to the web-server's hard-drive and connecting to the file.  Can we connect to the uploaded SDF without saving it to the hard-drive?  We are using the DbProviderFactory.CreateConnection method, but we're open to suggestions.

A: You must open SQL CE from a file location. Maybe you can use a RAM drive or similar?


text:
Q: Workaround for firebase "IN" limit of 10 compatible with onSnapshot? I have run into the firebase "IN" limit of 10.  Although a workaround solution was already answered here:
Is there a workaround for the Firebase Query "IN" Limit to 10?
None of the solutions in that thread seem to work with the listener "onSnapshot".  For my use case (Vue 3), I have a composable/function call I that queries firebase passing in an array that could have up to 100 document ID values and returns an object as below.
Is this possible?
import { ref, watchEffect } from 'vue'
import { db } from '@/firebase/config'
import { collection, onSnapshot, query, where, documentId } from 'firebase/firestore'

const getUsersList = (idList) => {
    // idList is an array of document ID's
    const documents = ref(null)
    let collectionRef = collection(db, 'users')
    collectionRef = query(collectionRef, where(documentId(), 'in', idList))
    // this fails if I pass in more than 10 elements in the array
    const unsub = onSnapshot(collectionRef, snapshot => {
        let results = []
        snapshot.docs.forEach(doc => {
            results.push({ ...doc.data(), id: doc.id })
        })
        // update values
        documents.value = results
    })
    watchEffect((onInvalidate) => {
        onInvalidate(() => unsub())
    })
    return { documents }
}

export default getCollectionRt

A: Since no replies here completely answered the question, I ended up paying a freelancer to take a look and here's what they came up with.  The solution does seem to have a random issue I am trying to sort out when the underlying changes, one of the records will disappear.  It does work, is in scope of the original question and seems to have solved the problem.
import { ref, watchEffect } from 'vue'
import { db } from '@/firebase/config'
import { collection, onSnapshot, query, where, documentId } from 'firebase/firestore'

const getUserList = (idList) => {
    console.log('idList', idList)
    let documents = ref(null)
    let collectionRef = collection(db, 'users')

    let unsub, unsubes = [], resultsList = [{}];
    for (let i = 0; i < idList.length; i += 10) {
        let idList1 = idList.slice(i, i + 10); //console.log(idList1);
        let collectionRef1 = query(collectionRef, where(documentId(), 'in', idList1))
        unsub = onSnapshot(collectionRef1, snapshot => {
            let results = []
            snapshot.docs.forEach(doc => {
                results.push({ ...doc.data(), id: doc.id })
            })
            resultsList.splice(resultsList.length, 0, ...results);
            console.log('results', results)
            documents.value = results
        })
        unsubes.push(unsub);
    }
    watchEffect((onInvalidate) => {
        onInvalidate(() =>{ unsubes.forEach(unsub => { unsub();         console.log("unsut", unsub); }) });
    })
    Promise.all(unsubes);
    resultsList.shift(0);
    console.log("docu", documents.value);
    return { documents };
}

export default getUserList

A: You will have to initialize multiple listeners i.e. same number of queries but with onSnapshot() (might be better than setting up a listener for each individual document). Try:
import { ref } from 'vue';
import { collection, query, where, documentId, onSnapshot } from 'firebase/firestore'

const users = ref({})
const dataLoaded = ref(false)

const addFirestoreListeners = async () => {
  const idList = [];

  for (let i = 0; i < idList.length; i += 10) {
    const items = idList.slice(i, i + 10)

    const q = query(collection(db, 'users'), where(documentId(), 'in', items))

    onSnapshot(q, (snapshot) => {
      if (dataLoaded.value) {
        snapshot.docChanges().forEach((change) => {
          if (change.type === 'added' || change.type === 'modified') {
            users.value[change.doc.id] = change.doc.data()
          } else (change.type === 'removed') {
            users.value[change.doc.id] = null
          }
        })
      } else {
        snapshot.forEach((doc) => {
          users.value[doc.id] = doc.data()
        })

        dataLoaded.value = true
      }
    })
  }
}

The dataLoaded flag checks if the listeners have fetched data for first time or has received an update. I've use a map where the key is document ID so it can be removed easily but do change that to an array or any other required structure.


text:
Q: Extbase: get/save specific language of object In a CommandController, I need to sync objects with an external source. The source is multi-language and shall be mapped to localized records in Typo3.
I just seem too blind to find options to ...
a) get records in a specific language
b) add/update records in a specific language
... (from a CommandController context).
I was expecting this to be a function of the model (AbstractEntity) or maybe the repository, but could not find any public lang/sys_lang/localize-functions there.
(Typo3 version 6.2)

A: You can write a method in your repository class to get all records with the sys_language_uid  you need and use that method to get all the records.
If you model does not have the sys_language_uid, add it so you can use it in your controller.
(if your model has sys_laguage_uid, you can use $yourrepo->findBySysLanguageUid(1)  )
Probably you need to change the defaultQuerySettings so you can retrieve the any language, regarding the site language (if you are using a FE ext)
adding the records with a specific language is $yourobject->setSysLangUid(1); (or whatever lang id)


text:
Q: How to measure the statistical significance of a click through rate? I'm building an open source project which will measure whether or not the differences in the click through rate of various Facebook advertisements are significantly significant. Taking inspiration from http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=167743 I wrote the following ruby code (presume any methods not defined within do exactly what they say).
The click through rate is defined as the percentage of people who click on an ad compared to the number of people who see an impression of that advert.

  # ** exponentiation
  # * multiplication
  # / division
  def standard_deviation
    (experiment_ctr/(control_ctr**3) * (no_of_clicks_for_control +
                                        no_of_clicks_for_experiment - product_of_ctrs *
                                        total_no_of_impressions ) / product_of_impressions) ** 0.5
  end

 def z_score
   (ratio_of_experiment_ctr_to_control - 1) / standard_deviation
  end

I copied the standard deviation code from the Google website but it looks fishy to me. Has anyone any ideas as to whether this is correct or not?
Much appreciated.

A: It does not look familiar because it is not the ordinary significance tests most people are accustom to seeing.  Most significance test are formulated by (grossly over generalized, please no flames):

*

*computing a sample statistic, X

*determine the expected value of that statistic, E

*determine the standard deviation of that statistic, S

*compute the test statistic T = (X - E) / S

*determine if T is significant based on the hypothesized distribution of T.

For the common mean significance tests, E is the sample mean and S the sample standard deviation we are most familiar with.
This significance test is based on some ratio for the sample statistic. The (E-C)/C formula provided by Google.  This statistic, according to Google, has an expected value of (1 / (1-p)) - 2 and has an standard deviation of (p / ( (C+E) * (1-p)^3 ))^0.5.  So, those should be the numbers plugged into the T formula above.  The z-score in Google's explanation.
So, even though the formula looks odd, it is based on sound fundamentals.  You should be able to use it with confidence.


text:
Q: JS editing array - result amount is incorrect and stray object When i click this button:
 const addToCart = () => {

    dispatch({
      type: "ADD_TO_CART",
      item:{
        id:id,
        name: name,
        image: image,
        price: price,
        score: score,
        releaseDate: releaseDate,
        amount: amount // this is defaulted as 1
      }
    })
  }

It sends it to my reducer class that stores data, im trying to edit it so it will only have a single instance of a specific item and only increase the amount
 case 'ADD_TO_CART':

            for (let x of state.cart){
// this should get fired if the object is found and increase amount by specified
                if (x.id === action.item.id){
                    let newCart1 = [...state.cart];
                    newCart1[x] = { ...newCart1[x], amount: x.amount += action.item.amount }

                    return {...state, cart: [newCart1]}
                }
            }

            return {  ...state, cart: [...state.cart, action.item], };
// this should get fired if it is not found and add the whole object

There are two issues.

*

*If I add an initial item it works (initial object) if I add a second of the same item it will increase amount to 3 instead of 2

*On top of that it adds a "Object object" with amount 3 which I don't know what this is or how it is included given the array is of length 1 (second object)

A: This question relates more towards an finding and resolving a bug in the code. Below is an attempt to do so.

*

*This line for (let x of state.cart) indicates that x is an element of the state.cart (an array)

*The next line: if (x.id === action.item.id) reinforces that x is not just an element, but it is probably an object which has a prop id.

*Next, let newCart1 = [...state.cart]; indicates that newCart1 is a shallow-copy of the object-array state.cart

*And here (in the next assignment) lies the problem (I think): newCart1[x] = { ...newCart1[x]..... <--- x is an object and it is being used as an index to access newCart1. May be one needs to find the index of the matched id and use that here (instead of [x])?

This answer may need to be updated based on further response/clarification from OP.
Observation
Rather than loop through the cart array, if it may be guaranteed that action.item.id will only match one item in the cart array, then why not just do this:
case 'ADD_TO_CART':
  const newCart1 = [...state.cart];
  const tgtIdx = newCart1.findIndex(({ id }) => id === action.item.id);
  if (tgtIdx >= 0 && tgtIdx < newCart1.length) {
    newCart1[tgtIdx] = {
      ...state[tgtIdx],
      amount: state.cart[tgtIdx].amount + action.item.amount
    };
    return { ...state, cart: [...newCart1]};
  };
  return { ...state, cart: [...state.cart, action.item] };

Note: The existing for...of loop will also only target the first occurrence as the moment it finds a match, it executes a return from within the loop.

A: case 'ADD_TO_CART':

            const newCart1 = [...state.cart];
            const tgtIdx = newCart1.findIndex(({ id }) => id === action.item.id);

            if (tgtIdx >= 0 && tgtIdx < newCart1.length) {
                newCart1[tgtIdx] = { ...newCart1[tgtIdx], amount: newCart1[tgtIdx].amount + action.item.amount}
                return { ...state, cart: [...newCart1]};
            };
            return { ...state, cart: [...state.cart, action.item] };


text:
Q: AppSync check if DynamoDB record exists I am trying to write a resolver for AppSync that derives the value for a Boolean field based on the existence of a record in DynamoDB.
I currently have the following request mapping template:
{
    "version": "2017-02-28",
    "operation": "GetItem",
    "key": {
        "field1": $util.dynamodb.toDynamoDBJson($ctx.args.field1),
        "field2": $util.dynamodb.toDynamoDBJson($ctx.args.field2)
    }
}

And the following response mapping template:
#if($util.isNull($ctx.result))
    #set($exists = false)
#else
    #set($exists = true)
#end

$util.toJson({
    "field1": $ctx.args.field1,
    "field2": $ctx.args.field2,
    "exists": $exists
})

This works correctly if the record exists but if it does not then AppSync simply returns "null" for the entire API call and does not seem to evaluate the response mapping template at all. Is there any way I can instruct it not to do this?
Another option would be to perform a query and look at the length of the response but I have no idea how to check length in these templates.

A: This is an expected behavior for the 2017 version of the Request template. If you would like the $ctx.result to be evaluated, switch to the 2018 version as below:
{
  "version": "2018-05-29",
  "operation": "GetItem",
  "key": {
    "id": $util.dynamodb.toDynamoDBJson($ctx.args.id),
  },
}

Refer to this change log for additional details.


text:
Q: How to parse a table column with multiple elements using Cheerio? I have a table as shown below:

    some text

      data I want

some elements

    some text

      data I want

some elements

Using:
$("tr.odd:nth-child(1) > td:nth-child(2)").text()

I am getting the text available inside the div tag also.  But I need only the text data I want.
How can get that?

A: I think it would be simpler to remove() the
s and then parsing the data.
$("tr td > div").remove()
$("tr.odd:nth-child(1) > td:nth-child(2)").text()


text:
Q: Does the standard guarantee, that std::string::resize will not do reallocate memory, if the new size is less than or equal to as the old one? I need to frequently make a string empty and then append some chars into it.
std::string::clear() may realloc
Does std::string::resize(0) do realloc? The standard's words didn't garentee any about it.

A: I think the best possible answer to this is the "Notes" section at http://en.cppreference.com/w/cpp/string/basic_string/clear.

Unlike for std::vector::clear, the C++ standard does not explicitly require that capacity is unchanged by this function, but existing implementations do not change capacity.

And if the capacity is unchanged, that would almost certainly mean that no allocation or freeing functions are called. That's probably the best you can do, short of looking at each and every implementation you care about.


text:
Q: How to restrict App Only permissions to one site In an Azure AD app registration under API Permissions I've added Sites.Read.All AppOnly to let my app access SharePoint resources through the Microsoft Graph API.
How do I restrict this permission to apply to just one site collection?
My app only need to access this one site collection and it would be irresponsible to require access to anything else (principle of least privilege), and it is unlikely that any client administrator would allow this.
So I need to restrict the permissions of the app service principal, but where/how do I do that?
EDIT: My app is not a SharePoint Add In. It is a standalone service application that simply access SharePoint through MS Graph. As such there is no AppManifest as nothing is installed in SharePoint (the question is relevant to other Graph resources than SharePoint as well).
Here is how the app is registered:
https://docs.microsoft.com/en-us/azure/healthcare-apis/register-service-azure-ad-client-app

A: This is indeed not possible yet (still not, 7 months after you posted this).
Here is proof: https://github.com/SharePoint/sp-dev-docs/issues/5730
Microsoft did however announce they will solve this issue in the near future.
This reply from MS to the UserVoice request from October 2020 mentions a new feature called "resource-specific consent" for Teams:
https://microsoftgraph.uservoice.com/forums/920506-microsoft-graph-feature-requests/suggestions/37796059-restrict-permissions-to-app-only-azure-ad-applicat
This will then supposedly be similar for SharePoint.
Image a Site.Read RSC scope for app-only access which can be consented for by a site-admin. This site-level access is apparently something that is still missing in Graph and currently in beta for Teams apps:
https://docs.microsoft.com/en-us/microsoftteams/platform/graph-api/rsc/resource-specific-consent
Looking forward to it..

A: Use the Sites.Selected permission (Due release February 2021):

Applications can now use the new "Sites.selected" permission to
request access to SharePoint sites.  By default an application that
requests "Sites.Selected" instead of a tenant wide permission may not
access any SharePoint sites. The tenant administrator can grant or
revoke an application's access to individual sites through new
endpoints in the Microsoft Graph API.

Source: https://www.microsoft.com/en-us/microsoft-365/roadmap?filters=&searchterms=Sites.selected
Be aware that the Sites.Selected approach requires you to register permissions for your app via the Sites/Permissions endpoint (there is currently no interface for this). Now this endpoint itself can only be used with the App Only permission mask Sites.FullControl.All. Some would argue that this permission may be even harder to get from a client administrator that in the first place would not grant Sites.Read.All ;-)
The mitigating aspect however, is that you can now design a secondary granter app/script and let the client administrator execute that. You will probably need a new app registration for that alone. Jeremy Kelley explains that design here.
Consider using a service account
If you are an ISV that has to work with large client tenants on a daily basis, you might still want to consider a classic service account approach: Set up a standard user account, ask the client administrator to add that user to the specific site collection, with the required permissions and let your application authenticate with that user and perform requests in a delegated context (i.e. you only need delegated permissions). This way you can avoid the whole App Only and Granter app condundrum, and client administrators seem to take in the concept of service accounts much easier.

A: Here's the blog post announcing how to make this work: https://developer.microsoft.com/en-us/graph/blogs/controlling-app-access-on-specific-sharepoint-site-collections/

A: You may check this - go to the
https://yoursposite.sharepoint.com/sites/SharePointRND/_layouts/15/appinv.aspx
Example:
https://globalsharepoint2019.sharepoint.com/sites/SharePointRND/_layouts/15/appinv.aspx
Add the below XML in the "Permission Request XML" box:
<AppPermissionRequests AllowAppOnlyPolicy="true">
<AppPermissionRequest Scope="http://sharepoint/content/sitecollection" Right="FullControl" />

Note:

*

*Scope="http://sharepoint/content/sitecollection/" here sitcollection indicates as   site collection level scope.

For other permission levels, you may refer the below MSDN article:
Add-in permissions in SharePoint


text:
Q: It seems that I cannot parse_dates on two or more colunms I parse_dates when I pd.read_excel, but it only works on one columns "ClassStartDate", but fails on the other "ClassEndDate".
PSL1= pd.read_excel(r"C:\Users\xx.xlsx",parse_dates=["ClassStartDate","ClassEndDate"])
PSL1[["ClassStartDate","ClassEndDate"]]

A: If I understand it correctly, you use dicts. Please check if you did not make a typo in Excel. Please check if the names are really exactly ClassStartDate and ClassEndDate.


text:
Q: How to parse a JSON string in Inno Setup? I have the following JSON:
{
    "Info": {
        "User": 2,
        "String": "foo"
    }
}

Unfortunately TLama's Inno JSON Config library doesn't work with JSON strings but only with json files.
I tried to use JSON string instead of path to json file, but it didn't work.
if JSONQueryInteger('{"Info":{"User":2,"String":"foo"}}', 'Info', 'User', 0, IntValue) then
    MsgBox('User=' + IntToStr(IntValue), mbInformation, MB_OK);

I know I could save my JSON to a file and then parse it but it seems kind of messy.
How to parse a JSON string in Inno Setup?

A: You can use JsonParser library instead. It can parse JSON strings.
It's not as easy to use as JSONConfig.dll – but that's the reason why it is more flexible. Also it's a native Pascal Script code. So, it not only saves you from a temporary .json file, but also from a temporary .dll.
The code can be like:
[Code]

#include "JsonParser.pas"

function GetJsonRoot(Output: TJsonParserOutput): TJsonObject;
begin
  Result := Output.Objects[0];
end;

function FindJsonValue(
  Output: TJsonParserOutput; Parent: TJsonObject; Key: TJsonString;
  var Value: TJsonValue): Boolean;
var
  I: Integer;
begin
  for I := 0 to Length(Parent) - 1 do
  begin
    if Parent[I].Key = Key then
    begin
      Value := Parent[I].Value;
      Result := True;
      Exit;
    end;
  end;

  Result := False;
end;

function FindJsonObject(
  Output: TJsonParserOutput; Parent: TJsonObject; Key: TJsonString;
  var Object: TJsonObject): Boolean;
var
  JsonValue: TJsonValue;
begin
  Result :=
    FindJsonValue(Output, Parent, Key, JsonValue) and
    (JsonValue.Kind = JVKObject);

  if Result then
  begin
    Object := Output.Objects[JsonValue.Index];
  end;
end;

function FindJsonNumber(
  Output: TJsonParserOutput; Parent: TJsonObject; Key: TJsonString;
  var Number: TJsonNumber): Boolean;
var
  JsonValue: TJsonValue;
begin
  Result :=
    FindJsonValue(Output, Parent, Key, JsonValue) and
    (JsonValue.Kind = JVKNumber);

  if Result then
  begin
    Number := Output.Numbers[JsonValue.Index];
  end;
end;

function FindJsonString(
  Output: TJsonParserOutput; Parent: TJsonObject; Key: TJsonString;
  var Str: TJsonString): Boolean;
var
  JsonValue: TJsonValue;
begin
  Result :=
    FindJsonValue(Output, Parent, Key, JsonValue) and
    (JsonValue.Kind = JVKString);
  if Result then
  begin
    Str := Output.Strings[JsonValue.Index];
  end;
end;

function ParseJsonAndLogErrors(
  var JsonParser: TJsonParser; const Source: WideString): Boolean;
var
  I: Integer;
begin
  ParseJson(JsonParser, Source);

  Result := (Length(JsonParser.Output.Errors) = 0);
  if not Result then
  begin
    Log('Error parsing JSON');
    for I := 0 to Length(JsonParser.Output.Errors) - 1 do
    begin
      Log(JsonParser.Output.Errors[I]);
    end;
  end;
end;

procedure ParseJsonString;
var
  Json: string;
  JsonParser: TJsonParser;
  I: Integer;
  JsonRoot, InfoObject: TJsonObject;
  UserNumber: TJsonNumber; { = Double }
  UserString: TJsonString; { = WideString = string }
begin
  Json := '{"Info":{"User":2,"String":"abc"}}';

  if ParseJsonAndLogErrors(JsonParser, Json) then
  begin
    JsonRoot := GetJsonRoot(JsonParser.Output);
    if FindJsonObject(JsonParser.Output, JsonRoot, 'Info', InfoObject) and
       FindJsonNumber(JsonParser.Output, InfoObject, 'User', UserNumber) and
       FindJsonString(JsonParser.Output, InfoObject, 'String', UserString) then
    begin
      Log(Format('Info:User:%d', [Round(UserNumber)]));
      Log(Format('Info:String:%s', [UserString]));
    end;
  end;

  ClearJsonParser(JsonParser);
end;

Another option is to fork the Inno JSON Config library and add support for parsing strings.


text:
Q: CSS pseudo-classes and :disabled:valid selector I want to apply some styles based on my input conditions. I don't want to use any additional classes and looking for a CSS only solution.
The problem is when I trying to use this selectors
:disabled:valid
:disabled:invalid

it just won't work. Any ideas?
Thank you for your time!

input:disabled + span {
  color: gray;
}

input:valid + span, input:disabled:valid + span {
  color: green;
}

input:invalid + span, input:disabled:invalid + span {
  color: red;
}

fieldset {
  padding: 10px;
  border: none;
}

fieldset > div {
  margin-bottom: 10px;
}

label {
  display: block;
}

button:first-child {
   margin-left: 10px;
}

  <fieldset>

      First name
      <input type="text" name="firstname" value="Stephan" required>
      Valid

      Last name
      <input type="text" name="lastname" required>
      Invalid

  </fieldset>

  <button onclick="document.querySelector('fieldset').disabled = true">Send</button>
  <button onclick="document.querySelector('fieldset').disabled = false">Cancel</button>

A: Unfortunately, once an input is disabled, the browser doesn't look at valid or invalid anymore. The invalid will rule out the other pseudo classes.


text:
Q: libpq code to create, list and delete databases (C++/VC++, PostgreSQL) I am new to the PostgreSQL database. What my visual c++ application needs to do is to create multiple tables and add/retrieve data from them.
Each session of my application should create a new and distinct database. I can use the current date and time for a unique database name.
There should also be an option to delete all the databases.
I have worked out how to connect to a database, create tables, and add data to tables. I am not sure how to make a new database for each run or how to retrieve number and name of databases if user want to clear all databases.
Please help.

A: See the libpq examples in the documentation. The example program shows you how to list databases, and in general how to execute commands against the database. The example code there is trivial to adapt to creating and dropping databases.
Creating a database is a simple CREATE DATABASE SQL statement, same as any other libpq operation. You must connect to a temporary database (usually template1) to issue the CREATE DATABASE, then disconnect and make a new connection to the database you just created.
Rather than creating new databases, consider creating new schema instead. Much less hassle, since all you need to do is change the search_path or prefix your table references, you don't have to disconnect and reconnect to change schemas. See the documentation on schemas.
I question the wisdom of your design, though. It is rarely a good idea for applications to be creating and dropping databases (or tables, except temporary tables) as a normal part of their operation. Maybe if you elaborated on why you want to do this, we can come up with solutions that may be easier and/or perform better than your current approach.


text:
Q: Scraping JavaScript WEB page requires HTTP Basic Authentication I'm trying to write script accessing JavaScript page secured by authentication mechanism.
When I do the following:
r = requests.get(url1, auth=('user', 'password'))

...it pass the authentication smoothly, but since the page is generated by JavaScript code it brings me the code and not the HTML content:
u'<SCRIPT Language=Javascript>\r\nif (window.navigator.cookieEnabled == true)\r\n{\r\nvar gmtString, d;\r\nvar vDay, vDate, vMonth, vYear, vHour;\r\nvar x = new Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat");\r\nvar y = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");\r\nd = new Date();\r\nvDay = d.getDay();\r\nvDate = d.getDate();\r\nvMonth = d.getMonth();\r\nv

From other hand, I've tried to resolve this using PyQt4 like it explained here. It should work, but this time I do not manage to pass the authentication.
Could someone point me the right direction?


text:
Q: glob exclude alphanumeric mix in gitignore Problem:
I want to ignore the time directories in openfoam, i.e.

*

*foo/1; foo/200

*foo/153.6546

*foo/0.5e-05

thus I've added
#gitignore
[0-9]*/
[0-9]*.[0-9]*/

but this ignores the casefolder as well if it contains any number, i.e. "testCase1D".
Question:  Is there a way to exclude arbitrary alphanumeric combinations in the gitignore file so just pure numerical values are ignored?
My solution approach:
![0-9][a-zA-Z]*/
[0-9]*.[0-9]*e-[0-9][0-9]

the former helps with the 1D bit, but parametervariations like foo={"density1000","density1200"} would still be ignored. The latter ignores the "e-" from problem 3 directories.

A: Adding an asterisk after the numeric value in the first line and adding a second one like so:
![0-9]*[a-zA-Z]*/
![a-zA-Z]*[0-9]*/

seems to do the trick.


text:
Q: Firestore not receiving data when using setDoc I have a problem with my app connecting to my Firestore database when trying to use setDoc.
I have the database up and running for next-auth which is functioning as intended and creating records in the database. However, when I try and allow the rest of my app to use the database I cannot get the data to update.
I believe the problem could be to do with my config file not firing correctly but its hard to know for sure as I am not getting any errors. The onClick fires (tested) and the update does not occur.
I will provide some console screenshots and code to try and make clear the problem.
/firebase/config.js
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
import { getStorage } from "firebase/storage";

const firebaseConfig = {
  apiKey: process.env.FIREBASE_API_KEY,
  appId: process.env.FIREBASE_APP_ID,
  authDomain: process.env.FIREBASE_AUTH_DOMAIN,
  databaseURL: process.env.FIREBASE_DATABASE_URL,
  projectId: process.env.FIREBASE_PROJECT_ID,
  storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
};

const app = initializeApp(firebaseConfig);

const storage = getStorage(app);
const db = getFirestore(app);

export { storage, db };

Then here is my form submit to add the form field values to an existing document.
/components/signup/SignupSubmit.js
import { getSession } from "next-auth/react";
import { setDoc, doc } from "firebase/firestore";
import { db } from "../../firebase/config";

export default async function SignupSubmit(value) {
  const session = await getSession();
  const userId = session.user.id;

  const values = {
    profile: value.profile,
    screenName: value.screenName,
  };

  const docRef = doc(db, "users", `${userId}`);
  console.log(docRef);

  setDoc(docRef, { values }, { merge: true })
    .then(() => {
      console.log("Document has been updated successfully");
    })
    .catch((error) => {
      console.log(error);
    });
}

I have screenshot the output of console.log(docRef).

Let me know if I can provide any further information as I am keen to put this issue to bed.
Thanks in advance for any and all help.
UPDATE: Here is my _app code
/pages/_app.js
import React from "react";
import { SessionProvider } from "next-auth/react";
import { SWRConfig } from "swr";

import Layout from "../components/Layout.js";
import AccountSettingsLayout from "../components/AccountSettingsLayout";

import "../styles/globals.css";

export default function App({ Component, router, pageProps }) {
  if (router.pathname.startsWith("/auth/")) {
    return (
      <React.StrictMode>
        <SessionProvider session={pageProps.session}>
          <SWRConfig>
            <AccountSettingsLayout>
              <Component {...pageProps} />
            </AccountSettingsLayout>
          </SWRConfig>
        </SessionProvider>
      </React.StrictMode>
    );
  }

  return (
    <React.StrictMode>
      <SessionProvider session={pageProps.session}>
        <SWRConfig>
          <Layout>
            <Component {...pageProps} />
          </Layout>
        </SWRConfig>
      </SessionProvider>
    </React.StrictMode>
  );
}

UPDATE - 01/10/22
I am using Next-auth in this project which is creating users and data in firebase without issue. Could this be preventing the rest of my app from using the firestore to add data?
Here is my next-auth code..
/pages/api/auth/[...nextauth].js
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import EmailProvider from "next-auth/providers/email";
import { FirestoreAdapter } from "@next-auth/firebase-adapter";

const authOptions = {
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_SECRET,
    }),
    EmailProvider({
      server: {
        host: process.env.EMAIL_SERVER_HOST,
        port: process.env.EMAIL_SERVER_PORT,
        auth: {
          user: process.env.EMAIL_SERVER_USER,
          pass: process.env.EMAIL_SERVER_PASSWORD,
        },
      },
      from: process.env.EMAIL_FROM,
    }),
  ],
  session: {
    jwt: false,
  },
  adapter: FirestoreAdapter({
    apiKey: process.env.FIREBASE_API_KEY,
    appId: process.env.FIREBASE_APP_ID,
    authDomain: process.env.FIREBASE_AUTH_DOMAIN,
    databaseURL: process.env.FIREBASE_DATABASE_URL,
    projectId: process.env.FIREBASE_PROJECT_ID,
    storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
    messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
  }),
  theme: {
    colorScheme: "dark",
  },
  pages: {
    signIn: "/auth/signin",
    newUser: "/auth/signup",
  },
  debug: false,
  callbacks: {
    async signIn({ user, account, profile }) {
      if (account.provider === "google") {
        return profile.email_verified;
      }
      return true;
    },
    async redirect({ url, baseUrl }) {
      return baseUrl;
    },
    async session({ session, user }) {
      session.user.id = user.id;
      return Promise.resolve(session);
    },
    async jwt({ token, user, account, profile, isNewUser }) {
      return token;
    },
  },
};
export default NextAuth(authOptions);

Thanks

A: I think the issue is with your env variables. In the first screenshot you get this options
_options : ( apiKey : undefined , appId : undefined , authDomain : undefined , databaseURL : undefined

Your env variables defined correctly in next-auth config, because next-auth page is pages/apis/auth/[...nextauth].js file. apis directory is executed on the server and since env variables that you set in env are by default available on the server, your configuration worked here.
since, in the beginning yourfirestore config run on the client side, process.env.FIREBASE_API_KEY env variables were undefined. To make the env variables both available on client and server, use NEXT_PUBLIC prefix in env file.
NEXT_PUBLIC_FIREBASE_API_KEY=#####################

then use it as process.env.NEXT_PUBLIC_FIREBASE_API_KEY.
What's the difference between exposing environment variables in nextjs through the next.config.js vs with the NEXT_PUBLIC prefix?

A: You are using the firebase-admin package to initialize the app, but you are using the firebase package to update the document, so you can try to use the firebase-admin package to update the document. Example:
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
import { getStorage } from "firebase/storage";
import { setDoc, doc } from "firebase/firestore";

const firebaseConfig = {
  apiKey: process.env.FIREBASE_API_KEY,
  appId: process.env.FIREBASE_APP_ID,
  authDomain: process.env.FIREBASE_AUTH_DOMAIN,
  databaseURL: process.env.FIREBASE_DATABASE_URL,
  projectId: process.env.FIREBASE_PROJECT_ID,
  storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
};

const app = initializeApp(firebaseConfig);

const storage = getStorage(app);
const db = getFirestore(app);

export { storage, db };

import { db } from "../../firebase/config";

export default async function SignupSubmit(value) {

  const values = {
    profile: value.profile,
    screenName: value.screenName,
  };

  const docRef = doc(db, "users", `${userId}`);
  console.log(docRef);

  setDoc(docRef, { values }, { merge: true })
    .then(() => {
      console.log("Document has been updated successfully");
    })
    .catch((error) => {
      console.log(error);
    });
}

I hope this helps.