text:
Q: trouble executing SSH remote ash script on ESXI Host I have two servers: Linux shell (192.168.1.11) and ESXI host ash shell (192.168.1.12).
Desired outcome:

*

*Local testsuspend.sh scp uploads suspendvm.sh to remote ESXI server and executes on ESXI. When finished testsuspend.sh continues and exits.

*Script testsuspend.sh on .11 uploads an ash script (suspendvm.sh) to ESXi host .12, should execute it and wait until it's finished,then finish testsuspend.sh.

On Linux I want to remote execute a script suspendvm.sh from another script testsuspend.sh to suspend all VMs and put ESXI host in maintenance mode.
When I execute the testsuspend.sh on Linux it stops on executing suspendvm.sh via SSH. If I execute the suspend script sustendvm.sh on the ESXI host directly it works.
File after copy on ESXI:
-rwxr-xr-x    1 root     root          1260 Apr 16 07:06 suspendvm.sh

Would you have an idea on what I need to do here to get the ssh remote script to execute properly on the ESXi host and the local script to wait until remote is finished?
... So I found that if I run this in the testsuspend.sh it works:
cat suspendVM.sh | ssh -T $user@$host

Why does this work but not the copy and execute?
Local script 192.168.1.11, testsuspend.sh should execute suspenvm.sh remotely:
#!/bin/sh
user="root"
host="192.168.1.120"

scp suspendvm.sh $user@$host:/tmp
echo "copy suspend script"
ssh $user@$host 'sh -s /tmp/suspendvm.sh' &
exit

Remote script 192.168.1.12, suspendvm.sh works when I execute on ESXI host .12):
#!/bin/sh
RUNNING=0
VMS=`vim-cmd vmsvc/getallvms | grep -v Vmid | awk '{print $1}'`
for VM in $VMS ; do
     # echo "Probing VM with id: $VM."
     PWR=`vim-cmd vmsvc/power.getstate $VM | grep -v "Retrieved runtime info"`
     name=`vim-cmd vmsvc/get.config $VM | grep -i "name =" | awk '{print $3}' | head -1 | awk -F'"' '{print $2}'
     echo "VM with id $VM has power state $PWR (name = $name)."
     if [ "$PWR" == "Powered on" ] ; then
          RUNNING=1
          echo "Powered on VM with id $VM and name: $name"
          echo "Suspending VM with id $VM and name: $name"
          vim-cmd vmsvc/power.suspend $VM > /dev/null &
     fi
done

while true ; do
     if [ $RUNNING -eq 0 ] ; then
          echo "Gone..."
          break
     echo "Powered on VM with id $VM and name: $name"
          echo "Suspending VM with id $VM and name: $name"
          vim-cmd vmsvc/power.suspend $VM > /dev/null &
     fi
done

while true ; do
     if [ $RUNNING -eq 0 ] ; then
          echo "Gone..."
          break
     fi
     RUNNING=0
     for VM in $VMS ; do
          PWR=`vim-cmd vmsvc/power.getstate $VM | grep -v "Retrieved runtime info"`
          if [ "$PWR" == "Powered on" ] ; then
               name=`vim-cmd vmsvc/get.config $VM | grep -i "name =" | awk '{print $3}' | head -1 | awk -F'"' '{$
               echo "Waiting for id $VM and name: $name..."
               RUNNING=1
          fi
     done
     sleep 1
esxcli system maintenanceMode set --enable true
done

Remote script #2 that should do the same via esxicli, it also works when I execute it on .12 but not via ssh from .11:
#! /bin/ash
#test2
rm -f listid
touch listid

######## Listing the running vms################

esxcli vm process list |grep -v "^\s.*"| grep -v "^$" > list

######## If you want to reuse list for later use #######
####### put the file in a datastore, else it ##########
#######gonna be erease on next reboot ##########
####### Command look like this: ###############

## esxcli vm process list |grep -v "^\s.*"| grep -v "^$" > /vmfs/volumes/tmp/list

########## cleaning the id.s file by keeping only the id
for name in `cat list`;do
########## Dont forget to change the path if #######
########## you choose to put it in a datastore #####
####### put the file in a datastore, else it ##########
#######gonna be erease on next reboot ##########
####### Command look like this: ###############

## esxcli vm process list |grep -v "^\s.*"| grep -v "^$" > /vmfs/volumes/tmp/list

########## cleaning the id.s file by keeping only the id
for name in `cat list`;do
########## Dont forget to change the path if #######
########## you choose to put it in a datastore #####

## Example: for name in `cat /vmfs/volumes/yourDatastore/list`;do

        vim-cmd vmsvc/getallvms | grep $name | grep vmx | grep -v "^$" | awk '{print $1}'>> listid
done

for id in `cat listid`;do
        ###### suspending vms##########
        echo "Suspending the running machines"
        vim-cmd vmsvc/power.suspend $id

## Example: for name in `cat /vmfs/volumes/yourDatastore/list`;do

        vim-cmd vmsvc/getallvms | grep $name | grep vmx | grep -v "^$" | awk '{print $1}'>> listid
done

for id in `cat listid`;do
        ###### suspending vms##########
        echo "Suspending the running machines"
        vim-cmd vmsvc/power.suspend $id

done

echo "done."
echo "shutting down the host now.."
#/bin/poweroff
vim-cmd hostsvc/maintenance_mode_enter
#excli system maintenanceMode set --enable true
#done


text:
Q: Difficulty to create .txt file from loop in bash I've this data :
cat >data1.txt <<'EOF'
2020-01-27-06-00;/dev/hd1;100;/
2020-01-27-12-00;/dev/hd1;100;/
2020-01-27-18-00;/dev/hd1;100;/
2020-01-27-06-00;/dev/hd2;200;/usr
2020-01-27-12-00;/dev/hd2;200;/usr
2020-01-27-18-00;/dev/hd2;200;/usr
EOF

cat >data2.txt <<'EOF'
2020-02-27-06-00;/dev/hd1;120;/
2020-02-27-12-00;/dev/hd1;120;/
2020-02-27-18-00;/dev/hd1;120;/
2020-02-27-06-00;/dev/hd2;230;/usr
2020-02-27-12-00;/dev/hd2;230;/usr
2020-02-27-18-00;/dev/hd2;230;/usr
EOF

cat >data3.txt <<'EOF'
2020-03-27-06-00;/dev/hd1;130;/
2020-03-27-12-00;/dev/hd1;130;/
2020-03-27-18-00;/dev/hd1;130;/
2020-03-27-06-00;/dev/hd2;240;/usr
2020-03-27-12-00;/dev/hd2;240;/usr
2020-03-27-18-00;/dev/hd2;240;/usr
EOF

I would like to create a .txt file for each filesystem ( so hd1.txt, hd2.txt, hd3.txt and hd4.txt ) and put in each .txt file the sum of the value from each FS from each dataX.txt. I've some difficulties to explain in english what I want, so here an example of the result wanted
Expected content for the output file hd1.txt:
2020-01;/dev/hd1;300;/
2020-02;/dev/hd1;360;/
2020-03;/dev/hd1;390:/

Expected content for the file hd2.txt:
2020-01;/dev/hd2;600;/usr
2020-02;/dev/hd2;690;/usr
2020-03;/dev/hd2;720;/usr

The implementation I've currently tried:
for i in $(cat *.txt | awk -F';' '{print $2}' | cut -d '/' -f3| uniq)
do
    cat *.txt | grep -w $i | awk -F';' -v date="$(cat *.txt | awk -F';' '{print $1}' | cut -d'-' -f-2 | uniq )" '{sum+=$3} END {print date";"$2";"sum}' >> $i

done

But it doesn't works...
Can you show me how to do that ?

A: Because the format seems to be so constant, you can delimit the input with multiple separators and parse it easily in awk:
awk -v FS='[;-/]' '
prev != $9 {
    if (length(output)) {
        print output >> fileoutput
    }
    prev = $9
    sum = 0
}
{
    sum += $9
    output = sprintf("%s-%s;/%s/%s;%d;/%s", $1, $2, $7, $8, sum, $11)
    fileoutput = $8 ".txt"
}
END {
    print output >> fileoutput
}
' *.txt

Tested on repl generates:
+ cat hd1.txt
2020-01;/dev/hd1;300;/
2020-02;/dev/hd1;360;/
2020-03;/dev/hd1;390;/
+ cat hd2.txt
2020-01;/dev/hd2;600;/usr
2020-02;/dev/hd2;690;/usr
2020-03;/dev/hd2;720;/usr

