text:
Q: Accessing another partition My Ubuntu crashed so I installed a new one in a new partition.
I now need to access the old partition.
How do I do that?
I found a partial answer here:
How to access old partitions after installing Ubuntu?
but I'm stuck because there's a huge list of entries at my /dev  and I don't know which one is my old partition.

A: If you run dmesg you can see a listing of every partition you have and where you can access it (/dev/sda, sdb ...)
For example
[    1.652568] sd 0:0:0:0: [sda] 625142448 512-byte logical blocks: (320 GB/298 GiB)
[    1.652575] sd 0:0:0:0: Attached scsi generic sg0 type 0
[    1.652740] sd 0:0:0:0: [sda] Write Protect is off
[    1.652745] sd 0:0:0:0: [sda] Mode Sense: 00 3a 00 00
[    1.652870] sd 0:0:0:0: [sda] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA

dmesg outputs a lot of data, but you can redirect the output to a file and then search through it, for example:
dmesg > log
nano log

A: lshw includes disk information under the entries labelled 'disk' - that should give you some idea - look for a disk with no mounted partitions there.
-disk
                description: SCSI Disk
                physical id: 0.0.0
                bus info: scsi@2:0.0.0
                logical name: /dev/sda

A: If you want the easy GUI way, try pysdm. Install and then run it, like this:
sudo apt-get install pysdm
sudo pysdm

You will see the available partitions in the left pane something like sda, stb, ... You can click on them to reveal the logical partitions there. Choose the one that looks like the old partition. It is likely to have the type "ext4".
Click on Assistant to change the options as desired, for example, to enable auto-mount on boot. Or enable read-only mode should you want to protect the mounted partition.
You should also specify the "Mountpoint" as the directory where you will be accessing the mounted partition. Something like /media/oldstuff might do. You may choose an existing (empty) directory, or create a new one.
Then click on Mount. The partition should be mounted now.
How it works: The program edits the /etc/fstab file where the mounted partitions are defined. An expert might edit the file directly. You might want to make a backup copy before trying. And if you want to do the mounting by hand - read man fstab.


text:
Q: Trying to Fix my remote for my house Fan, is this component a fuse? Decided I would try and fix the remote for this 3 speed fan I have a home since it is summer now. Here's the circuitry I'm dealing with here:

So here our are some notes:

*

*There was some battery leakage when I opened it up, but I cleaned the battery contacts. Would this be harmful to say the ceramic resonator or capacitors?

*I replaced the IR bulb with no luck (in the right orientation)

*All contacts look good, nothing looks like it burned up

My next move was to replace what I think is a fuse below that NPN transitor. Can anyone confirm that little red thing is indeed a fuse? If so, I have a bunch of these standard green ones lying around that I could put in.
EDIT::  Here's the bottom:

A: The "little red thing" is a diode. Without physical evidence of damage, it's probably fine.

A: Battery leakage typically just corrodes the battery terminals. If it leaks onto the circuit board and gets between pins of devices, it could cause some issues but that is rare. Isopropyl rubbing alcohol and a small brush or cotton swab will usually clean it up very well.
The "IR bulb" is an IR LED, and appears to be wired correctly. But where did this replacement come from? There are literally a million different types of LED's; getting an exact match can be quite difficult. Generally, they don't "burn out" the way a traditional bulb would, so there is very little chance the original is defective unless it is broken, melted, or burnt-looking (or smelling) in any way.
Is the new LED soldered correctly?
A tip: try pointing the remote at any modern type of video recorder (such as a cellphone) and press a button. Modern (CMOS-imager based) video recording devices are usually sensitive to IR, so if the circuit it working, you should see the LED light up on the recording. An example of a remote being visible by webcam can be found here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to make jquery draggable works on touch devices? i have a project thats already work on desktops and i need it to be supported on touch devices
currently i'm using jQuery ui .draggable()
object.droppable( {
  accept: '#draggable div',
  hoverClass: 'hovered',
  drop: handleDrop,
} );

is there any way that i can make touch events treated as draggable so i'll not needed to edit my code a lot ??
i've tried this touch punch http://touchpunch.furf.com
but it doesn't work for some reason even the demo on the link doesn't work on my android as well


text:
Q: PHP : Is there a way, to write this if/elseif/else statement shorter? So I have been actively learning PHP for the past days and, for practise, I wrote PHP script, which takes HTML Form values.
I tried writing script, where I have 5 persons, and you have to input your name and last name. If it matches with one of the five persons, it sends one message, if not, other. Here it is (Without form part, only PHP):
    $first = $_POST["first"];
    $last = $_POST["last"];

    if ($first == "Jeb") {
        if ($last == "Jeb") {
            print "Hello!";
        } else {
            print "I dont know you!";
        }
    } elseif ($first == "Bob") {
        if ($last == "Bob") {
            print "Hello!";
        } else {
            print "I dont know you!";
        }
    } elseif ($first == "Bill") {
        if ($last == "Bill") {
            print "Hello!";
        } else {
            print "I dont know you!";
        }
    } elseif ($first == "Annie") {
        if ($last == "Annie") {
            print "Hello!";
        } else {
            print "I dont know you!";
        }
    } elseif ($first == "Hugo") {
        if ($last == "Hugo") {
            print "Hello!";
        } else {
            print "I dont know you!";
        }
    } else {
        print "I dont know you!";
    }

It works great, but I have question- can this be done easier / written shorter? And can this be done using switch statement?
Any respone will be apprecieted!

A: i can see a way using arrays
$people=array('Bob Bob', 'Bill Bill');//etc

if(in_array($first.' '.$last,$people)){
 print "Hello!";
}else{
   print "I dont know you!";
}

A: A solution using arrays. Assumes all known names are pairs of the same name (bob bob, jeb jeb, etc)
$knownNames = array("Jeb", "Bob", "Bill", "Annie", "Hugo");
if (in_array($first, $knownNames) && $first == $last)
  print "Hello!";
else
  print "I don't know you!"

A: I'd use arrays instead (avoids duplicating code/ifs)
$name = array(
  'first' => $_POST["first"],
  'last'  => $_POST["last"]
);

$knownNames = array(
  array(
    'first' => 'Bob',
    'last'  => 'Bob'
  ),
  array(
    'first' => 'Bill',
    'last'  => 'Bill'
  ),
  array(
    'first' => 'Annie',
    'last'  => 'Annie'
  ),
  array(
    'first' => 'Hugo',
    'last'  => 'Hugo'
  )
);

if (in_array($name, $knownNames)) {
    print "Hello!";
} else {
    print "I dont know you!";
}

A: In your example, you are making a decision based on two tests:
Do I recognize the submitted first name?
Do I recognize the submitted last name?
Then you are responding based on whether the above tests are BOTH true.
I would suggest that you separate each test into it's own function:
    function isValidFirstName($name)
    {
        $valid_names = array('Jeb','Bob','Bill','Annie','Hugo');
        return in_array($name, $valid_names);
    }

    function isValidLastName($name)
    {
        $valid_names = array('Jeb','Bob','Bill','Annie','Hugo');
        return in_array($name, $valid_names);
    }

    $first = $_POST['first'];
    $last = $_POST['last'];

    if( isValidFirstName($first) && isValidLastName($last) )
    {
        print "Hello!";
    } else
    {
        print "I don't know you!";
    }


text:
Q: Check if elements from different lists are in df column and append to another column I have a df like this:

Casa
Name
Clase_jfs
Categoria

Just_For_Sports
mochila reebok active
ACCESORIOS
mochila

Just_For_Sports
tubo lejopi de pelotas softee
ACCESORIOS
tubo

Just_For_Sports
pack de medias puma x2
ACCESORIOS
pack

Just_For_Sports
gorro adidas de natación 3 rayas
ACCESORIOS
natacion

And 27 different Lists like these:
MODA=['mochila','wear', 'urban', 'pack']
TENIS=['tubo', 'raqueta','red']
NATACION=['natacion', 'pileta','tapon']

on the other hand I have an empty list:
intermedia1=[]

this is my current script:
for element in df_JFS['Categoria']:
    if  element in VOLEY:
        intermedia1.append('VOLEY')
    elif element in UNIFORMES:
        intermedia1.append('UNIFORMES')
    elif element in TREKKING_OUTDOOR_ADVENTURE:
        intermedia1.append('TREKKING_OUTDOOR_ADVENTURE')
    elif element in TRAINING:
        intermedia1.append('TRAINING')
    elif element in TENIS:
        intermedia1.append('TENIS')
    elif element in SURF:
        intermedia1.append('SURF')
    elif element in SQUASH:
        intermedia1.append('SQUASH')
    elif element in SKATEBOARD:
        intermedia1.append('SKATEBOARD')
    elif element in RUNNING:
        intermedia1.append('RUNNING')
    elif element in RUGBY:
        intermedia1.append('RUGBY')
    elif element in PING_PONG:
        intermedia1.append('PING_PONG')
    elif element in PESAS:
        intermedia1.append('PESAS')
    elif element in PADDLE:
        intermedia1.append('PADDLE')
    elif element in NATACION:
        intermedia1.append('NATACION')
    elif element in MODA:
        intermedia1.append('MODA')
    elif element in INFANTIL:
        intermedia1.append('INFANTIL')
    elif element in HOCKEY:
        intermedia1.append('HOCKEY')
    elif element in HANDBALL:
        intermedia1.append('HANDBALL')
    elif element in GOLF:
        intermedia1.append('GOLF')
    elif element in FUTBOL:
        intermedia1.append('FUTBOL')
    elif element in FRONTON:
        intermedia1.append('FRONTON')
    elif element in CICLISMO:
        intermedia1.append('CICLISMO')
    elif element in BASQUET:
        intermedia1.append('BASQUET')
    elif element in BASICOS:
        intermedia1.append('BASICOS')
    elif element in BASEBALL_SOFTBALL:
        intermedia1.append('BASEBALL_SOFTBALL')
    elif element in ARTES_MARCIALES_Y_BOX:
        intermedia1.append('ARTES_MARCIALES_Y_BOX')
    elif element in AEROBICS_Y_FITNESS:
        intermedia1.append('AEROBICS_Y_FITNESS')
    else:
        intermedia1.append('OTROS')

df_JFS['Categoria']=intermedia1

How can it be done efficiently?
output should look like this:

Casa
Name
Clase_jfs
Categoria

Just_For_Sports
mochila reebok active
ACCESORIOS
MODA

Just_For_Sports
tubo lejopi de pelotas softee
ACCESORIOS
TENIS

Just_For_Sports
pack de medias puma x2
ACCESORIOS
MODA

Just_For_Sports
gorro adidas de natación 3 rayas
ACCESORIOS
NATACION

df['Categoria'] value, should be the name of the list where the word was found
Thanks!

A: Not sure about the time efficiency, but if you want to prevent boilerplate coding, you can use apply function along with a few other steps:
import pandas as pd
# Defining the lists of data(rest of the code)
# .
# .
myDict ={'MODA':MODA, "TENIS":TENIS, "NATACION":NATACION}
def search(valueToSearch):
  for key, valuesList in myDict.items():
    if valueToSearch in  valuesList:
      return key
  return "Not Found"
df["Categoria"] = df["Categoria"].apply(search)
df

Output

