text:
Q: Populating rest of the column values for each of value of one column in a dataframe I have a dataframe with some columns.

ID
string
test

0
zero
abc

1
one
def

2
two
ghi

3
three
jkl

4
four
mno

I want to populate rest of the columns for each ID value

ID
string
test

0
zero
abc

0
one
def

0
two
ghi

0
three
jkl

0
four
mno

1
zero
abc

1
one
def

1
two
ghi

1
three
jkl

1
four
mno

2
zero
abc

2
one
def

2
two
ghi

2
three
jkl

2
four
mno

3
zero
abc

3
one
def

3
two
ghi

3
three
jkl

3
four
mno

4
zero
abc

4
one
def

4
two
ghi

4
three
jkl

4
four
mno

A: You can do a self cross join :
df1 = df.alias("a").crossJoin(df.alias("b")) \
    .select("a.ID", "b.string", "b.test")

df1.show()

#+---+------+----+
#| ID|string|test|
#+---+------+----+
#|  0|   one| def|
#|  0|   two| ghi|
#|  0| three| jkl|
#|  0|  four| mno|
#|  1|  zero| abc|
#|  1|   two| ghi|
#|  1| three| jkl|
#|  1|  four| mno|
#|  3|  zero| abc|
#|  3|   one| def|
#|  3|   two| ghi|
#|  3|  four| mno|
#|  2|  zero| abc|
#|  2|   one| def|
#|  2| three| jkl|
#|  2|  four| mno|
#|  4|  zero| abc|
#|  4|   one| def|
#|  4|   two| ghi|
#|  4| three| jkl|
#+---+------+----+

Another way is collecting ID values and using list comprehension, create dataframes with column ID as a literal value, and other values from columns string and test. Then using union to get the desired result
import functools
from pyspark.sql import functions as F
from pyspark.sql import DataFrame

dfs = [
    df.filter(F.col("ID") != r.ID).selectExpr(f"{r.ID} as ID", "string", "test")
    for r in df.select("ID").distinct().collect()
]

df1 = functools.reduce(DataFrame.union, dfs + [df])

A: You can do a cross join:
result = df.select('ID').crossJoin(df.select('string', 'test'))

result.show(99)
+---+------+----+
| ID|string|test|
+---+------+----+
|  0|  zero| abc|
|  1|  zero| abc|
|  2|  zero| abc|
|  3|  zero| abc|
|  4|  zero| abc|
|  0|   one| def|
|  1|   one| def|
|  2|   one| def|
|  3|   one| def|
|  4|   one| def|
|  0|   two| ghi|
|  1|   two| ghi|
|  2|   two| ghi|
|  3|   two| ghi|
|  4|   two| ghi|
|  0| three| jkl|
|  1| three| jkl|
|  2| three| jkl|
|  3| three| jkl|
|  4| three| jkl|
|  0|  four| mno|
|  1|  four| mno|
|  2|  four| mno|
|  3|  four| mno|
|  4|  four| mno|
+---+------+----+


text:
Q: List of relevant RPC Protocols I need to evaluate and dig more into the use of Remote Procedure Call Protocols (over the network) and haven't found a comprehensive list of which I could include.
There are some I already know from experience like

*

*RMI

*"RESTful style RPCs"

*XML-RPC

*SOAP

*JSON-RPC

*(CORBA ?)

*GWT-RPC and other Vendor specific ones, commonly used

But I'm still not sure if I am missing some important ones. I want to keep the evaluation as objective as possible so I just need some input on which I might have forgotten and maybe when and for what it is mainly used.

A: *

*Hessian

*Burlap

A: *

*DCE RPC

*Sun/ONC RPC

*OSI ROSE

A: *

*Rabbit MQ

*Websphere MQ

*Spread

*PYRO
There are quite a few more but that should show you some of the diversity. Yes, CORBA is an RPC protocol from before the web. To find out more you should be able to Google on any of the RPC names people have given you, along with the word RPC.

A: *

*Google Protocol Buffers

*BERT-RPC

A: Thrift as well.

A: *

*Versile Platform

A: *

*Internet Communications Engine

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to check the value of an input correctly? i have made a little quiz
but i have one last problem
when clicking next button it checks to see if the value is not undfinded.
if its true it checks to see if the client choosen radio is equals to the spouse correct answer then
a var correctAnswer get +1.
the problem is that at the first question its working (checking to see that a client really choose something out of the answers and checking to see if its correct)
but when the next question is presented its not working. I tried to figure it out but came with no sulotion...
also check jsfiddle: http://jsfiddle.net/boazmier/ru8Qj/1/
i have tried to put the checkClientChoice function into the loadquestion function it didnt worked as well
var allQuestions = {
    question: {
        question0: {
            question: "Who is the first Prime Minister of Israel?",
            choices: ["David", "Rabin", "Peres", "Bibi"],
            correct: "David"
        },
        question1: {
            question: "What Is israel date of birth?",
            choices: ["1948", "1958", "1950", "1944"],
            correct: "1948"
        },
        question2: {
            question: "What is PhoneGap framework for?",
            choices: ["apache", "apps", "server", "client"],
            correct: "apps"
        }
    },

    correctAnswer: 0
};

var allquestion = allQuestions["question"];

var calcAnswers =allQuestions["correctAnswer"];

var qNum = 0;

var value;

//function that deploies the question and the choices to the section.
function loadquestions(qNum){
    $(".question").text(allquestion["question"+qNum]["question"]); //set the the question to the title
    for(var i=0;i<allquestion["question"+qNum]["choices"].length;){
        //loops throughout the li's
        var cH =(allquestion["question"+qNum]["choices"][i]); // a var that holds text of choice in poistion i
        $("label[for=li"+i+"]").text(cH); //define for every label its text
        $("#li"+i).attr("value",cH); //define for every input radio its value which is equals to label which is equals to var cH
        i++;//count i with +1
    }
}

//function that fires when clicked the "next" button and when trigered hides the current question and presents the next one

function checkClientChoice(){
 $("#next").click(function(){
     value = $("input[type='radio']:checked").val();

     if(value == undefined){
        alert("Please choose a valid answer");
    }
    else {
        if(allquestion["question0"]["correct"] == value){
            alert("correct");
            calcAnswers++;
            alert(calcAnswers);
            qNum++;
            loadquestions(qNum);
        }
         else{
            qNum++;
            loadquestions(qNum);
        }
    }
});
};

$(document).ready(function(){
    loadquestions(qNum);
    checkClientChoice();
});

A: Okay, here what we got:
if(allquestion["question0"]["correct"] == value)

You always check answer to the very first question. You should change this to
if(allquestion["question" + qNum]["correct"] == value)

Or track question num in function checkClientChoice some other way.


text:
Q: Simulating/triggering touch events in Protractor scenario I'm looking for a way to trigger touch/swipe events during my Protractor test scenarios.
I know that the underlying Selenium JsonWireProtocol supports it, but it seems like it has the requirement of using appium (which I'd rather not use).
I found this answer on SO which triggers/tests very specific touch events, but I'm not trying to test the events themselves - I just want to navigate the app like a user would (and test what comes AFTER they've navigated through it).


text:
Q: Table Joints on MySQL with collation "utf8_general_ci" error I have 2 tables. Table1 contains a profile. Table2 contains user login details. The two tables are related by the same column: gurdianID. I want to get a single row from 'Table1' and 'Table2' where the 'gurdianID' matches in both the tables. i.e. Example gurdianID'='15001'.
I tried the following but it keeps giving me a MySQL error:
SELECT *
FROM  portalGurdian, gurdLogin
WHERE portalGurdian.guardID=gurdLogin.guardID
AND   portalGurdian.guardID='15001';

The Error Message is:
MySQL said: Documentation
#1267 - Illegal mix of collations (utf8_general_ci,IMPLICIT) and (utf8_unicode_ci,IMPLICIT) for operation '='

Any guidance on how to resolve this ?

A: I just did a search on the MySQL Error code and found that the collations were slightly different, and causing the issue.
I went ahead and made sure both the tables had the same collation ... i.e. 'utf8_general_ci'
Lesson Learned: Read the error message carefully ...


text:
Q: My system can't find installed otf and ttf fonts I have texlive 2019 on windows 10 OS, I tried several times to install True Type Font or Open Type Font and after installation my system couldn't find them (the problem did not occur with my previous distribution texlive 2018).
For example I installed Gidole font from http://gidole.github.io/ then run
fc-cache

After that
fc-list Gidole

And I don't get a result, trying to use the font with xetex or luatex do not succeed.

A: TeX Live on Windows can only find fonts that are installed in system directories.  You must Install for All Users, which requires Administrator privileges.  The default installation will put them in a hidden user directory, which doesn't work.  If you do not want to install a file system-wide as an administrator, you can instead put it in a project directory and use the Path = command option of fontspec.
You could also put it in a subdirectory of your local TeX Live directory, normally C:\texlive\texmf-local\fonts.  Re-run fc-cache -fsv and luaotfload-tool -f -u -v to update your font caches.  (I can confirm that luaotfload checks texmf-local, but I am not sure about fc-cache.  On the other hand, fc-cache checks %WINDIR%\Fonts\Deleted and will sometimes match a version of the font you removed instead of the one you installed to replace it.)
Having a shadow copy of the font, which might go out of date, is a bad idea.  If you reinstall a font for all users, you should remove the user-installed copy from the Fonts control panel.
A properly-configured TeX Live on Linux has no such limitation, and I am honestly not sure what the reason is for it on Windows.  The documentation for fc-cache and luaotfload-tool list options that are supposed to search local directories for fonts, but do not work.

A: You can add the following line to file C:\texlive\2021\texmf-var\fonts\conf\fonts.conf:
<dir>C:/Users/<YourName>/AppData/Local/Microsoft/Windows/Fonts</dir>

Then run fc-cache -vf to update the font cache.
See https://tex.stackexchange.com/a/54582


text:
Q: Scrollbars on canvas in tkinter does not work Yes there are many stackoverflow questions regarding this, i saw everything but could not get this working so i am asking a new question with my code:
Basically i want to create a table in tkinter with 4 columns. But i want to be able to scroll this because the rows will be later taken from the mysql database. but i cannot get the scroll working.
Here is my code :
from tkinter import *

root = Tk()
root.geometry("700x600")

frame_canvas = Frame(root)
frame_canvas.rowconfigure(0, weight=1)
frame_canvas.columnconfigure(0, weight=1)
frame_canvas.grid(row=0, column=0, sticky="news")

canvas = Canvas(frame_canvas)
canvas.grid(row=0, column=0, sticky="news")

vsb = Scrollbar(frame_canvas, orient="vertical", command=canvas.yview)
vsb.grid(row=0, column=1, sticky='ns')
canvas.configure(yscrollcommand=vsb.set)

for i in range(0, 50):
    for j in range(0, 4):
        canvas.columnconfigure(j, minsize=150)
        Label(canvas, text="hello"+str(i)+str(j)).grid(row=i, column=j)

canvas.config(scrollregion=canvas.bbox("all"))

app = root
root.mainloop()

How to i get the canvas to scroll ? Is there another way to create a table ? Also later if i want to add a row to the bottom of the table, how is it possible ? or do i have to clear the whole canvas and re-render it or something ?
EDIT
Have added a frame window to the canvas. Still scroll won't work. That could be the issue now ?
from tkinter import *

root = Tk()
root.geometry("700x600")

frame_canvas = Frame(root)
frame_canvas.rowconfigure(0, weight=1)
frame_canvas.columnconfigure(0, weight=1)
frame_canvas.grid(row=0, column=0, sticky="news")