Alternatively, you could -v FS=';' and use split to split first and second column to extract the year and month and the hdX number.
If you seek a bash solution, I suggest you invert the loops - first iterate over files, then over identifiers in second column.
for file in *.txt; do
    prev=
    output=
    while IFS=';' read -r date dev num path; do
        hd=$(basename "$dev")
        if [[ "$hd" != "${prev:-}" ]]; then
            if ((${#output})); then
                printf "%s\n" "$output" >> "$fileoutput"
            fi
            sum=0
            prev="$hd"
        fi
        sum=$((sum + num))
        output=$(
            printf "%s;%s;%d;%s" \
            "$(cut -d'-' -f1-2 <<<"$date")" \
            "$dev" "$sum" "$path"
        )
        fileoutput="${hd}.txt"
    done < "$file"
    printf "%s\n" "$output" >> "$fileoutput"
done

You could also almost translate awk to bash 1:1 by doing IFS='-;/' in while read loop.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can I use my two laptops as dual monitors? I want to connect my Dell (Windows 7) to my Acer (Windows Vista) and use them as dual monitors. The screen on my Dell is broken and I can't read anything on it. I tried to hook it up to my television and that didn't work. I found out that I need a VGA to HDMI adapter.
Is it possible to connect my two laptops even though they have different operating systems? Do I need any specific cables? I have three cables but I'm not sure if I can use them. One has two ends that seem like you can use them for the phones or something. Any help is appreciated.

A: The short answer is no.
Consumer laptops will only ever have a video out port, never video in. Video capture cards are actually kinda niche, even among desktops. The damaged laptop can send any signal it likes, the other one wont receive it.
Your TV will work, you may just need a different cable. Does the dell have VGA(blue with holes) or HDMI(gold plated, like a larger USB) out? If its HDMI a straight HDMI to HDMI will work. If its VGA and the TV only has HDMI then use a vga to HDMI adapter. A passive one like this should work:
http://www.dx.com/p/1080p-hdmi-male-to-vga-female-adapter-black-242515#.U3EEsPldWgY
Whichever one you do, you may need to use the WindowsKey+P to toggle displays. Connect the cables, turn on, wait for it to fully start(listen for that sound you get at the login screen), then hold the WindowsKey and tap on P until something comes up on the tv.

A: Directly as a monitor, no, however there are software solutions, such as Synergy. You run the server on one machine, the client on the other, and it will share your mouse/keyboard between them - move your mouse to the side of one screen, and control will switch to that of the other machine, so it will act like a shared display.
However, this isn't quite the same as dual monitors; you cannot move applications between displays, and each can only run programs that exist on that machine. So depending on your use case, this may not work for you :)


text:
Q: Minimal permissions for Kubernetes backup with Kasten on AWS S3 I would like to set up a Location profile for Kasten to perform backup on a S3 bucket on AWS. The documentation recommends giving minimal permissions to the user/role designated to perform the backup, but I keep getting an error when trying to add the profile only with those permissions in my IAM policy.
https://docs.kasten.io/latest/usage/configuration.html#profile-creation
When I give full S3 access to the user, the profile is added correctly, but I don't want to do that.

A: The correct minimal permissions are a combination of the permissions specified on these 2 pages in the documentation:

*

*https://docs.kasten.io/latest/usage/configuration.html#profile-creation

*https://docs.kasten.io/latest/install/aws/using_aws_iam_roles.html#using-aws-iam-roles
Here is how your minimal permissions policy should look like (just replace your bucket name at the end):
{
"Version": "2012-10-17",
"Statement": [
    {
        "Sid": "VisualEditor0",
        "Effect": "Allow",
        "Action": [
            "s3:GetBucketObjectLockConfiguration",
            "s3:PutObject",
            "s3:GetObject",
            "s3:GetObjectRetention",
            "s3:PutObjectRetention",
            "s3:PutBucketPolicy",
            "s3:ListBucket",
            "s3:DeleteObject",
            "s3:DeleteBucketPolicy",
            "s3:GetBucketLocation",
            "s3:GetBucketPolicy"
        ],
        "Resource": [
            "arn:aws:s3:::{BUCKET_NAME}",
            "arn:aws:s3:::{BUCKET_NAME}/*"
        ]
    }
]
}


text:
Q: TestNG: asser.assertEquals not found in Eclipse I am a new one to Eclipse and TestNG.. now trying to write assertion once installed TestNG and once I use "Assert.AssertEquals" get an error that this method is undefined for Basic class..
What am I doing wrong? Thanks
I tried to refresh project/library, reinstall TestNG, but still method not working
screenshot


text:
Q: Net force exerted by pressure Why do the net force $K$ exerted by the pressure of
a hard sphere gas according to the Maxwellian distribution on the walls of the container
$A \subset R^3$ vanishes? (In the absence of external fields and regardless of the shape of $A$).
Maybe I should to use the equation of state??


text:
Q: Rectangles are not appearing the right way I'm trying to create some rectangles in D3 by getting data from a .csv file.
The rectangles are appearing but not in the right position. For example I want the first one to start for x=0 and y=0 but instead of that the y is wrong. And also I can not read properly from the file the Letters. It just show me "NaN" at the left axis but I want them to appear inside each rectangle.
My .csv file is this
x,y,width,height,color,txt
0,0,50,50,purple,A
80,40,100,400,blue,B
300,500,100,200,navy,C
320,306,100,100,green,D
800,500,50,50,red,E
850,550,150,100,gray,F
40,550,500,50,indigo,G
100,200,300,320,yellow,H

I also tried to translate all the triangles the same way I did for the axis but nothing happened, they were disappeared.
<!DOCTYPE html>
<meta charset="utf-8">
<style> /* set the CSS */

.rect { fill-opacity:.50; stroke: rgb(60,100,200); stroke-width:1px;}

</style>
<body>

<!-- load the d3.js library -->
<script src="//d3js.org/d3.v4.min.js"></script>
<script>

// set the dimensions and margins of the graph
var margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = 1074 - margin.left - margin.right,
    height = 818 - margin.top - margin.bottom;

// set the ranges
var x = d3.scaleLinear()
      .range([0, width]);
var y = d3.scaleLinear()
      .range([height, 0]);

// append the svg object to the body of the page
// append a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select("body").append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
 .append("g")
  .attr("transform",
      "translate(" + margin.left + "," + margin.top + ")");

// get the data
  d3.csv("rectangles.csv", function(error, data) {
    if (error) throw error;

// format the data
   data.forEach(function(d) {
   d.txt = +d.txt;
  });

 // Scale the range of the data in the domains
  x.domain([0, d3.max(data, function(d) { return d.x; })]);
  y.domain([0, d3.max(data, function(d) { return d.y; })]);

// append the rectangles for the bar chart
  svg.selectAll(".rect")
    .data(data)
  .enter().append("rect")
   .attr("class", "rect")
   .attr("x", function(d) { return x(d.x); })
   .attr("y", function(d) { return y(d.y); })
   .attr("width", function(d) { return d.width })
   .attr("height", function(d) { return d.height})
   .attr("fill", function(d) {return d.color});

  svg.selectAll("text")
    .data(data)
  .enter().append("text")
    .attr("fill","red")
    .attr("y", function(d) { return y(d.y); })
    .text(function(d) {return d.txt});

 // add the x Axis
 svg.append("g")
  .attr("transform", "translate(0," + height + ")")
  .call(d3.axisBottom(x));

 // add the y Axis
 svg.append("g")
  .call(d3.axisLeft(y));
});
 </script>
</body>

I want to create all the rectangles inside the two axis with the letters inside them.

A: For your rects the correct y-position is:
.attr("y", function(d) { return y(d.y) - d.height; })

Since you want the bottom of the rect to be placed at your y-position.
Your "txt" shows up as NAN because you cast it to a number with these lines:
data.forEach(function(d) {
  d.txt = +d.txt;
});

Just remove them.
To position the text the correct calculations are:
.attr("y", function(d) { return y(d.y) - d.height/2; })
.attr("x", function(d) { return x(d.x) + d.width/2; })

Which moves it to the center of the rects.
Here's it all put together.
EDITS
So this is more complicated then I thought.  The real y calculation is:
.attr("y", function(d) { return  y(d.y) - (height - y(d.height)); })

And the height is:
.attr("height", function(d) { return height - y(d.height); });

Update example.


text:
Q: How to validate an instance with dynamic code in rails 3.2 model? We need to validate a model instance with dynamic code based on the status of the instance. The status of the instance is returned by instance field wf_state.
Here is what we use in the model:
wf_validation_def = find_config_const('validation_string_for_status_new', 'model_name') if (wf_state == 'new')
eval(wf_validation_def) if (wf_state == 'new')

Here the validation string returned in wf_validation_def by find_config_const when status is new. The validation string is:
"validates :unit_price, :presence = true, :numericality => {:greater_than => 0} "

However the above code returns error in rspec:
.../activerecord-3.2.12/lib/active_record/dynamic_matchers.rb:55:in `method_missing': undefined local variable or method 'wf_state'

Tried self.wf_state and the error is the same. What's wrong with the code above?


text:
Q: How to change table prefixes in phpMyAdmin? So I have a host which provides me with phpMyAdmin. I run phpBB and would like to change some of the table prefixes.
How can I do this without phpMyAdmin?
I messaged my host and they said I couldn't do it in there. Is there a sql client I can do it with and, if so, how?

A: You can do this with phpMyAdmin.
Go to Structure page of the database that contains these tables.
Check the checkboxes in front of each of the tables you want to rename.
From With selected dropdown chose Replace table prefix.
Enter current prefix in From field and new prefix in To field and press submit.


text:
Q: Server response: 550 550 Verification failed for The mail server could not deliver mail (mailgun & compute-engine) when I send from  email01@mydomain.com  to email02@mydomain.com over smtp.mailgun.org I got this eroro:
"Failed: email01@mydomain.com → email02@mydomain.com 'RE: test mail' Server response: 550 550 Verification failed for  The mail server could not deliver mail to server_name. The account or domain may not exist, they may be blacklisted, or missing the proper dns entries. Sender verify failed"
but when I send from gmail.com to email02@mydomain.com
or when I send from email02@mydomain.com to gmail.com
the mail sent and delivered success.
can you tell me why.
Note:
I'm using Google compute engine and WHM.

A: The error (which is called Sender Address Verification)
I go to
WHM: Main >> Service Configuration >> Exim Configuration Editor >> Standard Options >> Mail
then put
Sender Verification Callouts -> off
Sender Verification -> off
Then everything is working fine.


text:
Q: Безопасно ли использовать бесплатные прокси по HTTPS? По-идее безопасно, т.к. шифрование происходит в браузере.
Имеет ли смысл с т.з. безопасности использование платного прокси или создание своей VPN?

A: Зависит от поведения конкретного прокси.
Если при работе через прокси вы получаете оригинальный сертификат целевого сервера - то безопасно. Значит этот прокси трафик не видит и не модифицирует.
Если при работе через прокси вы получаете в ответ левый сертификат - то небезопасно.
Вообщем,  критерий безопасности тот же,  что и при прямой работе с любым сайтом по HTTPS, как через прокси, так и напрямую.


text:
Q: How can i get a sequence of elements with a defined level into an element structure? How ca i use an xslt template to get from this:
<attribute name="Foo" level="1"/>
<attribute name="Bar" level="2"/>
<attribute name="Lorem" level="2"/>
<attribute name="Ipsum" level="3"/>

to a structure like this:
<attribute name="Foo">
    <attribute name="Bar"/>
    <attribute name="Lorem">
        <attribute name="Ipsum"/>
    </attribute>
</attribute>

I can use XSLT and XPATH 2.0 and i tried different things with grouping but i don't know how to get a recursion into it.

A: If you use a function applying a for-each-group group-starting-with you get
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:mf="http://example.com/mf"
    exclude-result-prefixes="xs mf">

    <xsl:output indent="yes"/>

    <xsl:function name="mf:group" as="element(attribute)*">
        <xsl:param name="attributes" as="element(attribute)*"/>
        <xsl:param name="level" as="xs:integer"/>
        <xsl:for-each-group select="$attributes" group-starting-with="attribute[@level = $level]">
            <attribute name="{@name}">
                <xsl:sequence select="mf:group(current-group() except ., $level + 1)"/>
            </attribute>
        </xsl:for-each-group>
    </xsl:function>

    <xsl:template match="root">
        <xsl:sequence select="mf:group(attribute, 1)"/>
    </xsl:template>

</xsl:transform>

which transforms
<root>
    <attribute name="Foo" level="1"/>
    <attribute name="Bar" level="2"/>
    <attribute name="whatever" level="3"/>
    <attribute name="Lorem" level="2"/>
    <attribute name="Ipsum" level="3"/>
    <attribute name="foobar" level="3"/>
</root>

into
<attribute name="Foo">
   <attribute name="Bar">
      <attribute name="whatever"/>
   </attribute>
   <attribute name="Lorem">
      <attribute name="Ipsum"/>
      <attribute name="foobar"/>
   </attribute>
</attribute>


text:
Q: Azure virtual machine, can't access from internet I have a Azure Virtual Machine with a docker-compose.
CONTAINER ID        IMAGE                          COMMAND                  CREATED             STATUS              PORTS                    NAMES
01c51a6b0111        yyy                       "/bin/sh -c 'ng serv…"   About an hour ago   Up 33 minutes       0.0.0.0:4300->4200/tcp   azureuser_web_app_speech_1
3701382682fd        xxx                       "java -Djava.securit…"   About an hour ago   Up 33 minutes       0.0.0.0:8087->8080/tcp   azureuser_api_speech_docker_1

But when I want to access my web application from my browser (http://public_ip:4300) I have a time out error.
I've already add network rules to accept requests on port 4300
Thanks for your help

A: For your issue, I think the possible reason is that your application is not run well or it does not listen to the port 4300 as you expect. So you can access it inside the VM through the command http://localhost:4300 to check the port is right. And you can also go inside the container to check if the application is run well.
By the way, the NSG rules also need to check if there is a rule with a higher priority denied the port.


text:
Q: The maximal connected compact submanifold of $O(n)$ Suppose that $S$ is a connected compact embedded submanifold of $O(n)$ with dimension equal to $O(n)$, is it true that $S$ has to be a component of $O(n)$?
My guess is that it should be true, but I do not know where to start.

A: Submanifolds of the same dimension must be open. Since it's open, closed and connected, it must be a component. There's nothing special about $O(n)$ here.


text:
Q: Wrapping custom notes in texreg output I'm trying to add a fairly long note to the bottom of a table created by texreg; I want this to simply wrap around, but there doesn't seem to be any functionality built into the function for doing so.
Take, e.g.:
texreg(
  lm(speed ~ dist, data = cars),
  custom.note = paste(
    "%stars. This regression should be",
    "intepreted with strong caution as",
    "it is likely plagued by extensive",
    "omitted variable bias"
  )
)

Which, when compiled, gives something like:

The formatting is atrocious; much better would be something like replacing the standard output:
\multicolumn{2}{l}{\scriptsize{$^{***}p<0.001$, $^{**}p<0.01$, $^*p<0.05$. This regression should be intepreted with strong caution as it is likely plagued by extensive omitted variable bias}}

With more digestible wrapping:
\multicolumn{2}{l}{\scriptsize{$^{***}p<0.001$, $^{**}p<0.01$, $^*p<0.05$.}} \\
\multicolumn{2}{l}{\scriptsize{This regression should be intepreted with}} \\
\multicolumn{2}{l}{\scriptsize{strong caution as it is likely plagued by}} \\
\multicolumn{2}{l}{\scriptsize{extensive omitted variable bias}}

Which gives output much closer to what I'm looking for:

Is there a way to do this programatically?

A: I might point out a neat alternative solution I received which could be of interest to you, at the latest when you need to update the texreg package.
Accordingly the custom note ends in a \multicolumn in the LaTeX code, thus we cannot use line break commands like par or \\. But we can achieve the automatic line break with \parbox. If we still want a custom line break we can use four backslashes \\\\. For better formatting we can use \\vspace{2pt} just at the beginning of the text content:
texreg(lm(speed ~ dist, data = cars),
       custom.note = ("\\parbox{.4\\linewidth}{\\vspace{2pt}%stars. \\\\
       This regression should be intepreted with strong caution as it is
       likely plagued by extensive omitted variable bias.}"))

A: With version 1.37.1 (released in May 2020), texreg introduces the threeparttable argument, which uses the threeparttable LaTeX package, which was designed for this purpose.
Example R code:
texreg(lm(speed ~ dist, data = cars),
       custom.note = paste("\\item %stars. This regression",
                           "should be interpreted with strong",
                           "caution as it is likely plagued by",
                           "extensive omitted variable bias."),
       single.row = TRUE,
       threeparttable = TRUE)

Output:
\begin{table}
\begin{center}
\begin{threeparttable}
\begin{tabular}{l c}
\hline
 & Model 1 \\
\hline
(Intercept) & $8.28 \; (0.87)^{***}$ \\
dist        & $0.17 \; (0.02)^{***}$ \\
\hline
R$^2$       & $0.65$                 \\
Adj. R$^2$  & $0.64$                 \\
Num. obs.   & $50$                   \\
\hline
\end{tabular}
\begin{tablenotes}[flushleft]
\scriptsize{\item $^{***}p<0.001$; $^{**}p<0.01$; $^{*}p<0.05$. This regression should be interpreted with strong caution as it is likely plagued by extensive omitted variable bias}
\end{tablenotes}
\end{threeparttable}
\caption{Statistical models}
\label{table:coefficients}
\end{center}
\end{table}

Which is rendered as:

Note that the custom note must start with \\item. It is also possible to have multiple items and/or use bullet points to format multiple notes like in a list:
texreg(lm(speed ~ dist, data = cars),
       custom.note = paste("\\item[$\\bullet$] %stars.",
                           "\\item[$\\bullet$] This regression",
                           "should be interpreted with strong",
                           "caution as it is likely plagued by",
                           "extensive omitted variable bias."),
       single.row = TRUE,
       threeparttable = TRUE)

The formatting is not perfect as you cannot set the desired width of the table; the note just adjusts to the width of the respective table. But I think it should be less of a problem in a realistic usage scenario where more than one model is displayed at a time and some of the coefficient names are longer than in the example. This solution also supports longtable environments, in which case the threeparttablex package is used instead.
Here is an example of how you could make it look nice with two models:

fit <- lm(speed ~ dist, data = cars)
texreg(list(fit, fit),
       custom.note = paste("\\item[\\hspace{-5mm}] %stars.",
                           "\\item[\\hspace{-5mm}] This regression",
                           "should be interpreted with strong",
                           "caution as it is likely plagued by",
                           "extensive omitted variable bias."),
       single.row = TRUE,
       threeparttable = TRUE)

This yields:
\begin{table}
\begin{center}
\begin{threeparttable}
\begin{tabular}{l c c}
\hline
 & Model 1 & Model 2 \\
\hline
(Intercept) & $8.28 \; (0.87)^{***}$ & $8.28 \; (0.87)^{***}$ \\
dist        & $0.17 \; (0.02)^{***}$ & $0.17 \; (0.02)^{***}$ \\
\hline
R$^2$       & $0.65$                 & $0.65$                 \\
Adj. R$^2$  & $0.64$                 & $0.64$                 \\
Num. obs.   & $50$                   & $50$                   \\
\hline
\end{tabular}
\begin{tablenotes}[flushleft]
\scriptsize{\item[\hspace{-5mm}] $^{***}p<0.001$; $^{**}p<0.01$; $^{*}p<0.05$. \item[\hspace{-5mm}] This regression should be interpreted with strong caution as it is likely plagued by extensive omitted variable bias.}
\end{tablenotes}
\end{threeparttable}
\caption{Statistical models}
\label{table:coefficients}
\end{center}
\end{table}

Which renders as:

A: I've come up with a workaround so far by rewriting the texreg function by adding a custom.note.wrap argument and changing:
note <- paste0("\\multicolumn{", length(models) + 1,
               "}{l}{\\", notesize, "{", custom.note, "}}")
note <- gsub("%stars", snote, note, perl = TRUE)

To:
if (custom.note.wrap){
  note<-paste(paste0("\\multicolumn{", length(models) + 1L,"}{l}{\\",notesize,"{",
                     strwrap(custom.note, width=custom.note.wrap), "}}"),
              collapse = " \\ \n")
  note <- gsub("%stars", snote, note, perl = TRUE)
}else{
  note <- paste0("\\multicolumn{", length(models) + 1L,
                 "}{l}{\\", notesize, "{", custom.note, "}}")
  note <- gsub("%stars", snote, note, perl = TRUE)
}

The idea is to pick a maximum string length for each line (custom.note.wrap) and then split the supplied note into strings of at most that length which end in a space, finally concatenating everything into a bunch of multicolumns with each split substring.
This is not optimal, as it would be better for texreg (to have the ability) to automatically set custom.note.wrap given the lengths of the model names, etc. But my raw LaTeX abilities are lacking, so I'm not sure how I would do this.


text:
Q: How to scrape mutiple tags of single container in Scrapy using Xpath? I used Xpath to scrape data in a website:
response.xpath('//*[@class="attr category hide--mobile"]/span/a/text()').extract()

it gives the following result which are tags to a post in a website.
['Furniture',
 'Wardrobes',
 'Furniture',
 'Wardrobes',
 'Furniture',
 'Wardrobes',
 'Furniture',
 'Wardrobes',
 'Furniture',
 'Wardrobes',
 'Furniture',]

Problem is the first two values are the tags of the same container on the website.
The website contains data like this in a single container:
White and Grey Galley Walk-in Closet PLYJ17017-057
White and Grey Galley Walk-in Closet PLYJ17017-057 Specification: Code: PLYJ17017-057 Style: Modern Door: Lacquer Carcase: Melamine White and Grey Galley Walk-in Wardrobe Closet, an important part of the design for the bedroom is the addition of a...
Category: Furniture | Wardrobes

How to capture two tags Furniture and Wardrobes as a whole of the single container.


text:
Q: Author and title of ca. 1960s serial in Analog SF conspiracy to sequester earth's atmosphere Conspiracy to use large numbers of big air compressors to compress and store all the earth's atmosphere.  Conspirators are humans, fairly near future. Serialized in Analog SF/SF, probably late 1960s. Author, title if anyone knows - thanks.
Read the second installment when it was published. Would like to read all of it.

A: This is Earth, Air, Fire and Water by Stephen Nemeth and William Walling. It was done as a three part serial in the February, March and April 1974 issues of Analog.
I found a link to a scanned first couple of pages and the main character is named Volpone, which I remembered.

Alex Volpone sighed. "Leonard, Leonard, there are no sure things in this'precarious world. It has to be an excellent bet, a clean, tremendously efficient innovation in mass transit, tucked neatly out of sight subsurface, providing aircraft speeds, near-foolproof safety, and gravity compensated acceleration-deceleration passenger comfort.
"You've watched the model work, listened to Dr. Seymour's pitch on the compressor equipment
we're to build. Can you ask more than CompAir's chance to participate in such a gigantic enterprise?"
"If the horse is allowed to run," maintained Colo doggedly. "And if young Seymour's blue sky approach proves feasible in this, the real world."


text:
Q: Getting wrong output for my DNA sequence matcher program So I'm making a program that's meant to match a sequence of DNA to a specific person in a "database" (CSV file) by getting the longest repeating substring in a sequence (CS50 pset6, the DNA problem). For example, the string 'AGAT' should return in a certain sequence called 'CTASFDGAGATAGATAGATKLCSAD', an amount of 3 for the string returned (AGATAGATAGAT). While I pass the first 4 test cases I'm meant to pass, other than those few cases, I only get 'No match' in my output. I don't know what I can change to get it working? I've narrowed down my problem to either the
get_longest_repeating_substr function or the matching function (Both are maybe the problem?).
Code I'm using:
# determine to whom a sequence of DNA belongs
import sys
import csv
import re

# main function

def main():
    # check the command-line arguments
    if len(sys.argv) != 3:
        sys.exit("Usage: python dna.py data.csv sequence.txt")
    else:
        # create file paths to load the files later on
        csv_filename = "dna/"+sys.argv[1]
        seqtxt_filename = "dna/"+sys.argv[2]

        # create 2 lists and string which contains the csv and txt file's contents respectively
        person_dna_list = []
        list_of_STR = load_STR_list(csv_filename)
        dna_string = load_txt(seqtxt_filename)
        load_csv(csv_filename, person_dna_list)

        # get longest repeating substring in string per STR and store them in a dict
        results_list = []
        for i in range(len(list_of_STR)):
            longest_result = get_longest_repeating_substr(dna_string, list_of_STR[i])
            results_list.append(longest_result)

        # match a person to the results_list
        temp_dna_list = person_dna_list
        index = matching(temp_dna_list, results_list)

        # give relevant output
        if index != -1:
            print(person_dna_list[index][0])
        else:
            print('No match')

# loads the csv's contents into a list

def load_csv(csvf, listfordict):
    with open(csvf, "r") as csv_file:
        reader = csv.reader(csv_file)
        next(reader)
        for row in reader:
            listfordict.append(row)
        for i in range(len(listfordict)):
            for j in range(1, len(listfordict[i])):
                listfordict[i][j] = int(listfordict[i][j])

# loads the txt files contents into a string

def load_txt(seqtxt):
    with open(seqtxt, "r") as txt_file:
        data = txt_file.read()
        return data

# loads list of STRs into a list by reading the first line of the csv file

def load_STR_list(csvf):
    with open(csvf, "r") as csv_file:
        string = csv_file.readline()
        values = string.replace('name', '').replace('\n', '')
        outgoing_list = values.split(',')
        del outgoing_list[0]
        return outgoing_list

# gets maximum num of times STR repeats

def get_longest_repeating_substr(dna_str, STR):
    array = re.findall(STR, dna_str)
    return len(array)

# return a match result from the DNA sequence's results

def matching(temp_dna_list, results_list):
    # initialize crucial variables
    person_list = temp_dna_list
    compare_list = results_list
    found_index = -1

    # find a match, if no match is found, respond accordingly
    for j in range(len(person_list)):
        if person_list[j][1:len(person_list)+1] == compare_list:
            found_index = j

    return found_index

main()

Test cases I'm meant to pass: (I pass the first four after the "exists" case, if I do it manually)

large.csv and small.csv

3.txt and 5.txt (the first and second string respectively
AGAAAGTGATGAGGGAGATAGTTAGGAAAAGGTTAAATTAAATTAAGAAAAATTATCTATCTATCTATCTATCAAGATAGGGAATAATGGAGAAATAAAGAAAGTGGAAAAAGATCAGATCAGATCTTTGGATTAATGGTGTAATAGTTTGGTGATAAAAGAGGTTAAAAAAGTATTAGAAATAAAAGATAAGGAAATGAATGAATGAGGAAGATTAGATTAATTGAATGTTAAAAGTTAA

GCTAAATTTGTTCAGCCAGATGTAGGCTTACAAATCAAGCTGTCCGCTCGGCACGGCCTACACACGTCGTGTAACTACAACAGCTAGTTAATCTGGATATCACCATGACCGAATCATAGATTTCGCCTTAAGGAGCTTTACCATGGCTTGGGATCCAATACTAAGGGCTCGACCTAGGCGAATGAGTTTCAGGTTGGCAATCAGCAACGCTCGCCATCCGGACGACGGCTTACAGTTAGTAGCATAGTACGCGATTTTCGGGAAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCCCGTCAACTCATTCACACCGCATCCTTTCCTGCCACTGTAACTAGTCGACTGGGGAACCTCATCATCCATACTCTCCCACATTATGCCTCCCAACCTTGTTAAGCGTGGCATGCTTGGGATTGCATTGATGCTTCTTGGAGAGGACGCTTTCGTTTTGGAGATTACAGGGATCCAATTTTATCATCGGTTCGACTCCCGTAACGACTTAGCAGTAAGGGTGCTAGTTCCTGGTTAGAATCTTAATAAATCACGTCGCTTGGAGCAAGACAAAGATCGTCGTAATGCCAAGTGCACGACCACCTTCAGACTTGCAGGACCCGTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTCGATAGCTATGCGGTTCAATACAATCTTAACGCAATGCAGCGATGTGGTTTCGTACACTTAGCATAAAACCCCCCACATTAAATCGATGTACCCGCCCTCTTAGACGCCAATTTCAATGCCGAACCTCCGGCGGGTATCTCTGCACTAGGAGAAGTAGCACGTCGCTGTAGCGAACTCCTATCGTGAGATAATTTGTAGAGCTGCTCTTATAATACAATAGCTCAGATGGATTATTCCATGGACATCCCCGTGCGTTGTTTCGAGGATGGTAGGTGGAAATTTTGCCAGACCTCTAGTCTTAAACATGGTTGACGTTATAGGCGCTATCTCTTGCGTCTGGAAGTGTTAATCCGTGAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAACACGCAACTCTGGAGGAGGGCACTGCACTGCAAACTTGCGTAATATCCTTCACCCACACTTGCCTGGCCTCCTTGCTTAAAGCTCTGGCGATGCGATTTTTCGGCCCAGTAGCTGAATAGGTCATGAAATGGGCACCGAACTGGAAAGACCCATATATTCGATACTCACAACTTAATGATAGCGCGATTAAGAGCGACACCAAAAACCAAATTACGTTCACGAACCTTTGAGAGTCAAGGAGACTTAGACCGAATTGAATGATCACTGATGCGCCCGCTGATACTGAGCCTCACCATTAATCGCCGACCAATACGGCGTGTACCGGGCGCGGCCTTGCCGCATAACGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATATCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTACACAGCCCCGTCCTCATTGCTAAGTGCACTGGCAACTGGACCTAAAGATTTTTCGAGTATGGCCCTCGAATCAAGCGCCCACCCAGAAACCTACGAGCCAGTAACCCCAGTAAACAAGCATTAGTGCTATATGCTTGCTGCCCACTAGGACCCTTATGGTTCATACCAGGGTGACGTGTCTTGCGGGCCAAGGATGAACCAGAAGCAAGATCCTTAGATGGACGACTGTCTCATTGCTTAAACTCCACATACCAAAGGGCGCGGTAAACGATAGTTTTAGGTAATGTTAGTCGGATGGTTGTCTGCAGCTACCAATACAGCCTGGCACCCAGGGTCTGAACAATAACGCGTGAGAGCAGCTCTCCCGCGTGTGGTGGATTTGCCGTCTATGAAATTGAGGCTCTTGCAACTATTCGCACTCGGAATGCCCTCATATCTGGTGCCTAGCGGCCTTTGCCCCGTGCCGGTAGGACTAAACTCTACGGATCGTTGACGGATCTCGATGTGGAAGATGGTTATGAAAGATAACAACGCGTGTGCTAATTGATTTAGACAAGTATTGCGGCAGTAAAAGATAATCGGCTGCAGAGTTACGAAAGACTTCCATGCATGGATTCCATTCCTTCTAGTATAGGACCCACTCTGAATACACGTCTTGCGGGCCGATCATCTCCACCGCTGCGGAAGAAAGCAATTAAGAATCTATGCTCATTAAGAGTGCGACTATAATGCGGATCTTACAGTGCTAATGATCAGGACGTCGTCCAAGCAGGCTGCATGCCGAATTTAGCTTACGTCAGGATCAGGCGTTATAGCCTGGGAATCGGACTATGAGGACGCCACGACCTCTGGGAGAAAGCTATATACATTGAGGATCGCGCCATCTTTATGAGACTCAAATGAATCTAGATAGGTAGCATTGCGGACTTGAGTTAGCACATCGGTATTGGAAGGTGAGGGTCCTGCCGCTCGTTCTATGTTCGGTTTATAGTATACAAATAGGTCATCCCGAACGTTGAAGTTAAACTCATGACACGTTGTCGTAATGAAACGGGCCTGTTATTAGGGATACAGACAAAAGGCACAAGCTGGCTTGCACATTAAGGCGCACTAGAGATCCTCACAACCGTTGCCCGCACGGAGGTCGTGTCTAACAGACAGTGAACCAGCCGTATTGGGGTGGATGACCTGAGCTTCTTGGGGCCTGTTGTACACCGCGTGTGGTTCAACTGGTACACATACTACGAATATTCGAAATCATTGTACTGTGCTCTTCGGTGCTACTGACTGTGAGCGAATGCATCCCAATCCCAAACAATGCTTGTGGTAGGAGAATTGAAACTCTCGAAGCCTGGCCCAATGTCATCTACTTTTAACATGTCGGGCCAGGAGTTACGGGCATTGCTTACTTACTTTGCCCCCTTACACCACAGCAGCGCGATTCTTGTTGTAGTAGATTTTATACGACTCGCGAATTAAATGGAACTTGTCTGTCCCATATCGATCGTGTCCATCGTAAGATGAGATTGTAGGAGCATTCGGAAGTCTATGCGGCCCAGGGACTACTACGTTAAATCTGGTCAGACGTGGTTTACAAGGCGTCCCGATCTTCTCAGAACATATGGGAAAGCACTACCGTTCCTTCACGCATACAGTTGTTCGTGCCGAACGAGTAAGCTTGCGACCAGCCCACCCGCTAGGGCTATGCAGCGGGTCATGGCTGGCGCCATACTGTGCGGACAACCCACGCTCTGGCAGAAAGCGTCTTGTGTTTTGTAGTAGCTCCAACGGTTAGACCTTCGATATCTATTCAGAGCGCGAGCGACCACTATTAGACGGCATGTAAACAATGTGTATTTGTTCGGCCCAACCGGTATATGGGTAAGACCGCGAAGGGCCTGCGCGAATACCAGCGTCCAAAAATTCCTCACCCGAGATATGCGGTTAGTACCCCTTGGGTAACGGTCCGCTACGGGTAGCGACGCGAGCCGGCCGCATCGGTTGGAGCCGAGTTGTCGGGCAGGCGAGTAACGTGTGCAATTTGATGGGCCCAAGCCTCCGGCACTATCCACCTCATACATCGACAAAAGCACCAAATATGGGGAAAAGCTGAGCGTCGATATGTACATCTACCCAGGAACCGGCCCGAACATTAGGCGGACGTGAATTTCCGACCTAGGTTCGGCTACATTTCTACGATCCAAGCACACGTGAAGGAGGAGGGGTGTTCCGACCGTAAATGAACGAGGTGCGCAGTGACCCGATGGCGTTTAGCGGATAGCCTTCCTATGCCGGCCTATGCTGTATGGTAGTTGGTTGGTGCCTCCAGAGCCACTGCACCCAATCATAGGGTCTACAGCAGCGTACTTATAAAATTGTACGGGTGACCCATATCCATTACGGGTTGCGACCAGTATAGGAGAGTATAACTGCGTGAACTAATGCGTTATGACGCTTCAGAGTTTGCTCGGGCCCGAGTTCTAGGGCTATAATGTGTTAGGGCGCAAGTATGCCAAGCTAAGATGTGGCGTGCACACTAGGAGTTGTGTTCCTCTGCAAGCAGACACGAGCACTCTGGCAGTAGTTTGACCACACCCGGGTATCACTGCTACTCCATTTCGAACAAGCTATTGGAGCGGACAAAATATGCTACTCAAGAGCATTAGTTATAGGTCTACGAGACAGAAGCAGTTACTGAGTCTGAATATTCGATATAAGTAGGCATGGAGGCGGAGCAAAACAACGTCTGCGATCAATCGTGTTGATGACGTATGGCGACTGGAAGGTAAGGACTATGGCCGGACGGAATGATTCATGTTCTGTTCAAAGCTATATTTCGAAGGGGTATATTAGCGGTCCTACACTTGGTTAGCACCCTCCCCCCTCTGGATCCTGCACTAATTCGAGCTGGCCTCCATCGGTATCAGTCCGGAAGCTCCACTCTCTATCGTAGTCCTAATCAACAGGGTGCCAGTTTGCTCACGTGGAAGTTTGAGGCCCTTTGTGCTCCATAGCCAATCACTAACCATGCACGCGCGACCCACTCTACGTCCAGATCGGCTATAATAGTTGCGCCCGGGACTGGCAGAGTAGACATGTAAGCTAGATAGAGCCCCGACATCGGCCAAGAGATCCTACGCTGCTTCCAGATAATGAGAGACATTCTAGCATTAGACATGCAAGTCGGCAGGGACTCCCCTTATCTAGTAATTTCGATGAATTGGTTTTTCGGCTAGCATCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGACCATGCCGACCTCATCATAGAAGGAATGCTCTAAACTTAGAGTGCTACTAGGAAAACTATTAATCAATGATCGTCCTGCTTACATAGCTGGACGGCGAAAGTTCTTATACTGCGGAGGTTGCTGACGTAGAGTGCGCTGGGTACAGCGGATAAGTTGATCAGGGTGGGGATAGGGTGGCTCACCGTTTATACTCATATAGATTCCTGGCGTCGACGCTGTGACAGGGTCGAGATCGAGGGGGAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGCGGAGCGGAGGGAAAATTATCACCAGAGGGTAGGGGCTCGCGACATTCTATTCAATGCATTTCAAGCTACTTACGTATTTCGGCACAGTGACTACTGCCTGCGCGGCAGCCGTAAGGTTTCCCGTCAATAGGTGGCACGTATCATTGATGAAAGTGTCAGCTAATCATTCAGGCCTTA

Thanks in advance for the help!

A: The correct way of getting the STR repeats
# gets maximum num of times STR repeats

def get_longest_repeating_substr(dna_str, STR):
    hits = re.findall(rf'(?:{STR})+', dna_str)
    result = max(hits, key=len)
    length = len(result)//len(STR)
    return length

The file paths were wrongly setup:(after correction)
    # create file paths to load the files later on
    csv_filename = sys.argv[1]
    seqtxt_filename = sys.argv[2]

Remove the else of the argv if statement from the main function and correct the indentation, etc of the rest of the main function's code.


text:
Q: Barcode reader on website without https// I'd like to build an web application where you can scan barcodes.
When i first found HTML5/Jquery plugins i was excited.
But as i´ve been reading for a while i notice that i cannot use the getUserMedia/Stream API without a SSL (https) certified website.
Maby i can use the HTML5 input capture="camera" and then "read" the img with some kind of Jquery plugin?
I find the quaggaJS interesting, but i think i cannot use the livestream without https.
Is there a way around of getting a https certificate?


text:
Q: Bounding sum of samples of a Gaussian Suppose we have $K$ points $x_1,\ldots,x_K$ in $\mathbb{R}^d$ and let
 $$f(x)=\sum_{k=1}^K \exp(-\lambda \Vert x-x_k \rVert^2).$$
Can we uniformly bound $f$ independent of $K$?
It is okay to use some assumption on the distribution of $\{x_k\}$.


text:
Q: Anyone knows what the code snippet means below? header('P3P: CP="IDC DSP COR CURa ADMa OUR IND PHY ONL COM STA"');

I've never seen such headers,what's it for?

A: It's a coded format expressing - in a machine-readable form - what the web site is going to do with your private data. IIRC, IE is using this already, it shows a human-readable translation of the P3P header in the status bar if the current site serves one.
See here: Platform for Privacy Preferences
The Gist:

The Platform for Privacy Preferences Project (P3P) enables Websites to express their privacy practices in a standard format that can be retrieved automatically and interpreted easily by user agents.

A: Take a look at this site for a translation of the commands:
http://www.p3pwriter.com/LRN_111.asp

A: The answers above are correct, but I think it's worth mentioning why you would want to do it from a functionality perspective. If you have a page that is being included by a frameset from a different domain, any version of IE 6 or newer will block the cookies for your page unless the p3p header is present.
The idea is that your page, if it placed in a frameset hosted by a different domain, is considered "third party" content. The fear is that you may trying to stick sneaky ad tracking or other cookies in a person's browser without their knowledge. The p3p header is a way of pinning your organization down as saying "we won't do anything sneaky with them 3rd party cookies". The user can set their browser to block your cookies if you don't set that header, and as of IE6 that is the default setting.

A: This specific chain of commands is included in sites that interact with facebook, and resolves Internet Explorer session issues.


text:
Q: How to create a new attribute and put it in the product creation form as custom field? How to create a new attribute and put it in the product creation form as custom field?
It may be that I am calling it wrong, may be it's not an attribute but a product feature or characteristic.
The idea is to have an additional field, like the log description or the short description.
Thanks!


text:
Q: Creating a Priority queue I need to create a Priority Queue but Im a bit lost how to do it.
I have these 2 lists.
        //Medic List
        ListaMedico.Add(new Medico(01, "Antonio", 555444333, "antonio@gmail.com", "Dermatologista"));
        ListaMedico.Add(new Medico(02, "Lucas", 555444333, "lucas78@gmail.com", "Cardiologista"));
        ListaMedico.Add(new Medico(03, "Duarte", 555444333, "Duarte90@gmail.com", "Otorrino"));
        ListaMedico.Add(new Medico(04, "Marcos", 555444333, "marcos123@gmail.com", "Clinica Geral"));
        ListaMedico.Add(new Medico(05, "Pedro", 555444333, "Pedro12@gmail.com", "Pediatra"));

And
           //Sick People List
            ListaUtente.Add(new Utente(100001, "Pedro", 914754123, "pedro@gmail.com", GetRandomColor()));
            ListaUtente.Add(new Utente(100002, "Lucas", 974123214, "lucas91@gmail.com", GetRandomColor()));
            ListaUtente.Add(new Utente(100003, "Rodrigo", 941201456, "rodrigo00@gmail.com", GetRandomColor()));
            ListaUtente.Add(new Utente(100004, "Gaspar", 987453210, "gaspar@gmail.com", GetRandomColor()));
            ListaUtente.Add(new Utente(100005, "Roberto", 974120219, "roberto@gmail.com", GetRandomColor()));
            ListaUtente.Add(new Utente(100006, "Eduardo", 974120219, "edu@gmail.com", GetRandomColor()));
            ListaUtente.Add(new Utente(100007, "Ismael", 974120219, "Isma@gmail.com", GetRandomColor()));
            ListaUtente.Add(new Utente(100008, "Paulo", 974120219, "Paulo90@gmail.com", GetRandomColor()));
            ListaUtente.Add(new Utente(100009, "Ana", 974120219, "ana.90@gmail.com", GetRandomColor()));

Im using this code to assign random colors to my patients.
    static ConsoleColor[] colors = { ConsoleColor.Red, ConsoleColor.Green, ConsoleColor.Yellow, ConsoleColor.Magenta }; // Cores disponíveis para usar nas Senhas
    static ConsoleColor GetRandomColor()
    {

        return colors[random.Next(colors.Length)];
    }

I need a priority queue because the magenta ones are priority, then red, then yellow and finnaly green. How can I assign some patients to my doctors respecting this color hierarchy?

A: You can define the value of the enum item accordingly with your priority and retrieve the list items ordering by it.
public enum ConsoleColor { Magenta = 1, Red =2, Yellow = 3, Green = 4 }

ListaUtente.OrderBy(x => (int)x);

A: You can use a custom order by to do that, but you must specify how to order by priority,
For example:
var orderedByPriority = ListaUtente.OrderBy(sick =>
    sick.Color == ConsoleColor.Magenta ? 1 :
    sick.Color == ConsoleColor.Red ? 2 :
    sick.Color == ConsoleColor.Yellow ? 3 : 4);

With this logic, you do not need to change your code.

A: The main thing about a priority queue is that it should keep track of what's being added at various priorities and keep them in order. To do that you really need a correctly constructed data structure, or you're going to wind up dummying it up with calls to sort a built-in .NET structure over and over, which is bad syntactically and for performance.
There is an int-priority implementation of a priority queue that should work fine for your purposes here: PriorityQueue source
A concurrent version, if you need that feature, is here:
ConcurrentPriorityQueue source
An int-ordered priority queue works fine with enumerations because enumerations are integer types with some syntactic sugar added. :) Hope this helps!


text:
Q: What is the correct way of routing different modules in Angular? I have a project with three modules: auth, libros and prestamo, every module has different components and his respective routing and I have a general routing module for al the project, the code in my "auth-routing-module" is the next:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { AuthComponent } from '../auth/auth.component';
import { LoginComponent } from '../login/login.component';
import { ForgotPasswordComponent } from '../forgot-password/forgot-password.component';
import { SignUpComponent } from '../sign-up/sign-up.component';

const authRoutes: Routes = [
  { path: 'auth', component: AuthComponent},
  { path: 'login', component: LoginComponent},
  { path: 'forgotPassword', component: ForgotPasswordComponent},
  { path: 'signUp', component: SignUpComponent}
];

@NgModule({
  declarations: [],
  imports: [
    CommonModule, RouterModule.forRoot(authRoutes)
  ],
  exports: [RouterModule]
})
export class AuthRoutingModule { }

I have a similar code in the other modules, and the code in my "routing-module" is the next:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';

const appRoutes: Routes = [
  {path: 'auth', loadChildren:() => import('../auth/auth.module').then(mod => mod.AuthModule)},
  {path: 'libros', loadChildren:() => import('../libros/libros.module').then(mod => mod.LibrosModule)},
  {path: 'prestamos', loadChildren:() => import('../prestamos/prestamos.module').then(mod => mod.PrestamosModule)}
];

@NgModule({
  declarations: [],
  imports: [
    CommonModule, RouterModule.forRoot(appRoutes)
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Finally this is the code of my "app-module":
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing/app-routing.module';

import { AppComponent } from './app.component';
import { AuthModule } from './auth/auth.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule, AuthModule, AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now, when I check the navigation with the auth components the navigation works, but when I try to use a component of other module I get the next error:
ERROR Error: Uncaught (in promise): Error: RouterModule.forRoot() called twice. Lazy loaded modules should use RouterModule.forChild() instead.
Error: RouterModule.forRoot() called twice. Lazy loaded modules should use RouterModule.forChild() instead.
    at Object.provideForRootGuard [as useFactory] (router.js:5749)
    at Object.factory (core.js:11468)
    at R3Injector.hydrate (core.js:11385)
    at R3Injector.get (core.js:11205)
    at injectInjectorOnly (core.js:4728)
    at Module.ɵɵinject (core.js:4732)
    at Object.RouterModule_Factory [as factory] (router.js:5714)
    at R3Injector.hydrate (core.js:11385)
    at R3Injector.get (core.js:11205)
    at core.js:11242
    at resolvePromise (zone-evergreen.js:1213)
    at resolvePromise (zone-evergreen.js:1167)
    at zone-evergreen.js:1279
    at ZoneDelegate.invokeTask (zone-evergreen.js:406)
    at Object.onInvokeTask (core.js:28497)
    at ZoneDelegate.invokeTask (zone-evergreen.js:405)
    at Zone.runTask (zone-evergreen.js:178)
    at drainMicroTaskQueue (zone-evergreen.js:582)

These are my first practices with Angular and I have no idea what are the "Lazy loaded modules" can anyone help me?

A: You are not supposed to call RouterModule.forRoot() multiple times in an application.
.forRoot() should be called only for the routes defined in the root module. For routes defined in any other routed modules you should call .forChild().
So, keep the .forRoot() in the AppRoutingModule module only, and change .forRoot(authRoutes) to .forChild(authRoutes) in the AuthRoutingModule. Do the same for the routes of libros and prestamos module.
Not directly related to the error:
With your current route definition, to navigate to the AuthComponent you'll need the route /auth/auth. Consider defining the routes in AuthRoutingModule as -
const authRoutes: Routes = [
    { path: 'login', component: LoginComponent},
    { path: 'forgotPassword', component: ForgotPasswordComponent},
    { path: 'signUp', component: SignUpComponent},
    { path: '', component: AuthComponent},
];

This will make 'auth' the default route for the auth module and display the AuthComponent with the route /auth. Follow similar approach for the other two lazy modules.

A: You can actually make it as lazy loaded module by doing child routes in parent route module.
Refer this : https://angular.io/guide/lazy-loading-ngmodules this might help you

A: Use RouterModule.forChild(authRoutes) in your AuthRoutingModule and other two Feature modules.
forRoot() should only be used with your root module


text:
Q: Single line (shorthand) background style? I'm following this guide: CSS background Property.
background: color image position/size repeat origin clip attachment initial|inherit;

I have this background CSS:
background-color: grey;
background-repeat: no-repeat;
background-size: contain;
background-position: center;
background-origin: content-box;

I'm trying to convert it to one line:
background: grey center / contain no-repeat content-box;

I need the background image and grey to be the background of the padding too.
Where am I going wrong?

div{
    width: 200px;
    height: 400px;
    background: grey center / contain no-repeat content-box;
    padding: 30px;
}

JSFiddle

A:
I need the background image and grey to be the background of the padding too.

If you need the background-image and grey to be the background of the padding too then you should set background-clip  as padding-box instead of content-box. content-box area does not include the padding or the border areas.

div {
  width: 200px;
  height: 400px;
  background: grey center / contain no-repeat padding-box;
  padding: 30px;
}

Note that I had mentioned background-clip and not background-origin in the above sentence. It is the background-clip that actually clips the background and not the background-origin. When only one box value is provided, both clip and origin are assumed to have the same value.

As per W3C Spec
If one  value is present then it sets both 'background-origin' and 'background-clip' to that value. If two values are present, then the first sets 'background-origin' and the second 'background-clip'.

Now the image goes to the edge, the image should be padded, and the color should not be, possible with separate rules but not one line.Link

If you mean to say that background-image is required (and must be restricted to content area only) whereas the color gets applied to padding area also as indicated in your question and comment here, the code provided in question will not work as-is.
When you use the shorthand background property to assign a value to the background-clip (like in question), you are giving it only a single value and so the same setting would apply to both the color and the image. This means both image and color will be clipped either to padding-box or content-box as applicable.

div {
  width: 200px;
  height: 400px;
  background: grey center / contain no-repeat content-box;
  padding: 30px;
}

You can still achieve what you need by using shorthand property but you have to use either of the following options:
Method 1: Assign  both the image and color in the same line like in the below snippet. The shorthand property works here because we are assigning clip values specifically for the color and the image.

div {
  width: 200px;
  height: 400px;
  background: url(https://upload.wikimedia.org/wikipedia/en/5/50/NES_Super_Mario_Bros.png) center / contain no-repeat content-box, grey center / contain no-repeat padding-box;
  padding: 30px;
}

Method 2: Assign separate values for the background-origin and background-clip properties like in below snippet (pointed out in comment by Karsten Buckstegge also).
This works because of two reasons:

*

*Background colors don't have a size, they fill up the entire area within the scope of the clip. So, color becomes available under padding area also.

*Background image's size is set to contain and as per spec this means that the image must be scaled to fit the background positioning area which is nothing but the background-origin as mentioned here. Since background-origin is only content-box and background-repeat is set to no-repeat, the image will not occupy the padding area.

div {
  width: 200px;
  height: 400px;
  background: grey center / contain no-repeat content-box padding-box;
  padding: 30px;
}

Note that the image must be specified before the color because the one that is specified first becomes the top-most layer. If you add color before image then color will hide the image.

A: This is a problem with the shorthand.
If you just set one  value in the end (in this case 'content-box'), it will set background-origin AND background-clip to that value. Therefor you have to set your background-clip after that to have it correct.
Final code then looks like this:
background: grey center / contain no-repeat content-box border-box;

See W3C background spec on that.


text:
Q: Django-adminfiles on Django 1.3: ERROR: "browser.link_text" is invalid I find django-adminfiles very useful. After I upgraded to Django 1.3 I get the text
ERROR: "browser.link_text" is invalid.

instead of the filepicker widget. On Django 1.2.5 it works correctly.
Has anybody else experienced this and maybe even found a solution?

A: Checking out the tip now works. I don't know exactly what caused it to work now and not then, but problem solved :-) .


text: Q: For the past few days I've been having problems with my reading list on safari on my iPad For the past few days I've been having problems with my reading list on safari on my iPad. When I go to my reading list, the search browser on the reading list is gone. Can someone tell me how to fix this?


text:
Q: Django 4.0.5: How to properly link static files into templates I'm following the CS50W course, and I noticed a weird behavior when going through the Django lecture. In summary, I was getting a 404 error when loading the styles.css file on one of the apps.
After checking the lecture source code, the main difference was that the lecture used the following to define STATIC_URL:
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_URL = '/static/'

And noticed that even Django's documentation defines STATIC_URL as STATIC_URL = 'static/', and somehow, adding that slash at the beginning fixes the 404 issues. Could someone explain to me why that is?
For reference, this is the project structure I have (the issue is within the app called newyear):
.
├── db.sqlite3
├── manage.py
├── myapp
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-38.pyc
│   │   ├── admin.cpython-38.pyc
│   │   ├── apps.cpython-38.pyc
│   │   ├── models.cpython-38.pyc
│   │   ├── urls.cpython-38.pyc
│   │   └── views.cpython-38.pyc
│   ├── admin.py
│   ├── apps.py
│   ├── migrations
│   │   ├── __init__.py
│   │   └── __pycache__
│   │       └── __init__.cpython-38.pyc
│   ├── models.py
│   ├── templates
│   │   └── myapp
│   │       ├── greet.html
│   │       └── index.html
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── newyear
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-38.pyc
│   │   ├── admin.cpython-38.pyc
│   │   ├── apps.cpython-38.pyc
│   │   ├── models.cpython-38.pyc
│   │   ├── urls.cpython-38.pyc
│   │   └── views.cpython-38.pyc
│   ├── admin.py
│   ├── apps.py
│   ├── migrations
│   │   ├── __init__.py
│   │   └── __pycache__
│   │       └── __init__.cpython-38.pyc
│   ├── models.py
│   ├── static
│   │   └── newyear
│   │       └── styles.css
│   ├── templates
│   │   └── newyear
│   │       └── index.html
│   ├── tests.py
│   ├── urls.py
│   └── views.py
└── prueba
    ├── __init__.py
    ├── __pycache__
    │   ├── __init__.cpython-38.pyc
    │   ├── settings.cpython-38.pyc
    │   ├── urls.cpython-38.pyc
    │   └── wsgi.cpython-38.pyc
    ├── asgi.py
    ├── settings.py
    ├── urls.py
    └── wsgi.py

Template linking the styles:
<!DOCTYPE html>

        {% load static %}
        <link rel="stylesheet" href="{% static 'newyear/styles.css' %}">
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Is it new year?</title>

        {% if newyear %}

Yes

        {% else %}

No

        {% endif %}

Side note: I know this might be a basic question and I can just use what works, which is adding the slash when defining STATIC_URL, however, I would really like to understand if this is the actual proper way of doing it, and if so, why the default settings.py file comes to set up in a way that it requires the addition of the slash.

A: Prior to Django 4.0 the default was, in fact, '/static/' as described by the docs.
There have been a couple of changelog entries regarding it (relatively) recently.

3.1 The STATIC_URL and MEDIA_URL settings set to relative paths
are now prefixed by the server-provided value of SCRIPT_NAME (or / if
not set). This change should not affect settings set to valid URLs or
absolute paths.
4.0 To allow serving a Django site on a subpath without changing
the value of STATIC_URL, the leading slash is removed from that
setting (now 'static/') in the default startproject template.

When I've changed the setting value in 4.0 to remove or add the forward slash, it hasn't made a difference, but if the course files settings.py has been changed from the default, it may be to accommodate some other bespoke changes that are part of the course.


text:
Q: Video.Js Problems Viewing Cross Browser I am completely new to VideoJs and media streaming on web pages, so please forgive me if the answer to this is obvious. I uploaded an MP4, OGV and WEBM file to www.sell2trade.com.au. If you view this page you will see that the video on the RHS works in Firefox, has an unsupported error in IE11 and plays the audio only in Chrome!! I downloaded the VideoJS sample and followed it diligently (I think!!) What on earth am I doing wrong!
Thanks for any help as tearing what little hair I have left out :)

A: The MP4 you're using doesn't appear to be compatible with Chrome. You can go directly to the mp4 url in chrome and see the same audio-only issue. You should try a different encoder, like Zencoder (paid service that I helped build) or Handbrake.
Also it looks like you swapped out the url for the video.js swf for a different swf that plays your video. That's not gonna work. You need to use the swf that's included with video.js.


text:
Q: SQLite ORDER BY month number in a 'yyyy-mm-dd' format I have a table with a column named call_date in the DATETIME format.
In this column I have the following date in this format yyyy-mm-dd.
What I want is to select the rows ordered by the month number in the column's value String.
Is there such SQLite function that does that??
I already tried strftime('%m', call_date) but ditn't work.
Thanks.

A: select * from myTable order by CAST(strftime('%m', call_date) AS INTEGER);

A: You can use strftime to get the month number and then order by that:
select ...
from your_table
order by strftime('%m', call_date)

A: In general I would try to avoid to order a result set by a calculated expression due to possible performance penalty. I would use an alternative approach: for example I would add MONTH column into the table and define a TRIGGER which will set the new column value. Then in queries you can order by a new column.


text:
Q: rails generate bootstrap layout with bootstrap-sass instead of twitter-bootstrap-rails I had to choose from bootstrap-sass and twitter-bootstrap-rails and I've opted for the first as per suggestions on the web.
However, I see that twitter-bootstrap-rails gem has some generators for application layout. Like,
rails g bootstrap:layout application fixed
rails g bootstrap:themed Posts

Which I find very good for kick-starting a project. But I don't find similar generators available in the bootstrap-sass gem. Running the command:
rails generate

doesn't show any generators like the previous ones.
Is there any way to have those layout using bootstrap-sass instead of using twitter-bootstrap-rails?
Thanks in advance.

A: There you can find a good way to generate theme for bootstrap-sass:
https://github.com/doabit/bootstrap-sass-extras
Basically you just:
 rails g scaffold Post title:string description:text
 rake db:migrate
 rails g bootstrap:themed Posts

A: I am using this gem, although I am unaware of generators for it.
I found a gem on GitHub which you might find useful:
https://github.com/decioferreira/bootstrap-generators
Alternatiely, you may simply define a new custom.css.scss file and start playing with the css of the whole app. And don't forget to add the bootstrap imports to your files!

A: There are also these (lesser known but probably worth a try) gems:
https://github.com/thrivesmart/bootscaf
https://github.com/leandroo/flexi_generators


text:
Q: Multiple radio type with a update query I have 1 form where I show a couple of records from my DB. In each row I want 2 radio buttons with a On and Off button.
Now I want to update a column "a_active" in my DB. With a answer 1=On 0=off. I have for each row a unique (name) token.
I tried couple of ways with a for each loop. But every time he chanced non of the records or he changed only the last one.
If I do only a Print_R after submitting my form I got the right array back. [rowid]= 1 or 0.
<form type="POST">
<input type="text" value="<?=$get_token?>" name="token[]" hidden/>

<input type="radio" name="actie[<?php echo $row["user_id"];?>]" value="1"<? if ($active === "1"){echo "checked";}?>/>On

<input type="radio" name="actie[<?php echo $row["user_id"];?>]" value="0"<? if ($active === "0"){echo "checked";}?>/>Off

<button class="btn btn-info" name="submit" type="submit">Save</button>
</form>

<?php

$id = $_POST['token'];
$code = $_POST['actie'];

foreach($_POST['actie'] as $count => $actie){

$query_core_user = "
UPDATE TableName
SET
a_active='".$code[$count]."'
WHERE user_id= '".$id[$count]."'";

$resultcore_user = $conn->query($query_core_user) or die($conn->error);
}
?>


text:
Q: Como pegar uma lista de objetos do JS no Controller C# MVC? Tenho um objeto com uma lista que vai me retornar 3 ou mais itens. Eu passo esse objeto assim:
 var jsonObjs = JSON.stringify(arrayObj);
  alert(jsonObjs);
  CarregaNotas(jsonObjs);

function CarregaNotas(notas) {
           jQuery.ajax({
                   type: "POST",
                    url: "/Expedicao/Minuta/GeraNotas",
                    dataType: "json",
                    data: notas,
                    success: function (data) {

                        }

                    });
                }
            });
        }

Como pegar essa lista no controller e passar ou varrer no Model ?
Pois para cada item eu terei que acrescentar um "And" ou "In" no "Select"

A: Primeiro você cria uma classe com as mesmas propriedades que a que você está passando no JSON.
public class Obj
{
    public int Quantidade { get; set; }
    public string Doc { get; set; }
    public string Serie { get; set; }
}

Na controller você pega a stringJson e converte em uma lista deste objeto.
var listaConvertida = JsonConvert.DeserializeObject<List<Obj>>(stringJson);

Para utilizar a classe JsonConvert é necessário ter o pacote NuGet Newtonsoft.Json instalado.


text:
Q: tbody is not filling up the width of the table but the content HTML:

Password Vault

                                Lorem ipsum dolor sit amet cons

                                <button type="button" class="btn btn-outline-light btn-sm">View</button>

CSS:
.t-transparent{
    background-color: transparent;
}

.half-opaque{
    opacity: 50%;
}

.nav-t{
    height: 70px;
}

.t-box{
    border-radius: 10px;
    padding: 10px;
}

.t-responsive{
    display: block;
    max-height: 300px;
    overflow-y: scroll;
}

tr{
    max-width: 778px;
}

I am using bootstrap 5, the issue is that in bootstrap's table class, there are lines under each row. But in this case the lines are dependent on the tbody, which wraps the content responsively. How do i fix this?

A: Why are you setting disaply:block to the
 element?
.t-responsive{
    display: block; // remove this
    max-height: 300px;
    overflow-y: scroll;
}

It is causing table to take full width of the viewport.
If you want
 to take full width as of parent container then set width:100%, etc.


text:
Q: Rake cucumber in Rails without dropping Database Running Cucumber Test in rails seems to by default drop and recreate Test database.
Was wondering if there is anywhere to not drop and recreate Test database during each test?
Using:
Rails 3.1
cucumber 1.1.o
cucumber-rails 1.1.1
Command used:
Rake cucumber

A: Cucumber does reset the test database after each scenario.  That's normally what you want, but sometimes you might want some persistent data that never gets reset.  If thats your case, you can modify how database_cleaner works in features/support/env.rb
Look for
DatabaseCleaner.strategy = :transaction

and replace it with your version of
DatabaseCleaner.strategy = :truncation, {:except => %w[directions locations]}

Where "directions locations" are the names of the tables you don't want cleared out ever.


text:
Q: $(this).load(function () { .... } ); not working along with JSTestDriver The source code adds a load event handler to an element using JQuery.
I am testing this using JSTestDriver.
The code looks something like this:-
       $(this).load(function () {
           alert("Foo");
       });

When I run the tests the alert("Foo") never happens.
If I change it to:-
       $(this).ready(function () {
           alert("Foo with Ready");
       });

The test works.
If however, the source code is executed separately within an HTML,
then it runs fine and I can get the alert("Foo") even when the event
is "load".
Is this a bug in JSTestDriver or am I doing something incorrectly? Do,
I have to wait till all the event handlers get triggered in the unit
tests. (Something on the lines of Thread.join()) ?
-Ajay

A: not sure why the load event is not being binded. an even better question is why jquery has two different methods with the same name (load() to bind an event, and load() to load some ajaxed content). here is an alternative syntax however that you migth want to try.
$(this).bind('load', handler);

if this works for you, please select the check mark next to this answer. i am trying to get enough rep to leave comments haha. thanks!
also, where is your binding code? is it possible that you are binding the event after the image has already loaded?

A: I believe your problem is not in the event binding, but in the meaning of $(this) in your code.
Could we get a broader scope?
One way to test would be to replace the $(this) with the actual selector for the element you are trying to trigger the event with.
or even right before the event binding, make this call to make sure the id of the element matches the id of the intended element.
alert($(this).attr('id'));


text:
Q: Add a repertory res/layout-large How Can I add the repertory res/layout-large with Eclipse ?
I don't find the way so if someone have the solution :)

A: You just create a folder called layout-large/ inside the resources folder.
I think it's File > New > Folder
You could also just copy and paste the existing layout folder and insert the new name when the Eclipse dialog pops up.
Normally, eclipse automatically generates it for you when you first create the project. Perhaps, you've initially created your project at an older api level.


text:
Q: Counting occurrences of edge color in prolog I have a graph defined like this:
edge(a1,c1,7,blue).
edge(a1,d1,3,blue).
edge(a1,l1,8,red).
edge(b1,c1,11,blue).
edge(d1,e1,2,red).
....

and so on.
I know how to write code to check if there's a path and to calculate weight and Shortest path. But what I want to do is to output 2 integers: one for no.of blue and one for no.of red edges in the path from X to Y.
In essence, I want something like this:
 colour(X,Y,C).

that either returns:
"blue" if all the edges in the path are blue(or Red for all red)
"false" if there are mixed edges.
or something like:
blue:5 red:2 if there are 7 edges
I'm new to Prolog and it's very confusing how to create a "counter" type variable.

A: For your edge/4 predicate there might be two more ways to count the number of edges of the same color:
1) using predicates for finding all solutions, like findall/3:
opt1 :-
    findall(_,edge(_,_,_,blue),ListBlue),   % collect all blue edges in ListBlue
    length(ListBlue,L),                     % find out the length of ListBlue
    display('blue: '),display(L),nl.        % print output

The _ symbol stands for an "anonymous variable", a variable for which bindings you do not care.
The disadvantage of this solution is that it is not resource-wise: first you pass through all edge/4 facts (inevitable cost), then you use additional memory to store the ListBlue list and then you have to traverse this list.
2) using side effects (see below) and dynamic predicates (predicates whore clauses can be added/deleted on run-time) in a failure-driven loop:
Side effects are some extra things that you can do when transitioning from one program state to another, like printing text (side effect) during an operation of assigning a value to a variable (direct effect).
:- dynamic counter/2.    % a dynamic predicate to be used as a mutable counter

opt2 :-
    retractall(counter(_,_)), % \_ delete any old value of a counter from previous
    asserta(counter(blue,0)), % /  runs and set it to 0 for the blue edges
    %
    count_edges(blue,NBlue),
    display('blue: '),display(NBlue),nl.

 count_edges(Col,_N) :-
    edge(_,_,_,Col),          % locate an edge of desired color Col
    counter(Col,N),           % \
    N1 is N + 1,              %  \_ update the counter value
    retract(counter(Col,N)),  %  /
    asserta(counter(Col,N1)), % /
    fail.                     % fail to force backtracking
count_edges(Col,N) :-
    counter(Col,N).           % read the current counter value

Forced backtracking allows for exploring all possible solutions to the edge(_,_,_,Col) query thus finding all blue edges.
I've tried the code online and it worked.

A: I would like to post a few benchmarks that may help to compare the two nice solutions posted by @s0nata. This is an additional answer mostly because it is too long for a comment.
Prolog is a nice language to devise and run benchmarks, also because a large set of benchmarks can be readily described by a single query.
Ad hoc benchmarks
For example, let us benchmark option 1, which uses findall/3, using the following query:

?- length(_, E),
   N #= 2^E,
   portray_clause(E),
   forall(between(1, N, _), assertz(edge(x, y, 1, blue))),
   time(opt1),
   false.

Note that we are using assertz/1 to create ever more facts for edge/4. This is quite inelegant, and it means that we must restart Prolog between such runs or clear the database again in order to start from a clean slate. I leave making this more elegant as an exercise.
In any case, this results in the following output:

0.
'blue: '1
% 3,454 inferences, 0.001 CPU in 0.009 seconds (16% CPU, 2364134 Lips)
1.
'blue: '3
% 22 inferences, 0.000 CPU in 0.000 seconds (76% CPU, 785714 Lips)
2.
'blue: '7
% 26 inferences, 0.000 CPU in 0.000 seconds (74% CPU, 1181818 Lips)
3.
'blue: '15
% 34 inferences, 0.000 CPU in 0.000 seconds (77% CPU, 1478261 Lips)
4.
'blue: '31
% 50 inferences, 0.000 CPU in 0.000 seconds (79% CPU, 1851852 Lips)

... lines omitted ...

21.
'blue: '4194303
% 4,194,322 inferences, 1.301 CPU in 1.439 seconds (90% CPU, 3224179 Lips)

For comparison, we get with option 2:

?- length(_, E),
   N #= 2^E,
   portray_clause(E),
   forall(between(1, N, _), assertz(edge(x, y, 1, blue))),
   time(opt2),
   false.
0.
'blue: '1
% 3,448 inferences, 0.001 CPU in 0.009 seconds (16% CPU, 2347175 Lips)
1.
'blue: '3
% 20 inferences, 0.000 CPU in 0.000 seconds (81% CPU, 769231 Lips)
2.
'blue: '7
% 32 inferences, 0.000 CPU in 0.000 seconds (80% CPU, 1142857 Lips)
3.
'blue: '15
% 56 inferences, 0.000 CPU in 0.000 seconds (84% CPU, 888889 Lips)
4.
'blue: '31
% 104 inferences, 0.000 CPU in 0.000 seconds (85% CPU, 1350649 Lips)

... lines omitted ...

21.
'blue: '4194303
% 12,582,920 inferences, 10.100 CPU in 10.305 seconds (98% CPU, 1245782 Lips)

More beautiful comparison
To reason more elegantly about such benchmarks, we will now slightly change opt1/0 and opt2/0 such that these predicates do not mess up our own benchmark output. That is, we will remove all side effects from these predicates, and thus also make testing these predicates a lot easier by making the actual counter available as an argument. We can write for example:

opt1(L) :-
    findall(_,edge(_,_,_,blue),ListBlue),
    length(ListBlue, L).

opt2(NBlue) :-
    retractall(counter(_,_)),
    asserta(counter(blue,0)),
    count_edges(blue, NBlue).

In addition, let us introduce the following auxiliary definition to obtain the wall time it takes to execute a goal. This may include slight perturbations due to other tasks, garbage collection etc., but importantly takes into account how much actual time (in seconds) it takes to execute the goal:

wall_time(Goal, T) :-
        statistics(walltime, [T0|_]),
        Goal,
        statistics(walltime, [T1|_]),
        T is (T1 - T0)/1000.

Let us now post for example:

?- format("~tE~t~5+~tNum~t~15+~tT1~10+~tT2~10+~n"),
   length(_, E),
   N #= 2^E,
   forall(between(1, N, _), assertz(edge(x, y, 1, blue))),
   wall_time(opt1(Num), T1),
   wall_time(opt2(Num), T2),
   format("~t~w~5+~t~w~15+~t~2f~10+~t~2f~10+~n", [E,Num,T1,T2]),
   false.

This results in the following table:

   E        Num              T1        T2
     0              1      0.00      0.00
     1              3      0.00      0.00
     2              7      0.00      0.00
     3             15      0.00      0.00
     4             31      0.00      0.00
     5             63      0.00      0.00
     6            127      0.00      0.00
     7            255      0.00      0.00
     8            511      0.00      0.00
     9           1023      0.00      0.00
    10           2047      0.00      0.01
    11           4095      0.00      0.01
    12           8191      0.00      0.03
    13          16383      0.01      0.04
    14          32767      0.02      0.08
    15          65535      0.02      0.16
    16         131071      0.04      0.32
    17         262143      0.09      0.64
    18         524287      0.18      1.31
    19        1048575      0.37      2.55
    20        2097151      0.74      5.14
    21        4194303      1.44     10.29

Please also take these actual benchmarks into account when comparing the two solutions. In Prolog, very often, impurities also cause a lot of inefficiency.
Note how we also use this opportunity to verify that both options yield the same result!

A: with the DB fragment you show, and library(aggregate):
?- aggregate(count,X^Y^W^edge(X,Y,W,C),N).
C = blue,
N = 3 ;
C = red,
N = 2.


text:
Q: Get a text from Html string using JavaScript Need to extract one key from a string containing HTML doc using JavaScript /NodeJs.
I am getting a HTML Page as response of one service which includes a key, which need to be extracted, the key is inside a  tag and the page is heavily nested , even after converting to JSON also didn't help.
Tried with regular expression that also not fetching all results (since there are many matches with  tag).
The key in  tag is like the following:
<script>
$function(){
//some codes
app.init({
//some code
access : {"AccessKey": "dwdfsfcnoidxjbvukv"}

});

//some code
</script>

A: Use this regex /\{"AccessKey":(.*)\}/  which I think suitable for this problem.
 var data = `<script>
    $function(){
    app.init({
    access : {"AccessKey": "dwdfsfcnoidxjbvukv"}
    });
    </script>`;

    var result = data.match(/\{"AccessKey":(.*)\}/);

    console.log(result[1]);


text:
Q: Найти установленные программы Как найти все установленные в заданный каталог программы?
Каталог является подкаталогом несистемного диска, в разных его подкаталогах находятся установленные программы, но большинство из них устанавливалось не в текущей системе. Нужно выбрать только те программы, которые установлены именно в данной системе. Часть программ 32-битная (грабли для wmic product get).
Нужно получить список названий и путей к exe'шникам в виде txt-файла.

A: В Windows нет точного определения термина "установленная программа". Можно понимать это как программа, которая содержится в пункте "Programs and Features" панели управления, и может быть удалена средствами системы. Однако существует огромное количество программ, которые под это определение не подпадают. Еще заметим, что большинство программ включают несколько .exe и .dll, так что часто бывает непросто вообще понять где там "программа".
Можно определить это более широко как программу, о которой существуют какие-то записи в системе, но опять же существует масса программ, причем от именитых фирм, которые после удаления системными средствами оставляют после себя тонны мусора в реестре и не только.
Если исходить из того, что каждая программа содержится в индивидуальном каталоге (в противном случае концов вообще не найти), то алгоритм поиска может быть таким:
1) Проверить ссылки в каталог программы из подключей разделов HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\ и HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\.
2) Проверить ссылки в каталог программы из списка HKEY_CLASSES_ROOT\CLSID. Ссылка обычно в подключе InprocServer32, но есть и другие возможные подключи, так что надо смотреть все.
3) Через интерфейс IShellLinkкомпонента CLSID_ShellLink загрузить и распарсить все файлы .lnk в деревьях каталогов c:\ProgramData\Desktop\, c:\Users\<user>\Desktop\, c:\ProgramData\Start Menu\ и c:\Users\<user>\Start Menu\. Конкретно нужно вызывать метод GetPath и смотреть путь исполняемого файла.
Это самые важные признаки - программы, которые внесли себя в список Uninstall, или имеют зарегистрированные COM-серверы, или имеют доступные ярлыки, безусловно относятся к категории "установленных". Для поиска программ, "установленных" в более широком смысле, нужно идти дальше:
4) Проверить прочие ключи HKEY_CLASSES_ROOT опять же на ссылку в каталог программы. В основном там ищутся зарегистрированные расширения файлов, но могут быть и прочие ссылки.
5) В разделах HKEY_LOCAL_MACHINE\SOFTWARE\ и HKEY_CURRENT_USER\SOFTWARE\ ищутся подключи 1-го или 2-го уровней, совпадающие с именем какого-либо из .exe файлов в каталоге программы. Нет гарантии, что раздел программы будет называться именно так, но вероятность большая.
В реестре могут быть и другие ссылки на программу, например, стоит посмотреть список исключений фаерволла в разделе HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\services\SharedAccess\Parameters\FirewallPolicy\FirewallRules.
Ну и напоследок
6) В подкаталогах c:\Users\<user>\AppData\Local\ и c:\Users\<user>\AppData\Roaming\ искать папки, совпадающие с именем какого-либо из .exe файлов в каталоге программы.
Разумеется, ни один из этих признаков не дает гарантии, что программа действительно установлена и доступна. Она может быть давно удалена. Сходу не припомню ни одной программы от крупных фирм, которая бы чисто себя удаляла. Оставляют после удаления практически что угодно, вплоть до регистрации COM серверов. Microsoft немного получше чем прочие, но тоже мусор оставляет.

A: В PowerShell запустить команду (для поиска, например каталогов, содержащих слово VMWare)
wmic product get name,InstallLocation| Select-String -Pattern "VMWare"

Результат можно распарсить по табуляции
C:\Program Files (x86)\VMware\Infrastructure\  VMware vSphere Client 5.5

В выборку попадут, разумеется, программы, установленные средствами Windows


text:
Q: How to loop in Kivy using kv language? I am trying to create an app of a game that i play with my friends.
I have this code and i want to loop the list "jugadores" in FourWindow.
import kivy
kivy.require('1.9.0')

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang.builder import Builder
from kivy.core.window import Window

Window.size = (300, 1280)

Jugadores = []
CantidadDeCartas = 0
Objetivo = 0
Manos = 0

class MainWindow(Screen):

    cartas = ObjectProperty(None)
    objetivo = ObjectProperty(None)

    def btn(self):
        CantidadDeCartas = int(self.cartas.text)
        Objetivo = int(self.objetivo.text)
        self.cartas.text = ""
        self.objetivo.text = ""

class SecondWindow(Screen):

    cartas = ObjectProperty(None)
    objetivo = ObjectProperty(None)

class ThirdWindow(Screen):

    def btn3(self):
        Nombre = self.njugador.text
        Jugadores.append(Nombre)
        self.njugador.text = ""
        self.jugador.text = str(Jugadores)
        print(Jugadores)

    def btn4(self):
        self.njugador.text = ""
        Jugadores.clear()
        self.jugador.text = ""

    def btn5(self):
        Jugadores.reverse()
        if len(Jugadores) != 0:
            largo = Jugadores.count(self)
            Jugadores.pop(largo)
            Jugadores.reverse()
            print(Jugadores)
            self.jugador.text = str(Jugadores)
        else:
            self.jugador.text = ""
class FourWindow(Screen):
    pass
class WindowManager(ScreenManager):
    pass

kv = Builder.load_file("tim4.kv")

class tim4App(App):
    def build(self):
        return kv

if __name__ == "__main__":
    tim4App().run()

KIVY
WindowManager:
    MainWindow:
    SecondWindow:
    ThirdWindow:
    FourWindow:

<MainWindow>:

    name: "main"
    cartas : cartas
    objetivo : objetivo

    GridLayout:
        cols:1

        GridLayout:
            cols: 2
            Label:
                text:"Cartas: "
            TextInput:
                id: cartas
                multiline: False
                input_type: "number"
                input_filter: "int"
            Label:
                text:"Objetivo: "
            TextInput:
                id: objetivo
                multiline: False
                input_type: "number"
                input_filter: "int"
        Button:
            text: "Siguiente>>"
            on_release:
                app.root.current= "second"
                root.manager.screens[1].ids.carta.text = "Se juega con " + root.ids.cartas.text + " cartas"
                root.manager.screens[1].ids.objetivo.text = "Se juega a " + root.ids.objetivo.text
                root.manager.screens[3].ids.iduno.text = "Se juega con " + root.ids.cartas.text + " cartas"
                root.manager.screens[3].ids.iddos.text = "Se juega a " + root.ids.objetivo.text
                root.btn()
                root.manager.transition.direction="left"
<SecondWindow>:
    name: "second"
    carta: carta
    objetivo: objetivo

    GridLayout:
        cols:1
        size: root.width, root.height
        pos: 0, 0

        Label:
            id: carta
            text: ""
        Label:
            id: objetivo
            text: ""

        GridLayout:
            cols:2

            Button:
                text: "Ir Atrás"
                on_release:
                    app.root.current= "main"
                    root.manager.transition.direction="right"

            Button:
                text: "Elegir Jugadores"
                on_release:
                    app.root.current= "third"
                    root.manager.transition.direction="left"

<ThirdWindow>
    name: "third"
    njugador: njugador
    jugador: jugador
    empezar: empezar

    GridLayout:
        cols: 2
        orientation: "horizontal"

        GridLayout:
            cols:1
            TextInput:
                id: njugador
                text: "quien juega"
                multiline: False
            GridLayout:
                cols:3

                Button:
                    text: "Agregar Jugador"
                    on_press: root.btn3()
                Button:
                    text:"Borrar Último"
                    on_press: root.btn5()
                Button:
                    text:"Limpiar todo"
                    on_press: root.btn4()

            GridLayout:
                cols:1
                orientation: "vertical"

                Label:
                    id : jugador
                    text: ""
                Button:
                    id: empezar
                    text:"Empezar Juego"
                    on_release:
                        app.root.current= "four"
                        root.manager.transition.direction="left"

<FourWindow>
    name: "four"
    iduno: iduno
    iddos: iddos
    idtres: idtres

    GridLayout:
        orientation:"horizontal"
        rows: 3

        Label:
            id: iduno
            text:""
        Label:
            id: iddos
            text:""
        Label:
            id: idtres
            text:"manos"

On FourWindow i want loop the list "Jugadores" to create labels. Theres is anyway of doing that through kv lenguage? Or how to do it on python file?

A: You can do it with an on_enter() method in your FourWindow class, or you can do it in kv by defining the on_enter method in kv. To do this, modify your FourWindow rule in the kv:
#: import Label kivy.uix.label.Label
<FourWindow>
    name: "four"
    iduno: iduno
    iddos: iddos
    idtres: idtres

    on_pre_enter: for p in self.players: l=Label(text=p); grid.add_widget(l);

    GridLayout:
        id: grid   # needed for the above code
        rows: 3

        Label:
            id: iduno
            text:""
        Label:
            id: iddos
            text:""
        Label:
            id: idtres
            text:"manos"

And modify your definition of the FourWindow class:
class FourWindow(Screen):
    players = ObjectProperty(Jugadores)

The players object is just to provide access to the Jugadores list.


text:
Q: xlsxwriter chart grid spacing I'm currently trying to create charts in excel via the xlsxwriter python module. I've gotten it to graph just fine, however I'm trying to get it to look nice. I've been able to add major and minor gridlines, change their line width, and dash type, but I can't figure out how to modify their spacing. (e.g., minor lines on every unit with major lines on every 5 units)
As far as I can tell, it's not an option, but I thought I'd throw this out there to see if an expert had a trick (I've just started using this module) and/or put this out there for people looking for this option in the future.
Here's the code I'm working with right now:
chart = wb.add_chart({'type': 'line'})
chart.add_series({
    'name': 'Sheet1!{:}'.format(xlsxwriter.utility.xl_rowcol_to_cell(0, data_column)),
    'categories': ['Sheet1', 1, time_column, num_of_data_pts, time_column],
    'values': ['Sheet1', 1, i, num_of_data_pts, data_column],
    'line': {'color': 'blue'},
})
chart.set_x_axis({
    'num_font': {'italic': True},
    'major_gridlines': {
        'visible': True,
        'line': {'width': 1}
    },
    'minor_gridlines': {
        'visible': True,
        'line': {'width': 1, 'dash_type': 'dash'}
    },
})
chart.set_legend({'position': 'none'})
ws.insert_chart(5, 5, chart)

Also I've tried using the 'major_unit' attribute, but it appears that is something to do with if the x axis is a date only.

A:
I can't figure out how to modify their spacing. (e.g., minor lines on every unit with major lines on every 5 units

I'm not sure if that is possible in Excel.
As explained in the XlsxWriter docs Excel treats Category and Values chart axes differently. The X axis for a line chart is a category axis and for text and numbers it is only possible to change the interval between the labels/ticks. You can verify that yourself in Excel.
That feature is also supported in XlsxWriter using the axis interval_unit.
Probably you need to format the chart as a scatter chart which has value axes for X and Y and which allows you to control the spacing


text:
Q: When and Where Angular CLI Has Been Installed Locally? After installing Node.js, I imported an Angular project from GitHub on VSCode, then I run the following usual commands successively:
npm install                      //This one created node_modules folder, but I don't have angular cli yet, because ng is still not recognized!
npm install -g @angular/cli      //Then after the installation of the global CLI finished..
ng --version

Now I get the following warning:
Your global Angular CLI version (7.3.5) is greater than your local version (7.3.2). The local Angular CLI version is used.
To disable this warning use "ng config -g cli.warnings.versionMismatch false".

This question is trying to explain that warning, but they are not explaining where and when the local CLI is installed, at least in my case here.
Please give some clarification, thanks.
Edit
Here are the dependencies in pakage.json, according to your comments, they are related, but what is the usual scenarios if there is no explicit CLI version definition?.
    "dependencies": {
    "@angular/animations": "^7.2.6",
    "@angular/cdk": "^7.3.3",
    "@angular/common": "~7.2.0",
    "@angular/compiler": "~7.2.0",
    "@angular/core": "~7.2.0",
    "@angular/forms": "~7.2.0",
    "@angular/material": "^7.3.3",
    "@angular/platform-browser": "~7.2.0",
    "@angular/platform-browser-dynamic": "~7.2.0",
    "@angular/router": "~7.2.0",
    "angular-formio": "^3.10.2",
    "bootstrap": "^4.3.1",
    "bootswatch": "^4.3.1",
    "core-js": "^2.5.4",
    "font-awesome": "^4.7.0",
    "jquery": "^3.3.1",
    "rxjs": "~6.3.3",
    "tslib": "^1.9.0",
    "zone.js": "~0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.13.0",
    "@angular/cli": "~7.3.1",
    "@angular/compiler-cli": "~7.2.0",
    "@angular/language-service": "~7.2.0",
    "@types/node": "~8.9.4",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "~4.5.0",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~3.1.1",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.11.0",
    "typescript": "~3.2.2"
  }

A: You have cloned an angular project from github, it has a file named package.json, which tells npm which packages to install when you do npm install.
So, in your package.json, please lookup for "@angular/cli" in devDependencies,  you will find the version written something like this
"@angular/cli": "^7.3.2"

This is the local version of @angular/cli.
when you ran npm install, it installed that version(7.3.2) of Angular CLI, AKA local version.
but when you ran npm install -g @angular/cli, it automatically installed the latest version globally (the -g flag in the install command). And, the latest version was 7.3.5. Hence, it is giving the warning that the local version is not same and it is using the local version of Angular CLI

A: The global version is installed with npm install -g @angular/cli@latest.
The local version is inside of your project in node_modules under node_modules/@angular/cli. You have to update your package.json to the same version as your global version.
The @angular/cli is installed locally when you run ng new appName.
And it is installed with every run of npm install in your project root.
To update it you need to change this line in package.json
...
"@angular/cli": "~7.3.2",
...

To this
...
"@angular/cli": "~7.3.5",
...

And then run npm install