Casa
Name
Clase_jfs
Categoria

0
Just_For_Sports
mochila reebok active
ACCESORIOS
MODA

1
Just_For_Sports
tubo lejopi de pelotas softee
ACCESORIOS
TENIS

2
Just_For_Sports
pack de medias puma x2
ACCESORIOS
MODA

3
Just_For_Sports
gorro adidas de natación 3 rayas
ACCESORIOS
NATACION

Note that, you should define the myDict as shown above. If you have any other list, you should define them in myDict variable in the same way.

A: There are few approaches I would suggests
Approach 1
The complexity of finding something in a list is O(n). it optimise that you can use a set instead which is O(1).
MODA = set(['mochila', 'wear', 'urban', 'pack'])

Approach 2
If all of the value of all the list is unique, you can create a dict that map values to key.
You can just write a loop to map value to key the result should be like below:
{
 'mochila': "MODA",
 'wear': "MODA",
 'urban': "MODA",
 'pack': "MODA",
 ...
}


text:
Q: Git commands to run for build machines to keep the repo as trouble free as possible We are finding out by trial error which commands we should be running on our git repository (through a Jenkins job) before the BM starts an automatic build.
As an example, we now run a git remote prune origin to clean up the branches due to the cannot lock ref issue.
Is there a known list of commands that we should be running to keep the repository as clean as possible for the next git pull --ff-only to always succeed?

Note that our repository, due to LFS, is huge and we cannot do what some CIs do, which is reclone the repository with every run.


text:
Q: The convergence or divergence of the $1-\frac{1}{2^\alpha}+\frac{1}{3}-\frac{1}{4^\alpha}+\frac{1}{5}+\cdots$ I am coming to get some feedback about a problem.

The convergence or divergence of the $1-\frac{1}{2^\alpha}+\frac{1}{3}-\frac{1}{4^\alpha}+\frac{1}{5}+\cdots$ when $\alpha$ has different value.

The following is my solution:
When $\alpha>0$, $\frac{1}{n^\alpha}\rightarrow 0$, so according to the Leibniz test, it is convergent.
When $\alpha<0$, it equals $1-2^{|\alpha|}+3-4^{|\alpha|}\cdots$, the even term $2n$ of  the partial sum is $$n\frac{(2n-1)+1}{2}-\sum_{i=1}^{n} 2^{|\alpha|i}=n\frac{(2n-1)+1}{2}-  \frac{2^{|\alpha|}(1-2^{|\alpha|n})}{1-2^{|\alpha|}}\rightarrow -\infty,$$ so the series is divergent.
Can you give me some advice about my solution? Or if there is other solution, looking forward to see it!

A: The general term of you series $\sum_{k\ge 1} u_k$ is
$$u_k=\frac{1}{2k-1}-\frac{1}{(2k)^\alpha}$$
$$=\frac{(2k)^\alpha-2k+1}{(2k-1)(2k)^\alpha}$$
For example, if $\alpha=1,$
$$u_k \sim \frac{1}{4k^2}$$
the series is convergent.
If $\alpha>1,$
$$u_k \sim \frac{1}{2k-1}$$
the series is divergent.
If $ \alpha<1,$
$$u_k \sim \frac{-1}{(2k)^\alpha}$$
the series is divergent.


text:
Q: Sed dynamic backreference replacement I am trying to use sed for transforming wikitext into latex code. I am almost done, but I would like to automate the generation of the labels of the figures like this:
[[Image(mypicture.png)]]

... into:
\includegraphics{mypicture.png}\label{img-1}

For what I would like to keep using sed. The current regex and bash code I am using is the following:
__tex_includegraphics="\\\\includegraphics[width=0.95\\\\textwidth]{$__images_dir\/"
__tex_figure_pre="\\\\begin{figure}[H]\\\\centering$__tex_includegraphics"
__tex_figure_post="}\\\\label{img-$__images_counter}\\\\end{figure}"

sed -e "s/\[\[Image(\([^)]*\))\]\].*/$__tex_figure_pre\1$__tex_figure_post/g"\

... but I cannot make that counter to be increased. Any ideas?
Within a more general perspective, my question would be the following: can I use a backreference in sed for creating a replacement that is different for each of the matches of sed? This is, each time sed matches the pattern, can I use \1 as the input of a function and use the result of this function as the replacement?
I know it is a tricky question and I might have to use AWK for this. However, if somebody has a solution, I would appreciate his or her help.

A: You could read the file line-by-line using shell features, and use a separate sed command for each line. Something like
exec 0<input_file

while read line; do
    echo $line | sed -e "s/\[\[Image(\([^)]*\))\]\].*/$__tex_figure_pre\1$__tex_figure_post/g"
    __images_counter=$(expr $__images_counter + 1)
done

(This won't work if there are multiple matches in a line, though.)
For the second part, my best idea is to run sed or grep to find what is being matched, and then run sed again with the value of the function of the matched text substituted into the command.

A: This might work for you (GNU sed):
sed -r ':a;/'"$PATTERN"'/{x;/./s/.*/echo $((&+1))/e;/./!s/^/1/;x;G;s/'"$PATTERN"'(.*)\n(.*)/'"$PRE"'\2'"$POST"'\1/;ba}' file

This looks for a PATTERN contained in a shell variable and if not presents prints the current line. If the pattern is present it increments or primes the counter in the hold space and then appends said counter to the current line. The pattern is then replaced using the shell variables PRE and POST and counter. Lastly the current line is checked for further cases of the pattern and the procedure repeated if necessary.


text:
Q: Why after Form violation input File field are empty? Maybe this will a dumb questions, but I'll try.
For Example:
<form>
 First name: <input type="text" name="name">

 Select a file: <input type="file" name="photo">

 <input type="submit" value="Submit">
</form>

in this classic form I have 2 fields, name and photo. The photo can be all kind of image, the name min 4 character.
If I submit the form with a valid photo but invalid name, I'll generally redirect to the form page with the name input precompiled with the invalid name, but not with photo field precompiled.
I saw this behavior in all my useCase (generally I use Symfony).
Is this a classic http flow or other else? Can I modify this behavior?


text:
Q: (Multivariable) Deriving a Formula for Volume of Cone The problem:
Let $P = (a, b, h), h > 0$, be a point in $\mathbf{R}^3$. If $D$ is a region in the $xy-$plane, the solid cone with base $D$ and apex $P$ is obtained by joining all points of $D$ to $P$ by line segments. If $A$ is the area of the base $D$, derive a formula of the cone in terms of $a, b, h$ and $A$.
I'm confused where to even start! (I need to use Multivariable Calculus)

A: Let $M$ be a circle of radius $R$ with center $(a,b,0)$ i.e $(x-a)^2+(y-b)^2 = R^2$. In view of this equation, we know that our region of integration is:
$$\left\{(x,y):-\sqrt{R^2-(x-a)^2}+b \leq y \leq \sqrt{R^2-(x-a)^2}+b,  -R \leq x \leq R\right\}$$
You can use polar coordinates to simplify the region. Let $x = R \cos \theta, y = R \sin \theta$ then expanding the above we have:
$$x^2-2ax+a^2+ y^2 - 2yb+b^2 = R^2 \iff R^2-2(aR\cos\theta + b R \sin \theta)+(a^2+b^2) = R^2$$
Knowing that $(a,b)$ lies on some circle of radius $\lambda$ (i.e $\lambda^2 = a^2+b^2$) and cancelling some terms above, we have:
$$2R(a \cos\theta + b \sin \theta) = \lambda^2 \iff R = \frac{\lambda^2}{2(a \cos \theta + b \sin \theta)}$$
Therefore the volume is given by:
$$\int_{0}^{2\pi}\int_{0}^{\frac{\lambda^2}{2(a \cos \theta + b \sin \theta)}} r\int_0^h dz \ dr \ d\theta$$

A: We all know that the volume of this cone $C$ computes to
$${\rm vol}(C)={1\over3}{\rm area}(D)\cdot h\ .\tag{1}$$
A calculus proof of $(1)$ can be given as follows: Let
$C_z:=\{(x,y)\>|\>(x,y,z)\in C\}$ be the section of $C$ cut out by the horizontal plane at level $z$. One then has
$${\rm area}(C_z)=\left({h-z\over h}\right)^2\cdot{\rm area}(D)\ .$$
Fubini's theorem now gives
$$\eqalign{{\rm vol}(C)&=\int_C 1\>{\rm d}(x,y,z)=\int_0^h\int_{C_z}1\>{\rm d}(x,y)\>dz\cr &=\int_0^h{\rm area}(C_z)\>dz={\rm area}(D)\int_0^h\left({h-z\over h}\right)^2\>dz\cr
&={1\over3}{\rm area}(D)\cdot h\ .\cr}$$

A: There's a really slick proof of this using the divergence theorem that I saw years ago, I think in "Grad, Div, Curl, and All That."  Position the apex of the cone at the origin and the base in a plane parallel to the $xy-$plane.  Let $F(x,y,z) = (x,y,z)$ and apply the divergence theorem.  On the left-hand side, you get 3 times the volume.  On the right hand side, the flux through the lateral surface is $0$, since the normal is orthogonal to the flow, and on the base, it's equal to the height times the area of the base.  QED.  I apologize for not putting this in formulas, but my MathJax skills just aren't up to it, and I like the proof too much not to share it.


text:
Q: gorm unsupported data type interface gorm unsupported data type interface.
How do I save different structures to one field in json (gorm)? Type checking needed, not just serialization in Json.
Example code with error: unsupported data type: models.Fields
// table questions (GORM)
type Questions struct {
    ID
    Fields  `json:"fields"`
//  .....
}

type Fields interface{
//  ...
}

// radio ----------
type Radio struct {
    Text string
    Img string
    //  ...
}

func (d Radio) Value() (driver.Value, error) {
    return json.Marshal(d)
}

func (d *Radio) Scan(value interface{}) error {
    b, ok := value.([]byte)
    if !ok {
        return errors.New("type assertion to []byte failed")
    }
    return json.Unmarshal(b, &d)
}

// Checkbox ----------
type Checkbox struct {
    Text string
    MaxCheckbox   uint16
    //  ...
}

func (d Checkbox) Value() (driver.Value, error) {
    return json.Marshal(d)
}

func (d *Checkbox) Scan(value interface{}) error {
    b, ok := value.([]byte)
    if !ok {
        return errors.New("type assertion to []byte failed")
    }
    return json.Unmarshal(b, &d)
}

A: You might have already solved this, but you need to use polymorphism.


text:
Q: Assertion failure for WebAuth data with libfido2 I have integrated libfido2 library release dlls in my Windows application which is developed in c# for enrolling and authenticating the user via FIDO device.
So, After enrolling the user I store the publicKey and CredentailId in the database generated from FidoCredential class and then authenticate the user using the same publicKey and CredentailId using the FidoAssertion class Verify method. So, As far as everything is working fine.
As This application also has integration over the Web so on web I have used WebAuthn for the FIDO2 for Enrolling and Authenticating the user. So, the enrollment and authentication on the web part also working fine.
But, When I try to authenticate the user on the windows application which uses libfido2 library by using the publicKey and CredentailId generated from WebAuthn it shows me the error of FIDO2 operation failed (InvalidSignature).
The same is also happening with the WebAuthn Assertion method that the public key and credentialId generated from libfido2 library are unable to authenticate using the WebAuthn Assertion method and throw the error PeterO.Cbor.CBORException Message: Too many bytes.
So, Please suggest a workaround for this problem as I am stuck here as these two apps are dependent on each other and required to enroll and authenticating the user at both ends using the public key and credentialId generated from any of the windows or web platforms.
FIDO Assertion Initialize at Windows Client(c#)
Fido2Settings.Flags = FidoFlags.Debug;
            using (var assert = new FidoAssertion())
            {
                using (var dev = new FidoDevice())
                {
                    dev.Open(device);
                    assert.SetClientData(Cd);
                    assert.Rp = rpId;
                    assert.SetExtensions(FidoExtensions.None);
                    var credId = Convert.FromBase64String(credentialId);
                    assert.AllowCredential(credId);
                    dev.GetAssert(assert, null);
                    dev.Close();
                }
                if (assert.Count != 1)
                {
                    throw new Exception($"{assert.Count} signatures required");
                }
                if (!_FidoDeviceSelected)
                {
                    Console.WriteLine("AuthData: {0}",Convert.ToBase64String(assert[0].AuthData.ToArray()));
                    Console.WriteLine("AuthData: {0}", Convert.ToBase64String(assert[0].Signature.ToArray()));
                    CompleteAuthentication(rpId, assert[0].AuthData, assert[0].Signature, FidoExtensions.None, publicKey);
                    return new ResponseDto(null, false);
                }
                else
                {
                    return new ResponseDto(null, true);
                }
            }

FIDO Assertion Complete at Windows Client(c#)
private void CompleteAuthentication(string rpId, ReadOnlySpan<byte> authData, ReadOnlySpan<byte> signature, FidoExtensions extensions, string publicKey)
    {
        byte[] keyBytes = Convert.FromBase64String(publicKey);
        using (var assert = new FidoAssertion())
        {
            assert.SetClientData(Cd);
            assert.Rp = rpId;
            assert.Count = 1;
            assert.SetAuthData(authData, 0);
            assert.SetExtensions(extensions);
            assert.SetSignature(signature, 0);
            assert.Verify(0, FidoCose.ES256, keyBytes);
        }
    }


text:
Q: Google directions route not working properly I have a project that needs to have multi-colors for a route between two points. I have used Google maps API to get the code working. Here is the code I am working on.
HTML part:
<!DOCTYPE html>

<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">

<title>Waypoints in directions</title>

    Start:
  <input id="start" type="text" onchange="calcRoute();">

  End:
  <input id="end" type="text" onchange="calcRoute();">

  Waypoints:

<input type="button" value="waypoint" onclick="waypoint();" width="100px"   height="60px">

<input type="button" value="submit" onclick="calcRoute();" width="100px" height="60px">

JavaScript part:
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer({
polylineOptions: {
  strokeColor: "blue"
}
  });
directionsDisplay1 = new google.maps.DirectionsRenderer({
 suppressMarkers: true,
   polylineOptions: {
     strokeColor: "green"
  }
     });
 directionsDisplay2 = new google.maps.DirectionsRenderer({
  suppressMarkers: true,
    polylineOptions: {
     strokeColor: "orange"
     }
   });
 directionsDisplay3 = new google.maps.DirectionsRenderer({
    suppressMarkers: true,
    polylineOptions: {
      strokeColor: "red"
}
  });

  var chicago = new google.maps.LatLng(41.850033, -87.6500523);
  var mapOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: chicago
   }
   map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
   directionsDisplay.setMap(map);
   directionsDisplay1.setMap(map);
   directionsDisplay2.setMap(map);
   directionsDisplay3.setMap(map);

}
function calcRoute() {
  start = document.getElementById('start').value;
  end = document.getElementById('end').value;

  for (var i = 0; i < counter; i++) {
   checkpts[i] = document.getElementsByClassName('way')[i];
   waypoints.push({
   location:checkpts[i].value,
   stopover:true});
}
  var request = {
  origin: start,
  destination: end,
  waypoints: waypoints,
  optimizeWaypoints: true,
  travelMode: google.maps.TravelMode.DRIVING
};
  directionsService.route(request, function(response, status,routes) {
   if (status == google.maps.DirectionsStatus.OK) {
  directionsDisplay.setDirections(response);
  myRoute = response.routes[0];
  }
  for (var i=0; i<myRoute.legs[0].steps.length; i++) {

      pts[i]=myRoute.legs[0].steps[i].polyline.points;
      points[i]=String(pts[i]);
      waypts[i]=decode(points[i]);
      Points.push(waypts[i]);
  }
for (var i=0; i<myRoute.legs[0].steps.length; i++){
   for (var j=0; j<Points[i].length; j++){
    routepts.push(Points[i][j]);
  }
}

  var s=routepts.length;
  var k=(s/4);
 for(var i=1;i<=4;i++)
 {
      latlng[i-1] = new google.maps.LatLng(routepts[(parseInt(i*k)-1)][0],       routepts[(parseInt(i*k)-1)][1]);

 }
  var geocoder = new google.maps.Geocoder();
  geocoder.geocode({'latLng': latlng[0]},function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
          if (results[1]) {
             address.push(results[1].formatted_address);
           }
          }
      });
   geocoder.geocode({'latLng': latlng[1]},function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
          if (results[1]) {
             address.push(results[1].formatted_address);
            }
      }
  });
   geocoder.geocode({'latLng': latlng[2]},function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {
      if (results[1]) {
          address.push(results[1].formatted_address);
        }
      }
  });
  geocoder.geocode({'latLng': latlng[3]}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {
      if (results[1]) {
          address.push(results[1].formatted_address);
        }
      }
  });
})
 var request1 = {
  origin: start,
  destination: String(address[1]),
  waypoints: waypoints,
  optimizeWaypoints: true,
  travelMode: google.maps.TravelMode.DRIVING
  };