canvas = Canvas(frame_canvas, height=600, width=500)
canvas.grid(row=0, column=0, sticky="news")

vsb = Scrollbar(frame_canvas, command=canvas.yview, orient="vertical")
vsb.grid(row=0, column=1, sticky='ns')
canvas.configure(yscrollcommand=vsb.set)

frame2 = Frame(canvas, bg="powder blue", height=600, width=700)
canvas.create_window((0, 0), anchor="nw", height=600, width=600, window=frame2)

for i in range(0, 50):
    for j in range(0, 4):
        frame2.columnconfigure(j, minsize=120)
        Label(frame2, bg="powder blue", text="hello"+str(i)+str(j)).grid(row=i, column=j)

canvas.config(scrollregion=frame2.bbox("all"))

app = root
root.mainloop()


text:
Q: Extending windows based installer to other Operating Systems I have build an installer using NSIS. And now I want to extend it to Solaris and Linux thorugh WINE. But I wanna know few things here-

*

*Is WINE flavour dependent? I mean are there different packages for different Linux versions?

*Whats if my Installer creates some SQL or Oracle database? Will this feature be also supported by WINE?

*Is there any tool which can be used to build installer which is platform independent?

A: Take a look at InstallJammer for a free, open source, cross-platform install builder that supports the platforms you need.  See if that'll do what you want. :)

A: The problem with your approach is that then you require the end-user to have Wine pre-installed. You may be better using a multiplatform installation tool like InstallBuilder
 (disclaimer, I am the author of InstallBuilder)


text:
Q: Formal introduction of product measure Having proven the existence and uniqueness of the product measure $\mu$, given two $\sigma$-finite measure spaces $(\Omega_1,\sum_1, \mu_1), (\Omega_2,\sum_2, \mu_2)$, you can extend this principle to finitely many measure spaces. For the induction step, I read that you put $\Omega_1 \times \Omega_2\times...\times \Omega_n =(\Omega_1 \times \Omega_2\times...)\times \Omega_n$, so that the n-tuples are interpreted as 2-tuples and the first case can be used again.
My question: I assume that there is not $really$ an equality between the two sets, but that one can fix this the same way as $\mathbb{R}^2\times \mathbb{R} \cong\mathbb{R}^3$. The two vector spaces are not $really$ equal, but you can forget about that thanks to the isomorphism. What's the case with the general n-times-cartesian product? Is there again an isomorphism two define the product measure, or something similar like a bijection between $\Omega_1 \times \Omega_2\times...\times \Omega_n $ and $(\Omega_1 \times \Omega_2\times...)\times \Omega_n$, that "preserves the measure"?
I guess this kind of question falls into the section "When do we identify isomorphic copies" or so.
I hope my question is understandable and relevant.

A: Just use the (canonical) map
$$
(\Omega_1 \times \cdots \times \Omega_{n-1}) \times \Omega_n \to \Omega_1 \times \cdots \times \Omega_n, ((x_1, \dots, x_{n-1}), x_n) \mapsto (x_1, \dots, x_n).
$$
You can then take for example the image measure of the product measure obtained on $(\Omega_1 \times \cdots \times \Omega_{n-1}) \times \Omega_n$ to get the product measure on $\Omega_1 \times \cdots \times \Omega_n$.
But to be honest, one usually ignores these subtleties. Sometimes, $\Omega_1 \times \cdots \times \Omega_n$ is even defined (inductively) as $(\Omega_1 \times \cdots \times \Omega_{n-1}) \times \Omega_n$.


text:
Q: Append an existing child to the new child? I have a xml file as:-
<Data>
<Caption>
</Caption>
</Data>

I added a new child CData in the the following code
foreach (XmlNode item in childNode.ChildNodes)
{
    if (item.Name == "Data")
    {
        XmlCDataSection CData;
        CData = xml2.CreateCDataSection("All Jane Austen novels 25% off starting 3/23!");

        item.InsertBefore(CData, item.FirstChild);

        foreach (XmlNode itemC in item.ChildNodes)
        {
            if (itemC.Name == "Caption")
            {

                XmlElement getTemplateID = xml2.CreateElement("TempalteID");
                getTemplateID.InnerText = "10010";
                itemC.AppendChild(getTemplateID);

                //if (OptionsData[0].Key == "NoChilds")
                //{
                //    XmlElement Getnochild = itemDoc.CreateElement("CaptionOptions");
                //    Getnochild.InnerText = "";
                //    itemC.AppendChild(Getnochild);
                //}
                //else
                //{
                XmlNode elemCap = xml2.CreateNode(XmlNodeType.Element, "CaptionOptions", null);
                itemC.AppendChild(elemCap);
                XmlElement Getelem1 = xml2.CreateElement("CaptionField");
                elemCap.AppendChild(Getelem1);
                XmlElement elem2 = xml2.CreateElement("FieldID");
                XmlElement elem3 = xml2.CreateElement("FieldID");

                elem2.InnerText = "#FieldId1";
                elem3.InnerText = "#FieldId2";

                XmlElement elem4 = xml2.CreateElement("TextString");
                XmlElement elem5 = xml2.CreateElement("TextString");
                elem4.InnerText = "#TextString1";
                elem5.InnerText = "#TextString2";
                Getelem1.AppendChild(elem2);
                Getelem1.AppendChild(elem4);
                Getelem1.AppendChild(elem3);
                Getelem1.AppendChild(elem5);

                //}
            }
        }
    }
}

Now my final xml is coming as
<Data>
  <![CDATA[All Jane Austen novels 25% off starting 3/23!]]>
  <Caption>
    <TempalteID>10010</TempalteID>
    <CaptionOptions><CaptionField>
    <FieldID>#FieldId1</FieldID>
    <TextString>#TextString1</TextString>
    <FieldID>#FieldId2</FieldID>
    <TextString>#TextString2</TextString>
    </CaptionField></CaptionOptions>
  </Caption>
</Data>

But I want to make it as the following way....
<Data><![CDATA[<Caption xmlns="http://www.iin.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.happy.xsd">
    <TemplateID>T000114-NOW</TemplateID>
    <CaptionOptions>
      <CaptionField>
        <FieldID>NOW1</FieldID>
        <TextString>"Ep 01"</TextString>
      </CaptionField>
      <CaptionField>
        <FieldID>NOW2</FieldID>
        <TextString>""</TextString>
      </CaptionField>
    </CaptionOptions>
  </Caption>]]>
</Data>

So as you can see I basically wanted my newly added child CData to make <Caption> as it's child. So basically I want to create a child and make an existing child as it's child.(But I don't think I would still get the same format?")
How to do it?

A: Using xml Linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

using System.Runtime.InteropServices;

namespace ConsoleApplication23
{
    class Program
    {

        static void Main(string[] args)
        {
            string xml = "<Data><Caption  xmlns=\"http://www.iin.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.happy.xsd\"/></Data>";

            XDocument doc = XDocument.Parse(xml);
            XElement caption = doc.Descendants("Data").FirstOrDefault();

            caption.Add(new XElement("TemplateID","T000114-NOW"));

            XElement options = new XElement("CaptionOptions");
            caption.Add(options);

            foreach (Field field in Field.fields)
            {
                XElement newField = new XElement("CaptionField", new object[] { new XElement("FieldID", field.ID), new XElement("TextString", field.text)});
                options.Add(newField);
            }

        }
    }
    public class Field
    {
        public static List<Field> fields = new List<Field>() {
            new Field() {  ID = "NOW1", text = "Ep 01"},
            new Field() { ID = "Ep 01", text = ""}
        };

        public string ID { get; set; }
        public string text { get; set; }
    }

}

A: If I understand right, what you want to do is storing XML data in CDATA element. I want to remind you, that this is not what CDATA was intended to be used for, but here is example how to do that:
XmlDocument doc = new XmlDocument();
doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" +
            "<title>Pride And Prejudice</title>" +
            "</book>");

//Add the new node to the document.
XmlElement root = doc.DocumentElement;

XmlCDataSection CData;
CData = doc.CreateCDataSection(root.InnerXml);

root.RemoveAll();
root.AppendChild(CData);

doc.Save(Console.Out);


text:
Q: How to roll one dice at a time? So here is what I have so far. I am very new to javascript. How do I make these dice roll sequentially inside of the divs? Such as only displaying the next random number only after the first one is displayed.

0

0

0

<button onclick="rollDice()"/>Generate Number</button>

0

A: You can use the setTimeout() method to delay execution of a function, so that the dice will be rolled one at a time:

function rollDice(){
  var status = document.getElementById("status");
  var nums = document.querySelectorAll(".numdiv");
  var diceTotal = 0;
  var current;

  for (current = 0; current < nums.length; current++) {
    nums[current].innerHTML = "?";
  }

  current = 0;
  status.innerHTML = "Rolling...";

  function rollNext() {
    currentRoll = Math.floor(Math.random() * 6) + 1;
    nums[current].innerHTML = currentRoll;
    diceTotal += currentRoll;
    current++;
    if (current < nums.length) {
      setTimeout(rollNext, 1000);
    } else {
      status.innerHTML = "You rolled " + diceTotal + ".";
      if(diceTotal == 15){
        status.innerHTML += "You Win!!";
      }
    }
  }
  setTimeout(rollNext, 1000);
}
.numdiv { height: 30px; width: 30px; border:solid 1px green; float: left; margin: 10px }

  <button onclick="rollDice()"/>Generate Number</button>

  0

Notice also that I've removed your separate number1, number2 and number3 variables, instead using a single variable num to refer to the list of all of the .numDiv div elements. That way you can easily change how many dice you want to use without changing the JS at all (you'd just add or remove .numDiv elements).
EDIT: As I was posting the above you clarified that you want the user to press the button for each die, not automatically roll all three with a delay. So I guess, maybe something like the following, keeping a counter and the total in variables declared outside the function:

  var statusSpan = document.getElementById("status");
  var nums = document.querySelectorAll(".numdiv");
  var diceTotal;
  var current = 0;

  function rollDice(){
    if (current === 0) { // reset display
      for (var i = 0; i < nums.length; i++)
        nums[i].innerHTML = "?";
      diceTotal = 0;
    }

    currentRoll = Math.floor(Math.random() * 6) + 1;
    nums[current].innerHTML = currentRoll;
    diceTotal += currentRoll;
    if (++current < nums.length) {
      statusSpan.innerHTML = "Current total: " + diceTotal + ".";
    } else {
      statusSpan.innerHTML = "You rolled " + diceTotal + ".";
      if(diceTotal == 15){
        statusSpan.innerHTML += "You Win!!";
      }
      current = 0;
    }
  }
.numdiv { height: 30px; width: 30px; border:solid 1px green; float: left; margin: 10px; text-align: center }

  <button onclick="rollDice()">Roll next die</button>

  Ready to roll?

A: Create a counter variable starting with one outside of your rollDice function and every time that is clicked then increase the counter by one. Then you need to replace all the number variables with just this:
var number = document.getElementById("number" + counter);

I think you know where to go from here. Let me know if you need more guidance!

A: Building on your existing logic, if you want to display 1 every time user clicks then an alternate approach....
    var totalIter = 0;//global var which is set to increments on each click
    var diceTotal = 0;

    function rollDice() {
        totalIter = totalIter + 1; //increment by 1
        //Existing logic from your script
        var ele = document.getElementById("number" + totalIter);
        var d1 = Math.floor(Math.random() * 6) + 1;
        var status = document.getElementById("status");
        diceTotal = diceTotal + d1;
        ele.innerHTML = d1;
        status.innerHTML = "You rolled " + diceTotal + ".";
        if (diceTotal == 15) {
            status.innerHTML += "You Win!!";
        }
    }


