text:
Q: PHP sending form accorded to a url token i'm learning php since a week from now, and one of my project is to make a form that adapt fields about a url token.
For example: if the user is a student token will be index.php?token=e3
the user is a professionnal will be index.php?token=p4
i'm realy happy because everything is working, except the last part.. the POST of the user informations in my db called "test" which as a single table called form and i the db got good settings, the table is well designed with int-varchars, anything that can handle the datas.
i would like to atleast make it work for e3 then i'll be able to adapt for the others, that's why i give you an example of what i did since now, maybe i'm missing something important but i got no php errors, the datas are not sending when i press send button and the page refresh as index.php
if you guys got an idea, you don't need to tell me realy how to do, i just need someone better than me that could tell me "well you should look at sessions" or something else that is wrong because i have no clue to debug i'm stuck since yesterday on this problem.
Here is my code remember if you want to make it appear clearly you need to specify the token "?token=e3"
thank you in advance everyone who'll help me:
<?php

session_start();

$connectionSql = array(
                        "hote" => "localhost",
                        "base" => "test",
                        "user" => "root",
                        "pwd" => "",
                        );
try {
    $db = new PDO("mysql:host=" . $connectionSql["hote"] . ";dbname=" . $connectionSql["base"],
                    $connectionSql["user"], $connectionSql["pwd"]);
    /*var_dump($db);*/
    $db->exec("set names utf8");
} catch  (PDOException $e) {
    echo $e->getMessage();
    die();
}

$getWholeUrl = "http://".$_SERVER['HTTP_HOST']."".$_SERVER['REQUEST_URI']."";
$url = substr($getWholeUrl , -2);