directionsService.route(request1, function(response, status,routes) {
   if (status == google.maps.DirectionsStatus.OK) {
     directionsDisplay1.setDirections(response);
    }
   })

 var request2 = {
  origin: String(address[1]),
  destination: String(address[2]),
  waypoints: waypoints,
  optimizeWaypoints: true,
  travelMode: google.maps.TravelMode.DRIVING
  };

directionsService.route(request2, function(response, status,routes) {
if (status == google.maps.DirectionsStatus.OK) {
  directionsDisplay2.setDirections(response);
}
  })

var request3 = {
  origin: String(address[2]),
  destination: end,
  waypoints: waypoints,
  optimizeWaypoints: true,
  travelMode: google.maps.TravelMode.DRIVING
  };

directionsService.route(request3, function(response, status,routes) {
if (status == google.maps.DirectionsStatus.OK) {
  directionsDisplay3.setDirections(response);
}
  })

}
function decode(instring) {
  var out=[];
  //instring = instring.replace(/\\\\/g, "\\");
  out = decodeLine(instring);
  return out;
}
function decodeLine(encoded) {
 var len = encoded.length;
 var index = 0;
 var array = [];
 var lat = 0;
 var lng = 0;

  while (index < len) {
   var b;
   var shift = 0;
var result = 0;
do {
  b = encoded.charCodeAt(index++) - 63;
  result |= (b & 0x1f) << shift;
  shift += 5;
} while (b >= 0x20);
var dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
lat += dlat;

shift = 0;
result = 0;
do {
  b = encoded.charCodeAt(index++) - 63;
  result |= (b & 0x1f) << shift;
  shift += 5;
} while (b >= 0x20);
var dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
lng += dlng;

array.push([lat * 1e-5, lng * 1e-5]);
  }

  return array;
}

function waypoint(){
  var d=document.getElementById("div");
  d.innerHTML+="
<input type='text' placeholder='waypoint' class='way'>";
  counter++;

}
 google.maps.event.addDomListener(window, 'load', initialize);

While running the code, I got an error.

*

*On entering a location in start or end input boxes, a route is being plotted between the location entered and an unknown location in Spain.

I am new to Google Maps API.Please suggest something to help me out.
Thanks in advance.


text:
Q: Flow towards a stationary large objects Consider such a flow heading towards the surface of a stationary and impenetrable
object. Apparently, a stagnation point will be produced as shown in the figure.

I am trying to solve for the flow in the vicinity of the stagnation point.
I am assuming I can use Laplace equation for the velocity potential: $$ \nabla^2 \phi = 0  $$
The form of the solution I am guessing is $$ \phi = A x^2 +B y^2+C z^2 $$
I just can't figure out what the boundary conditions are. The $ \vec{u} = 0 $ at the origin is the only thing I can think of, but I don't think this is providing me anything actually useful.
The anwser to the problem provided has this form: $$ \phi = W(x^2+y^2-2z^2) $$
This satisfies the B.C. at the surface (flow normal to surface is zero). And gives zero velocity at stagnation point. I have no more boundary conditions given in the actual problem statement, so I am guessing they should be inferred.

A: First the velocity at the surface is parallel to the surface, or the surface would not be impenetrable.
Also unless the flow is frictionless, velocity is 0 at the surface.

A: For potential flow, on the solid surface your boundary condition is
$$\frac{\partial\phi}{\partial \mathbf n}={\mathbf n}\cdot\nabla\phi=0$$
where $\mathbf n$ is the surface normal vector. You also need boundary conditions at all other boundaries, which come from your free-stream velocity conditions. This is typically something of the form
$$\nabla\phi={\mathbf u}_0$$,
where ${\mathbf u}_0$ is your free-stream velocity.
P.S.: In the vicinity of the stagnation point, assuming the object you are talking about can locally be approximated as just a plane surface with flow normal to it, the potential flow solution is given by
$$\phi(r,\theta)=C\, r^2 \cos(2\theta)$$
in polar coordinates, $r=\sqrt{x^2+y^2}$, $\theta=\arctan(y/x)$.

A: Here is a description for non-lifting potential flow around a cylinder, which might be helpful depending on what exactly you are seeking. Below is an image of the potential flow solution and superposition required to "build" such a flowfield subject to the Laplace equation. It requires the superposition of a uniform flow and doublet to yield the potential flow solution for non-lifting flow over a cylinder.