text:
Q: Google Storage - Read timeout I am using signed url of in Google Storage. I have a python code using requests that upload a file to the signed url using http PUT. The code is running in a GKE 1.17 deployment with 18 threads on ubuntu 18.04. The code implements retry using the retry python library. In addition the code is crawling websites.
The Problem
The code sometimes fail with the exception ReadTimeout:
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/urllib3/connectionpool.py", line 421, in _make_request
    six.raise_from(e, None)
  File "<string>", line 3, in raise_from
  File "/usr/local/lib/python3.6/dist-packages/urllib3/connectionpool.py", line 416, in _make_request
    httplib_response = conn.getresponse()
  File "/usr/lib/python3.6/http/client.py", line 1346, in getresponse
    response.begin()
  File "/usr/lib/python3.6/http/client.py", line 307, in begin
    version, status, reason = self._read_status()
  File "/usr/lib/python3.6/http/client.py", line 268, in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  File "/usr/lib/python3.6/socket.py", line 586, in readinto
    return self._sock.recv_into(b)
  File "/usr/lib/python3.6/ssl.py", line 1012, in recv_into
    return self.read(nbytes, buffer)
  File "/usr/lib/python3.6/ssl.py", line 874, in read
    return self._sslobj.read(len, buffer)
  File "/usr/lib/python3.6/ssl.py", line 631, in read
    v = self._sslobj.read(len, buffer)
socket.timeout: The read operation timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/requests/adapters.py", line 449, in send
    timeout=timeout
  File "/usr/local/lib/python3.6/dist-packages/urllib3/connectionpool.py", line 720, in urlopen
    method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2]
  File "/usr/local/lib/python3.6/dist-packages/urllib3/util/retry.py", line 400, in increment
    raise six.reraise(type(error), error, _stacktrace)
  File "/usr/local/lib/python3.6/dist-packages/urllib3/packages/six.py", line 735, in reraise
    raise value
  File "/usr/local/lib/python3.6/dist-packages/urllib3/connectionpool.py", line 672, in urlopen
    chunked=chunked,
  File "/usr/local/lib/python3.6/dist-packages/urllib3/connectionpool.py", line 423, in _make_request
    self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
  File "/usr/local/lib/python3.6/dist-packages/urllib3/connectionpool.py", line 331, in _raise_timeout
    self, url, "Read timed out. (read timeout=%s)" % timeout_value
urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='storage.googleapis.com', port=443): Read timed out. (read timeout=30)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
...

    response = self.__upload(target, file_stream, headers)
  File "<decorator-gen-18>", line 2, in __upload
  File "/usr/local/lib/python3.6/dist-packages/retry/api.py", line 74, in retry_decorator
    logger)
  File "/usr/local/lib/python3.6/dist-packages/retry/api.py", line 33, in __retry_internal
    return f()
  File "/home/crawler/crawler/upload/UploadResults.py", line 179, in __upload
    target, zip_file_stream, headers=headers, timeout=TIMEOUT)
  File "/usr/local/lib/python3.6/dist-packages/requests/sessions.py", line 593, in put
    return self.request('PUT', url, data=data, **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/requests/sessions.py", line 533, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/local/lib/python3.6/dist-packages/requests/sessions.py", line 646, in send
    r = adapter.send(request, **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/requests/adapters.py", line 529, in send
    raise ReadTimeout(e, request=request)
requests.exceptions.ReadTimeout: HTTPSConnectionPool(host='storage.googleapis.com', port=443): Read timed out. (read timeout=30)

This means that the connection was made successfully and no data was received in the readtimeout window.
My Attempts To Fix It

*

*More retries - Up to 10

*Larger delay between retries

*exponential backoff

*Test if I raise ReadTimeout() in the function if the functions retries this specific exception, and it did.

*Allow more connections in for the session and allow more connections per host.

*The google storage url is avoiding naming bottleneck by using a different folder for each file.

*Larger read timeout value - tried with up to 60 seconds.

My Code
import requests
from google.api_core.exceptions import GatewayTimeout, GoogleAPICallError, ServiceUnavailable
from requests.exceptions import ConnectionError
from crawler.exceptions.CrawlerException import CrawlerException, eCrawlingStatusCodes
from retry import retry

RETRIES = 10
BACKOFF = 1.5
DELAY = 2
TIMEOUT = (9.05, 30)

class UploadResults:
    GOOGLE_STORAGE = GoogleStorage()
    SESSION = requests.Session()
    SESSION.mount('https://', requests.adapters.HTTPAdapter(
        pool_connections=20, pool_maxsize=30))

    @retry(exceptions=(CrawlerException, requests.exceptions.RequestException, ValueError,
            requests.exceptions.Timeout, requests.exceptions.ReadTimeout, requests.exceptions.ConnectTimeout),
           tries=RETRIES, delay=DELAY, backoff=BACKOFF)
    def __upload(self, target, zip_file_stream, headers):
        response = UploadResults.SESSION.put(
            target, zip_file_stream, headers=headers, timeout=TIMEOUT)

        if response.status_code >= 300:
            raise CrawlerException(eCrawlingStatusCodes.InternalError,
                                   "Internal error on uploading to path, Server status: %d" % response.status_code)

        return response

Questions
What can cause this exception?
Is there a limit I am missing that can cause this behaviour?


text:
Q: Altering Hashes I have a hash
original_hash = {"10"=>3, "15"=>2, "20"=>1}

I want to make a new hash, call it results_hash, where the keys of original_hash will be appended '$' sign and the new values to the keys will be (key * value) of the original_hash. The generated results_hash should be:
results_hash = {"$10"=>30, "$15"=>30, "$20"=>20}

How can I do that?

A: resulted_hash = {}

original_hash.each do |key, val|
 resulted_hash["$" + k] = v*k.to_i
end

A: original_hash = {"10"=>3, "15"=>2, "20"=>1}
results_hash = Hash[original_hash.map { |k,v| ['$'+k,k.to_i*v] }]
p results_hash # => {"$10"=>30, "$15"=>30, "$20"=>20}

original_hash = {"10"=>3, "15"=>2, "20"=>1}
results_hash = original_hash.each_with_object({}) { |(k,v),h| h['$'+k]=k.to_i*v }
p results_hash # => {"$10"=>30, "$15"=>30, "$20"=>20}


text:
Q: WebStorm React Native cant start debug I get this error starting the debug session. I have never used WebStorm before and following the setup from JetBrains
"C:\Program Files\JetBrains\WebStorm 2018.2.6\bin\runnerw.exe" "C:\Program Files\nodejs\node.exe" --inspect-brk=51768 L:\react\PropertyFinder\PropertyFinder\index.js
Debugger listening on ws://127.0.0.1:51768/b33603e7-c88c-4336-b4d1-6042b064fcb0
For help, see: https://nodejs.org/en/docs/inspector
Debugger attached.
L:\react\PropertyFinder\PropertyFinder\index.js:1
(function (exports, require, module, __filename, __dirname) { import {AppRegistry} from 'react-native';
                                                                     ^

SyntaxError: Unexpected token {
    at new Script (vm.js:79:7)
    at createScript (vm.js:251:10)
    at Object.runInThisContext (vm.js:303:10)
    at Module._compile (internal/modules/cjs/loader.js:656:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
    at Module.load (internal/modules/cjs/loader.js:598:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
    at Function.Module._load (internal/modules/cjs/loader.js:529:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:741:12)
    at startup (internal/bootstrap/node.js:285:19)
Waiting for the debugger to disconnect...

Process finished with exit code -1073741510 (0xC000013A: interrupted by Ctrl+C)

Here´s the Index.js
/** @format */

    import {AppRegistry} from 'react-native';
    import App from './App';
    import {name as appName} from './app.json';

    AppRegistry.registerComponent(appName, () => App);

Any idea? Looks like there a problem at index.js:1 but what?

A: You should use React Native run configuration to start your application - see Help instructions and blog post.
 I don't understand what you meant to accomplish when starting your index.js with Node.js


text:
Q: how to access nested values inside json object inside javascript I have this URL which returns me a JSON value, my task is to access 3 values out of it that is name, title and ISBN.
Since the content is heavily nested, I am not able to access the values inside it.
All the tutorials I have referred so far, have simple nesting in them
I have attached my code that I have written so far:
$(document).ready(function() {
  var globalJsonVar;
  alert("check");
  $.getJSON("https://openlibrary.org/api/books?bibkeys=ISBN:9781606868829&jscmd=details&format=json", function(result) {
    if (Object.keys(result).length > 0) {
      alert("conetnt is present");
      console.log(result);
      alert(Object.values(result));
      alert(result.ISBN: 9781606868829. bib_key); // my attempt at accessing the values
    } else {
      alert("hoax");
    }
  });
});

The JSON content that I am receiving is
{
  "ISBN:9780143039648": {
    "bib_key": "ISBN:9780143039648",
    "preview": "noview",
    "preview_url": "https://openlibrary.org/books/OL17924003M/The_guide",
    "info_url": "https://openlibrary.org/books/OL17924003M/The_guide",
    "details": {
      "number_of_pages": 196,
      "series": [
        "Penguin classics"
      ],
      "lc_classifications": [
        "PR9499.3.N3 G85 2006"
      ],
      "latest_revision": 7,
      "uri_descriptions": [
        "Contributor biographical information",
        "Publisher description"
      ],
      "genres": [
        "Fiction."
      ],
      "title": "The guide",
      "languages": [{
        "key": "/languages/eng"
      }],
      "subjects": [
        "Malgudi (India : Imaginary place) -- Fiction.",
        "Tour guides (Persons) -- Fiction.",
        "Bharata natyam dancers -- Fiction.",
        "Spiritual life -- Hinduism -- Fiction.",
        "India -- Fiction."
      ],
      "publish_country": "nyu",
      "by_statement": "R.K. Narayan ; introduction by Michael Gorra.",
      "type": {
        "key": "/type/edition"
      },
      "uris": [
        "http://www.loc.gov/catdir/enhancements/fy0716/2006044314-b.html",
        "http://www.loc.gov/catdir/enhancements/fy0716/2006044314-d.html"
      ],
      "revision": 7,
      "publishers": [
        "Penguin Books"
      ],
      "dewey_decimal_class": [
        "823/.914"
      ],
      "last_modified": {
        "type": "/type/datetime",
        "value": "2012-08-05T21:10:58.887826"
      },
      "key": "/books/OL17924003M",
      "authors": [{
        "name": "Rasipuram Krishnaswamy Narayan",
        "key": "/authors/OL5911201A"
      }],
      "publish_places": [
        "New York"
      ],
      "oclc_number": [
        "65644730"
      ],
      "pagination": "xxiv, 196 p. ;",
      "created": {
        "type": "/type/datetime",
        "value": "2008-10-07T19:30:19.584308"
      },
      "url": [
        "http://www.loc.gov/catdir/enhancements/fy0716/2006044314-b.html",
        "http://www.loc.gov/catdir/enhancements/fy0716/2006044314-d.html"
      ],
      "notes": {
        "type": "/type/text",
        "value": "Originally published: New York : Viking Press, 1958.\n\nIncludes bibliographical references (p. [xxi]-xxii)."
      },
      "identifiers": {
        "goodreads": [
          "129877"
        ],
        "librarything": [
          "6930"
        ]
      },
      "isbn_13": [
        "9780143039648"
      ],
      "lccn": [
        "2006044314"
      ],
      "isbn_10": [
        "0143039644"
      ],
      "publish_date": "2006",
      "works": [{
        "key": "/works/OL1057183W"
      }]
    }
  }
}

A: You have to use [] if you want to have access to keys that have special chars, for example result['something-with:special-chars']

A: result.ISBN:9781606868829.bib_key

is a syntax error. : is not allowed here. You want to use the following syntay :
result["ISBN:9781606868829"].bib_key


text:
Q: how to split up a string by delims and then select part of it current code:
set str=11.22.33
for /F "tokens=1* delims=." %%a in ("%str%") do (
  echo %%a
)

I wish to produce the following outcome: .22.33

A: Try this:
set str=11.22.33
for /F "tokens=2,3 delims=." %%a in ("%str%") do (
echo .%%a.%%b
)

A: Monacraft has a working option.
Here is another option:
set "str=11.22.33"
for /f "tokens=2* delims=." %%A in ("%str%") do echo .%%a

And yet another option
set "str=11.22.33"
echo .%str:*.=%


text:
Q: An anonymous class using mockito (son class use father class)
*

*my java source code:

father class:
@Service

public class ProviderBasicDAO {

    @Autowired

    protected JdbcTemplate jdbcTemplate;

    public List<Long> getNetworkIds(List<EHIPlan> ehiPlans) {
        if (CollectionUtils.isEmpty(ehiPlans)) {
            return new ArrayList<>();
        }
        return jdbcTemplate.execute(buildSQL(ehiPlans), new CallableStatementCallback<List<Long>>() {

            @Override
            public List<Long> doInCallableStatement(CallableStatement callableStatement)
                    throws SQLException, DataAccessException {
                ResultSet resultSet = callableStatement.executeQuery();
                List<Long> networkIds = new ArrayList<>();
                while (resultSet.next()) {
                    networkIds.add(resultSet.getLong("network_id"));
                }
                return networkIds;
            }
        });
    }

}

Son class:
public class ProviderNameDAO extends ProviderBasicDAO {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Value("#[provider.log.to]")
    private int logTo;

    private int apiType = 2;

    public List<Provider> getProvider(ZipRepository coordinate, NameSearchRequest request, List<Long> carrierIds,
            List<EHIPlan> ehiPlans) throws SQLException, ClassNotFoundException {
        List<Long> networkIds = getNetworkIds(ehiPlans);

        if (!CollectionUtils.isEmpty(ehiPlans) && CollectionUtils.isEmpty(networkIds)) {
            return new ArrayList<>();
        }

        return jdbcTemplate.execute(new CallableStatementCreator() {
            @Override
            public CallableStatement createCallableStatement(Connection connection) throws SQLException {
                final StringBuffer sqlBuffer = new StringBuffer(
                        "{call pv_mc_infosearch_by_name(?, ?, ?, ?, ?, ?, ?, ?, ?, ? ,? ,?)}");
                CallableStatement preparedStatement = connection.prepareCall(sqlBuffer.toString());
                preparedStatement.setInt(1, apiType);
                preparedStatement.setString(2, SecurityUtil.escapeSQLChar(request.getFirstName()));
                preparedStatement.setString(3, SecurityUtil.escapeSQLChar(request.getLastName()));
                preparedStatement.setString(4, SecurityUtil.escapeSQLChar(request.getFacilityName()));
                preparedStatement.setDouble(5, coordinate.getLatitude());
                preparedStatement.setDouble(6, coordinate.getLongitude());
                preparedStatement.setInt(7, request.getRadius());
                preparedStatement.setString(8, StringUtils.join(networkIds,","));
                preparedStatement.setString(9, StandardizerUtils.convertToString(carrierIds));
                preparedStatement.setInt(10, SearchType.getTypeValue(request.getSearchType()));
                preparedStatement.setInt(11, logTo);
                preparedStatement.setString(12, UUID.randomUUID().toString());
                return preparedStatement;
            }
        }, new CallableStatementCallback<List<Provider>>() {
            public List<Provider> doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException {
                Map<String, Provider> idAndProviderDetailsMap = new HashMap<>();
                boolean isResultSet = cs.execute();
                int rsCount = 0;
                while (isResultSet) {

                    ResultSet childRs = cs.getResultSet();
                    if (rsCount == 0) {
                        parseProvider(childRs,idAndProviderDetailsMap);
                    }
                    if (rsCount == 1) {
                        parseAddress(childRs,idAndProviderDetailsMap);
                    }

                    if (rsCount == 2) {
                        parseSpecialty(childRs,idAndProviderDetailsMap);
                    }

                    if (rsCount == 3) {
                        parseAffiliation(childRs,idAndProviderDetailsMap);
                    }

                    if (rsCount == 4) {
                        parsePhone(idAndProviderDetailsMap, childRs);
                    }

                    if (rsCount == 5) {
                        parseCarrierGroupIdMap(childRs, idAndProviderDetailsMap);
                    }

                    if (rsCount == 6) {
                        parseLanguage(childRs,idAndProviderDetailsMap);
                    }

                    childRs.close();
                    isResultSet = cs.getMoreResults();
                    rsCount++;
                }
                cs.close();
                return new ArrayList<>(idAndProviderDetailsMap.values());
            }

        });

    }

 1. **my test code:**

@RunWith(PowerMockRunner.class)
@PrepareForTest({StandardizerUtils.class,StringUtils.class,UUID.class})
public class ProviderNameDAOTest {

    ProviderNameDAO providerNameDAO;
    ProviderBasicDAO providerBasicDAO;
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;
    JdbcTemplate jdbcTemplate;
    @Before
    public void preTest() {
        providerNameDAO=new ProviderNameDAO();
        providerBasicDAO=new ProviderBasicDAO();
        jdbcTemplate=PowerMockito.mock(JdbcTemplate.class);
        Whitebox.setInternalState(providerNameDAO, "jdbcTemplate", jdbcTemplate);
        providerBasicDAO.jdbcTemplate=jdbcTemplate;
    }

    @Test
    public void testParseAffiliation() {
        String name="hehe";
        long key=1;
        String value="hehe";
        ZipRepository coordinate=new ZipRepository();
        coordinate.setLongitude(20);
        coordinate.setLatitude(10);

        NameSearchRequest request=new NameSearchRequest();
        request.setFirstName(name);
        request.setLastName(name);
        request.setFacilityName(name);
        request.setRadius(20);
        request.setSearchType("physician");

        List<Long> carrierIds=new ArrayList<>();
        carrierIds.add(key);

        List<EHIPlan> ehiPlans=new ArrayList<>();
        EHIPlan ehiPlan=new EHIPlan();
        ehiPlan.setNetwork("haha");
        ehiPlan.setPlanCategory("hehe");
        ehiPlans.add(ehiPlan);

        //networkIds
        {
            CallableStatement callableStatement=PowerMockito.mock(CallableStatement.class);
            PowerMockito.when(jdbcTemplate.execute(Mockito.any(String.class),Mockito.any(CallableStatementCallback.class))).thenAnswer(new Answer<Object>() {
                @Override
                public Object answer(InvocationOnMock invocation) throws Throwable {
                    Object[] args=invocation.getArguments();
                    CallableStatementCallback arg = (CallableStatementCallback)args[1];
                    return ((CallableStatementCallback) arg).doInCallableStatement(callableStatement);
                }
            });

            ResultSet resultSet =PowerMockito.mock(ResultSet.class);
            try {
                PowerMockito.when(callableStatement.executeQuery()).thenReturn(resultSet);
                PowerMockito.when(resultSet.next()).thenReturn(true).thenReturn(false);
                PowerMockito.when(resultSet.getLong(Mockito.any(String.class))).thenReturn(key);
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        //mian jdbc
        {
            //prarmeter 1
            PowerMockito.mockStatic(StandardizerUtils.class);
            PowerMockito.mockStatic(StringUtils.class);
            PowerMockito.mockStatic(UUID.class);
            Connection connection=PowerMockito.mock(Connection.class);
            CallableStatement preparedStatement=PowerMockito.mock(CallableStatement.class);
            PowerMockito.when(jdbcTemplate.execute(Mockito.any(CallableStatementCreator.class),Mockito.any(CallableStatementCallback.class)))
                    .thenAnswer(new Answer<Object>() {
                @Override
                public Object answer(InvocationOnMock invocation) throws Throwable {
                    Object[] args=invocation.getArguments();
                    CallableStatementCreator arg = (CallableStatementCreator)args[0];
                    return arg.createCallableStatement(connection);
                }
            });
            try {
                PowerMockito.when(connection.prepareCall(Mockito.any(String.class))).thenReturn(preparedStatement);
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //prarmeter 2
            CallableStatement cs=PowerMockito.mock(CallableStatement.class);
            PowerMockito.when(jdbcTemplate.execute(Mockito.any(CallableStatementCreator.class),Mockito.any(CallableStatementCallback.class)))
               .thenAnswer(new Answer<Object>() {
                @Override
                public Object answer(InvocationOnMock invocation) throws Throwable {
                    Object[] args=invocation.getArguments();
                    CallableStatementCallback arg = (CallableStatementCallback)args[1];
                    return arg.doInCallableStatement(cs);
                }
            });
            try {
                String y="N";
                long l=2;
                PowerMockito.when(cs.execute()).thenReturn(true);
                ResultSet childRs=PowerMockito.mock(ResultSet.class);
                PowerMockito.when(cs.getResultSet()).thenReturn(childRs);
                PowerMockito.when(childRs.getString(Mockito.any(String.class))).thenReturn(y);
                PowerMockito.when(childRs.getLong(Mockito.any(String.class))).thenReturn(l);
                PowerMockito.when(cs.getMoreResults()).thenReturn(true).thenReturn(true).thenReturn(true)
                        .thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(false);
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            //test body
            try {
                List<Provider> result=providerNameDAO.getProvider(coordinate, request, carrierIds, ehiPlans);
                Assert.assertEquals(1, result.size());
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
}

**

 1. error informations:

**
org.powermock.reflect.exceptions.MethodNotFoundException: No methods matching the name(s) executeQuery were found in the class hierarchy of class java.lang.Object.
    at org.powermock.reflect.internal.WhiteboxImpl.getMethods(WhiteboxImpl.java:1720)
    at org.powermock.reflect.internal.WhiteboxImpl.getMethods(WhiteboxImpl.java:1745)
    at org.powermock.reflect.internal.WhiteboxImpl.getBestMethodCandidate(WhiteboxImpl.java:983)
    at org.powermock.core.MockGateway$MockInvocation.findMethodToInvoke(MockGateway.java:317)
    at org.powermock.core.MockGateway$MockInvocation.init(MockGateway.java:356)
    at org.powermock.core.MockGateway$MockInvocation.<init>(MockGateway.java:307)
    at org.powermock.core.MockGateway.doMethodCall(MockGateway.java:142)
    at org.powermock.core.MockGateway.methodCall(MockGateway.java:125)
    at com.ehi.provider.dao.ProviderNameDAOTest.testParseAffiliation(ProviderNameDAOTest.java:93)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:66)

**

 1. question:

**why the father class method not to uesed in son class? and meantime i am not sure my test code is right completely, if you find my error or have a better idea, please point out in here, thank you !!!


text:
Q: Mercurial .hgignore negative lookbehind regex I'm trying to ignore everything but file "test.ext" in directory "data" & all of it's subdirectories.
however when i put in hgignore:
syntax: regexp
^data\/.*(?<!\/test\.ext)$

It only ignores
data\test.ext

And does not ignore:
data\images\test.ext

A: Unless new subdirectories pop up often, you're much better off just ignoring data and then hg adding the test.ext files you want tracked.   Adding a file 100% overrides ignore, and running find data -name test.ext | xargs hg add once in a blue moon is better than a tortured regex.

A: From the hg docs:
"There is no straightforward way to ignore all but a set of files. Attempting to use an inverted regex match will fail when combined with other patterns. This is an intentional limitation, as alternate formats were all considered far too likely to confuse users to be worth the additional flexibility."


text:
Q: Android Periodic Sensor Data For an Android App, that will show the value of an internal sensor (e.g. Acceleration) in a graph, i need to find a way to access this signal periodically.
At the moment i am using a SensorEventListener, but unfortunately this only gives me the possibility to get a value whenever it changes.
Since I want to display the graph (point to point) in dependency of the time, this means it would directly draw a line from the old to the new value (and if the old value has been a long time, it looks like a linear changing of the value).
So my question: How can I get access to a sensor's data periodically?

A: The documentation for SensorManager says that registerListener(android.hardware.SensorEventListener, android.hardware.Sensor int)
"Registers a SensorEventListener for the given sensor at the given sampling frequency."
To get these events, though, your application would need to be active (hold a partial wake lock). It would be better to do this in a background service so that the application doesn't need to remain active. See for example, SensorEventListener in a service

A: So in the end i used a timer, which checked the values from my sensor, which I put into an array, periodically.
Unfortunately registerListener didnt work, since the value is just a suggestion for the system.
Thanks though for the help.


text:
Q: Theoretical Basis for Eigenvalue transformation on Bessel's Equation The method I've been taught for finding all of the eigenvalue solutions to Bessel's operator $$b(f)\equiv f''(x)+\frac{1}{x}f'(x)$$ goes as follows. Let $g(a)=f(\sqrt{\lambda}x)$. Then $$b(g)=\lambda g(a)$$ $$\lambda \frac{d^2g}{da^2}+\frac{\sqrt{\lambda}}{x}\frac{dg}{da} -\lambda g(a)=0$$ $$\frac{d^2g}{da^2}+\frac{1}{a}\frac{dg}{da}-g(a)=0$$ We can then solve this equation for $g(a)$ and apply the inverse change of variables to yield all of our eigenfunctions. My question is: what kind of transformation is this change of variables applying to our Hilbert Space? I would think that, given the nice algebraic properties of the operator (call it $M_a(\cdot)$) which when applied to some function $h(x)$ returns $h(a)$, it would be fairly straightforward to describe, but  I'm not seeing it. It almost feels like we're applying a Mobius transform on our Hilbert Space where every for every function $f(x) \in H$, there are two subspaces in $H$, one which corresponds to the scaling of $f(x)$ and another which corresponds to evaluating $f(x)$. By extension, what kind of linear operators can have their eigenfunctions found in this way? I would think that there is something analogous to the characteristic polynomial method in finite dimensional linear algebra going on here, but I can't put my finger on it. Any and all insights are welcome, although geometric arguments are at somewhat of a premium here.

A: The Bessel operator $Lf = -(xf')'$ applied to functions on $(0,\infty)$ has a nice scale property. Define $S_{\alpha}$ acting on such functions by $(S_{\alpha}f)(x)=f(\alpha x)$ for $0 < \alpha < \infty$. Then
\begin{align}
                LS_{\alpha}f & = -x\frac{d^{2}}{dx^{2}}f(\alpha x) -\frac{d}{dx}f(\alpha x) \\
        & = -x \alpha^{2}f''(\alpha x)-\alpha f'(\alpha x) \\
        & = \alpha S_{\alpha}\{-xf''(x)-f'(x)\} \\
        & = \alpha S_{\alpha} Lf.
\end{align}
Therefore, if you have a solution $Lf = \lambda f$ on $(0,\infty)$, then
$$
                       LS_{\alpha} f = \alpha\lambda S_{\alpha}f
$$
So the one solution of $Lf=\lambda f$ can be used to get a solution of $Lf=\alpha\lambda f$ for every $\alpha > 0$. This has to do with the radial scaling properties of the Laplacian, which are inherited by the Bessel operator in the radial variable. If you have the two linearly independent solutions of $Lf=f$ on $(0,\infty)$, then you have all the solutions of $Lf=\alpha f$ for all any $\alpha > 0$.
Knowing two linearly independent solutions of $Lf=\lambda f$ on $(0,\infty)$, you can get them all for all parameters $\lambda$. You can then restrict to an interval if you want. If you want to find an eigenvalue function that vanishes at $x=b$, then you can apply $S_{\alpha}$ to the one eigenfunction $Lf=\lambda f$ and adjust $\alpha$ until $f(\alpha b)$ hits a zero of $f$. And this is general method for dealing with Bessel's equation. The action of the radial scaling group must act on the eigenspaces; this is a general principle.


text:
Q: AddressBook: trying to add 'Home' and 'Work' addresses, only 1 shows up I'm trying to add a 'Home' and 'Work' address my Person record. It seems only 1 shows up (the one added later. Is if possible to add multiple addresses to a Person and see them displayed in the UnknownPersonViewController? If so, how should I do this?
Here's my code:
void multiValueAddDictionaryValueAndLabel(ABMultiValueRef multi, CFDictionaryRef values, CFStringRef label) {
    if (multi && values != NULL) {
       ABMultiValueAddValueAndLabel(multi, values, label, NULL);
    }
}

CFStringRef getValueForKey(CFDictionaryRef dict, CFStringRef key) {
   CFStringRef value = NULL;

   if (CFDictionaryContainsKey(dict, key)) {
      value = CFDictionaryGetValue(dict, key);
   }

   return value;
}

ABRecordRef createPerson(CFDictionaryRef dict) {
   ABRecordRef person = ABPersonCreate();

   /*
    Add work address ...
    */

   ABMultiValueRef workAddress = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);
   NSDictionary *values = [NSDictionary dictionaryWithObjectsAndKeys:
                               (NSString *)getValueForKey(dict, CFSTR("d:street")), (NSString *)kABPersonAddressStreetKey,
                               (NSString *)getValueForKey(dict, CFSTR("d:postalcode")), (NSString *)kABPersonAddressZIPKey,
                               (NSString *)getValueForKey(dict, CFSTR("d:l")), (NSString *)kABPersonAddressCityKey,
                               (NSString *)getValueForKey(dict, CFSTR("d:st")), (NSString *)kABPersonAddressCityKey,
                               (NSString *)getValueForKey(dict, CFSTR("d:co")), (NSString *)kABPersonAddressCountryKey,
                               nil];
   multiValueAddDictionaryValueAndLabel(workAddress, (CFDictionaryRef)values, kABWorkLabel);
   ABRecordSetValue(person, kABPersonAddressProperty, workAddress, NULL);
   CFRelease(workAddress);

   /*
    Add home address ...
    */

   ABMultiValueRef homeAddress = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);
 values = [NSDictionary dictionaryWithObjectsAndKeys:
             (NSString *)getValueForKey(dict, CFSTR("d:homeStreet")), (NSString *)kABPersonAddressStreetKey,
             (NSString *)getValueForKey(dict, CFSTR("d:homePostalCode")), (NSString *)kABPersonAddressZIPKey,
             (NSString *)getValueForKey(dict, CFSTR("d:homeCity")), (NSString *)kABPersonAddressCityKey,
             (NSString *)getValueForKey(dict, CFSTR("d:homeState")), (NSString *)kABPersonAddressCityKey,
             (NSString *)getValueForKey(dict, CFSTR("d:homeCountry")), (NSString *)kABPersonAddressCountryKey,
             nil];
   multiValueAddDictionaryValueAndLabel(homeAddress, (CFDictionaryRef)values, kABHomeLabel);
   ABRecordSetValue(person, kABPersonAddressProperty, homeAddress, NULL);
   CFRelease(homeAddress);
}

A: What you want to do is use the same mutable ABMultiValueRef for both addresses:
ABMultiValueRef addresses = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);

// set up your 2 dictionaries here as you did in your question (though obviously with differing names)

ABMultiValueAddDictionaryValueAndLabel(addresses, (CFDictionaryRef)workValues, kABWorkLabel);
ABMultiValueAddDictionaryValueAndLabel(addresses, (CFDictionaryRef)homeValues, kABHomeLabel);

ABRecordSetValue(person, kABPersonAddressProperty, homeAddress, NULL);
CFRelease(addresses);

A: This code works:
ABMultiValueRef addresses = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);

values = [NSDictionary dictionaryWithObjectsAndKeys:
                        (NSString *)getValueForKey(dict, CFSTR("d:street")), (NSString *)kABPersonAddressStreetKey,
                        (NSString *)getValueForKey(dict, CFSTR("d:postalcode")), (NSString *)kABPersonAddressZIPKey,
                        (NSString *)getValueForKey(dict, CFSTR("d:l")), (NSString *)kABPersonAddressCityKey,
                        (NSString *)getValueForKey(dict, CFSTR("d:st")), (NSString *)kABPersonAddressCityKey,
                        (NSString *)getValueForKey(dict, CFSTR("d:co")), (NSString *)kABPersonAddressCountryKey,
                        nil];
multiValueAddDictionaryValueAndLabel(addresses, (CFDictionaryRef)values, kABWorkLabel);

values = [NSDictionary dictionaryWithObjectsAndKeys:
          (NSString *)getValueForKey(dict, CFSTR("d:homeStreet")), (NSString *)kABPersonAddressStreetKey,
          (NSString *)getValueForKey(dict, CFSTR("d:homePostalCode")), (NSString *)kABPersonAddressZIPKey,
          (NSString *)getValueForKey(dict, CFSTR("d:homeCity")), (NSString *)kABPersonAddressCityKey,
          (NSString *)getValueForKey(dict, CFSTR("d:homeState")), (NSString *)kABPersonAddressCityKey,
          (NSString *)getValueForKey(dict, CFSTR("d:homeCountry")), (NSString *)kABPersonAddressCountryKey,
          nil];
multiValueAddDictionaryValueAndLabel(addresses, (CFDictionaryRef)values, kABHomeLabel);

ABRecordSetValue(person, kABPersonAddressProperty, addresses, NULL);
CFRelease(addresses);


text:
Q: Linux self recovering DHCP after really long downtime? I have a few CentOS 6/7 systems (non-production, experimental purposes) that have been configured to use DHCP for their IP address. Last week there was a big network disruption and I found that those systems had lost their IP address and the DHCP client had terminated. I guess after too many/too long retries.
What is the proper way to make it try to recover forever?
Is there a dhcp client setting that can do this? Or should I add a cron entry that does something like 'ifup eth0' every hour? Or is there a much better way to do this?
I know CentOS 6 and CentOS 7 do these things differently and I'm looking for answers for both these cases.

Update:
For now I have created this script (which I put in /etc/cron.hourly/ ) that seems to work in the specific situation of CentOS 6.
This is probably not the best solution but it "Works on my machine".
#!/bin/bash

IF=eth0

ifconfig ${IF} | fgrep 'inet addr' > /dev/null

if [ $? -ne 0 ];
then
    echo "Network is dead, trying restart"
    ifup ${IF}
fi

Still looking for the proper way to do this so I do not think this is the right answer to my question.

A: Both CentOS 6 and 7 should accept the PERSISTENT_DHCLIENT option within /etc/sysconfig/network-scripts/ifcfg* files .e.g.
# /etc/sysconfig/network-scripts/ifcfg-eth0
BOOTPROTO=dhcp
PERSISTENT_DHCLIENT=yes
ONTBOOT=yes
DEVICE=eth0

This instructs the ifup-eth script to run the dhclient without the (default) -1 option
if is_true "${PERSISTENT_DHCLIENT}"; then
    ONESHOT="";
else
    ONESHOT="-1";
fi;
...
DHCLIENTARGS="${DHCLIENTARGS} ${ONESHOT} -q ${DHCLIENTCONF} -lf ${LEASEFILE} -pf /var/run/dhclient-${DEVICE}.pid"

With that option dhclient will try once. From the man page
-1 Try once to get a lease. One failure, exit with code 2.

Without that option dhclient should retry occasionally (every 5 minutes by default) again from dhclient.conf man page
retry time;

The retry statement determines the time that must pass after the client
has determined that there is no DHCP server present before it tries
again to contact a DHCP server. By default, this is five minutes.


text:
Q: c++ multiple regex extractions to an array from dbc entry Hello I would like to extract the parameters from the following string:
VAL_ 234 State1 123 "Description 1" 0 "Description 2 with \n new line" 90903489 "Big value and special characters &$§())!" ;
The desired matches are

*

*234

*State1

*and then an array with unsigned integer and string combination

*

*123 "Description 1"

*0 "Description 2 with \n new line"

*90903489 "Big value and special characters &$§())!"

The array shall be split in a second step if it is not possible to do it directly.
With the following regex I just get always the last match of the array 90903489 "Big value and special characters &$§())!"
^VAL_ ([0-9]+) ([A-Za-z_][A-Za-z_0-9]*) ([0-9]*\\s\"[^\"]*\"\\s)+
Is there a possibility to extract the values?
I found already
auto blah = std::string{"5001 | 5002 | 5003"};
auto values = std::vector<std::string>{
    std::sregex_token_iterator{blah.begin(), blah.end(), std::regex{R"(\d+)"}},
    std::sregex_token_iterator{}};

from this post but it returns me just the complete string. Is there a possibility to iterate over the submatches?

A: Not sure if you have any specific requirements on how the matches need to be separated, but you can match either of the patterns with the following regular expression:
(?:^VAL_\s(\d+)\s(\w+)|\s(\d+\s".+?"))

Sample code:
const std::string input{ R"(VAL_ 234 State1 123 "Description 1" 0 "Description 2 with \n new line" 90903489 "Big value and special
characters &$§())!")" };
const std::regex regex{ R"((?:^VAL_\s(\d+)\s(\w+)|\s(\d+\s".+?")))" };
const std::sregex_iterator end{};
for(auto it = std::sregex_iterator{ std::cbegin(input), std::cend(input), regex };
    it != end; ++it) {
    auto match = *it;
    if (match.empty()) {
        std::cerr << "Nothing matched" << '\n';
        continue;
    } else {
        if (match[1].matched) {
            std::cout << "Val match: " << match[1].str() << '\n';
        }
        if (match[2].matched) {
            std::cout << "State match: " << match[2].str() << '\n';
        }
        if (match[3].matched) {
            std::cout << "Etc match: " << match[3].str() << '\n';
        }
    }
}

A: Based on @rustyx link I created my own parser
enum VALToken {
    Identifier = 0,
    CANId,
    SignalName,
    Value,
    Description
};

struct ValueDescription{
    std::string value;
    std::string description;
};

int main(int argc, char *argv[])
{
    const std::string s = R"(VAL_ 234 State1 123 "Description 1" 0 "Description 2 with \n new line" 90903489 "Big value and special characters &$§())!" ;)";

    auto state = Identifier;
    const char* a = s.data();
    std::string can_id;
    std::string signal_name;
    std::vector<ValueDescription> vds;
    ValueDescription vd;
    for (;;) {
        switch (state) {
        case Identifier: {
            if (*a != 'V')
                return 0;
            a++;
            if (*a != 'A')
                return 0;
            a++;
            if (*a != 'L')
                return 0;
            a++;
            if (*a != '_')
                return 0;
            a++;
            if (*a != ' ')
                return 0;
            a++; // skip whitespace
            state = CANId;
            break;
        }
        case CANId: {
            while(*a >= '0' && *a <= '9') {
                can_id += *a;
                a++;
            }
            if (can_id.empty())
                return 0;
            if (*a != ' ')
                return 0;
            a++; // skip whitespace
            state = SignalName;
            break;
        }
        case SignalName: {
            if ((*a >= 'a' && *a <= 'z') || (*a >= 'A' && *a <= 'Z') || *a == '_')
                signal_name += *a;
            else
                return 0;
            a++;
            while ((*a >= 'a' && *a <= 'z') || (*a >= 'A' && *a <= 'Z') || *a == '_' || (*a >= '0' && *a <= '9')) {
                signal_name += *a;
                a++;
            }
            if (*a != ' ')
                return 0;
            a++; // skip whitespace
            state = Value;
            break;
        }
        case Value: {
            std::string value_str;
            while (*a >= '0' && *a <= '9') {
                value_str += *a;
                a++;
            }
            if (value_str.empty())
                return 0;

            if (*a != ' ')
                return 0;
            a++; // skip whitespace
            vd.value = value_str;
            state = Description;
            break;
        }
        case Description: {
            std::string desc;
            if (*a != '"')
                return 0;
            a++;
            while (*a != '"' && *a != 0) {
                desc += *a;
                a++;
            }
            if (*a == 0)
                return 0;
            a++;
            if (*a != ' ')
                return 0;
            a++; // skip whitespace

            vd.description = desc;
            vds.push_back(vd);

            state = Value;
            break;
        }
        }
    }

    return 0;
}

A: I would do a regex_match followed by a loop using an sregex_iterator.
[Demo]
#include <fmt/core.h>
#include <regex>
#include <string>

int main() {
    const std::string text{ "VAL_ 234 State1"
        " 123 \"Description 1\""
        " 0 \"Description 2 with \\n new line\""
        " 90903489 \"Big value and special characters &$§())!\""
    };
    const std::regex pattern{ R"(VAL_ (\d+) \w+(\d+)(.*))" };
    std::smatch matches{};
    if (std::regex_match(text, matches, pattern)) {
        fmt::print("{}\n{}\n", matches[1].str(), matches[2].str());

        std::regex array_pattern{ R"(\s+(\d+)\s+\"([^"]+)\")" };
        auto array_text{ matches[3].str() };
        for (std::sregex_iterator it{ array_text.begin(), array_text.end(), array_pattern };
            it != std::sregex_iterator{};
            ++it) {

            std::smatch array_matches{ *it };
            fmt::print("\t'{}', '{}'\n", array_matches[1].str(), array_matches[2].str());
        }
    }
}

// Outputs:
//
// 234
// 1
//    '123', 'Description 1'
//    '0', 'Description 2 with \n new line'
//    '90903489', 'Big value and special characters &$§())!'


text:
Q: Pyqt5 QTableWidget custom keyboard functions I am using pyqt5 to make a table that user needs to add some information to:
self.table = QTableWidget(Dialog)
self.table.setGeometry(QtCore.QRect(30, 100, 650, 380))
self.tableItem = QTableWidgetItem()

I then use setItem methods to add information to the table.
The user can navigate to different cells of the table by left, right, bottom, and right keys. When the user presses tab, the function is essentially the same as the right key.
However, I want the tab key to go down instead of right.
If anyone could direct me to the correct chapters in the documentation or an example to get me started, would be a great help.
Thanks!

A: A possible solution is to intercept the event of pressing the Tab key and prevent it from propagating using eventFilter(), and believing a key event sends the Down key:
from PyQt5 import QtCore, QtGui, QtWidgets

class Helper(QtCore.QObject):
    def __init__(self, parent=None):
        super(Helper, self).__init__(parent)
        self.m_widgets = []

    def appendWidget(self, widget):
        self.m_widgets.append(widget)
        widget.installEventFilter(self)

    def eventFilter(self, obj, event):
        if obj in self.m_widgets and event.type() == QtCore.QEvent.KeyPress:
            if event.key() == QtCore.Qt.Key_Tab:
                # create new event
                new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
                    QtCore.Qt.Key_Down,
                    QtCore.Qt.NoModifier)
                # send new event
                QtCore.QCoreApplication.postEvent(obj, new_event)
                # if True, the event is discarded
                return True
        return super(Helper, self).eventFilter(obj, event)

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        self.table = QtWidgets.QTableWidget(4, 4)
        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(self.table)

        helper = Helper(self)
        helper.appendWidget(self.table)

if __name__ == '__main__':
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())


text:
Q: NGINX internal redirect from uri path to JSF context root I'm configuring a cloud server which use NGINX as reverse proxy to serve different applications on different URI (all the applications are on the same wildfly standalone instance).
To be more specific i've a JSF application with a contextroot, let's say, /jsfcontext and i've set up a NGINX location like /mypublicuri.
What happens is that when I navigate to https://myserver.com/mypublicuri/index.xhtml i receive the following error:
/mypublicuri/index.xhtml Not Found in ExternalContext as a Resource.
I'm pretty sure it's related to a missing internal redirect route or some kind of "hack" that i need to specify in order to make everything work but i'm a newbie in NGINX and I don't know how to properly set everything up.
Thanks for the help
Cheers
Read NGINX documentation but my lack of english knowledge makes difficoult to understand what should I have to do
My actual NGINX config
server {
    server_name myserver.com www.myserver.com;
    access_log /usr/share/logs/access.log;
    error_log /usr/share/logs/error.log;
    location / {
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_intercept_errors on;
        location /anotherworkingapp {
            add_header Allow "GET, POST, HEAD, PUT, DELETE" always;
            proxy_pass http://127.0.0.1:8080$request_uri;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "Upgrade";
        }
        location /mypublicuri {
            proxy_pass http://127.0.0.1:8080/jsfcontext$request_uri;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "Upgrade";
        }
    }
}


text:
Q: How to compute a new variable that is defined by two categorical variables using SPSS? I have a questionnaire with a part (a) and part (b). It looks like this:
(a) "Do you ever feel sad":
    0="never", 1="sometime", 2="often", 3="nearly always"
(b) "How distressed are you by this":
    0="not distressed", 1="a bit distressed", 2="quite distressed",
    3="very distressed".

I want to create a new variable:
"Do you feel sad?"
Response: 0="no", but 1="Yes, but no distress", 3="Yes and its distressing".

How can I create this new variable using SPSS?

A: You would have to use logical operators and conditionals.
part a: 0 1 2 3
part b: 0 1 2 3

Composite:

    0 = (a0)
    1 = ~(a0) & (b0)
    3 = ~(a0) & ~(b0)

I haven't tested this, but the SPSS code for computing the composite scores with the outcome 1 would be something like this:
DO IF ( (A ~= 0) & (B = 0)).
RECODE A (0=1) INTO C.
END IF.
VARIABLE LABELS C 'Composite'.
EXECUTE.


text:
Q: internal/modules/cjs/loader.js:960 throw err; ^ Error: Cannot find module 'fs/promises' When I try to run the yarn install, the command doesn't seem to run instead it throws a error as shown in below
internal/modules/cjs/loader.js:960
  throw err;
  ^

Error: Cannot find module 'fs/promises'
Require stack:
- /Users/sakrishnas/.nvm/versions/node/v12.16.3/lib/node_modules/corepack/dist/corepack.js
- /Users/sakrishnas/.nvm/versions/node/v12.16.3/lib/node_modules/corepack/dist/yarn.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:957:15)
    at Function.Module._load (internal/modules/cjs/loader.js:840:27)
    at Module.require (internal/modules/cjs/loader.js:1019:19)
    at require (internal/modules/cjs/helpers.js:77:18)
    at Object.fs/promises (/Users/sakrishnas/.nvm/versions/node/v12.16.3/lib/node_modules/corepack/dist/corepack.js:16716:18)
    at __webpack_require__ (/Users/sakrishnas/.nvm/versions/node/v12.16.3/lib/node_modules/corepack/dist/corepack.js:17137:42)
    at Module../sources/fsUtils.ts (/Users/sakrishnas/.nvm/versions/node/v12.16.3/lib/node_modules/corepack/dist/corepack.js:16033:69)
    at __webpack_require__ (/Users/sakrishnas/.nvm/versions/node/v12.16.3/lib/node_modules/corepack/dist/corepack.js:17137:42)
    at Module../sources/corepackUtils.ts (/Users/sakrishnas/.nvm/versions/node/v12.16.3/lib/node_modules/corepack/dist/corepack.js:15738:66)
    at __webpack_require__ (/Users/sakrishnas/.nvm/versions/node/v12.16.3/lib/node_modules/corepack/dist/corepack.js:17137:42) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/Users/sakrishnas/.nvm/versions/node/v12.16.3/lib/node_modules/corepack/dist/corepack.js',
    '/Users/sakrishnas/.nvm/versions/node/v12.16.3/lib/node_modules/corepack/dist/yarn.js'
  ]
}

This seems to happen after the mac OS monetery update. I tried uninstalling xcode and reinstalling, removed node and nvm completely and reinstalled again.
Node version: 12.16.3
Can anyone help me to fix this error.


text:
Q: One Signal Push Notification? I have made movie review app on android.Users create an account with firebase authentication and review movies and rate them.Admin of app can add new movies.
My question is how can I(admin) send a notification to all users (of firebase) whenever I added a new movie?And I want to use one signal push notification.
Please Help me.

A: Using Tags its possible to send the notification to all users.
1.Primarily you have create a channel eg: allusers from mobile end need to register
JSONObject tags = new JSONObject();
tags.put("allusers", "1");
OneSignal.sendTags(tags);

2.From server end who are all registered in the tag allusers=1 ..Notification will send to all the users
Sending Push from serverside
https://documentation.onesignal.com/reference#create-notification


text:
Q: Immersed curve in $\mathbb{R}^2$ and regular curve I read that a curve $\gamma:S^1 \to \mathbb{R}^2$ is an immersion iff it's regular. So it's an immersion iff $\gamma'(t) \neq 0$ for all $t \in S^1$.
An immersed curve is one whose derivative is an injective linear map. When the domain is single-variabled, this is the same as requring $\alpha'(t) \neq 0$ for all $t$.
Is this right? But what about $t=0?$ Shouldn't $0$ make the derivative equal $0$? Why isn't this included in this characterisation (since regular means non-zero everywhere)?
How does one check that such a curve is immersive? If $\gamma(t) = (e^t, 1)$, which I know is regular, how do I check that the derivative is an injective linear map? Clearly the "derivative" in this context isn't referring to $\gamma'(t)$ since that is not linear.
Thanks

A: *

*In one-variable calculus one introduces the derivative of a function $f:{\mathbb R}\to{\mathbb R}$ as derivative at a point $t_0$ by defining
$$f'(t_0):=\lim_{t\to t_0}{f(t)-f(t_0)\over t-t_0}\ .\qquad(1)$$
This is a number. In a second step one envisages this process performed at all points $t_0\in{\rm dom}(f)$, which leads to the idea of the derivative being a function $$f':\quad {\mathbb R}\to{\mathbb R},\qquad t_0\mapsto f'(t_0)\ .$$
This works as well for vector-valued functions of a single variable $t$, e.g. for the function $\gamma:\ t\mapsto(e^t,1)$. Here one gets $\gamma'(t)=(e^t,0)$.

*When one has more than one independent variables the derivative $d{\bf f}({\bf p})$ of a function $${\bf f}:\quad {\mathbb R}^n\to{\mathbb R}^m$$ at a point ${\bf p}$ can no longer be defined as a limit in the form $(1)$. Instead $d{\bf f}({\bf p})$ is a linear map mapping the  tangent space at ${\bf p}$ into the tangent space at ${\bf q}={\bf f}({\bf p})$. The matrix of $d{\bf f}({\bf p})$ is nothing else but the Jacobian matrix of ${\bf f}$ at ${\bf p}$. The map ${\bf f}$ is an immersion if this matrix has rank $n$ at all points ${\bf p}$ in the domain of ${\bf f}$.

*What we have said in 2. also makes sense in the one-variable case, i.e. for $n=1$:
$$t\mapsto{\bf f}(t)=(f_1(t),\ldots,f_m(t))\ .$$ In this case the Jacobian at a point $p$ in the domain of ${\bf f}$ has just one column given by $[f_1'(p),\ldots,f_m'(p)]^T$, and it has rank $1$ iff ${\bf f}'(p)\ne{\bf 0}$, where ${\bf f}'(p)$ is the derivative of ${\bf f}$ at $p$ considered in 1. In your example $\gamma'(t)\ne(0,0)$ for all $t\in{\mathbb R}$, so $\gamma$ defines an immersion.

A: The basic problem here is a confusion of terminology around "derivative".
The basic idea of differentiation in one dimension is finding a tangent to a graph at the point. A tangent can be viewed as a linear approximation of the graph, in the following (not necessarily obvious) sense:
$$f(x + h) - f(x) \approx hf^\prime(x)$$
The function that you are really linearly approximating is not $f$ as such but the difference between $f(x)$ and $f$ near $x$. Since this will be zero when $h$ is zero, it seems much more plausible that we could approximate it in this way (rather than $f$ which can be whatever it likes).
In higher dimensions, the derivative of $f$ at $x$ is defined to be a linear map $A$ such that $$f(x + h) - f(x) \approx A(h)$$
And in fact, the 1D case fits here, since $h\mapsto ah$ is linear for any constant $a$. The problem is that in fact every linear map in 1D is of the form $h\mapsto ah$, so there is a direct correspondence, in the one-dimensional case, between scalar constants and linear maps. So there ends up being confusion in our definitions whether the derivative of $f$ at $x$ is a number or a function, and I think it is that confusion that you are coming up against.
In this context, don't think of $f^\prime$ as the derivative of $f$, think of it as a function that takes an argument $x$ and gives you the $a$ such that the derivative of $f$ at $x$ is "multiply by $a$". This is a linear map, which is injective exactly when $a\not=0$. The key is to understand that $f^\prime$ isn't a linear map itself, it produces linear maps for each $x$.


text:
Q: How can Shared Memory be dangerous in server environments & how to secure it? I just understand somewhat about what's the purpose of shared memory which is for faster exchange or use of data among several programs. But having seen a lot of people trying to or talking about secure it, I dont understand how it could be dangerous & what could be done to secure it ?
I am asking this in context of configuring a server environment on a VPS.

A: It can be dangerous if the program creating it is written wrong and sets up the permissions so that other users can attach to it.  You secure it by writing the program properly to restrict the permissions to only that user.  As such this isn't an administration problem.

A:
"It can be dangerous if the program creating it is written wrong"<.

Or by a exploiter trying to inject code into a running proc (program) on the server that has been established and has been deployed on the server; and that has elevated (possible) privileges; thereby inheriting those privileges, which sets up a possible api for the attacker.
Sorry for the 5 years after. I'm in the process of deploying a server. This shared memory issue has been well documented

By default, /run/shm is mounted read/write, with permission to execute programs. In recent years, many security mailing lists have noted many exploits where /run/shm is used in an attack against a running service, such as httpd. Most of these exploits, however, rely on an insecure web application rather than a vulnerability in Apache or Ubuntu< from help.ubuntu.com

But yes as psusi related, coders can write code that does not allow shared memory. But do they, something as important as a server needs to be at least 99% bullet proof.
Linux, own it or someone will own it and you.
Google is your friend


text:
Q: How to write to Database from datahandler? I have a datahandler for my Sencha Touch application and am trying to write to a database.  When reading from a database, I call reader.Read() and that works just fine.  What should I call to run an insert into query on my database from the datahandler?  Any thoughts?  Thanks!

A: You can use the ExecuteNonQuery (or async equivalents) of the SqlCommand class.


text:
Q: OpenGL 3.3 Core profile - glDrawArrays fails silently I am making use of OpenGL 3.3 and EGL 1.4. The laptop I use to build and run my code (C) makes use of Intel's HD 3000 integrated GPU and runs linux. I thus use the Mesa 3D library. In my program, I create and bind an OpenGL 3.3 core profile compatible context in an X11 window, confirmed by the later returned string of glGetString(GL_VERSION), "3.3 (Core Profile) Mesa 13.0.6".
Next, I use EGL to load various functions of the OpenGL specification (I've opted not to use a library such as GLEW). After doing this, I start setting up OpenGL state to render a run-of-the-mill triangle. I initialize an array of floats which make up the 3 hard-coded vertices of my triangle. Then, I initialize and bind a vertex array object, followed by initializing and binding a vertex buffer object. Finally, I pass my vertex array to glBufferData, to link the vertex data with the vertex buffer object.
unsigned int vao;
  glGenVertexArrays(1, &vao);
  glBindVertexArray(vao);
unsigned int vbo;
  glGenBuffers(1, &vbo);
  glBindBuffer(GL_ARRAY_BUFFER, vbo);

glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

Then, I initialize a basic vertex and fragment shader. Both compile successfully, my shader program links successfully, and validates successfully.
#version 330 core
layout (location = 0) in vec3 p;
void main(){
  gl_Position = vec4(p, 0.0);
}

#version 330 core
out vec4 color;
void main(){
  color = vec4(0.0, 0.0, 0.0, 1.0);
}

I then proceed to tell GL how to interpret my vertex data;
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void *)0);
glEnableVertexAttribArray(0);

Finally, I enter my program's main loop responsible for drawing to and swapping the framebuffer, where bufferloop is struct timespec bufferloop = (struct timespec){0, 250000};
while(app.running){
  glClearColor(1.0, 1.0, 1.0, 1.0);
  glClear(GL_COLOR_BUFFER_BIT);
  glDrawArrays(GL_TRIANGLES, 0, 3);
  eglSwapBuffers(egldisplay, eglsurface);
  nanosleep(&bufferloop, (void *)0);
}

And all I get is a white screen; my triangle is nowhere to be found. I cannot for the life of me determine what the problem is. I have pasted printf("%d\n", glGetError()); all over my code, and no error is turned up.
glDrawArrays(GL_TRIANGLES, 0, 3); fails without so much as a peep.

A: In your vertex shader, the w component should be 1 rather than 0. There's a good description from the OpenGL red book here that describes how w is used. Briefly:

OpenGL commands usually deal with two- and three-dimensional vertices, but in fact all are treated internally as three-dimensional homogeneous vertices comprising four coordinates. Every column vector (x, y, z, w)T represents a homogeneous vertex if at least one of its elements is nonzero.
As long as w is nonzero, the homogeneous vertex (x, y, z, w)T corresponds to the three-dimensional point (x/w, y/w, z/w)T. If w = 0.0, it corresponds to no euclidean point, but rather to some idealized "point at infinity." To understand this point at infinity, consider the point (1, 2, 0, 0), and note that the sequence of points (1, 2, 0, 1), (1, 2, 0, 0.01), and (1, 2.0, 0.0, 0.0001), corresponds to the euclidean points (1, 2), (100, 200), and (10000, 20000). This sequence represents points rapidly moving toward infinity along the line 2x = y. Thus, you can think of (1, 2, 0, 0) as the point at infinity in the direction of that line.


text:
Q: Testing preserveLegacyExternalStorage on Android The developer docs for preserveLegacyExternalStorage state:

If you set preserveLegacyExternalStorage to true, the legacy storage model remains in effect only until the user uninstalls your app. If the user installs or reinstalls your app on a device that runs Android 11, then your app cannot opt out the scoped storage model, regardless of the value of preserveLegacyExternalStorage.

I have an app that targets SDK 30, and would like to test the behavior of existing files on a physical device that already has a release version of the same app which targets SDK 29. I also have the same release binary at hand, so I can install it first (without using the Play store) and then install the updated one targeting SDK 30.
Installing via adb fails with complaints about signatures (both with the installed version from the Play store and my adb installed APK).
I don't want to uninstall the app previously, since per the documentation it means preserveLegacyExternalStorage is ignored. But everything I have seen so far concerning resolving the signature errors involves uninstalling the app first. This isn't the use case I want to test though, I want to test that the app update works with existing files.
Are alpha/beta channels the only other option here? Is it possible to test this behavior using a physical device, Android Studio, and my local release variant APKs without having to uninstall anything first?


text:
Q: Where are questions about the HTTP specification on-topic? Where would questions about details regarding the HTTP specification be on-topic?
I have found two questions so far that fit the bill (the first one being mine, and the reason I started this Meta thread):

*

*Super User: What if the form-data boundary is contained in the attached file?

*Stack Overflow: Http Header - Cache-Control: max-age behaviour?
A moderator recommended moving my question to Stack Overflow, and the second question is already there, but I'm hesitant. I feel a question is only relevant on Stack Overflow if you have an actual piece of code written and have questions on how to "fix" a specific problem. Not about the nuances of W3C specifications.


text:
Q: How to change the "timestamp without time zone" to "timestamp with time zone" using Django models using migrations?  class test(models.Model):
      mobile_last_login = models.DateTimeField()

I need to change the "timestamp without time zone" to "timestamp with time zone" for the "mobile_last_login" field.

A: You can't add a timezone to DateTimeField - Django store date-time in UTC if you have set USE_TZ = True in your settings, or naive date time otherwise. If USE_TZ is set, then Django will automatically apply timezone offset, according to your settings, one's data is fetched from DB.
If you really need to store the timezone, probably an easiest solution will be to store it as a separate field:
import pytz

class test(models.Model):
    TIMEZONE_CHOICES = tuple(zip(pytz.all_timezones, pytz.all_timezones))

    mobile_last_login = models.DateTimeField()
    timezone = models.CharField(max_length=32, choices=TIMEZONE_CHOICES, default=str(pytz.utc))


text:
Q: openid implicit flow authorized user cant pull from syncgateway couchbase Hi everybody I use openid implisit flow in this document https://docs.couchbase.com/sync-gateway/current/authentication.html#implicit-flow for authorization of my user and syncgateway get me this response
 {
    "authentication_handlers": [
        "default",
        "cookie"
    ],
    "ok": true,
    "userCtx": {
        "channels": {
            "!": 1
        },
        "name": "staging-dialysiscloud.icdgroup.org%2Fids_00000000-0000-0000-0000-100000000000"
    }
}

what does "1" means in front of "!" and how can i access to other channels I dont want my user limit to using from public channel .what should I add to jwt token or sync config file ?
I can push to my bucket but I cant pull data from it by this sessionId too

A: The value 1 represents the sequence mapped to the public channel (i.e., the sequence value when the channel was added). The public channel is automatically created when Sync Gateway starts. OpenID Connect authentication is successful in your case, but the user has access only to the public channel. You can grant the user/role access to a specific set of channels or the * channel through the admin REST API, the configuration file or via the Sync Function when a document is updated.
To grant the user access to a specific set of channels via Admin REST API, issue something the like below command from your terminal where Sync Gateway is running:
http --verbose PUT http://localhost:4985/default/_user/alice admin_channels:='["channel-1", "channel-2"]'

This will grant user alice access to channel-1 and channel-2.
If you want the user to access all documents in the database, you can grant user access to the * channel. For instance, the below command will grant the user bob access to the * channel and he will be able to access all documents in the database.
http --verbose PUT http://localhost:4985/default/_user/bob admin_channels:='["*"]'

You might want to change the username bob with your username, i.e., staging-dialysiscloud.icdgroup.org%2Fids_00000000-0000-0000-0000-100000000000.

Note: You need to have httpie installed to run http commands from
terminal. If you don't have it already and you're using Mac OS X, just issue
brew install httpie.

If you would like to read more about Access Control and Sync Gateway Channels here is a nice documentation.


text:
Q: cross-dbms way to check if string is numeric Ok, I have this field:  code varchar(255). It contains some values used in our export routine like
DB84
DB34
3567
3568

I need to select only auto-generated (fully numeric) fields
WHERE is_numeric(table.code)

is_numeric() checks if code field contains only positive digits.
Can you propose anything that will work both under mysql 5.1 and oracle 10g?

A: Below are three separate implementations for each of SQL Server, MySQL and Oracle.  None use (or can) the same approach, so there doesn't seem to be a cross DBMS way to do it.
For MySQL and Oracle, only the simple integer test is show; for SQL Server, the full numeric test is shown.
For SQL Server:
note that isnumeric('.') returns 1.. but it can not actually be converted to float.  Some text like '1e6' cannot be converted to numeric directly, but you can pass through float, then numeric.
;with tmp(x) as (
    select 'db01' union all select '1' union all select '1e2' union all
    select '1234' union all select '' union all select null union all
    select '1.2e4' union all select '1.e10' union all select '0' union all
    select '1.2e+4' union all select '1.e-10' union all select '1e--5' union all
    select '.' union all select '.123' union all select '1.1.23' union all
    select '-.123' union all select '-1.123' union all select '--1' union all
    select '---1.1' union all select '+1.123' union all select '++3' union all
    select '-+1.123' union all select '1 1' union all select '1e1.3' union all
    select '1.234' union all select 'e4' union all select '+.123' union all
    select '1-' union all select '-3e-4' union all select '+3e-4'  union all
    select '+3e+4' union all select '-3.2e+4' union all select '1e1e1' union all
    select '-1e-1-1')

select x, isnumeric(x),
    case when x not like '%[^0-9]%' and x >'' then convert(int, x) end as SimpleInt,
    case
    when x is null or x = '' then null -- blanks
    when x like '%[^0-9e.+-]%' then null -- non valid char found
    when x like 'e%' or x like '%e%[e.]%' then null -- e cannot be first, and cannot be followed by e/.
    when x like '%e%_%[+-]%' then null -- nothing must come between e and +/-
    when x='.' or x like '%.%.%' then null -- no more than one decimal, and not the decimal alone
    when x like '%[^e][+-]%' then null -- no more than one of either +/-, and it must be at the start
    when x like '%[+-]%[+-]%' and not x like '%[+-]%e[+-]%' then null
    else convert(float,x)
    end
from tmp order by 2, 3

For MySQL
create table tmp(x varchar(100));
insert into tmp
    select 'db01' union all select '1' union all select '1e2' union all
    select '1234' union all select '' union all select null union all
    select '1.2e4' union all select '1.e10' union all select '0' union all
    select '1.2e+4' union all select '1.e-10' union all select '1e--5' union all
    select '.' union all select '.123' union all select '1.1.23' union all
    select '-.123' union all select '-1.123' union all select '--1' union all
    select '---1.1' union all select '+1.123' union all select '++3' union all
    select '-+1.123' union all select '1 1' union all select '1e1.3' union all
    select '1.234' union all select 'e4' union all select '+.123' union all
    select '1-' union all select '-3e-4' union all select '+3e-4'  union all
    select '+3e+4' union all select '-3.2e+4' union all select '1e1e1' union all
    select '-1e-1-1';

select x,
    case when x not regexp('[^0-9]') then x*1 end as SimpleInt
from tmp order by 2

For Oracle
case when REGEXP_LIKE(col, '[^0-9]') then col*1 end


text:
Q: Proving that a function is convex $\Leftrightarrow f''(x)\geq0$ I am able to prove $\Rightarrow$, but I am unable to prove the converse.
Recall that a function is called convex on $E$ (which is a subset of a linear space) if for every $x,y\in E$ and every $\lambda\in [0,1]$, we have $f(\lambda x+(1-\lambda)y)\leq \lambda f(x)+(1-\lambda)f(y)$. Prove that if a function is twice differentiable, then it is convex if and only if $f''(x)\geq 0.$

A: For $\Longleftarrow$, take the contrapositive: $f$ is not convex $\implies$ $f''$ is negative somewhere.
If $f$ is non-convex, there is some $x,y\in\Bbb R$ with $x<y$ and some $\lambda\in[0,1]$ such that
$$
f(\lambda x+(1-\lambda)y)>\lambda f(x)+(1-\lambda)f(y)
$$
Let $c=\lambda x+(1-\lambda)y$.
Because $f(c)$ lies strictly above the line between $(x,f(x))$ and $(y,f(y))$, by the mean value theorem, there is some $c_1\in[x,c]$ such that $f'(c_1)>\frac{f(y)-f(x)}{y-x}$, and there is some $c_2\in[c,y]$ such that $f'(c_1)<\frac{f(y)-f(x)}{y-x}$. Now what does the mean value theorem say exists in $[c_1,c_2]$?


text:
Q: UIColor: Is grayscale value a property? https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIColor_Class/#//apple_ref/occ/clm/UIColor/blackColor

Creating a UIColor with Preset Component Values
+ blackColor

Returns a color object whose grayscale value is 0.0 and whose alpha
  value is 1.0.

Is there a method to retrieve a color objects "grayscale value"?

A: You can use the getWhite(_:alpha:) method on UIColor to effectively get the grayscale values.
Playground example:
import UIKit

let piColor = UIColor(red: 0.31, green: 0.41, blue: 0.59, alpha: 1.0)
var grayscale: CGFloat = 0
var alpha: CGFloat = 0

if piColor.getWhite(&grayscale, alpha: &alpha) {
    grayscale
    let grayscaleColor = UIColor(white: grayscale, alpha: alpha)
}


text:
Q: Remove a row on uncheck in iview I have an iview form which contains several items, each item has a checkbox in its first column. The code snippet of the checkbox is:
<input type='checkbox' v-model='item.isChecked' @change='switchBillSelected(item)'></input>

    switchBillSelected(item) {
      if (!item.isChecked) {
        for (let i=0; i<bills.length; i++) {
          if (bills[i].id == item.id) {
            bills.splice(i, 1)
            break;
          }
        }
      }
    }

At first, all items are checked. Then if I uncheck an item except the last one, the item is disappeared, but the next item is unchecked! Is there a way to avoid this side effect?

A: I've modified my code to force refreshing the whole form, it works. But I think its not elegant enough. Is there a better way?
...
<input type='checkbox' v-model='item.isChecked' @change='switchBillSelected(item)'></input>

switchBillSelected(item) {
  if (!item.isChecked) {
    for (let i=0; i<bills.length; i++) {
      if (bills[i].id == item.id) {
        bills.splice(i, 1)
        break;
      }
    }

    // Keep an alias of this.bills
    let alias = this.bills;

    // Clear & re-assign this.bills to refresh the check status of visible rows
    this.bills = [];
    setTimeout((bills) => {
      this.bills= bills;
    }, 500, alias)
  }
}

...


text:
Q: Page rendering time are not steady in IE6 I have to support IE6 and I calculate rendering time by creating a timestamp in javascript at the beginning of the page and doing the difference when document.ready is fired in jQuery.
If I do 3 pages load, the rendering times in milliseconds can look like this :
page 1 : 735, 2672, 734
page 2 : 3063, 1516, 3375
page 3 : 8281, 2531, 3703

Why is that? How can I have more consistency?

A: *

*Exit all other programs.

*Perform each render with the same conditions.

These conditions include an empty cache.

A: without knowing a whole lot about the pages in question, it could be due to just about anything.  could be due to the browser caching things, etc.

A: Something to do with your internet connection possibly? I don't know, without more details it really could be anything.