if ($url=="e3" && isset($_POST['send'])) {
    if(!empty($_POST['gender']) AND !empty($_POST['name']) AND
        !empty($_POST['firstname']) AND !empty($_POST['mail']) AND
        !empty($_POST['phone']) AND !empty($_POST['speciality']) AND
        $_POST['speciality'] != "Votre spécialité" AND !empty($_POST['year']) AND
        !empty($_POST['birthday']) AND !empty($_POST['school']) AND
        !empty($_POST['zipcode']) AND !empty($_FILES['attachment']) AND
        !empty($_FILES['pi']))
    {
        $gender = $_POST['gender'];
        $name = htmlspecialchars($_POST['name']);
        $firstname = htmlspecialchars($_POST['firstname']);
        $mail = htmlspecialchars($_POST['mail']);
        $phone = $_POST['phone'];
        $speciality = $_POST['speciality'];
        $year = $_POST['year'];
        $birthday = $_POST['birthday'];
        $school = htmlspecialchars($_POST['school']);
        $zipcode = htmlspecialchars($_POST['zipcode']);
        $filename = $_FILES['attachment']['name'];
        $idname = $_FILES['pi']['name'];

        $reqmail= $db->prepare("SELECT * FROM `form` WHERE mail = ?");
        $reqmail->execute(array($mail));
        $mailexist = $reqmail->rowCount();
        if($mailexist == 0) {
            if (filter_var($mail, FILTER_VALIDATE_mail)) {
                if (is_numeric($phone) == true && preg_match('/^\d{10}$/', $phone)) {
                    if (is_numeric($year) == true) {
                        if(!empty($_FILES['attachment']['name']) && !empty($_FILES['pi']['name'])){

                            if ($_FILES['attachment']['error'] == 0 && $_FILES['attachment']['size'] < 2097152 && $_FILES['pi']['error'] == 0 && $_FILES['pi']['size'] < 2097152) {

                                $extension = pathinfo($filename);
                                if ($extension["extension"] == "jpg" || $extension["extension"] == "png" || $extension["extension"] == "pdf") {
                                    $extensionid = pathinfo($idname);
                                    if($extensionid["extension"] == 'jpg' || $extensionid['extension'] == "png" || $extensionid['extension'] == "pdf") {

                                        $req = $db->query('SELECT MAX(id) FROM form');

                                        $res = $req->fetchColumn();

                                        $res += 1;

                                        if(!is_dir('img/')) {
                                            mkdir('img/', 0755);
                                        }

                                        if(!is_dir('img/img' . $res . '/')){
                                            mkdir('img/img' . $res . '/', 0755);
                                        }

                                        move_uploaded_file($_FILES['attachment']['tmp_name'], 'img/img' . $res . '/' . $res . $filename);
                                        move_uploaded_file($_FILES['pi']['tmp_name'], 'img/img' . $res . '/' . $res . 'id' . $idname);

                                        $require = $db->prepare("INSERT INTO `form` (`gender`, `name`, `firstname`, `mail`, `phone`, `speciality`, `year`, `birthday`, `school`, `zipcode`, `attachment`, `idcard`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

                                        $require->execute(array($gender, $name, $firstname, $mail, $phone, $speciality, $year, $birthday, $school, $zipcode, $res . $filename, $res . $idname));
                                        $succes = "Form as been sent !";
                                    }else{
                                        $erreur = "idcard's extension isn't admitted.";
                                    }
                                }else{
                                    $erreur = "attachment's extension isn't admitted.";
                                }
                            }else{
                                $erreur = "File too big - Max 2Mo";
                            }
                        }else{
                            $erreur = "Please join the two required attached files.";
                        }
                    } else {
                        $erreur = $year . " isn't a valable year !";
                    }
                } else {
                    $erreur = $phone . " isn't a right phone number !";
                }
            }else{
                $erreur = "invalid mail";
            }
        }else{
            $erreur = "mail already exists !";
        }
    }else{
        $erreur = "please complete all the fields !";
    }
}

?>

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Form</title>
    <link rel="stylesheet" type="text/css" href="css/styles.css">
    <link rel="icon" type="image/icon-x" href="images/favicon.ico">

            <?php
            if(isset($succes))
            {
                echo "
".$succes."
";
            }
            if(isset($erreur))
            {
                echo "
".$erreur."
";
            }
            ?>

                    <form method="post" action="index.php" enctype="multipart/form-data">

                            <input type="radio" name="gender" id="gender" value="1"/>
                            Woman
                            <input type="radio" name="gender" id="gender" value="2"/>
                            Man
                            <input type="radio" name="gender" id="gender" value="3"/>
                            Unicorn

                                <input type="text" name="name" id="name"/ required>
                                name

                                <input type="text" name="firstname" id="firstname"/ required>
                                firstname

                                <input type="mail" name="mail" id="mail"/ required>
                                mail

                                <input type="tel" name="phone" id="phone" required>
                                phone

                            <?php
                                $getWholeUrl = "http://".$_SERVER['HTTP_HOST']."".$_SERVER['REQUEST_URI']."";
                                if(substr($getWholeUrl , -2)=='e3'){
                                $listespeciality = array("your speciality",
                                                "Fitness",
                                                "Bodybuilding",
                                                "Flower-eating");
                                echo "<select name=\"speciality\" id=\"speciality\">";
                                foreach ($listespeciality as $indice => $speciality) {
                                    echo "<option value=\"";
                                    echo $speciality;
                                    echo "\">";
                                    echo $speciality;
                                    echo "</option>";
                                }
                                echo "</select>";
                            }
                            else {
                                echo "
"."<input type=\"text\" name=\"secteur\" id=\"secteur\">"."activity"."
";
                            }
                            ?>

                                <input type="text" name="year" id="year" required>
                                Year of activity

                            <?php
                            $getWholeUrl = "http://".$_SERVER['HTTP_HOST']."".$_SERVER['REQUEST_URI']."";
                            if(substr($getWholeUrl , -2)=='e3'){
                                echo "

                                <input type=\"text\" name=\"school\" id=\"school\" required>
                                school

";}
                            else if(substr($getWholeUrl , -2)=='p4' || substr($getWholeUrl , -2)=='o1') {
                                echo "

                                    <input maxlength=\"14\" type=\"text\" name=\"idcode\" id=\"idcode\" required>
                                    identity code

";} ?>

                            <?php
                                $getWholeUrl = "http://".$_SERVER['HTTP_HOST']."".$_SERVER['REQUEST_URI']."";
                                if(substr($getWholeUrl , -2)=='a2') {
                                $listmedia = array("Blog",
                                "Facebook",
                                "Instagram",
                                "Own website");
                                 echo "<select name=\"media\" id=\"media\">";
                                         foreach ($listmedia as $indice => $media) {
                                             echo "<option value=\"";
                                             echo $media;
                                            echo "\">";
                                            echo $media;
                                            echo "</option>";
                                         }
                                            echo "</select>";
                                         } ?>

                            <?php $getWholeUrl = "http://".$_SERVER['HTTP_HOST']."".$_SERVER['REQUEST_URI']."";
                            if(substr($getWholeUrl , -2)=='o1' || substr($getWholeUrl , -2)=='p4'){
                                echo "

                                <input type=\"text\" name=\"company\" id=\"company\" required/>
                                company

";}
                            else if (substr($getWholeUrl , -2)=='a2') {
                                echo "

                                <input type=\"text\" name=\"url\" id=\"url\" required/>
                                Link of media

";}
                            else if (substr($getWholeUrl , -2)=='e3'){
                                echo "

                                <input type=\"text\" name=\"zipcode\" id=\"zipcode\" required/>
                                Zipcode

"
                            ;}?>
                            <?php if (substr($getWholeUrl , -2)=='e3' || substr($getWholeUrl , -2)=='a2' || substr($getWholeUrl , -2)=='p4'){
                                echo "
                            <input type=\"Date\" name=\"birthday\" id=\"birthday\" min=\"1930-01-01\" max=\"2020-12-29\" value=\"2000-01-01\">
                            birthday
                            ";}
                            else echo "

"
                            ?>
                            <?php if (substr($getWholeUrl , -2)=='e3') {
                            echo "

"; if(isset($error)) echo $error; echo "

                                    <input type=\"file\" name=\"attachment\" id=\"attachment\" value=\"\"/>
                                    attachment:

"; }
                            else if (substr($getWholeUrl , -2)=='p4' || substr($getWholeUrl , -2)=='a2') { echo "

";}
                            else if (substr($getWholeUrl , -2)=='o1') { echo "

";}
                            ?>

<?php if(isset($error)) echo $error;?>

                                    <input type="file" name="pi" id="pi" value=""/>
                                    identity card :

                            <input type="submit" id="send" name="send" value="Send"/>

                    </form>


text:
Q: JPA entries are not created or retrieved I'm having program that creates JPA entries with the entity manager.
during the process I don't get any errors.
...
factory = Persistence.createEntityManagerFactory("perst");
EntityManager entityManager = factory.createEntityManager();

entityManager.getTransaction().begin();
entityManager.persist(object);
entityManager.getTransaction().commit();

...

entityManager.close();

I have created a program like follows to read the data but it doesn't return any data,
the query returns empty. What could be the reason ?
This is the program to read the data:
static List<String> classList = new ArrayList<String>();
    private static EntityManagerFactory factory;

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        factory = Persistence.createEntityManagerFactory("perst");
        EntityManager entityManager = factory.createEntityManager();

        classList.add("LeaveRequest");
        classList.add("person");

        for (Object classOjc : classList) {

            String className = classOjc.toString();

            Query query = entityManager.createQuery("SELECT p FROM " + className + " p");

            @SuppressWarnings("rawtypes")
            List resultList = query.getResultList();

            System.out.println(resultList.size());

            for (Object result : resultList) {

                System.out.println(result.toString());
            }
        }
    }

the xml persist is:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
    xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
        http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">

    <persistence-unit name="perst" transaction-type="RESOURCE_LOCAL">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <class>LeaveRequest</class>
        <class>person</class>
        <properties>
            <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver" />
            <property name="javax.persistence.jdbc.url"
                value="jdbc:derby:/home/vogella/databases/simpleDb;create=true" />
            <property name="javax.persistence.jdbc.user" value="Sales" />
            <property name="javax.persistence.jdbc.password" value="" />
            <!-- EclipseLink should create the database schema automatically -->
            <property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
            <property name="eclipselink.ddl-generation.output-mode"
                value="database" />
            <property name="eclipselink.logging.level" value="SEVERE" />
            <property name="eclipselink.logging.exceptions" value="true" />
        </properties>
    </persistence-unit>
</persistence>

A: You configured eclipselink to drop and recreate the schema each time the app is started:
<property name="eclipselink.ddl-generation" value="drop-and-create-tables" />

So obviously, if you run a first application that persists some entries, and then a second application which tries to read what the first one has written, you won't find anything anymore, since eclipselink drops everything and recreates the schema every time.

redpajama_set_name: RedPajamaStackExchange


text:
Q: First item in gridview not showing? I am creating a chess app and my board gets drawn but the first square with the black Rook doesn't appear until after the first move. I will attach pictures below as well as my xml code and my code for the adapter which creates the gridView. But does anyone have any idea as to why the first square won't show. I'm assuming it is because my view has no size until my getView method is invoked but I do not know how to fix that. If someone could please explain how to fix this, that'd be awesome.
Board Before First Move
Board After First Move
Adapter Code:
public class SquareAdapter extends BaseAdapter {

    private Context context;
    private Piece[][] board;

    public SquareAdapter(Context context, Piece[][] board) {
        this.context = context;
        this.board = board;
    }

    @Override
    public int getCount() {
        return 64;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {

        ImageView view;
        if (convertView == null)
        {

            view = new ImageView(context);
            int size = parent.getWidth()/8;

            view.setLayoutParams(new GridView.LayoutParams(size,size));

            int col = position/8 %2;

            if (col == 0)
            {
                if (position%2 == 0)
                    view.setBackgroundColor(Color.parseColor("#DFAE74"));
                else
                    view.setBackgroundColor(Color.parseColor("#6B4226"));
            }
            else
            {
                if (position%2 == 0)
                    view.setBackgroundColor(Color.parseColor("#6B4226"));
                else
                    view.setBackgroundColor(Color.parseColor("#DFAE74"));
            }

            Piece p = board[position/8][position%8];

            if(p!= null)
            {
                if(p.isWhite)
                {
                    view.setImageResource(context.getResources().getIdentifier("w"+p.type, "drawable", context.getPackageName()));
                }
                else if(!p.isWhite)
                {
                    view.setImageResource(context.getResources().getIdentifier("b"+p.type, "drawable", context.getPackageName()));
                }
            }

        }
        else {
            view = (ImageView) convertView;
        }

        return view;
    }
}

XML Code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".StartGameActivity">

    <Button
        android:id="@+id/resignButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="4dp"
        android:text="@string/resign"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/drawButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="1dp"
        android:text="@string/draw"
        app:layout_constraintBottom_toTopOf="@+id/gridViewBoard"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/gameText"
        android:layout_width="197dp"
        android:layout_height="36dp"
        android:layout_marginStart="18dp"
        android:layout_marginTop="12dp"
        android:layout_marginEnd="16dp"
        android:text="@string/game_text"
        android:textAlignment="center"
        android:textColor="#000000"
        android:textSize="25sp"
        app:layout_constraintEnd_toStartOf="@+id/resignButton"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toEndOf="@+id/drawButton"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/aiButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/ai"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/undoButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="4dp"
        android:text="@string/undo"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

    <GridView
        android:id="@+id/gridViewBoard"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="1dp"
        android:layout_marginEnd="1dp"
        android:layout_marginBottom="49dp"
        android:columnWidth="60dp"
        android:gravity="center_horizontal"
        android:horizontalSpacing="0dp"
        android:numColumns="8"
        android:padding="0dp"
        android:stretchMode="columnWidth"
        android:verticalSpacing="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/drawButton" />
</androidx.constraintlayout.widget.ConstraintLayout>


text:
Q: ImportError: undefined symbol zmq_strerror I'm trying to install Jupyter Notebook to run the TensorFlow 2 models tutorial. (https://tensorflow2objectdetectioninstallation.readthedocs.io/en/latest/install.html#tensorflow-models-installation) The packages seemed to have installed fine but when I try to run:
jupyter notebook
or python3.7 -m jupyter notebook
I get this error:
pi@raspberrypi:~/Desktop/stonesoup_testing/TensorFlow/models/research/object_detection $ python3.7 -m jupyter notebook
Traceback (most recent call last):
  File "/home/pi/.local/bin/jupyter-notebook", line 5, in <module>
    from notebook.notebookapp import main
  File "/home/pi/.local/lib/python3.7/site-packages/notebook/notebookapp.py", line 51, in <module>
    from zmq.eventloop import ioloop
  File "/home/pi/.local/lib/python3.7/site-packages/zmq/__init__.py", line 50, in <module>
    from zmq import backend
  File "/home/pi/.local/lib/python3.7/site-packages/zmq/backend/__init__.py", line 40, in <module>
    reraise(*exc_info)
  File "/home/pi/.local/lib/python3.7/site-packages/zmq/utils/sixcerpt.py", line 34, in reraise
    raise value
  File "/home/pi/.local/lib/python3.7/site-packages/zmq/backend/__init__.py", line 27, in <module>
    _ns = select_backend(first)
  File "/home/pi/.local/lib/python3.7/site-packages/zmq/backend/select.py", line 28, in select_backend
    mod = __import__(name, fromlist=public_api)
  File "/home/pi/.local/lib/python3.7/site-packages/zmq/backend/cython/__init__.py", line 6, in <module>
    from . import (constants, error, message, context,
ImportError: /home/pi/.local/lib/python3.7/site-packages/zmq/backend/cython/error.cpython-37m-arm-linux-gnueabihf.so: undefined symbol: zmq_strerror
pi@raspberrypi:~/Desktop/stonesoup_testing/TensorFlow/models/research/object_detection $

On Raspbian Stretch, using Python 3.7, pymzq version: 19.0.2
here is my pip freeze output:
pi@raspberrypi:~/Desktop/stonesoup_testing/TensorFlow/models/research/object_detection $ python3.7 -m pip freeze
actionlib==1.11.13
angles==1.9.11
argon2-cffi==20.1.0
attrs==20.1.0
backcall==0.2.0
bleach==3.1.5
bondpy==1.8.3
camera-calibration-parsers==1.11.13
catkin==0.7.14
certifi==2020.6.20
cffi==1.14.2
cv-bridge==1.12.8
cycler==0.10.0
Cython==0.29.21
decorator==4.4.2
defusedxml==0.6.0
diagnostic-analysis==1.9.3
diagnostic-common-diagnostics==1.9.3
diagnostic-updater==1.9.3
dynamic-reconfigure==1.5.50
entrypoints==0.3
gencpp==0.6.0
geneus==2.2.6
genlisp==0.4.16
genmsg==0.5.11
gennodejs==2.0.1
genpy==0.6.7
importlib-metadata==1.7.0
ipykernel==5.3.4
ipymd==0.1.3
ipython==7.18.1
ipython-genutils==0.2.0
ipywidgets==7.5.1
jedi==0.17.2
Jinja2==2.11.2
jsonschema==3.2.0
jupyter==1.0.0
jupyter-client==6.1.7
jupyter-console==6.2.0
jupyter-core==4.6.3
kiwisolver==1.2.0
MarkupSafe==1.1.1
matplotlib==3.3.1
message-filters==1.12.14
mistune==0.8.4
nbconvert==5.6.1
nbformat==5.0.7
notebook==6.1.3
numpy==1.19.1
object-detection==0.1
packaging==20.4
pandocfilters==1.4.2
parso==0.7.1
pexpect==4.8.0
pickleshare==0.7.5
Pillow==7.2.0
pluginlib==1.11.3
prometheus-client==0.8.0
prompt-toolkit==3.0.7
ptyprocess==0.6.0
pycparser==2.20
Pygments==2.6.1
pyparsing==2.4.7
pyrsistent==0.16.0
python-dateutil==2.8.1
python-qt-binding==0.3.4
PyYAML==5.3.1
pyzmq==19.0.2
qtconsole==4.7.6
QtPy==1.9.0
resource-retriever==1.12.4
rosbag==1.12.14
rosboost-cfg==1.14.4
rosclean==1.14.4
roscreate==1.14.4
rosgraph==1.12.14
roslaunch==1.12.14
roslib==1.14.4
roslint==0.11.0
roslz4==1.12.14
rosmake==1.14.4
rosmaster==1.12.14
rosmsg==1.12.14
rosnode==1.12.14
rosparam==1.12.14
rospy==1.12.14
rosserial-python==0.7.7
rosservice==1.12.14
rostest==1.12.14
rostopic==1.12.14
rosunit==1.14.4
roswtf==1.12.14
Send2Trash==1.5.0
sensor-msgs==1.12.7
six==1.15.0
smach==2.0.1
smach-ros==2.0.1
smclib==1.8.3
terminado==0.8.3
testpath==0.4.4
tf==1.11.9
tf-conversions==1.11.9
tf2-kdl==0.5.20
tf2-py==0.5.20
tf2-ros==0.5.20
topic-tools==1.12.14
tornado==6.0.4
traitlets==5.0.0
wcwidth==0.2.5
webencodings==0.5.1
widgetsnbextension==3.5.1
xacro==1.11.3
zipp==3.1.0
zmq==0.0.0

A: I uninstalled pyzmq and built it from source instead. This solved my issue and I can run jupyter notebook fine now. I'm now having a different problem where numpy is not importing properly from within jupyter.


text:
Q: Change date format in multiple text files in PowerShell I have around 5000 text files (CSV) in one directory. Files are comma delimited. I'm trying to change the date format (it is stored in the first column of each file) from M/d/yyyy to MM/dd/yyyy.
There are around 1 milion lines in those 5000 files, so I think the StreamWriter command is a way to go. Some CSV files have a header, but not all. Please see the code below. I think I'm pretty close...
The code below do its job for one specific file (test.csv), but it doesn't work for all CSV files (*.csv) files in a single directory. Is there more space for speed improvement of this code?
$file = "C:\Test\Test.csv";

try
{
    $stringBuilder = New-Object System.Text.StringBuilder;

    try
    {
        $reader = New-Object System.IO.StreamReader($file)

        while($reader.Peek() -ge 0)
        {
            [datetime]$dirDate = New-Object DateTime;
            $line = $reader.ReadLine();
            $dateVal = $line.Split(",")[0];

            if ([DateTime]::TryParseExact($dateVal,
                                          "M/d/yyyy",
                                          [System.Globalization.CultureInfo]::InvariantCulture,
                                          [System.Globalization.DateTimeStyles]::None,
                                          [ref]$dirDate))
            {
                $result = $line -replace $line.Substring(0, $line.IndexOf(",")), $dirDate.ToString("MM/dd/yyyy");
                $stringBuilder.Append($result + "`r`n") | Out-Null;
            }
            else
            {
                $stringBuilder.Append($line + "`r`n") | Out-Null;
            }
        }
    }
    finally
    {
        $reader.Close();
    }

    try
    {
        $sw = New-Object System.IO.StreamWriter $file;
        $sw.Write($stringBuilder.ToString());
        Write-Host "File processed successfully.";
    }
    finally
    {
        $sw.Close();
    }
}
catch
{
    Write-Host "Caught an exception:" -ForegroundColor Red;
    Write-Host "Exception Type: $($_.Exception.GetType().FullName)" -ForegroundColor Red;
    Write-Host "Exception Message: $($_.Exception.Message)" -ForegroundColor Red;
}

File sample without a header:
 8/1/2014,35,35.6,32.64,34.17,4217150
 8/4/2014,34.34,35.86,33.66,34.17,2231804
 8/5/2014,33.74,34.08,33.11,33.58,3456364
 8/6/2014,33.91,35.08,33.76,33.92,2805103
 8/7/2014,33.8,34.99,33.01,33.43,2474410
 8/8/2014,33.23,34.19,32.5,33.76,1929437

file sample with Header:
 Date,Header2,Header3,Header4,Header5,Header6
 8/1/2014,75.65,78,74.21,76.7,1376428
 8/4/2014,77.07,81.459,76.92,80.96,1871618
 8/5/2014,80.87,82.5,78.101,79.34,1894376
 8/6/2014,78.42,83.49,77.99,82.75,2792467
 8/7/2014,81.27,86,78.82,85.8,4496068

A: I converted it to a function for you. You were really close, but had some issues with the excess try catch finally blocks. I also changed $reader.peek -ge 0 to -not $reader.endofstream
function ParseCSV ($file) {
    try {
        $stringBuilder = New-Object System.Text.StringBuilder;
        $reader = New-Object System.IO.StreamReader($file)
        while(-not $reader.EndOfStream) {
            [datetime]$dirDate = New-Object DateTime;
            $line = $reader.ReadLine();
            $dateVal = $line.Split(",")[0];
            if([DateTime]::TryParseExact($dateVal,
                                         "M/d/yyyy",
                                         [System.Globalization.CultureInfo]::InvariantCulture,
                                         [System.Globalization.DateTimeStyles]::None,
                                         [ref]$dirDate))
            {
                $result = $line -replace $line.Substring(0, $line.IndexOf(",")), $dirDate.ToString("MM/dd/yyyy");
                $stringBuilder.Append($result + "`r`n") | Out-Null;
            }
            else
            {
                $stringBuilder.Append($line + "`r`n") | Out-Null;
            }
        }
        $reader.Close()
        $sw = New-Object System.IO.StreamWriter $file;
        $sw.Write($stringBuilder.ToString());
        Write-Host "File processed successfully.";
    }
    catch {
        Write-Host "Caught an exception:" -ForegroundColor Red;
        Write-Host "Exception Type: $($_.Exception.GetType().FullName)" -ForegroundColor Red;
        Write-Host "Exception Message: $($_.Exception.Message)" -ForegroundColor Red;
    }
    finally {
        if($reader) {
            $reader.Dispose()
        }
        if($sw) {
            $sw.Dispose()
        }
    }
}

I used it like this:
dir *.csv | %{ParseCSV $_.FullName}

It parsed 25 of the sample files you provided, converting the dates from m/d/yyyy to mm/dd/yyyy.


text:
Q: How to create xhtml elements with javascript How can I dynamicaly create xhtml elements with javascript? I want to add a checkbox inside a table cell.
So I want the code to look like this:

    <input type="checkbox" />

Unfortunatly  the slash at the end of the input element is not added thus making it not xhtml compatible. The result of my code looks like this:

    <input type="checkbox">

I tried both innerHTML as createElement but both didn't add the slash.
1)
cell.innerHTML = "<input type='checkbox' />";

2)
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
cell.appendChild(checkbox);

Is there a way to add an xhtml emement?

A: XHTML is just another input language into the common DOM. What sets XHTML syntax apart is how it is *parsed**, not how it is represented in the DOM. So your code is fine - you ARE adding the element successfully, it's just translated when it hits the DOM.
* except Internet Explorer, which, despite declaring XHTML as the doctype, IE will parse it as HTML anyway.


text:
Q: how do you check different api calls until it is succesful in python I have a server list:
hosts=['server1','server2','server3','server4']

there are server 4 monitoring tools accessed by api calls. these monitoring env urls basically the same except for each env has unique id which is part of the url. These servers can be on any of the 4 monitoring tools. I need to find out which url these servers belong to.
for example, these are the monitoring tools urls:
production_env="https://example.com/e/envid123"
dev_env="https://example.com/e/envid678"
test_env="https://example.com/e/envid567"
uat_env="https://example.com/e/envid1000"

given the server name, I need to find out which env they belong to.
given a server name, for example "server1",
api url would become https://example.com/e/envid123&serverName="server1", this url will give whether server1 exists in production_env or not. I need to check each env url until I find the given server.
I am trying something like this:
envId=['envid123','envid678','envid567','envid1000']

for server in hosts:
   for id in envId:
    url="https://example.com/e/"+id+&serverName=server
    resp=request.get(url)

Any ideas how could do this the best way?

A: You need quotes around &serverName= to concatenate them. But it's simpler to use a formatting method, such as f-strings.
To find the desired URL, use resp.json to get the decoded JSON, and check the value of the appropriate dictionary element.
found = False
for server in hosts:
    for id in envId:
        url = f"https://example.com/e/{id}&serverName={server}"
        resp = request.get(url)
        if resp.json['totalCount'] > 0:
            found = True
            print(f"Success at host = {server} id = {id}")
            break
    if found:
        break
else:
    print("No server found")


text:
Q: how to convert NSNumber into NSString rwx type i'm new in unix permission and chmod.
In my IOS app, i try to get a file permission value from SFTP server. The value i've got is in a NSNumber value and the value is 19455. I want to convert it into NSString in rwx (read, write, execute) value, how can i do that?

A: objective-c NSFilePosixPermissions to human readable NSString


text:
Q: Firewall throughput I saw on multiple site vendor sites about firewall throughput in 1518/512/64 bytes UDP packet and each result from 1518/512/64 bytes UDP packet is 1xxx/smaler than 1xxx/significantly smaller than 1xxx.
Can anyone let me know why this is the case? The only theory that I can come up with is that in one physical connection (i.e. 1Gb), it can fit up to xx amount of 1518 UDP packet and therefore, the number of 64 UDP packets are larger than 1518 UDP packets. Thus, firewall need to inspect more packets in that physical connection and that explain the throughput (Mbps) is smaller in 64 bytes. Is my observation correct?
Also, if that is the case, then what is the correct calculation or if someone can point me to any website that explain this type of throughput.
(edit)
Take this website for example, http://www.zyxel.com/us/en/products_services/zywall_1100_310_110.shtml?t=p
Zywall 1100/310/110 stated their firewall throughput as 6000/5000/1600 Mbps on 1518/512/64 bytes UDP packet.
()
Thank you

A: Packet inspection is much more affected by the packets per second than bandwidth. This is caused by the fact that it is much more CPU intensive to parse a packet, than to skip the payload. The metric used to measure this is called 'packets per second' or PPS.
Some equipments have specialized integrated circuits called ASIC that can offload this processing from the main CPU.


text:
Q: Java script addition of numbers with giving wrong answer I am working with a simple java script code which goes here
<script>
var x=prompt("Enter a number");
var n=x+2;
alert(n);
</scrip>

This code will throws a prompt If i enter 2 in the prompt.I am expecting output as 4,But it is generating 22 in alert. What mistake is happening here.

A: Yes.
 var n;
 if(!isNaN(x)) {
    n = parseInt(x) + 2; // make sure x is always a number here
 }

This is because the prompt function will return an String, not a number.
String + Number = String

A: <script>
var x=prompt("Enter a number");
var n=parseInt(x)+2;
alert(n);
</scrip>

A: Try
<script>
var x = prompt("Enter a number");
var n = parseInt(x)+2;
alert(n);
</script>

A: Here an alternative way of doing this:
var x = +prompt("Enter a number");
var n = x+2;
alert(n);

The plus sign (in front of prompt) converts the string to a number.


text:
Q: ELB with SSL pass through to either nginx or haproxy. Which is suited to handle more certs? So I plan on having a ELB with SSL passthrough to either servers running haproxy or nginx.
I will be hosting potentially thousands of lets-encrypt certs.
Is either nginx or haproxy better at handling thousands of ssl certs?  Or is there basically no difference in this regard?
I want to terminal SSL at either haproxy or nginx, and with so many cert files etc. I want an idea if one will be better at handling that many certs or not.

A: As per the Elastic Load Balancer documentation, Classic Load Balancers allow a single certificate per listener, with up to 100 listeners (on different ports).
Application Load Balancers in the other hand, have a limit of 25 certificates per balancer, although you can use all of them with the same listener.
I would say your only viable approach for such a huge ammount of certificates will be deploying your EC2 instances behind a Network Load Balancer, which works in a lower network layer and delegates the SSL negotiation completely on the backend instances.
Should your workload be HTTP oriented, I would say Nginx will make the deal better than HAProxy. If you intend to proxy other protocols, HAproxy is your best choice.

A: Both are great. I would use nginx personally as you're not running multiple back ends from that perspective (from what I understand) so you don't need haproxy on that side of things.
Just have nginx setup with ssl and proxy pass :)

A: I think that loading thousands of certs is easier to do with HAProxy. All you need to do is put your certs in a single directory and HAProxy will load all the certs with the crt directive.
So a minimal configuration for ssl offloading would be:
listen ssl_offload
   mode http
   bind IP:443 ssl crt <path-to-ssl-directory>
   timeout     client  30s
   timeout     server  30s
   timeout     connect 5s
   server srv1 IP:80 check

HAProxy will use the right certificate based on the SNI hostname provided by the client (which is currently supported by most modern browsers).
Loading multiple SSL certs is only a matter of memory consumption here. HAProxy needs to have a PEM file containing both the required certificates and any
associated private keys. So if the average PEM file is around 5K (2048 rsa key) loading million of them will cost you around 5GB of memory.
Now while HAProxy assigns certificates per listener, I think that NGINX  assigns certificates per "server name" so you will need as many server blocks as many domains you have. If you are using thousands of them you'll probably have to script this.


text:
Q: Android Studio: What does the blueprint area do? What benefit is it? I'm working through Android layout and I know there is this new(er) thing call Blueprint.   I'm wondering what the Blueprint view offers.
What I've Tried
1. Added Button and Moved It Around Via Constraints
I don't see really any difference between the two design views (normal and blueprint).
Oh, I did see one difference in the two views.
You only see the outlines of the controls if you are floating above the normal design view (image 1 below).  If your cursor is not in the window you don't see them (image 2 below).
Is that the difference?

2. Searched Google's Android Dev Site
I could only find one small bit of information at : https://developer.android.com/studio/write/layout-editor
It said:

the Blueprint view (only outlines for each view)

The blueprint takes up a lot of screen space and I'm wondering if that is all it offers (just outlines of controls)?
I can't see how that is more beneficial than just seeing the "outlines" in the normal design view by floating over view.
Does blueprint offer something additional that I'm not understanding?  Is there some other benefit?

A: AFAIK there really isn't any 'huge' advantage to the blueprint view. It provides a wireframe view of your design.
There are a few cases where it comes in useful though, for example,

*

*If your View is invisible, it won't be seen in the preview but it will visible in the blueprint view.

*Overlapping views are more clearly visible and identifiable.

*It provides a more clutter-free view where the constraints and views are more immediately identifiable.

*It's also used to be useful for preview of components that are 'invisible' (for example, imageview who's src get set programmatically).

*Rendering the blueprint view is faster. (As pointed out by  Martin Marconcini in the comments)

A: Its shows you only how the view looks like


text:
Q: Warning message when using business_calendar in python I would like to use the business_calendar function in python. I have a list of public holidays I would like to add to my calendar. I have followed the example code in creating my calendar, here is my code:
from business_calendar import Calendar, MO, TU, WE, TH, FR
import datetime
date1 = datetime.datetime(2017,9,22)
cal = Calendar(holidays=list([datetime.datetime(2017,9,25),datetime.datetime(2017,9,28)]))
date2 = (cal.addbusdays(date1, 3))
print (date2)

The function seems to be working correctly, however I am concerned about the warning message that is displayed:
C:\Program Files\WinPython-64bit-3.5.2.3\python-3.5.2.amd64\lib\site-packages\spyder\utils\ipython\start_kernel.py:5: CalendarHolidayWarning: Holiday list exhausted at end, addbusday(2017-09-22 00:00:00,3) output may be incorrect. # (see spyder/__init__.py for details)

I have attempted to find out how to resolve this, but have had no luck. Any assistance would be appreciated.
Thank you

A: It's giving you this warning because it has reached the last holiday in your list, and has no way of knowing how far into the future that list covers.  Specifically, it has no way of knowing whether the 29th is a holiday or not.  Adding a holiday far in the future, or having the whole year's holidays in the list (which is probably the normal use-case for this module), would avoid the warning.

A: In case someone is wondering. The list may be exahusted because the remaining holidays are in a non-working days. So basically you can add few artificial holidays on 29,30,31.12 or around asian new year, if this is the case :)
Or you may just ignore the message.


text:
Q: How To Give Widgets Individual ID's or Classes? On my wordpress installation, I created a new theme for a new page template I created. However, when I goto create new widgets, each widget automatically gets the class of "textwidget". I have two different styles I have for widgets that require different styles, so I'm not too sure how to give each indivudal widget a different class or to label them differently?
Anyone know how to do this?
Here's a page from my site with the 2 widgets: http://www.simonsayswebsites.com/how-we-get-you-more-customers/
You can see each one is within a widget that has the same class name.
This is what I added to my page functions.php to add the widget:
    if ( function_exists('register_sidebar') ){
    register_sidebar(array(
        'name' => 'sidebarpage',
        'before_widget' => '
',
        'after_widget' => '
',
        'before_title' => '',
        'after_title' => '',
));
}

And here's the snippet from the page template itself for it to display:
<?php /* Widgetized sidebar */
    if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('sidebarpage') ) : ?><?php endif; ?>

I could make it using different widgetized areas, but want to learn about having individual widget styles.

A: You are mistaking name and id.
Also, in before_widget, you shouldn't declare a fixed ID, in your site both Widgets have the same ID and that's... no good.
If you follow the example in the Codex, your widget will receive an unique ID and a relevant class.
http://codex.wordpress.org/Function_Reference/register_sidebar
Default usage
<?php $args = array(
    'name'          => __( 'Sidebar name', 'theme_text_domain' ),
    'id'            => 'unique-sidebar-id',
    'description'   => '',
    'class'         => '',
    'before_widget' => '
',
    'after_widget'  => '
',
    'before_title'  => '
',
    'after_title'   => '
' ); ?>


text:
Q: Appending user input to a list not working I am trying to take user input and append all numbers to a list. However the output I am getting just a blank list with nothing inside.
while True:
    my_add = input("Give me numbers and I will add them to the list. Enter 'q' to quit.")
    my_list = []

    if my_add == 'q':
        break

    else:
        my_list.append(my_add)

print(my_list)

A: my_list = []
while True:
    my_add = input("Give me numbers and I will add them to the list. Enter 'q' to quit.")
    if my_add == 'q':
        break
    else:
        my_list.append(my_add)
print(my_list)

my_list was set to empty list [] at every loop iteration

A: Remove the variable my_list from the while loop as it is resetting on every iteration.

my_list = []

while True:

    my_add = input("Give me numbers and I will add them to the list. Enter 'q' to quit.")

    if my_add == 'q':
        break

    else:
        my_list.append(my_add)

print(my_list)


text:
Q: What is the equivalent of .NET Framework ModelMetadataProvider in .Net Core? for get property DisplayName attribute value, ModelMetadataProvider used at .NET Framework versions.
ModelMetadataProviders.Current.GetMetadataForProperty(null, ClassType, PropertyName).DisplayName;

and I tried get DisplayName in .NET 6:
class SampleClass{
   [Display(Name = "FirstName", ResourceType = typeof(MyResource))]
   public string Name{ get; set; }
}

Type ClassType = typeof(SampleClass);
string PropertyName = "Name";
string displayName = TypeDescriptor.GetProperties(ClassType)
                            .Cast<PropertyDescriptor>()
                            .ToDictionary(p => p.Name, p => p.DisplayName)
                            .FirstOrDefault(p => p.Key == PropertyName).ToString();

The DisplayName value will be received, but the output value does not change when the CultureInfo is changed!

A: using the following code, DisplayName value (which has a resource) can be accessed without using ModelMetadataProvider and dependency injection, and it also works by changing the language.
class SampleClass{
   [Display(Name = "FirstName", ResourceType = typeof(MyResource))]
   public string Name{ get; set; }
}

Type ClassType = typeof(SampleClass);
string PropertyName = "Name";
string displayName = "";

MemberInfo property = ModelType.GetProperty(Property);
displayName = property.GetCustomAttribute<DisplayAttribute>()?.GetName();


text:
Q: Why cant i kill the task remotly through my .bat Script? [solved] I want to write a .bat Script, where i want to kill a task remotly from my pc on my windows server 2022.
When i try the command "taskkill /u Administrator /p mypassword /s 192.168.178.226 /im Cluster_Manager.exe /f /t"
it says:
Error: The process with pid 4664 (child process of pid 2384) could not be terminated.
Cause: internal error
Firewall is already disabled.
I have no idea what it could be...
[Edit]
I used the PSExec tool form "https://learn.microsoft.com/en-us/sysinternals/downloads/psexec". The tool solved the problem for me.


text:
Q: Can random constructive interference with sound waves cause damage? Any two sound waves have a random chance to constructively interfere with each other at a given spot and this will cause an increase or decrease in pressure. So is it possible that a large number of local noises in a loud environment could interfere perfectly at a single point, such as on a person or building, and cause damage? I'm not worried, just curious if this is a daily occurrence or if the probability of it is extremely low or if it can even happen.

A: Let's say you have $n$ sources, each producing a sine wave of amplitude $A$, and they combine with random phases. In principle, the sum could be as large as $nA$, and if $n$ is very large we could imagine that this amplitude could be big enough to be destructive. However, because the terms being added are independent and identically distributed, with finite variance, the central limit theorem tells us that the probability distribution of the sum should be well approximated by a normal (Gaussian) distribution. Normal distributions have thin tails, so the probability of a very large sum is negligible.
To get extreme values ("black swans") of a random sum with high probability, you need to violate one of the hypotheses of the central limit theorem. E.g., in economics, many times the individual variables don't have finite variances, and instead of a normal distribution for the sum, you get a Levy-stable distribution, which has fat tails.

A: You're right that sound waves can interfere constructively or destructively leading to dead spots or live spots (which is an effective phenomenon to be considered when constructing large auditoriums) which can be harmful sometimes.
Your example of local noises in buildings fail for one reason you mention ...

So is it possible that a large number of local noises in a loud environment could interfere perfectly at a single point, such as on a person or building, and cause damage?

This weird occurrence seems unreasonable to me. I'd say it has the lowest possibility than anything and for such a phenomenon to occur...

*

*All those waves (low energy noises) shouldn't be absorbed, the reflected waves should be coherent with the other waves of similar pitch in order to undergo perfect constructive interference

*Finally, the resultant wave(s) should be focused on a person or building.

In theory, we can show that if these waves do interfere, they'd add up to some harmful high-pressure region traveling at speed of sound. But in reality, there's always some interruption for this to happen that make these to be the lowest probabilistic factors one can consider.

A: Two things against:

*

*It's unlikely that the waves will actually all interfere constructively. In a realistic setting the sounds won't be constant, so points of constructive interference are very temporary and don't have time to do anything even if they could.

*Each of the sound sources is putting out a certain amount of power as sound (in all directions), and this is the total power available for whatever destructive purposes you have in mind.

One source (http://engineering.mit.edu/ask/can-sound-be-converted-useful-energy) claims

What the human ear perceives as clanging cacophony—the roar of a train engine or the whine of a pneumatic drill—only translates to about a hundredth of a watt per square meter.

Constructive interference of several such sources (and their echoes) would deliver more power intensity than that, but as you can see the available power in sound isn't much to start with. It also doesn't transfer neatly to a single object. Most objects either reflect sound well, or else are flexible enough that absorbing sound doesn't damage them.
Sound is most commonly demonstrated to be destructive by matching a resonant frequency of some brittle object (such as a wine glass) and forcing the vibration of that object over a period of time until it breaks. That is, the target object stores some energy from the sound, in order to get over the fact that the power transferred from the sound wave is feeble.
This could in principle happen by chance given many loud sound sources. But we don't need to take special measures to prevent road-facing windows spontaneously shattering. Admittedly they're large, and their modes of vibration in the range of audible sound require far more energy than the wine glass. Even so I think it's fair to conclude that although I don't have a mathematical model to estimate the probability, a typical "noisy environment" such as a busy street doesn't do anything of the sort and so the probability must be tiny.


text:
Q: Chai check structure and values of return value I have a few functions that I would like to unit test with chai, that are written before the functions are implemented, so they also serve as design guidelines.
As such I would like to make sure that the return value of these functions always follows an exact pattern, for instance this one:
{
  id: #some unkown UID,
  seller: 'user1',
  seller_offer: [
    {
      inventory: #some inventory uuid,
      item: 'red_card',
      amount: '11',
    }
  ],
  recipient: 'user2',
  recipient_offer: [
    {
      inventory: #some inventory UUID,
      item: 'coin',
      amount: '1234',
    }
  ]
}

The return value should never have any additional keys and contain all the required ones.
If all the return values were known beforehand, that would be easy to with a deep equal. Now the problem with this is that some of these values are UUIDS, which are obviously not known before running the functions. There are many functions like this.
I would like to be able to simply set the inventory and id values to null  so that chai ensures that the key is present, but doesn't actually compare its value (or maybe even a wildcard object that checks if the values are actually UUIDS).
Is there a way that I can do this? Basically ensure that the structure of the JSON is correct and simulatenously check some of the values.

A: You can use Chai JSON Pattern plugin to match the structure of the JSON. The API documentation is here
E.g.
const chai = require('chai');
const chaiJsonPattern = require('chai-json-pattern').default;
const faker = require('faker');

chai.use(chaiJsonPattern);
const { expect } = chai;

describe('67484029', () => {
  it('should pass', () => {
    const obj = {
      id: faker.random.uuid(),
      seller: 'user1',
      seller_offer: [
        {
          inventory: faker.random.uuid(),
          item: 'red_card',
          amount: '11',
        },
      ],
      recipient: 'user2',
      recipient_offer: [
        {
          inventory: faker.random.uuid(),
          item: 'coin',
          amount: '1234',
        },
      ],
    };

    expect(obj).to.matchPattern(`
      {
        "id": String,
        "seller": "user1",
        "seller_offer": [
          {
            "inventory": String,
            "item": "red_card",
            "amount": "11"
          }
        ],
        "recipient": "user2",
        "recipient_offer": [
          {
            "inventory": String,
            "item": "coin",
            "amount": "1234"
          }
        ]
      }
    `);
  });
});


text:
Q: RE: Compiling OpenCV4.3.0 with GCC 8.3.0-1 on Debian Buster First, I listed this info. on the OpenCV.org site at https://docs.opencv.org/master/d2/de6/tutorial_py_setup_in_ubuntu.html.
Secondly, I used my git source to use this command: git clone https://github.com/opencv/opencv.git
Thirdly, I used these commands to try to build the OpenCV version of 4.3.0.
cd opencv/opencv4.3.0
mkdir build && cd build

cmake -DCMAKE_BUILD_TYPE=RELEASE -DCMAKE_INSTALL_PREFIX=/usr/local -DWITH_TBB=ON
-DBUILD_NEW_PYTHON_SUPPORT=ON -DWITH_V4L=ON
-DINSTALL_C_EXAMPLES=ON -DINSTALL_PYTHON_EXAMPLES=ON
-DBUILD_EXAMPLES=ON -DWITH_QT=OFF -DWITH_OPENGL=ON ../

make

In the /build directory, I keep getting kicked out of my session at 71% or my Linux SBC looses online Internet via WiFi at that percentage. Do you see an issue with my cmake command? Do you know or have you seen any issues pertaining to losing control of your Linux SBC during the make command on your side?


text:
Q: Undistort kinect depth image cause severe noise I calibrated a kinect RGB camera with chessboard and got its intrinsics parameters and distortion parameters.
I tried to undistort the Depth image and RGB image with OpenCV provided cvUndistort2 function, but unfortunately severe noise occured in the undistorted depth image.
Some posts said the noises is included by image smoothing during undistortion. I don't know why , and any tips to get rid of this problem?

A: I think OpenCV uses some kind of interpolation to generate the undistorted image. Since it assumes all pixel are valid it uses also invalid depth values to generate the undistorted depth image. Using a nearest neighbor interpolation could help. Or you write your own undistortion method.


text:
Q: Recurring events php I am trying to allow a user to schedule an event in a calendar app similar to Google Calendar. I need to achieve an event that Repeats every 3 week(s), ends after 2 occurrence(s)
My current code is as follows:
$week = array('0'=>"Sunday","1"=>"Monday","2"=>"Tuesday","3"=>"Wednesday","4"=>"Thursday","5"=>"Friday","6"=>"Saturday");
                       $day = $week[$val];

$days = array(
    'Monday',
    'Tuesday',
    'Wednesday',
    'Thursday',
    'Friday',
    'Saturday',
    'Sunday',
  );

  $today = new DateTime($day);
  //$today = new DateTime('Friday'); //can set specific day if needed
//  print "Today is " . $today->format('l') . "\n";

  foreach($days as $day) {

    $diff = new DateTime($day);
    $diff = $diff->format('N') - $today->format('N');

    if($diff > 0) {
      //print "$day is $diff days in the future\n";
      //print "\n$diff days future\n";
       $st=date('Y-m-d H:i:s',strtotime('+'.($diff).' day',strtotime($s)));
    $et=date('Y-m-d H:i:s',strtotime('+'.$date_diff.'day',strtotime($s)));
    }
    elseif($diff < 0) {
      $diff = abs($diff);
     // print "$day is $diff days in the past\n";
     //  print "$diff days fast\n";
        $st=date('Y-m-d H:i:s',strtotime('+'.($diff).' day',strtotime($s)));
    $et=date('Y-m-d H:i:s',strtotime('+'.$date_diff.'day',strtotime($s)));
    }
    else {
    $st=date('Y-m-d H:i:s',strtotime('+'.$recordsave.' day',strtotime($s)));
    $et=date('Y-m-d H:i:s',strtotime('+'.$date_diff.'day',strtotime($s)));
    }
  }

Any idea friends?

A: The only way to have PHP code fire is if a user is accessing it. I would suggest a CRON job for this matter.
You could set a CRON schedule to run a particular line of code by calling that PHP page in a CRON job every 3 weeks for 2 weeks.


text:
Q: why am getting couldn't load image in latest versions? when picking image from gallery and making crop for it then it is going to be cropped but my main issue is that when am picking google photos it is unable to crop and showing Toast message like "couldn't load image". Please help me where am doing wrong.

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)
            {
                Log.e("Came", "onActivityResult")
                super.onActivityResult(requestCode, resultCode, data)
                System.out.println("onActivityResulty===>" + data.toString() + "@@@@@" + resultCode + "#######" + requestCode)
                if (requestCode == RESULT_LOAD_GALLERY_IMAGE && null != data) {
                    mImageCaptureUri = data.data
                    try {

                        cropImage(mImageCaptureUri, output_pic, "square")
                    } catch (e: IOException) {
                        e.printStackTrace()
                    } catch (e: OutOfMemoryError) {
                        e.printStackTrace()
                    }

                } else if (requestCode == CAMERA_REQUEST) {
                    try {

                        cropImage(mImageCaptureUri, output_pic, "square")
                    } catch (e: Exception) {
                        e.printStackTrace()
                    } catch (e: OutOfMemoryError) {
                        e.printStackTrace()
                        System.out.println("OnActivity_Catch_Error===>" + e)
                    }

                }else if (requestCode == 1890) {

                    croppingImage()

                }}

https://www.android-examples.com/android-image-cropping-example-tutorial-pick-gallery-camera/

A: That happens because picking an image from the camera and from the gallery don't return the same result, you have to check which one the user has chosen by looking at the intent; you can do it this way.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == mRequestCode) {
            if (resultCode == Activity.RESULT_OK) {
                boolean isCamera = true;
                if (data != null && data.getData() != null) {
                    String action = data.getAction();
                    isCamera = MediaStore.ACTION_IMAGE_CAPTURE.equals(action);
                }

                try {
                    Uri uriFileSrc = isCamera ? mOutputFileUri : data.getData();

                    //Do what do you need with the Uri

                } catch (Exception ex) {
                    Toast.makeText(mActivity, R.string.error_creating_file, Toast.LENGTH_SHORT).show();
                }
            }
        }
}


text:
Q: Azure web app for containers (aspnetcore 2.2) not reading azure appsettings values on startup I've got a webapp for containers running in Azure that I have working locally with a local appsettings file.
once I deploy to Azure, I want the container to pull appsettings values from the azure settings.  These are set via AzureDevops and appear correctly when I check the portal.
However, the site is not pulling the appsettings values from Azure once deployed.  It is using the ones from the file.  I am using the double-underscore names as specified.
I have created a testcontroller to output the appsettings values.  This is an a snippet of what the test view outputs:

Build version: 2019.1.23.1
Location: local
Database__DatabaseConnectionString: Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=application;Data Source=.
---
-------
Env vars: Key WEBSITE_AUTH_SIGNING_KEY Value ASDS*(&*&*(SDSD05C29
Key DOTNET_RUNNING_IN_CONTAINER Value true
Key WEBSITE_ROLE_INSTANCE_ID Value 0
Key Database__DatabaseConnectionString Value Server=tcp:servername01.database.windows.net,1433;Initial Catalog=application;Persist Security Info=False;User ID=applicationUser;Password=password;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
Key APPSETTING_Database__DatabaseConnectionString Value Server=tcp:servername01.database.windows.net,1433;Initial Catalog=application;Persist Security Info=False;User ID=applicationUser;Password=password;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;

As can be seen, the Database__DatabaseConnectionString should be consumed by the app.  But it's not being.
What could be the problem here?  This should be standard functionality according to the aspnetcore documentation.

A: Turns out this was a bug in the application.  The controllers in question has an injected IOptions being injected into the constructor.  Unfortunately, one of the controllers had different behaviour as a concrete instance was being inject in instead.  As this object was not being correctly initialised in Startup.cs, this has the effect of passing empty values into the constructor.
Finally as empty values were found, this mean the default appsettings.json values were used.
Having fixed this above bug (by ensuring all controller use the same IOptions values), the azure appsettings values are being picked up and used correctly by the application at startup time.


text:
Q: JS Multiple image upload width validation I have a multiple file upload field for images that I want to validate each image's width before upload to ensure it's less than 640px.
If one of the images is larger, preferably I would have it removed from the FileList before the rest of the images are uploaded. Reading a bit around tells me this is not possible because FileList is read only? (Possible workaround would be to make a separate array, but I'm using Rails with gem s3_direct_upload which builds upon jquery-fileupload, so I'm not entirely sure how to go about doing that).
Therefore at least I would like to clear the FileList and alert the user so that he can select all the images another time without the images that were too large.
My problem is that I'm looping through all the images getting the width with FileReader and image.onload (which is async?), and since the invalid image(s) could be anywhere in the loop, I haven't been able to figure out a proper way to flag one or more of the images as invalid, wait for the loop to finish completely before handling the result. Setting 'validated' after the image has been loaded and the width is known does not seem to work since it's async hence the method always returns true.
Here's my code:
$('#fileUploadField').change(function (e) {
  if (window.FileReader) {
    if (this.files && this.files[0]) {
      var images = this.files;
      if(images && images[0]) {
        for (var i=0 ; i < images.length; i++) {
          var validated = validateImg(images[i]);
          if (validated = false) {
           //...do something
          }
        }
      }
    }
  }
});

function validateImg(file) {
  var reader = new FileReader(),
      image = new Image(),
      validated = true;

  reader.readAsDataURL(file);

  image.src = _file.target.result;
  reader.onload = function(_file) {
    image.onload = function() {
        var w = this.width,
            n = file.name;
      if (w > 640) {
        validated = false;
      } else {
        $('.imgs-preview-wrap').append('<img src="'+ image.src +'">');
      }
    };
  };
  return validated;
}

A: Not good. Javascript is insecure. Use PHP instead or any other server-side language.

A: I would do as follows. Make the upload button disabled by default. When an image is added, make it disabled, check the width and either leave the new image or remove it (mark it as invalid). After that enable the upload button. This way when the upload button is enabled, you will know that all the images are ok for upload.


text:
Q: How do I translate swift NSLayoutConstraint activateConstraints to objective c? I have successfully made a project in swift where I press buttons in my viewController to load other viewControllers or xib files into a container. Just to give you an idea:

It works great, but I'm having a difficult time translating it to objective-c which is where the code is actually needed. This is what the swift code looks like when pressing a button:
let sub3 = UINib(nibName: "thirdXib", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView

containerOutlet.addSubview(sub3)

NSLayoutConstraint.activate([
    sub3.leadingAnchor.constraint(equalTo: containerOutlet.leadingAnchor),
    sub3.trailingAnchor.constraint(equalTo: containerOutlet.trailingAnchor),
    sub3.topAnchor.constraint(equalTo: containerOutlet.topAnchor),
    sub3.bottomAnchor.constraint(equalTo: containerOutlet.bottomAnchor)
        ])

Now, I would like all that code to be in objective-c instead. In objective-c I have done the first part, which I assume is correct:
UINib *nib = [UINib nibWithNibName:@"SecondView" bundle:nil];
[nib instantiateWithOwner:self options:nil];

[containerOutlet addSubview:((UIView*)nib)];

But I'm having problem with the last part, NSLayoutConstraint activateConstraints
[NSLayoutConstraint activateConstraints:@[
        [nib.lead],
        [nib.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor],
        ]
 ];

The compiler says that property lead not found on object of type UIBib and same on the code just below. I have tried a variation of these, but don't get it right. How do I set trailing, leading, bottom and top constraints on my xib? Do I need to add #import SecondView.xib" in the.h` file? by the way?

A: You can try
UINib *nib = [UINib nibWithNibName:@"SecondView" bundle:nil];
UIView *sub3 = [nib instantiateWithOwner:self options:nil][0];
[containerOutlet addSubview:sub3];

[NSLayoutConstraint activateConstraints:@[
   [sub3.leadingAnchor constraintEqualToAnchor:scontainerOutlet.leadingAnchor],
   [sub3.trailingAnchor constraintEqualToAnchor:containerOutlet.trailingAnchor],
   [sub3.topAnchor constraintEqualToAnchor:containerOutlet.topAnchor],
   [sub3.bottomAnchor constraintEqualToAnchor:containerOutlet.bottomAnchor]
]];


text:
Q: Spring + Hibernate migration - currentSession() method throwing exception I have migrated Spring from 3.1 to 4.1.3 and Hibernate 3.2 to 4.3.9
As part of migration I have modified below import and code
old import
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
new Import
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;

and code changes
In hibernate 3 I have following code
public Session getCurrentSession() {
    Session session = getSession();
    session.setFlushMode(FlushMode.MANUAL);
    return session;
}

now I have modified according to new jars as below
public Session getCurrentSession() {
    Session session = currentSession();
    session.setFlushMode(FlushMode.MANUAL);
    return session;
    }

after the above changes I am getting below exception
    Could not obtain transaction-synchronized Session for current thread
org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
    at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:134)
    at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1014)
    at org.springframework.orm.hibernate4.support.HibernateDaoSupport.currentSession(HibernateDaoSupport.java:129)

I am not using annotations in my application
I am not able to resolve the issue. Please help me in knowing possible reasons for the exception

A: I guess you need to add transactionManager for your sesssionFactory:
<bean id="transactionManager"  class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory">
         <ref local="mySessionFactory"/>
    </property>
  </bean>

where, mySessionFactory is your Session Factory Bean Id.
As you said, you are not using Annotations in your project. Then, you must use AOP to enable Transaction Management at Method Level.
<tx:advice id="txAdvice" transaction-manager="transactionManager">
  <tx:attributes>
    <tx:method name="select*"  read-only="true" />
    <tx:method name="*" />
  </tx:attributes>
</tx:advice>
<aop:config>
  <aop:pointcut id="txPointcut" expression="execution(* example.MyClass.*(..))" />
  <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" />
</aop:config>

Add Transaction Support for your method like this.
Add following entry in your POM, if you are using MAVEN or gradle or you can simply download and add jar to your classpath.
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>4.3.3.RELEASE</version>
</dependency>


text:
Q: Can't use dep/glide packages from docker file task in azure devops to build images from other repos. Host Key Verifiaction failed error I'm trying to use docker container task in azure DevOps pipeline to build and push images to ACR and ECR. I am able to do that through a YAML file and automate all the processes but when I am trying the same with a docker file which has dep and glide packages to fetch from other repos both from public GitHub repos and private bitbucket repos. It fails with the Host Key Verification error. The same dockerfile works with Jenkins but I don't know how to solve this ssh-key error on a Hosted Ubuntu Agent.
Step 13/33 : RUN curl https://glide.sh/get | sh
 ---> Running in 26f7f0a19f91
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed

  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
  0  4833    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
100  4833  100  4833    0     0   6943      0 --:--:-- --:--:-- --:--:--  6934
ARCH=amd64
OS=linux
Using curl as download tool
Getting https://glide.sh/version
TAG=v0.13.3
GLIDE_DIST=glide-v0.13.3-linux-amd64.tar.gz
Downloading https://github.com/Masterminds/glide/releases/download/v0.13.3/glide-v0.13.3-linux-amd64.tar.gz
glide version v0.13.3 installed successfully
Removing intermediate container 26f7f0a19f91
 ---> d4aa1a720fab
Step 14/33 : RUN glide update --strip-vendor
 ---> Running in 4614138d27bc
[INFO]  wnloading dependencies. Please wait...
[INFO]  > Fetching bitbucket.org/myrepositoryname/common
[INFO]  > Fetching github.com/golang/protobuf
[INFO]  > Fetching bitbucket.org/myrepositoryname/myteksi
[INFO]  > Fetching bitbucket.org/myrepositoryname/sdk
[INFO]  > Fetching github.com/imdario/mergo
[INFO]  > Fetching gopkg.in/go-playground/validator.v9
[INFO]  > Fetching github.com/segmentio/kafka-go
[WARN]  able to checkout bitbucket.org/myrepositoryname/common
[ERROR] date failed for bitbucket.org/myrepositoryname/common: Unable to get repository: Cloning into '/root/.glide/cache/src/git-bitbucket.org-myrepositoryname-common.git'...
Host key verification failed.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
: exit status 128
Unable to get repository: Cloning into '/root/.glide/cache/src/git-bitbucket.org-myrepositoryname.git'...
Host key verification failed.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
: exit status 128
Unable to get repository: Cloning into '/root/.glide/cache/src/git-bitbucket.org-myrepositoryname.git'...
Host key verification failed.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
: exit status 128
The command '/bin/sh -c glide update --strip-vendor' returned a non-zero code: 1
##[debug]Exit code 1 received from tool '/usr/bin/docker'
##[debug]STDIO streams have closed for tool '/usr/bin/docker'
##[error]The command '/bin/sh -c glide update --strip-vendor' returned a non-zero code: 1
##[debug]Processed: ##vso[task.issue type=error;]The command '/bin/sh -c glide update --strip-vendor' returned a non-zero code: 1
##[debug]Trying to logout from registry: ***
##[debug]DOCKER_CONFIG=/home/vsts/work/_temp/DockerConfig_1564846219701
##[debug]agent.tempDirectory=/home/vsts/work/_temp
##[debug]Found the Docker Config stored in the temp path. Docker config path: /home/vsts/work/_temp/DockerConfig_1564846219701/config.json, Docker config: {"auths": { "***": {"auth": "***", "email": "ServicePrincipal@AzureRM" } }, "HttpHeaders":{"X-Meta-Source-Client":"VSTS"} }
##[debug]Deleting Docker config directory. Path: /home/vsts/work/_temp/DockerConfig_1564846219701/config.json
##[debug]DOCKER_CONFIG=/home/vsts/work/_temp/DockerConfig_1564846219701
##[debug]agent.tempDirectory=/home/vsts/work/_temp
##[debug]Deleting Docker config directory. Path: /home/vsts/work/_temp/DockerConfig_1564846219701
##[debug]set DOCKER_CONFIG=
##[debug]Processed: ##vso[task.setvariable variable=DOCKER_CONFIG;issecret=false;]
##[debug]task result: Failed
##[error]The process '/usr/bin/docker' failed with exit code 1
##[debug]Processed: ##vso[task.issue type=error;]The process '/usr/bin/docker' failed with exit code 1
##[debug]Processed: ##vso[task.complete result=Failed;]The process '/usr/bin/docker' failed with exit code 1

package: bitbucket.org/grabpay/ignite
import:
- package: bitbucket.org/myrepositoryname/common
  repo: git@bitbucket.org:myrepositoryname/common.git
  version: devel
  subpackages:
  - crimson
  - track
- package: bitbucket.org/myrepositoryname/myfolder1
  repo: git@bitbucket.org:myrepositoryname/myfolder1.git
  version: fface9afbb72a739d0de8c8969e0fa06fda44614
- package: bitbucket.org/myrepositoryname/myfolder2
  repo: git@bitbucket.org:myrepositoryname/myfolder2.git
  version: master
- package: github.com/imdario/mergo
  version: 2b9c8687f09d230f37f169eea24e1951bb7d1191
- package: gopkg.in/go-playground/validator.v9
- package: github.com/segmentio/kafka-go
- package: github.com/golang/protobuf
  version: ^1.3.1

The above file is the dependency repos that are to be fetched using glide.yml file.

A: I fixed it finally, what I needed was a service account which has read access to all the repos that glide is trying to access. Read access was required for all those repos with a Bitbucket Service Connection in Azure Pipeline. The error is not specific to glide, it is more inclined with the git repo access.


text:
Q: Server Render (SSR) One application in Single SPA I have below Layout (routes.html) in my Single SPA Application
<single-spa-router>
    <redirect from="/" to="/home"></redirect>

          <application name="@ppbet/layout-app"></application>

            <application name="@ppbet/layout-left"></application>

            <route path="home" exact>
              <application name="@ppbet/home-app"></application>
            </route>

                <application name="@ppbet/footer"></application>

            <application name="@ppbet/layout-right"></application>

  </single-spa-router>

I want the footer Application(A React Component) to be Server Render at the time of load of application.
I have read through SSR in Single SPA Looks like this to render a whole application on server side and rest of applications on client side. I even tried to use single-spa-html, But i see this will not render my HTML on Server side. Any help will be Appreciated.


text:
Q: Apply cohen.d to multiple columns I have a data frame of survey question responses. I would like to estimate Cohen's d effect sizes for each response using cohen.d from effsize.
Here are the first 6 rows of my data frame:
structure(list(id = c("HO1001", "HO1001", "HO1002", "HO1002",
"HO1003", "HO1003"), time = structure(c(1L, 2L, 1L, 2L, 1L, 2L
), .Label = c("0", "1"), class = "factor"), grit.distract = c(1,
1, 3, 2, 1, 2), grit.setback = c(5, 4, 3, 3, 4, 4), grit.obsess = c(3,
2, 2, 2, 3, 2), grit.work = c(4, 5, 3, 4, 5, 5), grit.goal = c(2,
3, 2, 1, 4, 4), grit.focus = c(3, 3, 3, 1, 2, 3), grit.finish = c(4,
4, 4, 4, 4, 3), grit.diligent = c(4, 4, 3, 4, 5, 4), grit.mean = c(3.25,
3.25, 2.875, 2.625, 3.5, 3.375)), class = c("tbl_df", "tbl",
"data.frame"), row.names = c(NA, -6L))

I successfully converted the df into wide format to use effsize on the summary statistics i.e. mean/total as follows:
structure(list(id = c("HO1001", "HO1002", "HO1003", "HO1004",
"HO1005", "HO1006"), pre = c(3.25, 2.875, 3.5, 2.25, NA, NA),
    post = c(3.25, 2.625, 3.375, 2.5, 2.75, 2.875), change = c(0,
    -0.25, -0.125, 0.25, NA, NA), highconf = structure(c(2L,
    1L, 2L, 1L, NA, NA), .Label = c("0", "1"), class = "factor")), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -6L)

cohen.d(grit.tot$pre, grit.tot$post, na.rm = T)

What I would like to do  is calculate the effect sizes for each survey item i.e. grit distract, grit.setback, etc. between time 0 and time 1 (please no comments on my statistical methods). Given that I have plenty more data frames like this and don't want to do them all individually, I believe that I should use a function and a loop such as apply but I'm not sure how to construct this.

A: If I have understood your question this may help.
If your data frame from the first part of your questions is stored as dt running the following should give the cohen d for each survey item.
lapply(dt[c(-1,-2)],function(x) cohen.d(x ~ dt$time))

dt[c(-1,-2)] removes the ID column and the time column as you don't want to run the cohen d test on these.


text:
Q: Is it a good programming practice to use import static fields? I declare some constant variables in my SQLiteOpenHelper class:
public static final String USERNAME = "user_name";
public static final String PASSWORD = "password";

In an Activity where I create SQL queries, I import these fields:
import com.mygame.ui.login.LoginInfoSQLiteOpenHelper.*;

Is this a good practice?
Or the traditional way of referring to constants better?
LoginInfoSQLiteOpen.USERNAME

A: A few years late to the party... but I feel it is worth providing the opposite point of view. There is a reason why Java was designed to have static field imports, and the reason is to hide how the class is implemented to users of the class. This is an important design principle for outwardly facing code. I would agree with c00kiemon5ter take on it, however, there might be situations in which it is worthwhile.
More info on static field importing can be found here: https://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html

A: I recommend the second method, only importing classes not fields. So prefixing your constants with the owning class, like LoginInfoSQLiteOpen.USERNAME. It can become highly redundant, but it is much more readable and maintainable in the long run.

A: If you look at someone's code and see a field like
foo.do(baz, USERNAME);

wut(!), where did that var come from ?
search, grep, where is it declared ?
Using it as ClassName.FIELD makes things much clearer and cleaner.
You avoid confusion, and sometimes it makes more sense to have a proper classname that denotes the field, than a field that came out of nowhere.

well, not everyone uses an IDE, and not everyone reads code through an IDE(maybe through a repository on the web), and even some consider VIM an IDE, and I do use vim a lot(although I don't think of it as an IDE).
So, it's not about what an IDE can or can't do, but more of what code reading is about. Code reading, code quality, expressing ideas in your programming language of choice, in a way through abstractions that make sense and tie well together.


text:
Q: Detect If push notifications were received when app is not launched and user didn't open the app through them Is it possible to detect if a push notification was received while the app was offline (not in background or foreground ? given the case that the user open the app directly from the spring board and not from the push notification alert.

A: From documentation of
- application:didReceiveRemoteNotification:fetchCompletionHandler:

the system calls this method when your app is running in the foreground or background.

But, as you may have found out by your question

However, the system does not automatically launch your app if the user has force-quit it. In that situation, the user must relaunch your app or restart the device before the system attempts to launch your app automatically again.

A: In your AppDelegate do this (sorry for swift implementation):
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    // We see if we have a recent push notification date stored in the user defaults.
    // If there hasn't been a recent one sent this if block will not be entered.
    if let mostRecentPushNotificationDate = NSUserDefaults.standardUserDefaults().objectForKey("mostRecentPushNotification") as? NSDate {

        // We find the difference between when the notification was sent and when the app was opened
        let interval = NSDate().timeIntervalSinceDate(mostRecentPushNotificationDate)

        // Check to see if we opened from the push notification
        if let notification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? [String: AnyObject] {
            print("we opened from the push notifcation and the time difference was \(interval) seconds.")
        }

        // We did not open from a push notification
        else {
            print("we opened from the spring board and the time difference was \(interval) seconds.")
        }

        // We remove the object from the store so if they open the app without a notification being sent we don't check this if block
        NSUserDefaults.standardUserDefaults().removeObjectForKey("mostRecentPushNotification")
    }

    return true
}

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {

    // Set a flag when a push notification was sent
    NSUserDefaults.standardUserDefaults().setObject(NSDate(), forKey: "mostRecentPushNotification")
}

A: - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // ...
    if (launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey]) {
        [self application:application didReceiveRemoteNotification:launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey]];
    }
}

This should work.
The moment you open the app, the notifications you have received in notification center that you will get as a payload in didFinishLaunchingWithOptions and then you can perform the specific operation.


text:
Q: PHP5 and DOM changing XML node attribute value Having the next XML(Idatzi.xml) :
<?xml version='1.0' encoding='ISO-8859-1'?>
<!DOCTYPE markables SYSTEM "markables.dtd">
<markables>
<markable id="markable_1" atrib="yes" span="word_1..word_4"> </markable>
<markable id="markable_2" atrib="no" span="word_6..word_7"> </markable>
<markable id="markable_3" atrib="yes" span="word_10..word_24"> </markable>
</markables>

And the next PHP code:
<?php

$xmlIdatziDok = new DOMDocument();
if($xmlIdatziDok->load("Idatzi.xml") === FALSE){die('Error');}
$xPath_IdatziDok = new DOMXPath($xmlIdatziDok);

foreach ($xPath_IdatziDok->query('//markables/markable') AS $Idaztekoa)
{
  $IdaztekoaID = $Idaztekoa->getAttribute('id');
  $IdaztekoaAtrib = $Idaztekoa->getAttribute('atrib');

    if($IdaztekoaAtrib != "yes")
    {
      $Idazteko->Attribute('atrib') = "yes";
    }
}

I would like to know how to correctly write the next line of code in the PHP code:
$Idazteko->Attribute('atrib') = "yes";

It is obviously wrong written. What I would like to do is to change the "no" of markable_2 to "yes". Any idea?

A: You can find this information in the documentation.
$Idaztekoa->setAttribute('atrib', 'yes');

A: Use the xpath query to directly select all attributes you'd like to change and manipulate them:
foreach($xp->query('/markables/markable/@atrib[. != "yes"]') as $attrib)
{
    $attrib->nodeValue = 'yes';
}

and done. Full example:
$xml = <<<XML
<?xml version='1.0' encoding='ISO-8859-1'?>
<!DOCTYPE markables SYSTEM "markables.dtd">
<markables>
    <markable id="markable_1" atrib="yes" span="word_1..word_4"> </markable>
    <markable id="markable_2" atrib="no" span="word_6..word_7"> </markable>
    <markable id="markable_3" atrib="yes" span="word_10..word_24"> </markable>
</markables>
XML;

$doc = new DOMDocument();
$doc->loadXML($xml);
$xp = new DOMXPath($doc);

foreach($xp->query('/markables/markable/@atrib[. != "yes"]') as $attrib)
{
    $attrib->nodeValue = 'yes';
}

echo $doc->saveXML();


text:
Q: How do I cluster values of y axis against x axis in scatterplot? Lets say I've 2 arrays
x = [1,2,3,4,5,6,7]
y = [1,2,2,2,3,4,5]
its scatter plot looks like this

what I want to do is that I want my x axis to look like this in the plot
0,4,8
as a result of which values of y in each piece of x should come closer .
The similar behavior I've seen is bar plots where this is called clustering , how do I do the same in case of scatter plot , or is there any other plot I should be using ?
I hope my question is clear/understandable .
All the help is appreciated

A: With you plot, try this, before you display the plot.
plt.xticks([0,4,8]))