Below each flow type is the associated stream function in polar coordinates. From the linearity of the Laplace equation, it then follows that the stream function for flow over a cylinder is thus,
$$ \psi = V_{\infty} r \sin \theta - \frac{\kappa}{2\pi} \frac{\sin \theta}{r} $$
where $V_{\infty}$ is the freestream velocity, and $\kappa$ is the strength of the doublet. It can be shown that the cylinder in question has a radius defined by,
$$ R^2 = \frac{\kappa}{2\pi V_{\infty}} $$
Re-writing the steam function in terms of $R$ yields,
$$\psi = \left(V_{\infty} r \sin \theta \right)\left(1 - \frac{R^2}{r^2}\right)$$
From the definition of the stream function we obtain,
$$ V_r = \frac{1}{r}\frac{\partial \psi}{\partial \theta} = \left(1 - \frac{R^2}{r^2}\right)V_{\infty} \cos \theta$$
$$ V_{\theta} = -\frac{\partial \psi}{\partial r} = -\left(1 + \frac{R^2}{r^2}\right)V_{\infty} \sin \theta$$
At the stagnation point we have $V_r = V_{\theta} = 0$, hence,
$$ \left(1 - \frac{R^2}{r^2}\right)V_{\infty} \cos \theta = 0$$
$$ \left(1 + \frac{R^2}{r^2}\right)V_{\infty} \sin \theta = 0$$
Solving these equations yields two stagnation point solutions identified in the image above as points $A$ and $B$. These points correspond to $(r,\theta) = (R,0)$ and $(R,\pi)$, respectively. Many features can be deduced from the above results, but the most commonly desired is the gradient along the body in the vicinity of the stagnation point. Hence,
$$\frac{d V_{\theta}}{d\theta} = -\left(1 + \frac{R^2}{r^2}\right)V_{\infty} \cos \theta$$
where at the stagnation point of interest, $(r,\theta) = (R,\pi)$,
$$\frac{d V_{\theta}}{d\theta} = 2 V_{\infty} $$
Therefore, along the surface, we have,
$$\frac{d V_s}{ds} = \frac{2 V_{\infty}}{R} $$
This result is commonly required for boundary layer analysis in the vicinity of the stagnation point of a blunt nosed body. However, I am not sure exactly what you are seeking. Hopefully this will get you started in the right direction or at least provide some helpful pointers.

A: So it turned out I was missing something completely obvious. The solution must satisfy zero flow at stagnation point and the rotational symmetry around the z-axis. Zero flow at stagnation point is already satisfied. To satisfy rotational symmetry of the problem, the solution must have this form:
$$ \phi = Ax^2+Ay^2+Cz^2$$
i.e. both $x^2$ and $y^2$ must have I the same coefficient in front of them.
Then, just from $$\nabla^2\phi =0 $$
I get $$ A+A+C=0, C=-2A$$


text:
Q: TabHost is not working with view pager android I am following this video to create my tabhost with navigation drawer and view pager,my page is sliding properly but after add tabhost,if i run my application it got crash,and giving nullpointer exception near this line
        tabhost.addTab(tabSpac);

MainActivity.java
public class MainActivity extends ActionBarActivity implements OnPageChangeListener,OnTabChangeListener{

    ViewPager viewpager;

    TabHost tabhost;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initViewpager();

        initTabhost();

    }

    private void initTabhost() {

        tabhost=(TabHost)findViewById(android.R.id.tabhost);
        tabhost.setup();

        String[] tabnames={"Tab1","Tab2","Tab3","Tab4","Tab5","Tab6"};

        for(int i=0;i<tabnames.length;i++)
        {
            TabHost.TabSpec tabSpac;
            tabSpac=tabhost.newTabSpec(tabnames[i]);
            tabSpac.setIndicator(tabnames[i]);
            tabSpac.setContent(new FakeContent(getApplicationContext()));
            tabhost.addTab(tabSpac);

        }

        tabhost.setOnTabChangedListener(this);
    }

    public class FakeContent implements TabContentFactory
    {
        Context context;
        public FakeContent (Context mcontext) {
            context=mcontext;
        }

        @Override
        public View createTabContent(String tag) {

            View fakeView=new View(context);
            fakeView.setMinimumHeight(0);
            fakeView.setMinimumWidth(0);
            return null;
        }

    }

    private void initViewpager() {
        viewpager=(ViewPager)findViewById(R.id.view_pager);
        List<Fragment> listFragments=new ArrayList<Fragment>();
        listFragments.add(new Fragment1());
        listFragments.add(new Fragment2());

        listFragments.add(new Fragment3());

        MyFragmentPagerAdapter myFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(), listFragments);

        viewpager.setAdapter(myFragmentPagerAdapter);

        viewpager.setOnPageChangeListener(this);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onTabChanged(String tabId) {
        // TODO Auto-generated method stub
        int selectedItem=tabhost.getCurrentTab();
        viewpager.setCurrentItem(selectedItem);

        HorizontalScrollView hscroolview=(HorizontalScrollView)findViewById(R.id.h_scrool_view);
        View tabView=tabhost.getCurrentTabView();
        int scrollPos=tabView.getLeft()-(hscroolview.getWidth()-tabView.getWidth())/2;
        hscroolview.smoothScrollTo(scrollPos, 0);

    }

    @Override
    public void onPageScrollStateChanged(int arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPageSelected(int selectedItem) {
        // TODO Auto-generated method stub
        tabhost.setCurrentTab(selectedItem);

    }

}

Log

10-24 18:38:13.091: E/AndroidRuntime(13748): FATAL EXCEPTION: main
  10-24 18:38:13.091: E/AndroidRuntime(13748):
  java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.example.tabhostviewpagerslidingmenu/com.example.tabhostviewpagerslidingmenu.MainActivity}:
  java.lang.NullPointerException 10-24 18:38:13.091:
  E/AndroidRuntime(13748):  at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1970)
  10-24 18:38:13.091: E/AndroidRuntime(13748):  at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1995)
  10-24 18:38:13.091: E/AndroidRuntime(13748):  at
  android.app.ActivityThread.access$600(ActivityThread.java:128) 10-24
  18:38:13.091: E/AndroidRuntime(13748):    at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1161)
  10-24 18:38:13.091: E/AndroidRuntime(13748):  at
  android.os.Handler.dispatchMessage(Handler.java:99) 10-24
  18:38:13.091: E/AndroidRuntime(13748):    at
  android.os.Looper.loop(Looper.java:137) 10-24 18:38:13.091:
  E/AndroidRuntime(13748):  at
  android.app.ActivityThread.main(ActivityThread.java:4517) 10-24
  18:38:13.091: E/AndroidRuntime(13748):    at
  java.lang.reflect.Method.invokeNative(Native Method) 10-24
  18:38:13.091: E/AndroidRuntime(13748):    at
  java.lang.reflect.Method.invoke(Method.java:511) 10-24 18:38:13.091:
  E/AndroidRuntime(13748):  at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993)
  10-24 18:38:13.091: E/AndroidRuntime(13748):  at
  com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760) 10-24
  18:38:13.091: E/AndroidRuntime(13748):    at
  dalvik.system.NativeStart.main(Native Method) 10-24 18:38:13.091:
  E/AndroidRuntime(13748): Caused by: java.lang.NullPointerException
  10-24 18:38:13.091: E/AndroidRuntime(13748):  at
  android.widget.TabHost$FactoryContentStrategy.getContentView(TabHost.java:663)
  10-24 18:38:13.091: E/AndroidRuntime(13748):  at
  android.widget.TabHost.setCurrentTab(TabHost.java:356) 10-24
  18:38:13.091: E/AndroidRuntime(13748):    at
  android.widget.TabHost.addTab(TabHost.java:246) 10-24 18:38:13.091:
  E/AndroidRuntime(13748):  at
  com.example.tabhostviewpagerslidingmenu.MainActivity.initTabhost(MainActivity.java:62)
  10-24 18:38:13.091: E/AndroidRuntime(13748):  at
  com.example.tabhostviewpagerslidingmenu.MainActivity.onCreate(MainActivity.java:42)
  10-24 18:38:13.091: E/AndroidRuntime(13748):  at
  android.app.Activity.performCreate(Activity.java:4470) 10-24
  18:38:13.091: E/AndroidRuntime(13748):    at
  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1053)
  10-24 18:38:13.091: E/AndroidRuntime(13748):  at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1934)
  10-24 18:38:13.091: E/AndroidRuntime(13748):  ... 11 more

A: Firstly you have a Reference Set as Null Which is causing this issue to occur.Secondly as said TabHost is depricated instead use Material TabLayout.
Here is a Piece of Reference Code try this.
ublic class SimpleTabsActivity extends AppCompatActivity {

private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_simple_tabs);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new OneFragment(), "ONE");
    adapter.addFragment(new TwoFragment(), "TWO");
    adapter.addFragment(new ThreeFragment(), "THREE");
    viewPager.setAdapter(adapter);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}
}

Here is My XML Layout.
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="fixed"
        app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"/>


text:
Q: Can I upgrade from 10.6 to 10.7 for free? When I bought my new Mac at the end of July, 2011, the dealer (Microcenter, Marietta, GA) Renee told me I had 4 months to upgrade to Lion. I calendared the drop dead date at the end of November, and now discover I only had 30 days.
Is there a way to upgrade for free at this time?

A: Apple's policy is that you get an OS upgrade for free as soon as the launch date of the new OS has been officially announced. For Lion, this was after July 21st. However, as you discovered yourself:

Remember your completed order must be entered within 30 days of the date of your purchase of a qualifying computer.

So no, you won't be able to get anything from Apple's up-to-date program, which is the only way to get an OS upgrade for free.


text:
Q: How to show (appear) elements in order in Xamarin Forms I have a grid of buttons (2 x 3) which will be always fixed size menu for my application.
I want to display them on start in order of appearing with a little bit of delay (going from left to right, top to bottom).
I have tried this way:
in onAppearing method use FadeTo animation and delay to show the elements in order:
 await schedule_label_shadow.FadeTo(0, 1);
 await schedule_label.FadeTo(0, 1);
 await employees_label.FadeTo(0, 1);
 await employees_label_shadow.FadeTo(0, 1);

 await schedule_label.FadeTo(1, 250);
 await schedule_label_shadow.FadeTo(1, 250);
 await employees_label.FadeTo(1, 250);
 await employees_label_shadow.FadeTo(1, 250);

It works, but I had to fade out first, so the elements won't be displayed at the start. However, this doesn't seem as a right or effective way to do such animation. I also wanted to try isVisible (true/false), but was told it is a bad practice as it is blocking the UI thread.
Can you tell me if I do it right or point me to right direction?

A: You need set opacity = 0 in schedule_label_shadow and other views. Also you can set the property from xaml.
 schedule_label.Opacity = 0;

And remove
 await schedule_label_shadow.FadeTo(0, 1);


text:
Q: Wordpress Contact Form 7 datepicker change date format I'm using Contact Form 7 plugin in Wordpress, I would like some help in my datepicker on how to change the display date format in the front end in my form.
The default displays mm/dd/yy and I want to change it to dd/mm/yy but unfortunately I could not used this code:
dateFormat:dd/mm/yy

it seems it was not working.
I also tried to change the code in the plugin editor of datepicker but it did not work also.
Do you have any idea? an you help me how to change the date format without installing contact form 7 datepicker because I would like to use the default datepicker that include in the contact form 7.

A: I changed the display date format to dd/mm/yy in the front end (also in the generated email) of my form by using plugin Custom Datepicker NMR for Contact Form 7.
This allows you to use a new input field in your contact form called [datepicker ]
Install/activate the plugin and specify format date to show in the web browser like this:
[datepicker myFirstDatepicker id:myFirstDatepicker format:dd/mm/yy]

This plugin uses jquery-ui datepicker.

A: You do the configuration in the shortcode.
[date date-test date-format:dd/mm/yy]

A: Worked perfectly for me. Try with no spaces: date-format:dd/mm/yy
So code for me in full for the line looked like this:

   Work Start Date (*)

   [date* start-date date-format:dd/mm/yy]

A: All you have to do is put:
[date your-date-from min:2017-01-01 max:2025-12-31 step:7 class:required "2017-01-01"]

Obviously put the dates you wish to use.


text:
Q: Forgot password workflow in Xamarin forms In general, how does the forgot password is implemented in Xamarin forms. I know for web applications, password rest link is sent and user is logged-in after changing the password.
For mobile apps, how do I invoke reset password screen when they click on the link. If it is not possible, do we need to create a website just for password reset.
Another possibility is have a token generated automatically and embed in the login link sent by mail and open the mobile app and automatically login.
I would like to know standard way of doing in Xamarin forms and appreciate if could provide references to articles/libraries.


text:
Q: How to use AES encryption twice using CryptoJS AES i try to encrypt twice using cryptojs but its nothing return how i do that this is my code
var defaultKey = "Part of the journy is the end. Whatever it takes";
var userKey = 'in this whole universe iron man is the best superhero';
var encryptMsg ='';

encryptMsg = CryptoJS.AES.encrypt(msg, defaultKey);
alert(encryptMsg);
encryptMsg = CryptoJS.AES.encrypt(encryptMsg , userKey );
alert(encryptMsg);

first alert show encrypted text but seconf alert not display anything

A: oooyeh i found a solution i dont know this is right way but this thing work for me
var defaultKey = "Part of the journy is the end. Whatever it takes";
var userKey = 'in this whole universe iron man is the best superhero';
var encryptMsg ='';

encryptMsg = CryptoJS.AES.encrypt(msg, defaultKey);
alert(encryptMsg);
encryptMsg = CryptoJS.AES.encrypt(String(encryptMsg) , userKey );
alert(encryptMsg);

i use String()


text:
Q: Making cucumber test succeed if there is no test data I am writing cucumber tests for a web-app that we are making for a 3rd party where they have complete control of our shared test-environment. As things are right now, my tests fail on almost a daily basis due to data being removed or changed in our test environment, giving me a lot of grief.
What I would like to do is to skip a scenario given that the test-data needed to execute it isn't there. That is, I would like to be able to skip a scenario based on me finding a specific element on a page or not

A: try this...although its not marked as successful
Feature: dummy

Scenario: First
  Given I set sessions to "10"
  Then it should have "10"

Scenario: second
  Given it should have "10"
  Then I set sessions to "10"

steps
Given(/^I set sessions to "(.*?)"$/) do |arg1|
  @data = ""
end

Then(/^it should have "(.*?)"$/) do |arg1|
  @data = "test"
end

AfterStep do |scenario|
  scenario.skip_invoke! if @data.empty?
end

2 scenarios (1 skipped, 1 passed)
4 steps (1 skipped, 3 passed)
0m0.008s

A: If you want to skip the scenario and make it to look like yellow in HTML reports, you can try calling pending step in your step definitions like this:
steps %{
Given pending
}


text:
Q: Help to make a Pick Chart \documentclass{standalone}
\usepackage[utf8]{inputenc}
\usepackage{pgfplots}
\usepackage{tikz}
\begin{document}
    \tikzset{mark options={mark size=2, line width=3pt}}
    \begin{tikzpicture}
        \begin{axis}[height=5cm,width=8cm,scale only axis,
        xlabel= \textbf{Esfuerzo},
        ylabel= \textbf{Impacto},
        ymax = 45,
        ymin = 15,
        legend columns=0,
        xticklabels={Bajo},
        yticklabels={Bajo}]

        \addplot[mark=none, black,very thick, dotted] coordinates {(0,30) (12,30)};
        \addplot[mark=none, black,very thick, dotted] coordinates {(6,00) (06,60)};

        \addplot[only marks, color=red,mark=*] coordinates { (1,31) (2,35) (2.5,20) (4,28) (5,19) (5,40) (7,20) (8,36) (9,35) (10,29) (7,29) (8,56) (9,35) (10,20) (12,24) };
        %\addlegendentry{}
        \node[] at (axis cs: 1,41.5) {Implementar};
        \node[] at (axis cs: 12,41.5) {Desafío};
        \node[] at (axis cs: 0,18) {Posible};
        \node[] at (axis cs: 12,18) {Ignorar};
        \end{axis}
    \end{tikzpicture}
\end{document}

Any suggest for get the labels like the graph below?

A: I removed the figure and measuredfigure environment since figure doesn't work by default in standalone, and I don't know off hand where measuredfigure comes from.
You can give a name to the axis, with name=ax, and use that to place nodes relative to it.

\documentclass[border=5mm]{standalone}
\usepackage[utf8]{inputenc}
\usepackage{pgfplots} % loads tikz
\begin{document}
\begin{tikzpicture}
    \begin{axis}[height=5cm,width=8cm,scale only axis,
        ymax = 45,
        ymin = 15,
        legend columns=0,
        xticklabels={},
        yticklabels={},
        mark options={ % unless you have multiple tikzpictures/axis, it makes more sense to have this here
          mark size=2,
          line width=3pt
        },
        name=ax  % <-- added
     ]

        \addplot[mark=none, black,very thick, dotted] coordinates {(0,30) (12,30)};
        \addplot[mark=none, black,very thick, dotted] coordinates {(6,00) (06,60)};

        \addplot[only marks, color=red,mark=*] coordinates { (1,31) (2,35) (2.5,20) (4,28) (5,19) (5,40) (7,20) (8,36) (9,35) (10,29) (7,29) (8,56) (9,35) (10,20) (12,24) };
        %\addlegendentry{}
        \node[] at (axis cs: 1,41.5) {Implementar};
        \node[] at (axis cs: 12,41.5) {Desafío};
        \node[] at (axis cs: 0,18) {Posible};
        \node[] at (axis cs: 12,18) {Ignorar};
        \end{axis}

    \node [below left] at (ax.north west) {High};
    \node [left]       at (ax.west)       {Payoff};
    \node [above left] at (ax.south west) {Low};

    \node [below right] at (ax.south west) {Easy};
    \node [below]       at (ax.south)      {Difficulty};
    \node [below left]  at (ax.south east) {Hard};

    \end{tikzpicture}
\end{document}


text:
Q: Batch to loop through variables and send API request I am facing an issue to get some data from an API using the command lines in Windows. Basically, this is what I want to do:
1- Get a list of clients from an API (using curl and jq),
2- Save this list in a .txt (I wanted to save it in a variable but did not manage),
3- Loop through the list of clients within the .txt and send a new API request to download a csv specific to this client
The first 2 steps are working fine, but I'm stuck on the last bit to loop through the clients. Here is my code:
setlocal ENABLEDELAYEDEXPANSION

Set tok=XXXXX
Set hURL="https://api.website.com/v2/clients?token=%tok%"
Set IDPath="C:\Users\My Self\subIDs.txt"
Set cuPath=%~dp0

del %IDPath%

curl -sS %hURL% | jq ".clients[].id" > %idPath%

FOR /F %%i in (%IDPath%) do (
    echo %%i
    Set subID=%%i
    Set rURL="https://api.website.com/v2/data?token=%tok%&subscriptionId=!subID!"
    curl -sS -o cuPath!subID!.csv !rURL!
)

endlocal
pause

What looks odd to me:
 - echo %%i returns: C:\Users\My
It looks like the space within the path is a problem for this loop, but it didn't cause any issue to save the file, so I'm a bit lost
- I am using !subID! as I understand it's the only way to get the variable ajusted each time however when looking at the output of the !rURL! variable, while %tok% is successfuly passed as XXXXX, !subID! remains as !subID!
- I finally get, of course, a curl: (6) Could not resolve host: rURL
I am completely new to APIs, batch or JSON and even though I feel I am getting closer, I am now stuck on this last bit. Any idea how to solve this?
Thanks,

A: You had some mistakes in your code which is fixed in the following code.
But since you have not specified the exact format that is returned by jq ".clients[].id" I could only guess that it returns a single token without any spaces between the characters, but it may have leading or trailing spaces.
So if this is not the case you have to setup the FOR /F options accordingly.
@echo off
setlocal DisableDelayedExpansion

Set "tok=XXXXX"
Set "hURL=https://api.website.com/v2/clients?token=%tok%"
Set "rURL=https://api.website.com/v2/data?token=%tok%&subscriptionId="
Set "IDPath=C:\Users\My Self\subIDs.txt"

:: No need to delete %IDPath%, It will be overwrriten by the below redirection
curl -sS "%hURL%" | jq ".clients[].id" > "%IDPath%"

FOR /F "usebackq" %%i in ("%IDPath%") do (
    echo subID=%%i
    curl -sS -o "%~dp0%%i.csv" "%rURL%%%i"
)

REM del "%IDPath%"

endlocal
pause

Some points:

*

*You have assigned the variables with embedded surrounding quotes in their values, while this will work in your particular case, It is a best practice to not embed the quotes in variables values, So instead of Set hURL="https://..." use Set "hURL=https://..." and you can later surround the variable in quotes when actually using them: "%hURL%"
Think of the situation where you want to access the value without quotes, then you have to write additional code to remove the quotes from the value if you assigned the value by set a="value" . But by set "a=value" you can access to both quoted ("%a%" ) and unquoted (%a%) value at the same time.

*You have used Set cuPath=%~dp0 without quotes, it should be Set "cuPath=%~dp0" but it is not needed either, you could just use %~dp0 directly in the loop.
And later you've used cuPath in the FOR loop without expanding it and without surrounding the cURL output file in quotes.

*When reading a file contents by FOR /F, if the path to the is surrounded in quotes then you have to use the UseBackq option to change the interpretation of quotes in the IN clause of the FOR to not interpret it as literal string.

*Based on what you are doing, delayed expansion is not needed at all.
But as side note you have to be more careful when using delayed expansion. when delayed expansion is enabled, any literal string that you may use in your code, including file and url paths, will get corrupted if they contain the ! character.
So It is better setup the required variables and strings while delayed expansion is off and later access them by !var! syntax when delayed expansion is enabled.


text:
Q: Junit Jmock testing: multiple @Before for tests I am not sure if it is possible to do, but I need to call different @Before methods depending on Tests. Is it possible, to make some resolver for it?
@Before
performBeforeOne();

@Before
performBeforeTwo();

@Test
callBeforeOneAndExecuteTestOne();

@Test
callBeforeTwoAndExecuteTestTwo();

Or should I just create several methods and call them manually from each test?

A: No, you can only have one method with each lifecycle annotation. Create a composite method that calls the others if they're too large to combine.

A: I think the best way to achieve this (and the clearest) is to refactor your tests as such:
@Before
public void performBeforeForAll() {}

@Test
testOne() {
    testOneBefore();
   //.. test execution
}

@Test
testTwo() {
   testTwoBefore();
   //.. test execution
}

private void testOneBefore() {}

private void testTwoBefore() {}

That way, you can see exactly what each test is setting up before it runs. You will probably find that some tests share the same setup code, in which can you have a private method already there to prevent duplication.


text:
Q: Have Enter key behave like Tab in QTableWidget I'm using a QTableWidget in PyQt5 and Qt Designer to create a data entry table. What I'd like is a simple way to make the "Enter" keyPressEvent to move across the table like the Tab button was pressed. The following code captures the Enter key press event. How do I make it move the cursor?
def keyPressEvent(self, ev):
    if ev.key() in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter):
        print("Enter key pressed")