or
import numpy as np
plt.xticks(np.arange(0, 8+1, step=4))

Then to change the scale you can try something like this,
plt.xticks([0,4,8]))
plt.rcParams["figure.figsize"] = (10,5)

I got this with my example,
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 30)
y = np.sin(x)

plt.xticks([0,4,8])
plt.rcParams["figure.figsize"] = (7,3)
plt.plot(x, y, 'o', color='black')

output

A: I think what you are looking for is close to swarmplots and stripplots in Seaborn. However, Seaborn's swarmplot and stripplot are purely categorical on one of the axes, which means that they wouldn't preserve the relative x-axis order of your elements inside each category.
One way to do what you want would be to increase the space in your x-axis between categories ([0,4,8]) and modify your xticks accordingly.
Below is an example of this where I assign the data to 3 different categories: [-2,2[, [2,6[, [6,10[. And each bar is dil_k away from its directly neighboring bars.
import matplotlib.pyplot as plt
import numpy as np

#Generating data
x= np.random.choice(8,size=(100))
y= np.random.choice(8,size=(100))
dil_k=20

#Creating the spacing between categories
x[np.logical_and(x<6, x>=2)]+=dil_k
x[np.logical_and(x<10, x>=6)]+=2*dil_k

#Plotting
ax=plt.scatter(x,y)

#Modifying axes accordingly
plt.xticks([0,2,22,24,26,46,48,50],[0,2,2,4,6,6,8,10])

plt.show()

And the output gives:

Alternatively, if you don't care about keeping the order of your elements along the x-axis inside each category, then you can use swarmplot directly.
The code can be seen below:
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

#Generating data
x= np.random.choice(8,size=(100))
y= np.random.choice(8,size=(100))

#Creating the spacing between categories
x[np.logical_and(x<2,x>=-2)]=0
x[np.logical_and(x<6, x>=2)]=4
x[np.logical_and(x<10, x>=6)]=8

#Plotting
sns.swarmplot(x=x,y=y)

plt.show()

And the output gives:


text:
Q: Multi-header column alignment with booktabs After looking at multiple tex.stackexchange questions, I'm still having trouble getting the alignment of multiple columns right.
Here's my code
\documentclass[a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{booktabs}
\begin{document}

\begin{tabular}{@{}lcccc@{}}
    \toprule
        & \multicolumn{2}{@{}c}{Ignoring Unlabeled Detections}
        & \multicolumn{2}{c@{}}{Approving Unlabeled Detections}\\
    \cmidrule(r){2-3}
    \cmidrule(r){4-5}
        & Recall  & Precision    & Recall  & Precision  \\
    \cmidrule(r){2-3}
    \cmidrule(r){4-5}
    % \midrule
    count           & 513     & 446         &  529     & 484     \\
    mean            & 0.428   & 0.787       &  0.507   & 0.841   \\
    std             & 0.343   & 0.365       &  0.337   & 0.310   \\
    min             & 0.000   & 0.000       &  0.000   & 0.000   \\
    \ensuremath{Q_1}& 0.000   & 0.667       &  0.286   & 0.800   \\
    \ensuremath{Q_2}& 0.500   & 1.000       &  0.500   & 1.000   \\
    \ensuremath{Q_3}& 0.667   & 1.000       &  0.750   & 1.000   \\
    max             & 1.000   & 1.000       &  1.000   & 1.000   \\
    \bottomrule
\end{tabular}

\end{document}

Which gives the result

I would naturally like the recall and precision columns to be equally spaced beneath each respective title.

A: You could give the table header more visual structure, along the lines of the following example, by creating an additional line. You're of course entirely free to modify the proposed overall header, "Actions regarding unlabeled detections".

\documentclass[a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{booktabs}
\begin{document}
\begin{center}
\begin{tabular}{@{} l cccc @{}}
    \toprule
    & \multicolumn{4}{c@{}}{Actions regarding unlabeled detections}\\
    \cmidrule(l){2-5}
    & \multicolumn{2}{c}{Ignore} & \multicolumn{2}{c@{}}{Approve}\\
    \cmidrule(lr){2-3} \cmidrule(l){4-5}
    & Recall & Precision & Recall & Precision  \\
    \midrule
    count & 513     & 446         &  529     & 484     \\
    \addlinespace
    mean  & 0.428   & 0.787       &  0.507   & 0.841   \\
    std   & 0.343   & 0.365       &  0.337   & 0.310   \\
    \addlinespace
    min   & 0.000   & 0.000       &  0.000   & 0.000   \\
    $Q_1$ & 0.000   & 0.667       &  0.286   & 0.800   \\
    $Q_2$ & 0.500   & 1.000       &  0.500   & 1.000   \\
    $Q_3$ & 0.667   & 1.000       &  0.750   & 1.000   \\
    max   & 1.000   & 1.000       &  1.000   & 1.000   \\
    \bottomrule
\end{tabular}
\end{center}
\end{document}

A: Here is a version that keeps the headers as they are and sets the column width of the second to fifth column with respect to the width of the corresponding multirow header.
However, I personally would prefer Mico's solution as there are quite large white spaces in my version of the table.

\documentclass[a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{booktabs}
\usepackage{calc}
\usepackage{array}

\begin{document}

\begin{tabular}{@{}l*{4}{>{\centering\arraybackslash}p{\widthof{Approving Unlabeled Detections}/2 - 2\tabcolsep}}@{}}
    \toprule
        & \multicolumn{2}{@{}c}{Ignoring Unlabeled Detections}
        & \multicolumn{2}{c@{}}{Approving Unlabeled Detections}\\
    \cmidrule(r){2-3}
    \cmidrule(r){4-5}
        & Recall  & Precision    & Recall  & Precision  \\
    \cmidrule(r){2-3}
    \cmidrule(r){4-5}
    % \midrule
    count           & 513     & 446         &  529     & 484     \\
    mean            & 0.428   & 0.787       &  0.507   & 0.841   \\
    std             & 0.343   & 0.365       &  0.337   & 0.310   \\
    min             & 0.000   & 0.000       &  0.000   & 0.000   \\
    $Q_1$           & 0.000   & 0.667       &  0.286   & 0.800   \\
    $Q_2$           & 0.500   & 1.000       &  0.500   & 1.000   \\
    $Q_3$           & 0.667   & 1.000       &  0.750   & 1.000   \\
    max             & 1.000   & 1.000       &  1.000   & 1.000   \\
    \bottomrule
\end{tabular}

\end{document}


text:
Q: How do I add a new datamember to my custom checkboxlist? Does anybody know how to add a new data member to a subclass of checkedboxlist?
I have tried messing around with creating my own widgets,
and have tried to get datagridview to behave the way I want it to.
the latter with no luck and the former I might not ever finish.
Here is a bindable checklistbox that I am trying to modify to fit my needs.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Design;

namespace WinformsTest.Controls
{

    [ToolboxBitmap(typeof(CheckedListBox))]
    public class BindableCheckboxList : CheckedListBox
    {
        public BindableCheckboxList()
        {
            this.CheckOnClick = true;

        }

        [DefaultValue("")]
        [TypeConverter("System.Windows.Forms.Design.DataMemberFieldConverter, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
        [Editor("System.Windows.Forms.Design.DataMemberFieldEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
        [Browsable(true)]
        [Category("Data")]
        public new string DisplayMember
        {
            get
            {
                return base.DisplayMember;
            }
            set
            {
                base.DisplayMember = value;
            }
        }

        [DefaultValue("")]
        [TypeConverter("System.Windows.Forms.Design.DataMemberFieldConverter, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
        [Editor("System.Windows.Forms.Design.DataMemberFieldEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
        [Browsable(true)]
        [Category("Data")]
        public string CheckedMember
        {
            get;
            set;
        }

        [DefaultValue("")]
        [TypeConverter("System.Windows.Forms.Design.DataMemberFieldConverter, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
        [Editor("System.Windows.Forms.Design.DataMemberFieldEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
        [Browsable(true)]
        [Category("Data")]
        public new string ValueMember
        {
            get
            {
                return base.ValueMember;
            }
            set
            {
                base.ValueMember = value;

            }
        }

        [DefaultValue("")]
        [AttributeProvider(typeof(IListSource))]
        [RefreshProperties(RefreshProperties.All)]
        [Browsable(true)]
        [Category("Data")]
        public new object DataSource
        {
            get
            {
                return base.DataSource;
            }
            set
            {
                base.DataSource = value;
            }
        }
    }
}

Note I am trying to add a CheckedMember
I expect the checkedlistbox to update the checkboxes to checkedMember if the datasource is valid and bindable.