A: Instead of using keyPressEvent that is low level you should use QShortcut + focusNextPrevChild() as shown below:
import sys
from PyQt5 import QtCore, QtWidgets
from functools import partial

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)

        self.tableWidget = QtWidgets.QTableWidget()
        self.tableWidget.setRowCount(4)
        self.tableWidget.setColumnCount(2)
        for i in range(self.tableWidget.rowCount()):
            for j in range(self.tableWidget.columnCount()):
                it = QtWidgets.QTableWidgetItem("Cell {}{}".format(i, j))
                self.tableWidget.setItem(i, j, it)

        self.layout = QtWidgets.QVBoxLayout(self)
        self.layout.addWidget(self.tableWidget)

        for key in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter):
            QtWidgets.QShortcut(key, self.tableWidget, partial(self.tableWidget.focusNextPrevChild, True))

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    ex = Widget()
    ex.show()
    sys.exit(app.exec_())


text:
Q: QGIS 3 Metadata to ISO XML Just found out that QGis 3.x has a metadata editor. That is great! Is there a tool to convert the metadata saved by QGIS (.qmd file) to a ISO-xml standard metadata file?
Why am I asking this: I though of using QGis to create the xml metadata file that we will use to populate a Metadata Catalog

A: Not 100% on this but I think metadata is a work in progress, being approached from a number of angles.
If you have metadata to save, apparently it can be saved to a file which sits in the same directory as the data. As per this answer QGIS Default Metadata
If you are trying to read existing metadata from another system (your case) I presume QGIS is expecting to read a *.qmd file.
There is a plugin which apparently used to help some users, but apparently it no longer works with updated version of QGIS. https://github.com/nextgis/metatools/issues


text:
Q: Copy background jobs and installed softwares to AWS AMI I have some installed software like node and some background cron jobs running on my EC2 instance. Now when I create a AMI I want all these configurations to be copied to the AMI. Do I have to write some script for the same or the AMI creation will take care of it.

A: The AMI creation will copy installed software and cron config files as it is based on a snapshot of the disk
The only thing to check is that the configuration that individual packages have is not somehow tied to the specific IP or subnet of the instances that it was originally installed on


text:
Q: glmmTMB - Model convergence problem; non-positive-definite Hessian matrix I am trying to conduct a model with the glmmTMB package - depression as an outcome and stress as a predictor, including age, gender, working hours, and observation number (=time) as covariates. I also want to disentangle stress into within-subject and between-subject effects, and include autocorrelation (using the number of observations) in the model.
Because the data is skewed, I am using a GLMM model with a gamma distribution.
First I used this code:
dep_gamma_ar1 = glmmTMB(dep_sum ~ cmean_gender + cmean_age +
                          cmean_workh + obs_cent
                             + mean_stress + cent_stress
                             + (cent_stress + obs_cent |id)
                             + ar1(factor(obs) + 0 | id),
                             data=dat,family=Gamma(link = "log"))
summary(dep_gamma_ar1)

However, I got the following warning:
Warning messages:
1: In fitTMB(TMBStruc) :
  Model convergence problem; non-positive-definite Hessian matrix. See vignette('troubleshooting')
2: In fitTMB(TMBStruc) :
  Model convergence problem; false convergence (8). See vignette('troubleshooting')

After searching for solutions, I found recommendations to add the following optimizer control = glmmTMBControl(optimizer = optim, optArgs = list(method="BFGS")) to the code:
dep_gamma_ar2 = glmmTMB(dep_sum ~ cmean_gender + cmean_age +
                          cmean_workh + obs_cent
                             + mean_stress + cent_stress
                             + (cent_stress + obs_cent |id)
                             + ar1(factor(obs) + 0 | id),
                           control = glmmTMBControl(optimizer = optim, optArgs = list(method="BFGS")),
                             data=dat,family=Gamma(link = "log"))
summary(dep_gamma_ar2)

I am still getting a non-positive-definite Hessian matrix. Here is the model summary:
     AIC      BIC   logLik deviance df.resid
      NA       NA       NA       NA     3520

Random effects:

Conditional model:
 Groups Name         Variance  Std.Dev. Corr
 id     (Intercept)  7.114e-02 0.26672
        cent_stress     9.308e-04 0.03051  0.14
        obs_cent     4.998e-05 0.00707  0.26        0.23
 id.1   factor(obs)1 1.026e-01 0.32038  -0.01 (ar1) -0.01 (ar1) -0.01 (ar1)
Number of obs: 3536, groups:  id, 123

Dispersion estimate for Gamma family (sigma^2): 4.69e-06

Conditional model:
               Estimate Std. Error z value Pr(>|z|)
(Intercept)   0.9568053  0.0319644  29.934  < 2e-16 ***
cmean_gender  0.0625847  0.0724055   0.864 0.387388
cmean_age    -0.0009886  0.0018623  -0.531 0.595537
cmean_workh     0.0050827  0.0046462   1.094 0.273970
obs_cent     -0.0013033  0.0008871  -1.469 0.141791
mean_stress  0.0292378  0.0100527   2.908 0.003632 **
cent_stress  0.0147936  0.0044367   3.334 0.000855 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
>

Is the code correct? How can I solve this warning message? I read some past threads like here, and also read the 'troubleshooting' file but I still don't really understand the problem (I am pretty new to these kinds of models).
I'd kindly appreciate your help.

A: Looking at what you have so far, I see the following:

*

*You have modeled your syntax correctly.

*You have attempted to optimize estimation with some of the built in arguments in this package.

*You have correctly assumed there are still problems.

Looking at your regression summary, I see the following potential reasons why there are still warnings:

*

*The autocorrelations are so weak they are almost zero.

*The random effects are somewhat complex.

*The fixed effect point estimates are fairly low as well, which contribute to the RE problem.

*Probably of most importance: your random effect variance is super low.

All of these seem to point to the issue that your model is simply too complex and doesn't represent your data well. It may help to look at some of your scatter plots and some of your by-subject variances to see where the issue may lie. Seeing how in the comments you have mentioned the issue going away after minimizing the complexity, this seems to be the correct path, but you'll need to do some data exploration to answer that concretely.
A couple articles on model complexity have been written or co-written by Douglas Bates, the man behind the lme4 package used for mixed models. I cite them below because they illustrate how model complexity can often cause issues of convergence.

*

*Bates et. al., 2018: Parsimonious mixed models.

*Matuschek et al., 2017: Balancing Type I error and power in linear mixed models


text:
Q: Only dummy audio on laptop when updating from Ubuntu 22.04 to 22.10 My laptop doesn't recognize my sound card and have only dummy audio. When running inxi -A I get this:
Audio:
  Device-1: Intel Sunrise Point-LP HD Audio driver: N/A
  Device-2: NVIDIA GP107GL High Definition Audio driver: snd_hda_intel
  Sound Server-1: ALSA v: k5.19.0-21-generic running: yes
  Sound Server-2: PipeWire v: 0.3.58 running: yes

I tried suggested solutions, like installing WirePlumber or restarting PulseAudio, but they don't work.

A: link to a thread on linux.org with the same problem
systemctl --user enable pulseaudio

systemctl --user start pulseaudio

I had the same problem and followed the steps from the link.

A: No sound output devices listed after upgrade from 21.10 to 22.04
I had the same problem and followed the steps from the above link
sudo touch /usr/share/pipewire/media-session.d/with-pulseaudio
sudo systemctl --user restart pipewire-session-manager
sudo reboot now

Solved !!!!

A: I had exactly the same problem but for AMD card:
Audio:
  Device-1: AMD Renoir Radeon High Definition Audio driver: snd_hda_intel
  Device-2: AMD Raven/Raven2/FireFlight/Renoir Audio Processor
    driver: snd_rn_pci_acp3x
  Device-3: AMD Family 17h HD Audio driver: snd_hda_intel
  Sound Server-1: ALSA v: k5.19.0-21-generic running: yes
  Sound Server-2: PipeWire v: 0.3.58 running: yes

For me it helps to boot to the 22.04 latest kernel
Linux tsebo-T14 5.15.0-52-generic #58-Ubuntu SMP Thu Oct 13 08:03:55 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux

After booting ubuntu with 5.15.0-52-generic, sound drivers are back and working as expected.

A: try this:
systemctl --user restart pipewire pipewire-pulse

and check if you have file: /usr/share/pipewire/media-session.d
if no such file then reinstall this:
sudo apt --reinstall install pipewire-media-session

A: Try this(if you need to auto start pulseaudio each time after reboot);

*

*Remove Pipewire using sudo apt remove pipewire

*Enable Pulseaudio using systemctl --user enable pulseaudio.service pulseaudio.socket

*Now start pulseaudio using pulseaudio --start or systemctl --user start pulseaudio.service pulseaudio.socket

*Now do a reboot.

A: Thanks Jurij Pitulja, this works for me
systemctl --user restart pipewire pipewire-pulse
sudo apt --reinstall install pipewire-media-session


text:
Q: stl unordered_set how to set initial bucket count For an unordered_map i set the initial bucket count by this:
unordered_map<string, dictionaryWord> dictionary(17749); // set initial bucket count to 17749

This way does not seem to work for unordered_set.
/*line 150*/ unsigned char mask;
/*line 151*/ unordered_set<QueryID> query_id(109); // set initial bucket count to 109

Compiler error =
1) expected identifier before numeric constant.
2) expected ',' or '...' before numeric constant.
And goes on with a bunch of errors
How to do the same thing for an unordered_set?
Thank you.
=================================================
There are no errors if i remove "(109)"
"/usr/bin/make" -f nbproject/Makefile-Release.mk QMAKE= SUBPROJECTS= .clean-conf
make[1]: Entering directory `/home/petros/NetBeansProjects/ACM_test'
rm -f -r build/Release
rm -f dist/Release/GNU-Linux-x86/acm_test
make[1]: Leaving directory `/home/petros/NetBeansProjects/ACM_test'

CLEAN SUCCESSFUL (total time: 80ms)

"/usr/bin/make" -f nbproject/Makefile-Release.mk QMAKE= SUBPROJECTS= .build-conf
make[1]: Entering directory `/home/petros/NetBeansProjects/ACM_test'
"/usr/bin/make"  -f nbproject/Makefile-Release.mk dist/Release/GNU-Linux-x86/acm_test
make[2]: Entering directory `/home/petros/NetBeansProjects/ACM_test'
mkdir -p build/Release/GNU-Linux-x86/ref_impl
rm -f build/Release/GNU-Linux-x86/ref_impl/core.o.d
g++ -pthread -O3 -std=c++11   -c -O2 -pthread -O3 -std=c++11 -MMD -MP -MF build/Release/GNU-Linux-x86/ref_impl/core.o.d -o build/Release/GNU-Linux-x86/ref_impl/core.o ref_impl/core.cpp
ref_impl/core.cpp:151:37: error: expected identifier before numeric constant
ref_impl/core.cpp:151:37: error: expected ',' or '...' before numeric constant
ref_impl/core.cpp: In function 'ErrorCode StartQuery(QueryID, const char*, MatchType, unsigned int)':
ref_impl/core.cpp:250:24: error: expected unqualified-id before '(' token
ref_impl/core.cpp:250:38: error: missing template arguments before ')' token
ref_impl/core.cpp:250:39: error: expected ';' before 'query_id'
ref_impl/core.cpp:257:19: error: 'query.SameQueries::query_id' does not have class type
ref_impl/core.cpp: In function 'ErrorCode EndQuery(QueryID)':
ref_impl/core.cpp:265:44: error: 'queries.std::vector<_Tp, _Alloc>::operator[]<SameQueries, std::allocator<SameQueries> >(((std::vector<SameQueries>::size_type)i)).SameQueries::query_id' does not have class type
ref_impl/core.cpp:265:58: error: unable to deduce 'const auto' from '<expression error>'
ref_impl/core.cpp:266:38: error: 'queries.std::vector<_Tp, _Alloc>::operator[]<SameQueries, std::allocator<SameQueries> >(((std::vector<SameQueries>::size_type)i)).SameQueries::query_id' does not have class type
ref_impl/core.cpp:267:32: error: 'queries.std::vector<_Tp, _Alloc>::operator[]<SameQueries, std::allocator<SameQueries> >(((std::vector<SameQueries>::size_type)i)).SameQueries::query_id' does not have class type
ref_impl/core.cpp:268:36: error: 'queries.std::vector<_Tp, _Alloc>::operator[]<SameQueries, std::allocator<SameQueries> >(((std::vector<SameQueries>::size_type)i)).SameQueries::query_id' does not have class type
ref_impl/core.cpp: In function 'void* TaskCode(void*)':
ref_impl/core.cpp:463:41: error: 'quer.SameQueries::query_id' does not have class type
ref_impl/core.cpp:463:48: error: unable to deduce 'auto' from '<expression error>'
ref_impl/core.cpp:463:70: error: 'quer.SameQueries::query_id' does not have class type
make[2]: *** [build/Release/GNU-Linux-x86/ref_impl/core.o] Error 1
make[2]: Leaving directory `/home/petros/NetBeansProjects/ACM_test'
make[1]: *** [.build-conf] Error 2
make[1]: Leaving directory `/home/petros/NetBeansProjects/ACM_test'
make: *** [.build-impl] Error 2

BUILD FAILED (exit value 2, total time: 1s)

A: It was inside a struct. It should have been:
unordered_set<QueryID> query_id = unordered_set<QueryID>(109);

Thank you

A: I suspect the bucket count is a red herring. It looks like QueryID is not visible.

A: I suspect your QueryID has no standard constructor ie QueryID::QueryID() { std::cout << "foo!" }; so the unordered set does not know how to prefill with empty QueryIDs.
Try adding one.
Or you can use the second parameter to set default data to be used for every prebuilt bucket.
Reference:
http://en.cppreference.com/w/cpp/container/unordered_set/unordered_set


text:
Q: Form icon resized wrong There is quite a lot of discussions about icons in .NET and they still seem to give different people different problems. Still I dind't find an answer for my case.
I'm writing an application in Visual Studio which runs in Windows 7.
I set application icon in Project/Properties/Application. Nope, still default icon used in taskbar.
So I read that I should set the same icon for the form too.It works now, but still not perfect.

*

*If I use icon 48x48 pictures it looks okay in taskbar but is badly resized to 16x16 at form's top.

*If I use 16x16 it looks okay at form's top but is badly resized with big square pixels in taskbar.
Is there any way to set two different icons for a form? one for form's top and another for taskbar? Or maybe some other approach would work?

A: You need to use a .ico file that contains multiple versions of the icon. The system embeds in your executable file these different versions in what is known as an icon group using the RT_GROUP_ICON resource type.
The documentation on MSDN list the sizes that are required to be included in the icon:

Application icons and Control Panel items: The full set includes 16x16, 32x32, 48x48, and 256x256 (code scales between 32 and 256). The .ico file format is required. For Classic Mode, the full set is 16x16, 24x24, 32x32, 48x48 and 64x64.

Note that the 256px icons can (and should) be PNG icons to keep the size manageable.
You'll need to find an icon editor that can make .ico files that contain multiple versions of the image.
You might find this question helpful: Which icon sizes should my Windows application's icon include?

A: An icon file (.ico) can contain many different sizes of icons
Wikipedia Reference ". ICO files contain one or more small images at multiple sizes and color depths, such that they may be scaled appropriately".
So you need to specify all sizes you want to display cleanly. Namely: 16x16, 32x32 and 48x48
Get yourself a copy of IcoFx of another good icon editing program that allows multiple sizes (and colour depths) to be saves into one ico file


text:
Q: Simplest way to log Hibernate SQL only for current thread/session I'm looking for simplest way to trace execution time of SQL query generated by Hibernate.
Unfortunately it cannot be done in traditional way - just by setting show_sql or hibernate logger, because monitored application is multithread on production environment and sql times tracing should be done only for one service, which is mots problematic.
Service means some component running within Spring application. But in my case it is safe to tell, that it is thread - thread is not changed during invocation. Service implementation is a Java method and this method calls others methods, components, etc, everything i one thread. It is possible for me to change one method source and deploy it, but I cannot release application.
Unfortunately AspectJ cannot be used as is, because I cannot change whole application, recompile nor plug something into JVM.
Unfortunately (next) DB administrators cannot turn on sql queries tracing - they don't know how to do it.
Please help, how to tune Hibernate execution without digging the whole application? What is the simplest way?
Facts: Hibernate 3.x, Spring 2.x, java 1.5

A: Here is how I would do it, assuming you're using Logback as your logging framework.

*

*Make sure you have scanning enabled on your logback configuration:
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false" scan="true" scanPeriod="30 seconds" >

*Make sure your file logger includes thread name in the output (%t):
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{yyyy-MM-dd HH:mm:ss} %-5p %C{1} %t - %m%n</pattern>
</encoder>

*Start with SQL logging turned off:
<logger name="org.hibernate.SQL" level="OFF">
<appender-ref ref="FILE_APPENDER"/>
</logger>
<logger name="sql-log" level="OFF">
<appender-ref ref="FILE_APPENDER"/>
</logger>

*Once your application is up and running, and you're ready to execute your test, edit the logback.xml file of the deployed application, and change those levels to 'DEBUG'. Then execute your tests. When tests are done, set those levels back to 'OFF'.

*Look through the log output, and identify the thread name of interest, then grep for that thread name:
grep "thread-1-pool-7" debug.log > sqldebug.log
A bit cumbersome, but it will work.

A: You are not very specific about filtering criteria: do you want to filter SQLs by thread/HTTP session or from a given service (sql times tracing should be done only for one service)?
Nevertheless everything can be done on logging framework level. First you need to enable logging of all queries and then filter out non-interesting ones. I am assuming you are using Logback (BTW Spring 2.x and Java 1.5.x are becoming obsolete...):
Per thread
Implement Logback filter and discard logs from not interesting thread. Alternatively use SiftingAppender with thread id as a key. All logs from a given thread will be dispatched to a separate file.
Per HTTP session
This is a bit tricky because you need to get access to HTTP session/session id from logging framework level. The easy way is to use MDC (see example: Logging user activity in web app). Having session id you can do filtering similar to Per thread section.
Per service
It's not obvious what do you mean. Do you only want to log SQL queries issued from a given class or from a class and all the methods and classes it calls? In both cases you need to examine a call stack while filtering, which isn't very effective. Also AspectJ has within directive - too heavyweight for you I guess.
If this is what you want to achive please clarify your question, I have some other ideas.


text:
Q: Return string of description given string of IDs (separated by commas) I have one table A that has a column C and a lookup table (lookup) that provides a description given an ID.
Here the setup:
table A with column C values:

1,2,3
2,3,4

table lookup:
1, 'This'
2, 'is'
3, 'tricky'
4, 'SQL'

Provide a SQL (SQL Server 2005) statement that returns the following strings:
Input: 1,2,3    Output: 'This','Is','tricky'
Input: 2,3,4    Output: 'Is','tricky','SQL'

basically turning the string of IDs (from an input table A) into a string of descriptions

A: The Samples that come with SQL Server 2005 include a CLR function called Split(). It's the best way of splitting comma-separated lists like this by far.
Suppose you have a table called inputs, with a column called input.
I forget what the particular outputs of dbo.Split() are... so work with me here. Let's call the fields id and val, where id tells us which entry it is in the list.
WITH
separated AS (
   SELECT i.input, s.id, s.val
   FROM
       dbo.inputs AS i
       CROSS APPLY
       dbo.Split(i.input) AS s
)
, converted AS (
    SELECT s.input, s.id, m.string
    FROM
        separated AS s
        JOIN
        dbo.mapping AS m
            ON m.number = CAST(s.val AS varchar(5))
)
SELECT c.input, (SELECT string + ' ' FROM converted AS c2 WHERE c2.input = c.input ORDER BY id FOR XML PATH('')) AS converted_string
FROM converted AS c
GROUP BY c.input;


text:
Q: Django file upload does not work fine models.py:
class File(models.Model):
    name = models.CharField(verbose_name="File name", max_length=200, blank=True, null=True)
    file = models.FileField(upload_to='files/%Y/%m/%d')
    upload_at = models.DateTimeField(auto_now_add=True)
    user = models.ForeignKey(User, related_name="uploader", blank=True, null=True)

    def __str__(self):
        return str(self.name)

Serializer.py
class FileSerializer(ModelSerializer):

    class Meta:
        model = File
        fields = ("id", "file", "upload_at", "user")

views.py:
class FileView(APIView):
    parser_classes = [FileUploadParser, MultiPartParser]
    serializer_class = FileSerializer
    permission_classes = [IsAuthenticated]
    authentication_classes = [TokenAuthentication]

    # @method_decorator(csrf_exempt)
    def post(self, request, format=None):
        serializer = FileSerializer(data=request.FILES)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=HTTP_200_OK)
        return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)

Anythings works fine, but when uploads file images are damaged!

Where I make mistake?

UPDATE
each uploaded file contains this line in file begins:
------WebKitFormBoundarybe2fuJLynmLSubNO^M
Content-Disposition: form-data; name=""; filename="2bc794eead99bf38140524ecbfa7e001_large.jpeg"^M
Content-Type: image/jpeg^M
^M

Why? How I can remove this?

A: As the documentation mentions:

The FileUploadParser is for usage with native clients that can upload the file as a raw data request. For web-based uploads, or for native clients with multipart upload support, you should use the MultiPartParser parser instead.

You should remove the FileUploadParser in your parsers or move MultiPartParser as the first one.


text:
Q: Running parallel Jobs I am working on titan cluster which is consisting of 464 HP blade systems, two head nodes and a virtualized pool of login (submit) nodes.Each node has eight cores (two quad-core processors), and either 16GB (430 nodes) or 32GB (34 nodes) of memory. This provices 3712 compute cores and 8 TB of total RAM (memory)
The task is to use 2 parts namely R1,R2 for each Sample file.So each Sample file has R1,R2 types present in pairs which are to be used together to create a .sam file ,the reference is human_g1k_v37.fasta,and the software is BWA.I am using for loop for this,however I am not able to parallelize it on the cluster,as it would take very long for each sample to be run one at a time.below script is for running iteratively each pair one at a time(Works)
sourcedir=/sourcepath/
destdir=/destinationpath/

for fname in *_R1.fastq.gz
do
base=${fname%_R1*}
bwa-0.7.5a/bwa mem -t 8 human_g1k_v37.fasta "${base}_R1.fastq.gz" "${base}_R2.fastq.gz" >   "$destdir/${base}_R1_R2.sam"

done

Since Using for loop would put each job on the same processor.I tried using "&" but its the same thing I believe and it does not seem to work in this case.I need all these processes to run on different processor parallel (might be an array job??)
Below script does not work (for parallel processing)
sourcedir=/sourcepath/
destdir=/destinationpath/

for fname in *_R1.fastq.gz
do
base=${fname%_R1*}
bwa-0.7.5a/bwa mem -t 8 human_g1k_v37.fasta "${base}_R1.fastq.gz" "${base}_R2.fastq.gz" >   "$destdir/${base}_R1_R2.sam" &

done
wait

For more details,please see this earlier post of mine.Looping files in bash
Thanks

A: How about just submitting your job to your grid engine, it will handle the parallelization itself :
#! /bin/sh
### Your script task.sh ###
#$ -S /bin/sh

bwa-0.7.5a/bwa mem -t 8 human_g1k_v37.fasta "${1}_R1.fastq.gz" "${1}_R2.fastq.gz" > "$destdir/${1}_R1_R2.sam"

and then in your loop :
for fname in *_R1.fastq.gz
do
    base=${fname%_R1*}
    qsub task.sh ${base}
done


text:
Q: Woocommerce: Interaction with Payment Plugin EDIT:
Hi, so what I have is a fully functional shop. I need to add a third party API call after payment is processed, it would work like this:
AUTH Payment Gateway
IF YES then call Third Party API to add customer information
    IF YES CAPTURE the Payment
        CALL Third Party API to ADD Transaction Information and Response from Gateway
    IF NO VOID the Payment
IF NO proceed with normal Payment Gateway Plugin behavior

Any ideas which would be the best way to achieve that? Where do I add those calls to the Third Party API? Thanks

A: Can I suggest you to ask that question again over at https://facebook.com/groups/woohelp and tag a guy by the name of "Luke Cavanagh"
He'll should still have the whole setup.


text:
Q: $a,b \in \bar{k}$, such that $k(a)=k(b)=k(ab)$ Let $k$ be a field of characteristic zero, and let $a, b \in \bar{k}$ ($\bar{k}$ is an algebraic closure of $k$) be two distinct elements, such that
$k(a)=k(b)$.
Notice that $k(a)=k(b)$ implies that the degree of the minimal polynomial of $a$ over $k$, $d_a$, equals the degree of the minimal polynomial of $b$ over $k$, $d_b$; denote $d:=d_a=d_b$.
Further assume that $k(ab)=k(a)=k(b)$ (hence the degree of the minimal polynomial of $ab$ over $k$, $d_{ab}$, equals $d$).

(1) Could one find a concrete example to the above situation with, for example, $k=\mathbb{Q}$?
(2) Is there something 'interesting' to say about $ab$?

Same questions (1) and (2) for the following special cases:

(i) $b=a-\lambda$, for some $\lambda \in k^{\times}$? Should it have 'easier/nicer' answers?
(ii) $d$ is a prime number $\geq 3$? Also, should the extension be Galois? See this and this questions.

Notice that this question is not relevant (at least not directly, but maybe something can be obtained from it), since it talks about relatively prime degrees and sum of elements, while here we talk about equal degrees (probably $d>1$) and product of elements.
Perhaps the primitive element theorem can help?
Thank you very much!

In short, I am asking: Assume that the product $ab$ of two distinct primitive elements $a,b \in L$ for the field extension $k \subseteq L$ (namely, $L=k(a)=k(b)$) is also a primitive element (namely, $L=k(ab)$), does this tell something interesting?


text:
Q: categories in a select dropdown using mysql and PHP I have a table Products.
Products:
id Name         category
1  Sony Bravia  TV
2  Samsung 32   TV
3  Kenwood      Microwave
4  Sony PS3     Video Game
5  Sharp        TV
...

I'd like to display them in a select dropdown as
-- TV   --
Sony Bravia
Samsung 32
Sharp
-- Microwave --
Kenwood
-- Video Games --
Sony PS 3

Is there any way I can do this in MySQL as a single query?
I'd also like to identify categories separately, so when someone selects a category rather than a product, the id in the select option somehow identifies this as a category and not a product (and when someone selects a product, it identifies it as a product). Is this possible at all?
Many thanks

A: $query = "SELECT *
          FROM Products
          ORDER BY category, Name";
$result = mysql_query($query);

echo "<select>\n";

$thisCat = NULL;
while ($row = mysql_fetch_assoc($result)) {
  if ($row['category'] != $thisCat) {
    echo '  <option value="category:'.htmlspecialchars($row['category']).'">-- '.htmlspecialchars($row['category']).' --</option>';
    $thisCat = $row['category'];
  }
  echo '  <option value="'.$row['id'].'">  '.htmlspecialchars($row['Name']).'</option>';
}

echo "</select>";

...although you should probably have a table of categories and use an FK to that table from Products

A: Sure, you can order by category.
  SELECT * FROM products ORDER BY category ASC

This puts all the products in alphabetical order by Category (the ASC is unnecessary, but I like to include it just to be verbose).
Good luck.

A: The query's simple:
SELECT category, Name
FROM yourtable
ORDER BY category, Name

The client-side code will have to implement a simple "state machine" to detect when a new category's been reached while retrieving/displaying the data.
$prev_cat = null;
while($row = mysql_fetch($results)) {
   if ($prev_cat <> $row['category']) {
       echo "<option>---- {$row['category']}----</option>"
       $prev_cat = $row['category'];
   }
   echo "<option>{$row['Name']}</option>";
}

A: First adapt your sort order in the query, so the result is
id Name         category
1  Sony Bravia  TV
2  Samsung 32   TV
5  Sharp        TV
3  Kenwood      Microwave
4  Sony PS3     Video Game
...

Now do the classic group-change-dance
$category='__INVALID__';
while (true) {
  $row=mysql_fetch_row($query);
  if ($row) break;
  if ($row[2]!=$category) {
  echo '<option value="'.$row[2].'">---'.$row[2]."---</option>\n";
  $category=$row[2];
  echo '<option value="'.$row[0].'">'.$row[1]."</option>\n";
}


text:
Q: How do you get the serializer to output JSON? I'm trying to use active_model_serializers to convert an object to JSON. As per this question, I created a file called config/initializers/serializers.rb with the following code:
puts 'Running serializers.rb.'
ActiveModelSerializers.config.adapter = :json_api

I see Running serializers.rb. when resetting the database, but not when running the Rails console. In the console, when I type UserSerializer.new(User.first).as_json, I get {:id=>1, :name=>"Regular User", :created_at=>Thu, 07 Jul 2016 06:03:46 UTC +00:00, :lists=>[{:id=>1, :title=>"Before Wednesday"}]}, which is clearly not JSON. How do I get the as_json method to actually return JSON?

A: UserSerializer.new(User.first).to_json
http://apidock.com/rails/Hash/to_json


text:
Q: Default List Parameter doesn't Reset Consider the following code:
def f(a=[]):
  print(a)
  a += [1]

f()
f()
f()

which outputs
[]
[1]
[1,1]

This behavior seems peculiar. Shouldn't the parameter a be reset to [] each time the function runs?
When the parameter is an integer I get the expected behavior:
def f(a=1):
  print(a)
  a += 1

f()
f()
f()

outputs
1
1
1

I realize lists are mutable and integers aren't, but I can't figure out if that would matter here.
Thank you.

A: No. It's a foible of Python that mutable object initializers do this. It's a better pattern to use None and set the initial value in the method body:
def f(a=None):
  if a is None:
    a = []
  print(a)
  a += [1]

If you use pylint, it provides a warning dangerous-default-value (W0102).

A: This is a little gotcha in Python.  A default parameter doesn't just set a default, it captures an object.  That is, as you can see, the default parameter is one specific list object that happens to be initialized empty.  You might think you could do this:
def f(a=[]):
    a = a[:]

but if you do that, then any time someone passes in a list, you'll make a copy, and your changes won't be seen in the original list.  This is sometimes a good choice:
def f(a=None):
    if not a:
        a = []


text:
Q: Export to CSV a list of addresses that fall within a shapefile? I currently have a shapefile (KML, but I also have it in other formats as well) that outlines neighborhoods within a city.  I also have a list of vacant property addresses in CSV.
I'm currently importing the addresses into Google Earth (GE) over the shapefile, but I don't think GE will do what I want.
I would like to be able to add data fields from the neighborhood shapefile such to the imported addresses and be able to export all the addresses to a CSV file and include the neighborhood shapefile data for the neighborhood they are in based on the shapefile.
Here is a screenshot of the neighborhood shapefile info:

Here is a screenshot of the imported address info:

A: Google Earth cannot do spatial joins or perform other vector analysis functions, so it will not be able to do this for you.
I suggest you take a look at QGIS, the free and open-source GIS package which can absolutely do this. You'll be able to import your shapefile (Add Vector Layer) and address CSV (Add Delimited Text Layer), and use the vector analysis tools including Point in Polygon, Spatial Query, etc.
Here is a good tutorial that walks you though the details:
http://www.qgistutorials.com/en/docs/points_in_polygon.html


text:
Q: Understanding IEnumerable - IEnumerator logic I got stuck with Adam Freeman "Asp net" book, I read a lot about IEnumerable and IEnumerator interface, but it's still hard to understand some results. I have these two classes.
public class ShoppingCart : IEnumerable<Product>
{
    public IEnumerable<Product> Products { get; set; }

    public IEnumerator<Product> GetEnumerator()
    {
        return Products.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

and an extension of the first one,
 public static class MyExtensionMethods
{
    public static decimal TotalPrices (this IEnumerable<Product> products)
    {
        decimal total = 0;
        foreach (Product prod in products)
        {
            total += prod?.Price ?? 0;
        }
        return total;
    }
}

Product is an easy class with some fields like Name, Price etc.
I have lot of doubts. First of all I don't understand how c# knows MyExtensionMethods is an extension of ShoppingCart, then I don't understand how can TotalPrices know that prod come from Products in ShoppingCart class. Could someone explain me briefly the logic behind these few lines?
Thank you everyone, sorry for the dumb question.

A:
First of all I don't understand how c# knows MyExtensionMethods is an extension of ShoppingCart

it isn't; the "magic" here is the this IEnumerable<Product> products, which says "the method is an extension method on anything that is IEnumerable<Product>" - and since ShoppingCart satisfies that, it works.

then I don't understand how can TotalPrices know that prod come from Products in ShoppingCart class

It doesn't access Products on ShoppintCart; it goes via GetEnumerator();
this works because foreach (Product prod in products) can work on (among other things) something that is IEnumerable<Product> - which we know products is, because that is how it is defined. This basically then becomes:
    public static decimal TotalPrices (this IEnumerable<Product> products)
    {
        decimal total = 0;
        using (var iter = products.GetEnumerator())
        {
            while (iter.MoveNext())
            {
                var prod = iter.Current;
                total += prod?.Price ?? 0;
            }
        }
        return total;
    }

which is all defined via IEnumerable<T>. The good news is: you usually never need to know this - just know that foreach works on sequences, and IEnumerable<T> is a sequence of T.