问:
Difference between ArrayIterator, ArrayObject and Array in PHP
Can somebody explain clearly the fundamental differences between ArrayIterator, ArrayObject and Array in PHP in terms of functionality and operation? Thanks!

答:
An Iterator is an object that enables a programmer to traverse a container, particularly lists. Various types of iterators are often provided via a container's interface.

There is no much difference between ArrayObject and Array as they represent the same things albeit using different object types.

ArrayIterator is an Iterator that iterates over Array-like objects, this includes all objects that implement ArrayAcess and the native Array type.
In fact, when you foreach over an array, PHP internally creates ArrayIterator to do the traversing and transform your code to look as if typed this,

```<code>for( $arrayIterator->rewind(); $arrayIterator->valid(); $arrayIterator-
>next())
{    $key = $arrayIteartor->key();
     $value = $arrayIterator->current();
}
</code>```

So you can see, every collection object has an Iterator except for your defined collections which you need to define your own Iterators for.

Body:
An Iterator is an object that enables a programmer to traverse a container, particularly lists. Various types of iterators are often provided via a container's interface.

There is no much difference between ArrayObject and Array as they represent the same things albeit using different object types.

ArrayIterator is an Iterator that iterates over Array-like objects, this includes all objects that implement ArrayAcess and the native Array type.
In fact, when you foreach over an array, PHP internally creates ArrayIterator to do the traversing and transform your code to look as if typed this,

for( $arrayIterator->rewind(); $arrayIterator->valid(); $arrayIterator-
>next())
{    $key = $arrayIteartor->key();
     $value = $arrayIterator->current();
}

So you can see, every collection object has an Iterator except for your defined collections which you need to define your own Iterators for.


来源: stackexchange

问:
TreeMap Key, Value pair exists, but .get(Key) returns the value as null
I have this code (below) that when I print the treemap, I can clearly see the key,value pairs. Every key has a value (no null values in the output). When I get the first key, it will give me the key, but when I try to get the value based on the key, it will return null.

```<code>TreeMap<String, Double> cosinesimilarityvalues = simvalfordoc.returnsortedcosinesimilarityvalues();
System.out.println(cosinesimilarityvalues);
String topkey = cosinesimilarityvalues.firstKey();
System.out.println(topkey);
Double topvalue = cosinesimilarityvalues.get(topkey);
System.out.println(topvalue);
topones.put(topkey, topvalue);
</code>```

Here is part of an output :

```<code>{article04_C9,article08_C12=0.0, article04_C9,article18_C10=0.0, article04_C9,article07_C1=0.0, article04_C9,article03_C10=0.0, article04_C9,article01_C10=0.0, article04_C9,article07_C10=0.0, article04_C9,article17_C10=0.0, article04_C9,article10_C10=0.0, article04_C9,article05_C10=0.0, article04_C9,article11_C10=0.0, article04_C9,article02_C10=0.0, article04_C9,article13_C10=0.0, article04_C9,article02_C13=5.676594773265355E-4, article04_C9,article02_C11=6.228132014119322E-4, article04_C9,article06_C10=6.732460014209593E-4, article04_C9,article12_C10=0.0011438670619737105, article04_C9,article03_C3=0.0011907203907551985, article04_C9,article03_C11=0.0012323612320990097}
</code>```

So I should be getting article04_C9,article08_C12 as firstKey() (which I do)
but when I go to retrieve the value associated with that key, it returns null.

Here is the code that I'm using to populate the treemap

```<code>HashMap<String, Double> cosinesimilarityvalues = new HashMap<String, Double>();
TreeMap<String, Double> sortedcosinesimilarityvalues = new TreeMap<String, Double>();
public void comparecosinesimilarityvalues(List<tfidfvalues> matrix, tfidfvalues currentvector) {
    String articlename = currentvector.returnarticlename();
    String foldername = currentvector.returnfoldername();
    ArrayList<Double> tfidfval = currentvector.returntfidfvaluesforrow();
    articlefolder = articlename+ "_" + foldername;
    CosineSimilarity calculator = new CosineSimilarity();
    for(int i = 0; i < matrix.size(); i++) {
        String compvectorarticlename = matrix.get(i).returnarticlename();
        String compvectorfoldername = matrix.get(i).returnfoldername();
        ArrayList<Double> compvector = matrix.get(i).returntfidfvaluesforrow();

        Double cosinesimilarity = calculator.CosineSimilarityCalc(tfidfval, compvector);

        String comparingwhat = compvectorarticlename + "_" + compvectorfoldername;

        String comparingthese = articlefolder + "," + comparingwhat;
        cosinesimilarityvalues.put(comparingthese, cosinesimilarity);
    }

    Iterator<Map.Entry<String, Double>> iterator = cosinesimilarityvalues.entrySet().iterator();
    while(iterator.hasNext()) {
        Map.Entry<String, Double> entry = iterator.next();
        if((entry.getValue() > 0.989 && entry.getValue() < 1) || entry.getValue() > 1) {
            iterator.remove();
        }
    }

    sortedcosinesimilarityvalues = sortMapByValue(cosinesimilarityvalues);
}

public TreeMap<String, Double> returnsortedcosinesimilarityvalues() {
    return sortedcosinesimilarityvalues;
}
</code>```

Here is the function I am using to sort by value...if that helps

from : https://www.programcreek.com/2013/03/java-sort-map-by-value/

```<code>class ValueComparator implements Comparator<String>{

    HashMap<String, Double> map = new HashMap<String, Double>();

    public ValueComparator(HashMap<String, Double> map){
        this.map.putAll(map);
    }

    @Override
    public int compare(String s1, String s2) {
        if(map.get(s1) >= map.get(s2)){
            return 1;
        }else{
            return -1;
        }
    }
}

public TreeMap<String, Double> sortMapByValue(HashMap<String, Double> map){
    Comparator<String> comparator = new ValueComparator(map);
    //TreeMap is a map sorted by its keys.
    //The comparator is used to sort the TreeMap by keys.
    TreeMap<String, Double> result = new TreeMap<String, Double>(comparator);
    result.putAll(map);
    return result;
}
</code>```

I'm not sure what I'm doing wrong. Please help!

Thanks!

UPDATE

I was able to retrieve the top key and top value via

```<code>Map.Entry<String, Double> entry1 = cosinesimilarityvalues.firstEntry();
String topkey = entry1.getKey();
Double topvalue = entry1.getValue();
</code>```

but I have no idea why this works and the other method does not work.
Although my code now works, I wish I could find out what the difference is!

答:
Made few changes to your existing implementation of the comparator, in order to adhere to the contract of comparator implementation:

Replaced Generic parameter from String to Object(not sure if its really needed)

Type casting value of map.get(s1) & fetching double value to compare

Separated the >, < & ==

It seems to work using the below implementation of the comparator.

```<code>    HashMap<String, Double> map = new HashMap<String, Double>();

    public ValueComparator(HashMap<String, Double> map){
        this.map.putAll(map);
    }

    @Override
    public int compare(Object s1, Object s2) {
        if(((Double) map.get(s1)).doubleValue() > ((Double) map.get(s2)).doubleValue()){
            return 1;
        }
        else if (((Double) map.get(s1)).doubleValue() == ((Double) map.get(s2)).doubleValue()){
    return ((String)s1).compareTo(((String)s2));
         }
         else{
            return -1;
        }
    }
</code>```

For the below sample values:

```<code>treemap.put( "two",2.0);
   treemap.put( "one",1.0);
   treemap.put( "three",3.0);
   treemap.put( "six",6.0);
   treemap.put( "five",5.0);
</code>```

Output:

```<code>First key is: one
Value against first key: 1.0
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have this code (below) that when I print the treemap, I can clearly see the key,value pairs. Every key has a value (no null values in the output). When I get the first key, it will give me the key, but when I try to get the value based on the key, it will return null.

TreeMap<String, Double> cosinesimilarityvalues = simvalfordoc.returnsortedcosinesimilarityvalues();
System.out.println(cosinesimilarityvalues);
String topkey = cosinesimilarityvalues.firstKey();
System.out.println(topkey);
Double topvalue = cosinesimilarityvalues.get(topkey);
System.out.println(topvalue);
topones.put(topkey, topvalue);

Here is part of an output :

{article04_C9,article08_C12=0.0, article04_C9,article18_C10=0.0, article04_C9,article07_C1=0.0, article04_C9,article03_C10=0.0, article04_C9,article01_C10=0.0, article04_C9,article07_C10=0.0, article04_C9,article17_C10=0.0, article04_C9,article10_C10=0.0, article04_C9,article05_C10=0.0, article04_C9,article11_C10=0.0, article04_C9,article02_C10=0.0, article04_C9,article13_C10=0.0, article04_C9,article02_C13=5.676594773265355E-4, article04_C9,article02_C11=6.228132014119322E-4, article04_C9,article06_C10=6.732460014209593E-4, article04_C9,article12_C10=0.0011438670619737105, article04_C9,article03_C3=0.0011907203907551985, article04_C9,article03_C11=0.0012323612320990097}

So I should be getting article04_C9,article08_C12 as firstKey() (which I do)
but when I go to retrieve the value associated with that key, it returns null.

Here is the code that I'm using to populate the treemap

HashMap<String, Double> cosinesimilarityvalues = new HashMap<String, Double>();
TreeMap<String, Double> sortedcosinesimilarityvalues = new TreeMap<String, Double>();
public void comparecosinesimilarityvalues(List<tfidfvalues> matrix, tfidfvalues currentvector) {
    String articlename = currentvector.returnarticlename();
    String foldername = currentvector.returnfoldername();
    ArrayList<Double> tfidfval = currentvector.returntfidfvaluesforrow();
    articlefolder = articlename+ "_" + foldername;
    CosineSimilarity calculator = new CosineSimilarity();
    for(int i = 0; i < matrix.size(); i++) {
        String compvectorarticlename = matrix.get(i).returnarticlename();
        String compvectorfoldername = matrix.get(i).returnfoldername();
        ArrayList<Double> compvector = matrix.get(i).returntfidfvaluesforrow();

        Double cosinesimilarity = calculator.CosineSimilarityCalc(tfidfval, compvector);

        String comparingwhat = compvectorarticlename + "_" + compvectorfoldername;

        String comparingthese = articlefolder + "," + comparingwhat;
        cosinesimilarityvalues.put(comparingthese, cosinesimilarity);
    }

    Iterator<Map.Entry<String, Double>> iterator = cosinesimilarityvalues.entrySet().iterator();
    while(iterator.hasNext()) {
        Map.Entry<String, Double> entry = iterator.next();
        if((entry.getValue() > 0.989 && entry.getValue() < 1) || entry.getValue() > 1) {
            iterator.remove();
        }
    }

    sortedcosinesimilarityvalues = sortMapByValue(cosinesimilarityvalues);
}

public TreeMap<String, Double> returnsortedcosinesimilarityvalues() {
    return sortedcosinesimilarityvalues;
}

Here is the function I am using to sort by value...if that helps

from : https://www.programcreek.com/2013/03/java-sort-map-by-value/

class ValueComparator implements Comparator<String>{

    HashMap<String, Double> map = new HashMap<String, Double>();

    public ValueComparator(HashMap<String, Double> map){
        this.map.putAll(map);
    }

    @Override
    public int compare(String s1, String s2) {
        if(map.get(s1) >= map.get(s2)){
            return 1;
        }else{
            return -1;
        }
    }
}

public TreeMap<String, Double> sortMapByValue(HashMap<String, Double> map){
    Comparator<String> comparator = new ValueComparator(map);
    //TreeMap is a map sorted by its keys.
    //The comparator is used to sort the TreeMap by keys.
    TreeMap<String, Double> result = new TreeMap<String, Double>(comparator);
    result.putAll(map);
    return result;
}

I'm not sure what I'm doing wrong. Please help!

Thanks!

UPDATE

I was able to retrieve the top key and top value via

Map.Entry<String, Double> entry1 = cosinesimilarityvalues.firstEntry();
String topkey = entry1.getKey();
Double topvalue = entry1.getValue();

but I have no idea why this works and the other method does not work.
Although my code now works, I wish I could find out what the difference is!

Body:
Made few changes to your existing implementation of the comparator, in order to adhere to the contract of comparator implementation:

Replaced Generic parameter from String to Object(not sure if its really needed)

Type casting value of map.get(s1) & fetching double value to compare

Separated the >, < & ==

It seems to work using the below implementation of the comparator.

    HashMap<String, Double> map = new HashMap<String, Double>();

    public ValueComparator(HashMap<String, Double> map){
        this.map.putAll(map);
    }

    @Override
    public int compare(Object s1, Object s2) {
        if(((Double) map.get(s1)).doubleValue() > ((Double) map.get(s2)).doubleValue()){
            return 1;
        }
        else if (((Double) map.get(s1)).doubleValue() == ((Double) map.get(s2)).doubleValue()){
    return ((String)s1).compareTo(((String)s2));
         }
         else{
            return -1;
        }
    }

For the below sample values:

treemap.put( "two",2.0);
   treemap.put( "one",1.0);
   treemap.put( "three",3.0);
   treemap.put( "six",6.0);
   treemap.put( "five",5.0);

Output:

First key is: one
Value against first key: 1.0


问:
Starting D-Bus Service using Golang
I'm now working on call and start a systemd service (mine just calls a shell script) using D-Bus API for golang.

I made a D-Bus service in /usr/share/dbus-1/system-services/org.freedesktop.hello.service

```<code>[D-BUS Service]
Name=org.freedesktop.hello
Exec=/bin/false
User=root
SystemdService=hello.service
</code>```

And a systemd service in /lib/systemd/system/hello.service

```<code>[Unit]
Description=Hello

[Service]
Type=dbus
BusName=org.freedesktop.hello
ExecStart=/opt/hello.sh
</code>```

I'm trying to acheive the same result of code below, which worked.

```<code>sudo gdbus call --system --dest org.freedesktop.hello --object-path /org/freedesktop/hello --method org.freedesktop.DBus.Introspectable.Introspect
</code>```

However I keep getting the error in Golang,

```<code>The name org.freedesktop.hello was not provided by any .service files
</code>```

My code for now is

```<code>package main

import (
    "encoding/json"
    "github.com/godbus/dbus"
    "os"
    "github.com/godbus/dbus/introspect"
)

func main() {
    conn, error1 := dbus.SessionBus()
    if error1 != nil {
        panic(error1)
    }
    node, err2 := introspect.Call(conn.Object("org.freedesktop.hello", "/org/freedesktop/hello"))
    if err2 != nil {
        panic(err2)
    }
    data, _ := json.MarshalIndent(node, "", "   ")
    os.Stdout.Write(data)
}
</code>```

There aren't so many info about this stuff, so I want to get some help. Thanks!

答:
```<code>sudo gdbus call --system ...
</code>```

That's on the system bus.

```<code>...
conn, error1 := dbus.SessionBus()
...
</code>```

And this is on the session bus.

Try to use something like dbus.SystemBus().

Title: Starting D-Bus Service using Golang

Body:
I'm now working on call and start a systemd service (mine just calls a shell script) using D-Bus API for golang.

I made a D-Bus service in /usr/share/dbus-1/system-services/org.freedesktop.hello.service

[D-BUS Service]
Name=org.freedesktop.hello
Exec=/bin/false
User=root
SystemdService=hello.service

And a systemd service in /lib/systemd/system/hello.service

[Unit]
Description=Hello

[Service]
Type=dbus
BusName=org.freedesktop.hello
ExecStart=/opt/hello.sh

I'm trying to acheive the same result of code below, which worked.

sudo gdbus call --system --dest org.freedesktop.hello --object-path /org/freedesktop/hello --method org.freedesktop.DBus.Introspectable.Introspect

However I keep getting the error in Golang,

The name org.freedesktop.hello was not provided by any .service files

My code for now is

package main

import (
    "encoding/json"
    "github.com/godbus/dbus"
    "os"
    "github.com/godbus/dbus/introspect"
)

func main() {
    conn, error1 := dbus.SessionBus()
    if error1 != nil {
        panic(error1)
    }
    node, err2 := introspect.Call(conn.Object("org.freedesktop.hello", "/org/freedesktop/hello"))
    if err2 != nil {
        panic(err2)
    }
    data, _ := json.MarshalIndent(node, "", "   ")
    os.Stdout.Write(data)
}

There aren't so many info about this stuff, so I want to get some help. Thanks!

Body:
sudo gdbus call --system ...

That's on the system bus.

...
conn, error1 := dbus.SessionBus()
...

And this is on the session bus.

Try to use something like dbus.SystemBus().


问:
REST-Requests not executed in newman due to not correct usage of ssl-certificates
Im currently using Newman for automatically testing my Rest-API calls.

The problem is i can run all my tests in Postman without any problems, using the certificates (.pem and pkcs8) for ssl authorization within Postman is also not a problem. But when i try to load a Collection into Newman on the command-line, i cannot run the tests because the certificates - which are recommended correctly in Postman are not recommended corretly in Newman.

if i run:

newman run postman_collection.json --ssl-client-cert cert.pfx --ssl-client-passphrase passphrase

Then no request is executed. if I instead use:

newman run postman_collection.json --ssl-client-cert cert.crt --ssl-client-key key.pkcs8 client-passphrase passphrase

so Using the key and authorization certificate both separately (cert.crt, key.pkcs8) and not together in a .pfx file, then it executes requests but says that it "Couldnt validate first certificate", so every request returns an error.

How can i fix this?

答: You can workaround this using parameter --insecure  instead parameters "--ssl-client-cert cert.crt --ssl-client-key key.pkcs8 client-passphrase passphrase"</p>


问:
Targeting an element with specific data attribute value
I am working on the code below. How can I add .click() to the a link with specific data attribute of HD?

if ($(a).data("quality") == "HD") {
  $(this).click();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="stream">
  <li>Low</li>
  <li>Med</li>
  <li>HD</li>
</ul></code>```

答:
pure js approach

window.onload = clickAnchor();

function clickAnchor() {
let anchorTags = document.getElementsByTagName('a');
for(i=0;i<anchorTags.length;i++) {
if(anchorTags[i].getAttribute('data-quality') == 'HD') {
     anchorTags[i].click();;
  }
}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="stream">
  <li>Low</li>
  <li>Med</li>
  <li>HD</li>
</ul></code>```

ContentLicense: CC BY-SA 4.0

Body:
I am working on the code below. How can I add .click() to the a link with specific data attribute of HD?

if ($(a).data("quality") == "HD") {
  $(this).click();
}

Low

Med

HD

Body:
pure js approach

window.onload = clickAnchor();

function clickAnchor() {
let anchorTags = document.getElementsByTagName('a');
for(i=0;i<anchorTags.length;i++) {
if(anchorTags[i].getAttribute('data-quality') == 'HD') {
     anchorTags[i].click();;
  }
}
}

<ul class="stream">
  <li><a onclick = "alert('low clicked')" data-quality="L">Low</a></li>
  <li><a onclick = "alert('med clicked')" data-quality="M">Med</a></li>
  <li><a onclick = "alert('HD clicked')" data-quality="HD">HD</a></li>
</ul>


问:
Resuming a thread by using notifyAll
Take the Pausing a Thread example. If I use notifyAll instead of notify, is there any side effect, and is it necessary?

答:
Create a new runnable. In the run method "start" countdownlatch is waiting and will not allow execution unless it is released using calling countdown on that latch for a predefined time. In this case 1. (since start is passed 1 as concurrent no)</p>

<p>// Revised Answer.
// A runnable class. </p>

```<code>public  class WorkerThread implements Runnable
    {
        CountDownLatch start;

        CountDownLatch end;

        String name;

        WorkerThread(CountDownLatch startLatch, CountDownLatch stopLatch)
        {
            this.start = startLatch;
            this.end = stopLatch;

        }

        public void run()
        {
            try
            {

                start.await();
            } catch (InterruptedException ex)
            {
                ex.printStackTrace();
            }
            System.out.println("Will run when start is released ");
            end.countDown();
        }
    }
</code>```

<p>// This is the entry point method that executes the worker thread. </p>

```<code>public  void  initiateProcess (final int count) {
           CountDownLatch start = new CountDownLatch(1);
        CountDownLatch stop = new CountDownLatch(count);
        for (int i = 0; i < count; i++)
        {
            new Thread(new WorkerThread(start, stop))
                    .start();
        }
        System.out.println("Go");
// This is where start latch is released. Now worked thread can complete its function.
        start.countDown();
        try
        {

 // Stop will wait until stop latch is countdowned to zero from count param. (see count param)
            stop.await();
        } catch (InterruptedException ex)
        {
            ex.printStackTrace();
        }
        System.out.println("Finished");
    }
</code>```

ContentLicense: CC BY-SA 2.5

Title: Resuming a thread by using notifyAll

Body:
Create a new runnable. In the run method "start" countdownlatch is waiting and will not allow execution unless it is released using calling countdown on that latch for a predefined time. In this case 1. (since start is passed 1 as concurrent no)

// Revised Answer.
// A runnable class.

public  class WorkerThread implements Runnable
    {
        CountDownLatch start;

        CountDownLatch end;

        String name;

        WorkerThread(CountDownLatch startLatch, CountDownLatch stopLatch)
        {
            this.start = startLatch;
            this.end = stopLatch;

        }

        public void run()
        {
            try
            {

                start.await();
            } catch (InterruptedException ex)
            {
                ex.printStackTrace();
            }
            System.out.println("Will run when start is released ");
            end.countDown();
        }
    }

// This is the entry point method that executes the worker thread.

public  void  initiateProcess (final int count) {
           CountDownLatch start = new CountDownLatch(1);
        CountDownLatch stop = new CountDownLatch(count);
        for (int i = 0; i < count; i++)
        {
            new Thread(new WorkerThread(start, stop))
                    .start();
        }
        System.out.println("Go");
// This is where start latch is released. Now worked thread can complete its function.
        start.countDown();
        try
        {

 // Stop will wait until stop latch is countdowned to zero from count param. (see count param)
            stop.await();
        } catch (InterruptedException ex)
        {
            ex.printStackTrace();
        }
        System.out.println("Finished");
    }


问:
OpenCV error file INSTALL cannot find /bin/opencv_annotation
I have a problem on compiling OpenCV 3.X.X on Debian but It is OK on Ubuntu. I compile OpenCV with these commands:

```<code>cmake -D CMAKE_BUILD_TYPE=RELEASE \
    -D CMAKE_INSTALL_PREFIX=/opt/opencv-3.3.0/build \
    -D OPENCV_EXTRA_MODULES_PATH=/opt/opencv_contrib-3.3.0/modules \
    -D BUILD_SHARED_LIBS=ON \
    -D WITH_FFMPEG=ON \
    -D PYTHON_EXECUTABLE=/opt/virtualenvs/cv/bin/python \
    -D BUILD_EXAMPLES=ON \
    -D WITH_QT=ON \
    -D WITH_OPENGL=ON \
    -D WITH_TBB=OFF \
    -D WITH_OPENMP=ON \
    -D BUILD_opencv_apps=ON \
    -D BUILD_DOCS=ON ..

make -j12

sudo make install - j12
</code>```

After "make install" I get this error and all shared library in build/lib that were built successfully before error, are deleted!

```<code>CMake Error at apps/annotation/cmake_install.cmake:42 (file):
  file INSTALL cannot find "/opt/opencv-3.3.0/build/bin/opencv_annotation".
Call Stack (most recent call first):
  apps/cmake_install.cmake:39 (include)
  cmake_install.cmake:88 (include)

Makefile:66: recipe for target 'install' failed
make: *** [install] Error 1
</code>```

If I set -D BUILD_opencv_apps=OFF, there is no error in compiling but again at the end all *.so files in build/lib are deleted.

Once in another computer I manage to compile OpenCV successfully but I don't know what exactly I had done.

My system has:

```<code>OpenCV 3.3.0
Debian GNU/Linux 8.9 (jessie) 3.16.43-2+deb8u5 (2017-09-19) x86_64 GNU/Linux
cmake version 3.0.2
gcc (Debian 4.9.2-10) 4.9.2
</code>```

What's the problem?

答:
I found the solution. This error happens when build directory is the same with install directory, At least on some Linux distributions!

I should change install directory.

Body:
I have a problem on compiling OpenCV 3.X.X on Debian but It is OK on Ubuntu. I compile OpenCV with these commands:

cmake -D CMAKE_BUILD_TYPE=RELEASE \
    -D CMAKE_INSTALL_PREFIX=/opt/opencv-3.3.0/build \
    -D OPENCV_EXTRA_MODULES_PATH=/opt/opencv_contrib-3.3.0/modules \
    -D BUILD_SHARED_LIBS=ON \
    -D WITH_FFMPEG=ON \
    -D PYTHON_EXECUTABLE=/opt/virtualenvs/cv/bin/python \
    -D BUILD_EXAMPLES=ON \
    -D WITH_QT=ON \
    -D WITH_OPENGL=ON \
    -D WITH_TBB=OFF \
    -D WITH_OPENMP=ON \
    -D BUILD_opencv_apps=ON \
    -D BUILD_DOCS=ON ..

make -j12

sudo make install - j12

After "make install" I get this error and all shared library in build/lib that were built successfully before error, are deleted!

CMake Error at apps/annotation/cmake_install.cmake:42 (file):
  file INSTALL cannot find "/opt/opencv-3.3.0/build/bin/opencv_annotation".
Call Stack (most recent call first):
  apps/cmake_install.cmake:39 (include)
  cmake_install.cmake:88 (include)

Makefile:66: recipe for target 'install' failed
make: *** [install] Error 1

If I set -D BUILD_opencv_apps=OFF, there is no error in compiling but again at the end all *.so files in build/lib are deleted.

Once in another computer I manage to compile OpenCV successfully but I don't know what exactly I had done.

My system has:

OpenCV 3.3.0
Debian GNU/Linux 8.9 (jessie) 3.16.43-2+deb8u5 (2017-09-19) x86_64 GNU/Linux
cmake version 3.0.2
gcc (Debian 4.9.2-10) 4.9.2

What's the problem?


问:
About iOS deprecated api and SDKs
About deprecated api and SDKs

UIAlertview is available from iOS 2.0 to iOS 9.0. From iOS 8.0 .XCode will warn that use UIAlertController instead.
But when i set base sdk as iOS 10.3 and set deployment target as iOS 7.1, the app will run from iOS 7.1 to iOS 10.3 devices succefully.
And when  set base sdk as iOS 10.3 and set deployment target as iOS 10.0, the app also run successfully ,just have many warning ,but build successfully.

答:
Yes, it will work. But bad practice to use deprecated things. Use UIAlertController instead.
 Some day it maybe won't work. who knows about Apple's decisions.</p>

```<code>UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Title" message:@"Your Message." preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:true completion:nil];
</code>```

Title: About iOS deprecated api and SDKs

Body:
Yes, it will work. But bad practice to use deprecated things. Use UIAlertController instead.
 Some day it maybe won't work. who knows about Apple's decisions.

UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Title" message:@"Your Message." preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:true completion:nil];


问:
Draw dots on a blank window
I am an artist. I have Python installed. It works. What I am trying to do is to create images on a white screen (window) based on reiterative algorithms. I can't seem to get anything to put dots on a window. If I could just get a bit of python code that, and the library(s) that contain that code, based on an x,y coordinate, that could draw a dot in that window I pretty much could figure out the rest. Also would be nice to vary the color of the dot.
So flow control would look like:

Calculate an x,y coordinate (my equations would do that)

Specify a dot color (this might always be the same color)

Draw the dot at the specified coordinate.

Pump the x y answers from 1 above back into equation and calculate a new x,y coordinate.

Loop to 2 above a specified number of times.

I can pretty much figure all this out but the "draw the colored dot" is beyond me.

答:
I believe the dot() method in the turtle library that comes with Python is your simplest solution:

```<code>from random import randint, choice
from turtle import Turtle, Screen

COLORS = ['red', 'green', 'blue', 'magenta', 'yellow', 'cyan']

screen = Screen()

width, height = screen.window_width(), screen.window_height()

turtle = Turtle(visible=False)
turtle.speed('fastest')
turtle.penup()

for _ in range(randint(10, 100)):
    radius = randint(5, 45)

    x = randint(radius - width//2, width//2 - radius)
    y = randint(radius - height//2, height//2 - radius)

    turtle.setposition(x, y)
    turtle.dot(radius * 2, choice(COLORS))

screen.exitonclick()
</code>```

Turtle also has a circle() method but it draws from the edge of a circle (based on a radius instead of a diameter) not the center like the dot() method.  One advantage of circle() is the outline and fill can be different colors unlike dot().

Title: Draw dots on a blank window

Body:
I believe the dot() method in the turtle library that comes with Python is your simplest solution:

from random import randint, choice
from turtle import Turtle, Screen

COLORS = ['red', 'green', 'blue', 'magenta', 'yellow', 'cyan']

screen = Screen()

width, height = screen.window_width(), screen.window_height()

turtle = Turtle(visible=False)
turtle.speed('fastest')
turtle.penup()

for _ in range(randint(10, 100)):
    radius = randint(5, 45)

    x = randint(radius - width//2, width//2 - radius)
    y = randint(radius - height//2, height//2 - radius)

    turtle.setposition(x, y)
    turtle.dot(radius * 2, choice(COLORS))

screen.exitonclick()

Turtle also has a circle() method but it draws from the edge of a circle (based on a radius instead of a diameter) not the center like the dot() method.  One advantage of circle() is the outline and fill can be different colors unlike dot().


问:
Make .xlsx template file available in published .NET Core 2.0 app
I have a .NET Core 2.0 solution containing 3 projects (DataAccess, Services, WebAPI). In the wwwroot folder of the WebAPI project I've created a templates folder that contains a couple of Excel template files. In Services I have an Export folder which contains the ExportService. The ExportService uses the templates to generate some reports. I have a private method that 'gets' the path to the templates directory. In fact I'm just specifying a relative path to it, which works fine when debugging, but not when I publish the project. How can I make the files available/reachable in my published app?</p>

```<code>private string GetExcelTemplatePath()
{
    var templatesDirectory = "..\\WebAPI\\wwwroot\\templates";
    var templateName = "Excel_template_v1.xlsx";
    var templatePath = Path.Combine(templatesDirectory, templateName);

    return templatePath;
}
</code>```

答:
With ASP.NET Core you’ll want to inject IHostingEnvironment into your controller (or wherever you need this). From that object you can get WebRootPath which contains the path to wwwroot. Use that to find the files inside it.

More information from the web.

Body:
I have a .NET Core 2.0 solution containing 3 projects (DataAccess, Services, WebAPI). In the wwwroot folder of the WebAPI project I've created a templates folder that contains a couple of Excel template files. In Services I have an Export folder which contains the ExportService. The ExportService uses the templates to generate some reports. I have a private method that 'gets' the path to the templates directory. In fact I'm just specifying a relative path to it, which works fine when debugging, but not when I publish the project. How can I make the files available/reachable in my published app?

private string GetExcelTemplatePath()
{
    var templatesDirectory = "..\\WebAPI\\wwwroot\\templates";
    var templateName = "Excel_template_v1.xlsx";
    var templatePath = Path.Combine(templatesDirectory, templateName);

    return templatePath;
}


问:
Loading a large array of shorts in Android
Suppose I have an array of shorts of length 1,000,000 and that I need this to be generated or loaded into RAM (ideally within a few seconds) when my app starts and before I get an activity thread timeout.

I'll then have quick access to its entries during runtime.

How would you go about loading this to memory from file? Loading from txt file? From an SQLite file (with two integer columns in a single table, one for index and the other for value)?

Is it possible for an activity to request a longer idle time before it's deemed to have timed out?

答:
The solution to your problem would be to spawn a thread to do the file reading.  This is going to be a high level overview so you can track down the relevant items.  It will address item 2 first, then item 1.

First, you need to get your long running processing off the UI thread.  The 'idle' time responsiveness issue (application not responding) is because you are tying up the UI thread which is needed to do other actions.  The thread cannot be reading a file and drawing the screen at the same time (at least not well).

I've found the easiest way to do this is using the Java ExecutorServices.  What you want to do is package the logic for reading the file or database into a java Runnable or Callable and then run that using an ExecutorService.  The executor will take care of starting a thread and reclaiming those resource when they are no longer in use.

One key issue to be aware of is that, once you create another thread, you need to be careful when updating the UI.  Because ui objects are not thread safe, you can only update the ui from the UI thread (common sense, right?).  If you are in an activity, you can do this by calling runOnUiThread() or you can create your own Handler in one of the ACtivity methods called by the UI thread in the first place.

Sam Dufel said:

Hmm... You could really pack that down if you could come with a format to replace all the dummy entries with just a count. Eg, 10,000 zeros get replaced by a pair of flag bytes followed by 10,000

Additionally, you may see increased speed by spawning multiple read threads.  If you could break the file up into two files which would allow two threads to execute simultaneously you could see a significant speed up (depending on what else you need to do to the data).  A sort of divide an conquer for loading up your data from file.  A cursory google search should give you information on how to load shorts from a file.  You should most definitely consider using a binary format given your specifications.


问:
Angular2 fire fails Namespace 'firebase' has no exported member 'Promise'
I have installed angular2 fire

```<code> "angularfire2": "^5.0.0-rc.0",
</code>```

Now in my app module(root module)

```<code>export const firebaseConfig = {
  apiKey: "mykey",
  authDomain: "....",
  databaseURL: "...",
  projectId: "...",
  storageBucket: "...",
  messagingSenderId: "..."
};

imports:[
    AngularFireModule.initializeApp(firebaseConfig),
    AngularFireDatabaseModule
 ]
</code>```

Now am geting an error

```<code> Class 'FirebaseApp' incorrectly implements interface 'App'.
  Property 'firestore' is missing in type 'FirebaseApp'.

node_modules/angularfire2/firebase.app.module.d.ts (12,28):
  Namespace 'firebase' has no exported member 'Promise'.
</code>```

Where am i going wrong or what else do i need to add to have it work

答: run npm install anularfire2 --save command it should work

Body:
I have installed angular2 fire

 "angularfire2": "^5.0.0-rc.0",

Now in my app module(root module)

export const firebaseConfig = {
  apiKey: "mykey",
  authDomain: "....",
  databaseURL: "...",
  projectId: "...",
  storageBucket: "...",
  messagingSenderId: "..."
};

imports:[
    AngularFireModule.initializeApp(firebaseConfig),
    AngularFireDatabaseModule
 ]

Now am geting an error

 Class 'FirebaseApp' incorrectly implements interface 'App'.
  Property 'firestore' is missing in type 'FirebaseApp'.

node_modules/angularfire2/firebase.app.module.d.ts (12,28):
  Namespace 'firebase' has no exported member 'Promise'.

Where am i going wrong or what else do i need to add to have it work


问:
How to extract parts of nested multi-level JSON objects / array and flatten it with JavaScript
I'm working with the following data structure:

```<code>"data": {
    "products": [
        [
            {
                "category": "A",
                "items": [
                    {
                        "name": "Aloe",
                        "price": 10
                    },
                    {
                        "name": "Apples",
                        "price": 5
                    }
                ]
            },
            {
                "category": "B",
                "items": [
                    {
                        "name": "Bread",
                        "price": 5
                    }
                ]
            }
        ],
        [
            {
                "category": "C",
                "items": [
                    {
                        "name": "Candy",
                        "price": 5
                    },
                    {
                        "name": "Crayon",
                        "price": 5
                    }
                ]
            },
            {
                "category": "D",
                "items": [
                    {
                        "name": "Dice",
                        "price": 5
                    },
                    {
                        "name": "Doll",
                        "price": 10
                    }
                ]
            }
        ]
    ]
}
</code>```

I'd like extract parts of it to flatten so the results is as follows:

```<code>[
    {
        "name": "Aloe",
        "price": 10
    },
    {
        "name": "Apples",
        "price": 5
    },
    {
        "name": "Bread",
        "price": 5
    },
    {
        "name": "Candy",
        "price": 5
    },
    {
        "name": "Crayon",
        "price": 5
    },
    {
        "name": "Dice",
        "price": 5
    },
    {
        "name": "Doll",
        "price": 10
    }
]
</code>```

How can I accomplish this?

I have tried this:

```<code>for (var sets in data.products) {
  for (var categories in sets) {
    for (var items in categories) {
      for (var item in items) {
        // assemble new array
      }
    }
  }
}
</code>```

... but had problems looping through the children objects. I've found a couple other similar questions, but they seem to address simpler data structures, and flatten the entire object rather than parts of it.

Any pointers would be appreciated.

答:
You will have to try something like this:

Logic:

Loop over data.products to get individual product details.

Sine details are also arrays, loop over them and return items from them.

The trick is, you will have to use Array.prototype.concat to merge arrays returned, to flatten them.

var data = {
  "products": [
    [{
        "category": "A",
        "items": [{
            "name": "Aloe",
            "price": 10
          },
          {
            "name": "Apples",
            "price": 5
          }
        ]
      },
      {
        "category": "B",
        "items": [{
          "name": "Bread",
          "price": 5
        }]
      }
    ],
    [{
        "category": "C",
        "items": [{
            "name": "Candy",
            "price": 5
          },
          {
            "name": "Crayon",
            "price": 5
          }
        ]
      },
      {
        "category": "D",
        "items": [{
            "name": "Dice",
            "price": 5
          },
          {
            "name": "Doll",
            "price": 10
          }
        ]
      }
    ]
  ]
}

var result = [].concat.apply([], data.products.map(function(product){
  return [].concat.apply([], product.map(function(p){
    return p.items
  }))
}))

console.log(result)```

Body:
I'm working with the following data structure:

"data": {
    "products": [
        [
            {
                "category": "A",
                "items": [
                    {
                        "name": "Aloe",
                        "price": 10
                    },
                    {
                        "name": "Apples",
                        "price": 5
                    }
                ]
            },
            {
                "category": "B",
                "items": [
                    {
                        "name": "Bread",
                        "price": 5
                    }
                ]
            }
        ],
        [
            {
                "category": "C",
                "items": [
                    {
                        "name": "Candy",
                        "price": 5
                    },
                    {
                        "name": "Crayon",
                        "price": 5
                    }
                ]
            },
            {
                "category": "D",
                "items": [
                    {
                        "name": "Dice",
                        "price": 5
                    },
                    {
                        "name": "Doll",
                        "price": 10
                    }
                ]
            }
        ]
    ]
}

I'd like extract parts of it to flatten so the results is as follows:

[
    {
        "name": "Aloe",
        "price": 10
    },
    {
        "name": "Apples",
        "price": 5
    },
    {
        "name": "Bread",
        "price": 5
    },
    {
        "name": "Candy",
        "price": 5
    },
    {
        "name": "Crayon",
        "price": 5
    },
    {
        "name": "Dice",
        "price": 5
    },
    {
        "name": "Doll",
        "price": 10
    }
]

How can I accomplish this?

I have tried this:

for (var sets in data.products) {
  for (var categories in sets) {
    for (var items in categories) {
      for (var item in items) {
        // assemble new array
      }
    }
  }
}

... but had problems looping through the children objects. I've found a couple other similar questions, but they seem to address simpler data structures, and flatten the entire object rather than parts of it.

Any pointers would be appreciated.


问:
Javascript - An array of object's value used the last value iterated
I am trying to push objects to an empty array, where its x property value incremented on each loop. I used console.log(B.x) to check that it does iterate but even so, each object will have its x property value set to 300

n = 20, therefore, 100 (original x's value) + 10 (iteration) * 20 (loop) = 300

```<code>function createBlocks(n) {
  var blockArray = [];

  var B = {
    x: 100,
    y: 100,
    width: 35,
    height: 35,
    color: "brown"
  }

  for (var i = 0; i < n; i++) {
    blockArray.push(B);
    B.x += 10;
    console.log(B.x);
    console.log(blockArray[i]);
  }
  return blockArray;
}
</code>```

I don't understand why all the objects have the same value (300) for its x's property.

答:
Because your object is single and you have multiple references to it. So why changing for one, it changes the actually object. You need to create separate objects for each item.

You can use object destructing to copy the properties from one object into a new object and push that temp object into the array.

const blockArray = [];

const B = {
  x: 100,
  y: 100,
  width: 35,
  height: 35,
  color: "brown"
}

for (var i = 0; i < 10; i++) {
  let temp = { ...B };
  blockArray.push(temp);
  B.x += 10;
}

console.log(blockArray);```

Body:
I am trying to push objects to an empty array, where its x property value incremented on each loop. I used console.log(B.x) to check that it does iterate but even so, each object will have its x property value set to 300

n = 20, therefore, 100 (original x's value) + 10 (iteration) * 20 (loop) = 300

function createBlocks(n) {
  var blockArray = [];

  var B = {
    x: 100,
    y: 100,
    width: 35,
    height: 35,
    color: "brown"
  }

  for (var i = 0; i < n; i++) {
    blockArray.push(B);
    B.x += 10;
    console.log(B.x);
    console.log(blockArray[i]);
  }
  return blockArray;
}

I don't understand why all the objects have the same value (300) for its x's property.


问:
Linux Kernel Stack
What kind of data is stored in the Kernel mode stack of a process ? Is a processes "user mode" call chain stored in the kernel stack ?

Thanks,
vIjay

答:
The kernel mode stack of a process is used when the process enters the kernel mode [because of an exception such as system call or fault, or because of a hardware interrupt]. The sequence of steps which the process executes when it enters the kernel mode until it leaves it, is called the kernel control path. State information for the kernel control path is stored in the kernel mode stack of the process. Also, say due to expired time slice, if a context switch occurs, the state of the process-cpu registers are stored on the kernel mode stack so that they can be retrieved when the process is rescheduled on the cpu.

Since the kernel mode stack is only used upon entering the kernel mode, the "user mode" call chain is not stored in this stack.

Title: Linux Kernel Stack


问:
cellForRowAtIndexPath: not called
My app has two states: logged in and not logged in, and I have the following architecture (vastly simplified):

- ViewController A which contains a search box and a table view.

- ViewController B which is used for logging in the app.

The flow is the following:

- the user is not logged in;

- A is pushed on the stack. In viewWillAppear I check if the user is logged in and if yes, an async network request is being made and, once that is done, the table is loaded with the data from the network. However since the user is not logged in at this point, the table view is empty;

- the user taps on the search box; because he's not logged in, B is pushed (after a confirmation);

- he logs in successfully in B, then presses a button which pops B and shows A again;

- at this point in time, because he's logged in, from viewWillAppear I do the async request;

- when that is completed, I call reloadData on the table view.

What I notice is that numberOfRowsInSection: is called and it returns the correct result, however cellForRowAtIndexPath: is NOT called afterwards and the table remains empty.

I've checked and reloadData is called on the main thread.

Any idea what can it be? Cause it's driving me nuts!

Thanks,

S.

EDIT: Here's the async bit of code from viewWillAppear in A.

```<code>if ([User isLoggedIn]) {
    [self.asyncRequest fetchDataWithCompletionHandler:^(id response, NSError *error) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        if (error) {
            [Utils displayError:error];
        } else {
            self.array = response;

            self.isLoaded = YES;
            [self.tableView reloadData];
            [self.tableView setContentOffset:CGPointMake(0.0f, 0.0f) animated:NO];
        }
    }];
}
</code>```

I've checked that the async request completes successfully and that response contains the correct data (this is the array used to back the UITableView).

After reloadData, I've put a breakpoint in tableView:numberOfRowsInSection: and it stops there and it returns the correct number of elements in array. After that, however, the breakpoint in tableView:cellForRowAtIndexPath: is never hit.

答:
I have same issue
i have use Table View inside the StackView and table view scroll disable and set height constrain but after that

```<code>tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
</code>```

Not working stop calling this method all Data Source and Delegate set properly.

if you have same issue than Solution is set Table View  bottom , leading , trailing constrain

Title: cellForRowAtIndexPath: not called

Body:
My app has two states: logged in and not logged in, and I have the following architecture (vastly simplified):

- ViewController A which contains a search box and a table view.

- ViewController B which is used for logging in the app.

The flow is the following:

- the user is not logged in;

- A is pushed on the stack. In viewWillAppear I check if the user is logged in and if yes, an async network request is being made and, once that is done, the table is loaded with the data from the network. However since the user is not logged in at this point, the table view is empty;

- the user taps on the search box; because he's not logged in, B is pushed (after a confirmation);

- he logs in successfully in B, then presses a button which pops B and shows A again;

- at this point in time, because he's logged in, from viewWillAppear I do the async request;

- when that is completed, I call reloadData on the table view.

What I notice is that numberOfRowsInSection: is called and it returns the correct result, however cellForRowAtIndexPath: is NOT called afterwards and the table remains empty.

I've checked and reloadData is called on the main thread.

Any idea what can it be? Cause it's driving me nuts!

Thanks,

S.

EDIT: Here's the async bit of code from viewWillAppear in A.

if ([User isLoggedIn]) {
    [self.asyncRequest fetchDataWithCompletionHandler:^(id response, NSError *error) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        if (error) {
            [Utils displayError:error];
        } else {
            self.array = response;

            self.isLoaded = YES;
            [self.tableView reloadData];
            [self.tableView setContentOffset:CGPointMake(0.0f, 0.0f) animated:NO];
        }
    }];
}

I've checked that the async request completes successfully and that response contains the correct data (this is the array used to back the UITableView).

After reloadData, I've put a breakpoint in tableView:numberOfRowsInSection: and it stops there and it returns the correct number of elements in array. After that, however, the breakpoint in tableView:cellForRowAtIndexPath: is never hit.

Body:
I have same issue
i have use Table View inside the StackView and table view scroll disable and set height constrain but after that

tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

Not working stop calling this method all Data Source and Delegate set properly.

if you have same issue than Solution is set Table View  bottom , leading , trailing constrain


问:
if else condition in shell script to check empty input by user
I am taking input from the user, and wants that if user give empty input , it should display the error message , I am trying below code , please correct me where I am wrong  .

```<code>  #!/bin/bash
    echo "please enter previous version number"
    read prevversion
    echo "please enter new version number"
    read newversion
    echo "please enter environment [DEV2/QAT2/PPE2/PRD]"
    read env

    if[["$env"=" " &&"$prevversion"=" " &&"$newversion"= " "]]
    then
        echo "Please enter the details and try again"

    else

        if [ "$env" = "QAT2" ]
        then
                prevversion="$prevversion"_QAT2
                echo "previous version is $prevversion"
                newversion="$newversion"_QAT2
                echo "new version is $newversion"
                env="$env"
                echo "enviornment is $env"
        elif [ "$env" = "PPE2" ]
        then
                prevversion="$prevversion"
                echo "previous version is $prevversion"
                newversion="$newversion"
                echo "new version is $newversion"
                env="$env"
                echo "enviornment is $env"
        elif [ "$env" = "PRD" ]
        then
                prevversion="$prevversion"
                echo "previous version is $prevversion"
                newversion="$newversion"
                echo "new version is $newversion"
                env="$env"
                echo "enviornment is $env"
        elif [ "$env" = "DEV2" ]
        then
                prevversion="$prevversion"_DEV2
                echo "previous version is $prevversion"
                newversion="$newversion"_DEV2
                echo "new version is $newversion"
                env="$env"
                echo "enviornment is $env"
        fi

    fi
</code>```

please provide me with correct solution

答:
your are using '&&' in your if-condition which means, that the error-message is only displayed when every(!) input is empty:
if[["$env"=" " &&"$prevversion"=" " &&"$newversion"= " "]]

You should change it like that:

```<code>if [ -z "${env}" ] || [ -z "${prevversion}" ] || [ -z "${newversion}" ]; then
    echo "either one of the vars is empty"
    exit 1
fi
</code>```

Body:
I am taking input from the user, and wants that if user give empty input , it should display the error message , I am trying below code , please correct me where I am wrong  .

  #!/bin/bash
    echo "please enter previous version number"
    read prevversion
    echo "please enter new version number"
    read newversion
    echo "please enter environment [DEV2/QAT2/PPE2/PRD]"
    read env

    if[["$env"=" " &&"$prevversion"=" " &&"$newversion"= " "]]
    then
        echo "Please enter the details and try again"

    else

        if [ "$env" = "QAT2" ]
        then
                prevversion="$prevversion"_QAT2
                echo "previous version is $prevversion"
                newversion="$newversion"_QAT2
                echo "new version is $newversion"
                env="$env"
                echo "enviornment is $env"
        elif [ "$env" = "PPE2" ]
        then
                prevversion="$prevversion"
                echo "previous version is $prevversion"
                newversion="$newversion"
                echo "new version is $newversion"
                env="$env"
                echo "enviornment is $env"
        elif [ "$env" = "PRD" ]
        then
                prevversion="$prevversion"
                echo "previous version is $prevversion"
                newversion="$newversion"
                echo "new version is $newversion"
                env="$env"
                echo "enviornment is $env"
        elif [ "$env" = "DEV2" ]
        then
                prevversion="$prevversion"_DEV2
                echo "previous version is $prevversion"
                newversion="$newversion"_DEV2
                echo "new version is $newversion"
                env="$env"
                echo "enviornment is $env"
        fi

    fi

please provide me with correct solution

Body:
your are using '&&' in your if-condition which means, that the error-message is only displayed when every(!) input is empty:
if[["$env"=" " &&"$prevversion"=" " &&"$newversion"= " "]]

You should change it like that:

if [ -z "${env}" ] || [ -z "${prevversion}" ] || [ -z "${newversion}" ]; then
    echo "either one of the vars is empty"
    exit 1
fi


问:
Concatenating two strings into a Textbox
I have been just learning about the basics of cryptography, and I wanted to give
one of the methods called zigzag transposition a try.

 All this method does is combining the entire sentence and give them index starting from zero.

it then separates the even indexed characters into an array and the odd ones into a different array .

When I convert the two arrays to strings and then place them in a textbox only the first string shows up.

```<code>private void ZigzagBu_Click(object sender, EventArgs e) {
    string s = PlaintextTB.Text;
    s = s.Replace(" ","");

    char[] whole = s.ToCharArray();
    char[] even = new char[whole.Length];
    char[] odd = new char[whole.Length];

    int evenIndex = 0;
    int oddIndex = 0;

    for(int i =0;i<whole.Length;i++) {
        if (i % 2 == 0) {
            even[evenIndex] = whole[i];
            evenIndex++;
        }
        else {
            odd[oddIndex] = whole[i];
            oddIndex++;
        }
    }

    s = new String(even);
    string m = new String(odd);

    CiphertextTB.Text = s+m;
}
</code>```

答:
Use of StringBuilder class is more elegant approach instead of creating 2 instances of String.

Implementation: DotnetFiddler

Body:
I have been just learning about the basics of cryptography, and I wanted to give
one of the methods called zigzag transposition a try.

 All this method does is combining the entire sentence and give them index starting from zero.

it then separates the even indexed characters into an array and the odd ones into a different array .

When I convert the two arrays to strings and then place them in a textbox only the first string shows up.

private void ZigzagBu_Click(object sender, EventArgs e) {
    string s = PlaintextTB.Text;
    s = s.Replace(" ","");

    char[] whole = s.ToCharArray();
    char[] even = new char[whole.Length];
    char[] odd = new char[whole.Length];

    int evenIndex = 0;
    int oddIndex = 0;

    for(int i =0;i<whole.Length;i++) {
        if (i % 2 == 0) {
            even[evenIndex] = whole[i];
            evenIndex++;
        }
        else {
            odd[oddIndex] = whole[i];
            oddIndex++;
        }
    }

    s = new String(even);
    string m = new String(odd);

    CiphertextTB.Text = s+m;
}


问:
WordPress: User with custom role cannot access wp-admin
First of all I am a WordPress learner. So sorry if my code looks stupid!

I have created a custom theme with a custom user role. I am not developing any plugin.

In my fucntions.php file I have written the following code to create a User role. Users assigned to this role are supposed to login to the admin but only be able to access their Profile pages.

```<code>add_action('init', 'yrc_cst_register_role_customer_service_rep');

/**
 * Register new user role
 */

function yrc_cst_register_role_customer_service_rep() {

    $wp_roles = new WP_Roles();

    $wp_roles->remove_role('subscriber');
    $wp_roles->remove_role('editor');
    $wp_roles->remove_role('contributor');
    $wp_roles->remove_role('author');

    $service_rep_caps = array(
        'read'              => false,
        'create_posts'      => false,
        'edit_posts'        => false,
        'edit_others_posts' => false,
        'publish_posts'     => false,
        'manage_categories' => false,
        'manage_options'    => false,
    );

    add_role('customer_service', __('Customer Service'), $service_rep_caps);
}
</code>```

I have removed all roles except Administrator, because no other role is required for this portal. Administrator will only create Users with Customer Service role.

I have no third party plugin installed in the system.

Users with the custom role are able to login to the system through a custom login page which is working OK. But whenever they are trying to access their Profile page the following error message comes up:

Sorry, you are not allowed to access this page.

Is there anything like 'edit_profile' => true?

I must be doing something wrong but my limited knowledge is not enough to figure this out. Any suggestion would be highly appreciated.

答:
Just change the manage_options to true in your case
But note that by allowing manage_options to true, those user will have access to other parts of dashboard as well</p>

```<code> $service_rep_caps = array(
    'read'              => false,
    'create_posts'      => false,
    'edit_posts'        => false,
    'edit_others_posts' => false,
    'publish_posts'     => false,
    'manage_categories' => false,
    'manage_options'    => true, // Most plugins and pages check for manage_options for checking access level to allow access to pages and settings.
);
</code>```

Body:
First of all I am a WordPress learner. So sorry if my code looks stupid!

I have created a custom theme with a custom user role. I am not developing any plugin.

In my fucntions.php file I have written the following code to create a User role. Users assigned to this role are supposed to login to the admin but only be able to access their Profile pages.

add_action('init', 'yrc_cst_register_role_customer_service_rep');

/**
 * Register new user role
 */

function yrc_cst_register_role_customer_service_rep() {

    $wp_roles = new WP_Roles();

    $wp_roles->remove_role('subscriber');
    $wp_roles->remove_role('editor');
    $wp_roles->remove_role('contributor');
    $wp_roles->remove_role('author');

    $service_rep_caps = array(
        'read'              => false,
        'create_posts'      => false,
        'edit_posts'        => false,
        'edit_others_posts' => false,
        'publish_posts'     => false,
        'manage_categories' => false,
        'manage_options'    => false,
    );

    add_role('customer_service', __('Customer Service'), $service_rep_caps);
}

I have removed all roles except Administrator, because no other role is required for this portal. Administrator will only create Users with Customer Service role.

I have no third party plugin installed in the system.

Users with the custom role are able to login to the system through a custom login page which is working OK. But whenever they are trying to access their Profile page the following error message comes up:

Sorry, you are not allowed to access this page.

Is there anything like 'edit_profile' => true?

I must be doing something wrong but my limited knowledge is not enough to figure this out. Any suggestion would be highly appreciated.

Body:
Just change the manage_options to true in your case
But note that by allowing manage_options to true, those user will have access to other parts of dashboard as well

 $service_rep_caps = array(
    'read'              => false,
    'create_posts'      => false,
    'edit_posts'        => false,
    'edit_others_posts' => false,
    'publish_posts'     => false,
    'manage_categories' => false,
    'manage_options'    => true, // Most plugins and pages check for manage_options for checking access level to allow access to pages and settings.
);


问:
How to play mp3 file in c++?
I'm looking for the easiest way to play an MP3 file in C++. Either a library I could use and just call the function, given the filename, or alternatively something someone has already written that will just run and quit.</p>

答:
Qt comes to the rescue (again). The documentation even comes with demo code on how to implement a media player. It can play videos as well, btw.

http://doc.qt.nokia.com/latest/demos-qmediaplayer.html

Works on all platform and with the same syntax = WIN.

Title: How to play mp3 file in c++?


问:
How to check for null within a concatenated String declaration? (JAVA)
How could I check for null within a concatenated String declaration?
For example I have :

String txt = "Employee Account Name" + employeeObject.accountObject.name + " : ";

I could only check for null by using:

```<code>String accountName = employeeObject.accountObject != null ? employeeObject.accountObject.name : " is null";
</code>```

Could this be done within the declaration for variable txt only. I'm looking for an alternative as my null check can cover many objects which results in many one time use variables.

答:
```<code>String accountName = (employeeObject.accountObject != null
            && employeeObject.accountObject.name != null) ?
            employeeObject.accountObject.name : " is null";
</code>```

Body:
How could I check for null within a concatenated String declaration?
For example I have :

String txt = "Employee Account Name" + employeeObject.accountObject.name + " : ";

I could only check for null by using:

String accountName = employeeObject.accountObject != null ? employeeObject.accountObject.name : " is null";

Could this be done within the declaration for variable txt only. I'm looking for an alternative as my null check can cover many objects which results in many one time use variables.


问:
Can't Change UIView Height When KeyboardDidHide is called
Any idea why I cannot change the height of my containerView when KeyboardDidHide notification happens? The height changes in KeyboardDidShow perfectly fine but won't change back in KeyboardDidHide. Also, it does change back if I change it in TextFieldDidEndEditing but that doesn't work quite perfectly for what I need.</p>

```<code>func setupKeyboardObserver() {
    NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardDidShow), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardDidHide), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
}

@objc func handleKeyboardDidHide() {
    if UIDevice().userInterfaceIdiom == .phone {
        if UIScreen.main.nativeBounds.height == 2436 {
            containerView.frame.size.height += 35
        }
    }
}

func textFieldDidEndEditing(_ textField: UITextField) {
    if UIDevice().userInterfaceIdiom == .phone {
        if UIScreen.main.nativeBounds.height == 2436 {
            containerView.frame.size.height += 35
        }
    }
}

@objc func handleKeyboardDidShow() {

    if UIDevice().userInterfaceIdiom == .phone {
        if UIScreen.main.nativeBounds.height == 2436 {
            containerView.frame.size.height -= 35
        }
    }
}
</code>```

答:
Use following code after you have set containerView height

```<code>containerView.updateConstraintsIfNeeded()
containerView.layoutIfNeeded()
</code>```

Hope will helpful to you

Body:
Any idea why I cannot change the height of my containerView when KeyboardDidHide notification happens? The height changes in KeyboardDidShow perfectly fine but won't change back in KeyboardDidHide. Also, it does change back if I change it in TextFieldDidEndEditing but that doesn't work quite perfectly for what I need.

func setupKeyboardObserver() {
    NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardDidShow), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardDidHide), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
}

@objc func handleKeyboardDidHide() {
    if UIDevice().userInterfaceIdiom == .phone {
        if UIScreen.main.nativeBounds.height == 2436 {
            containerView.frame.size.height += 35
        }
    }
}

func textFieldDidEndEditing(_ textField: UITextField) {
    if UIDevice().userInterfaceIdiom == .phone {
        if UIScreen.main.nativeBounds.height == 2436 {
            containerView.frame.size.height += 35
        }
    }
}

@objc func handleKeyboardDidShow() {

    if UIDevice().userInterfaceIdiom == .phone {
        if UIScreen.main.nativeBounds.height == 2436 {
            containerView.frame.size.height -= 35
        }
    }
}

Body:
Use following code after you have set containerView height

containerView.updateConstraintsIfNeeded()
containerView.layoutIfNeeded()

Hope will helpful to you


问:
Confused about Ruby on Rails routes.rb syntax
Suppose I had the following code in my routes.rb file.

```<code>  get '/dashboard', to: 'dashboard#index', :as => 'dashboard'
</code>```

I know what's going on (a public url being mapped to a specific controller/view file which will process and return the request). That is not what I am confused about.

As a Ruby beginner, I'm confused about what Ruby code convention this is. It doesn't look like the correct way to declare a variable or call a method? What exactly is going on and is this some sort of shorthand form to call a method?

```<code>get("/dashboard", "dashboard#index", "dashboard")
</code>```

答:
```<code>get '/dashboard', to: 'dashboard#index', :as => 'dashboard'
</code>```

This is just a normal message send (what you call a "method call", but note that messages and methods are different things in Ruby, and the metaphor of sending a message is really important).

In Ruby, you are allowed to leave out the parentheses around an argument list. So, this is the same as this:

```<code>get('/dashboard', to: 'dashboard#index', :as => 'dashboard')
</code>```

You are also allowed to leave out the receiver of the message send, in which case it is implied to be self, so this is the same as this:

```<code>self.get('/dashboard', to: 'dashboard#index', :as => 'dashboard')
</code>```

If the last argument to a message send is a Hash literal, you are allowed to leave out the curly braces, so this is the same as this:

```<code>self.get('/dashboard', { to: 'dashboard#index', :as => 'dashboard' })
</code>```

If the key in a Hash literal is a Symbol, you are allowed to write key: value instead of :key => value, so this is the same as this:

```<code>self.get('/dashboard', { :to => 'dashboard#index', :as => 'dashboard' })
</code>```

Now, doesn't that look just like a boring old message send?

Most of these rules are there to allow you to write code that looks more natural. For example, things that would be keywords in other languages, are just methods in Ruby, like attr_reader, attr_writer, attr_accessor, require, private, public, protected, etc. It would look weird, if you were required to use parentheses and receivers there:

```<code>self.protected()
def foo() end
# instead of
protected
def foo() end

# or

self.private(def foo() end)
# instead of
private def foo() end
</code>```

The rule that you can leave out the curly braces around a trailing Hash literal was introduced, so that you could "fake" keyword arguments:

```<code>def route(path, options = {}) end
route(:index, :from => :here, :to => :there)
</code>```

Even more so with the new-style symbol keys:

```<code>route(:index, from: :here, to: :there)
</code>```

Note that as of Ruby 2.0, Ruby also has proper keyword arguments, which for backwards-compatibility look exactly like a trailing Hash:

```<code>def route(path, from:, to:, with: nil) end
route(:index, from: :here, to: :there) # this line same as above
</code>```

Body:
Suppose I had the following code in my routes.rb file.

  get '/dashboard', to: 'dashboard#index', :as => 'dashboard'

I know what's going on (a public url being mapped to a specific controller/view file which will process and return the request). That is not what I am confused about.

As a Ruby beginner, I'm confused about what Ruby code convention this is. It doesn't look like the correct way to declare a variable or call a method? What exactly is going on and is this some sort of shorthand form to call a method?

get("/dashboard", "dashboard#index", "dashboard")

Body:
get '/dashboard', to: 'dashboard#index', :as => 'dashboard'

This is just a normal message send (what you call a "method call", but note that messages and methods are different things in Ruby, and the metaphor of sending a message is really important).

In Ruby, you are allowed to leave out the parentheses around an argument list. So, this is the same as this:

get('/dashboard', to: 'dashboard#index', :as => 'dashboard')

You are also allowed to leave out the receiver of the message send, in which case it is implied to be self, so this is the same as this:

self.get('/dashboard', to: 'dashboard#index', :as => 'dashboard')

If the last argument to a message send is a Hash literal, you are allowed to leave out the curly braces, so this is the same as this:

self.get('/dashboard', { to: 'dashboard#index', :as => 'dashboard' })

If the key in a Hash literal is a Symbol, you are allowed to write key: value instead of :key => value, so this is the same as this:

self.get('/dashboard', { :to => 'dashboard#index', :as => 'dashboard' })

Now, doesn't that look just like a boring old message send?

Most of these rules are there to allow you to write code that looks more natural. For example, things that would be keywords in other languages, are just methods in Ruby, like attr_reader, attr_writer, attr_accessor, require, private, public, protected, etc. It would look weird, if you were required to use parentheses and receivers there:

self.protected()
def foo() end
# instead of
protected
def foo() end

# or

self.private(def foo() end)
# instead of
private def foo() end

The rule that you can leave out the curly braces around a trailing Hash literal was introduced, so that you could "fake" keyword arguments:

def route(path, options = {}) end
route(:index, :from => :here, :to => :there)

Even more so with the new-style symbol keys:

route(:index, from: :here, to: :there)

Note that as of Ruby 2.0, Ruby also has proper keyword arguments, which for backwards-compatibility look exactly like a trailing Hash:

def route(path, from:, to:, with: nil) end
route(:index, from: :here, to: :there) # this line same as above


问:
App installation failed when transfered code
So i started my project on Mac OS and than with USB i transfered to MacOS, using same version of Android studio, but on Mac it doesn't want to run i tried to delte gradle and idea folders build a gradle and all but no success. The error i get is Application Installation Failed:

Installation failed with message Invalid File: /Users/myuser/Code/App/E:\Android\apps\build\intermediates\split-apk\debug\slices\slice_2.apk

Do you want to uninstall this existing application?

So as it looks like its picking up my Windows things from somewhere any idea how i can fix this?

答: Just Clean & Rebuild the project.

Body: Just Clean & Rebuild the project.


问:
getText() method doesn't work with integers
```<code>textfield2.addActionListener(new ActionListener()
{
    public void actionPerformed(ActionEvent actionevent)
    {
        String input = textfield2.getText();
        Output2.setText("Your age is " + (2017-input));
    }
});

button2.addActionListener(new ActionListener()
{
    public void actionPerformed(ActionEvent actioneven)
    {
        String input = textfield2.getText();
        Output2.setText("Your age is " + (2017 -input));
    }
});
</code>```

I am trying to get a number from the user (an integer) and subtract that number from 2017. It gives an error saying that it is a String and I can't subtract a number from a String. When I change String input to int input it gives errors again. It says that I can't use getText(). I've tried few ways such as parseInt() and it did not work. How can I fix this problem?

My Question is different from How to convert a String to an int in Java? because I looked at the answers there and they didn't really work with my code.

答:
You need to parse the input first before subtracting it</p>

```<code>int input = Integer.parseInt(textfield2.getText());
Output2.setText("Your age is " + (2017 -input));
</code>```

Body:
textfield2.addActionListener(new ActionListener()
{
    public void actionPerformed(ActionEvent actionevent)
    {
        String input = textfield2.getText();
        Output2.setText("Your age is " + (2017-input));
    }
});

button2.addActionListener(new ActionListener()
{
    public void actionPerformed(ActionEvent actioneven)
    {
        String input = textfield2.getText();
        Output2.setText("Your age is " + (2017 -input));
    }
});

I am trying to get a number from the user (an integer) and subtract that number from 2017. It gives an error saying that it is a String and I can't subtract a number from a String. When I change String input to int input it gives errors again. It says that I can't use getText(). I've tried few ways such as parseInt() and it did not work. How can I fix this problem?

My Question is different from How to convert a String to an int in Java? because I looked at the answers there and they didn't really work with my code.

Body:
You need to parse the input first before subtracting it

int input = Integer.parseInt(textfield2.getText());
Output2.setText("Your age is " + (2017 -input));


问:
How to shuffle data in python keeping some n number of rows intact
I want to shuffle my data in such manner that each 4 rows remain intact. For example I have 16 rows then first 4 rows can go to last and then second four rows may go to third  and so on in any particular order. I am trying to do thins in python</p>

答:
Reshape splitting the first axis into two with the later of length same as the group length = 4, giving us a 3D array and then use np.random.shuffle, which shuffles along the first axis. The reshaped version being a view into the original array, assigns back the results directly into it. Being in-situ, this should be pretty efficient (both memory-wise and on performance).

Hence, the implementation would be as simple as this -

```<code>def array_shuffle(a, n=4):
    a3D = a.reshape(a.shape[0]//n,n,-1) # a is input array
    np.random.shuffle(a3D)
</code>```

Another variant of it would be to generate random permutations covering the length of the 3D array, then indexing into it with those and finally reshaping back to 2D.This makes a copy, but seems more performant than in-situ edits as shown in the previous method.

The implementation would be -

```<code>def array_permuted_indexing(a, n=4):
    m = a.shape[0]//n
    a3D = a.reshape(m, n, -1)
    return a3D[np.random.permutation(m)].reshape(-1,a3D.shape[-1])
</code>```

Step-by-step run on shuffling method -

1] Setup random input array and split into a 3D version :

```<code>In [2]: np.random.seed(0)

In [3]: a = np.random.randint(11,99,(16,3))

In [4]: a3D = a.reshape(a.shape[0]//4,4,-1)

In [5]: a
Out[5]:
array([[55, 58, 75],
       [78, 78, 20],
       [94, 32, 47],
       [98, 81, 23],
       [69, 76, 50],
       [98, 57, 92],
       [48, 36, 88],
       [83, 20, 31],
       [91, 80, 90],
       [58, 75, 93],
       [60, 40, 30],
       [30, 25, 50],
       [43, 76, 20],
       [68, 43, 42],
       [85, 34, 46],
       [86, 66, 39]])
</code>```

2] Check the 3D array :

```<code>In [6]: a3D
Out[6]:
array([[[55, 58, 75],
        [78, 78, 20],
        [94, 32, 47],
        [98, 81, 23]],

       [[69, 76, 50],
        [98, 57, 92],
        [48, 36, 88],
        [83, 20, 31]],

       [[91, 80, 90],
        [58, 75, 93],
        [60, 40, 30],
        [30, 25, 50]],

       [[43, 76, 20],
        [68, 43, 42],
        [85, 34, 46],
        [86, 66, 39]]])
</code>```

3] Shuffle it along the first axis (in-situ) :

```<code>In [7]: np.random.shuffle(a3D)

In [8]: a3D
Out[8]:
array([[[69, 76, 50],
        [98, 57, 92],
        [48, 36, 88],
        [83, 20, 31]],

       [[43, 76, 20],
        [68, 43, 42],
        [85, 34, 46],
        [86, 66, 39]],

       [[55, 58, 75],
        [78, 78, 20],
        [94, 32, 47],
        [98, 81, 23]],

       [[91, 80, 90],
        [58, 75, 93],
        [60, 40, 30],
        [30, 25, 50]]])
</code>```

4] Verify the changes back in the original array :

```<code>In [9]: a
Out[9]:
array([[69, 76, 50],
       [98, 57, 92],
       [48, 36, 88],
       [83, 20, 31],
       [43, 76, 20],
       [68, 43, 42],
       [85, 34, 46],
       [86, 66, 39],
       [55, 58, 75],
       [78, 78, 20],
       [94, 32, 47],
       [98, 81, 23],
       [91, 80, 90],
       [58, 75, 93],
       [60, 40, 30],
       [30, 25, 50]])
</code>```

Runtime test

```<code>In [102]: a = np.random.randint(11,99,(16000,3))

In [103]: df = pd.DataFrame(a)

# @piRSquared's soln1
In [106]: %timeit df.iloc[np.random.permutation(np.arange(df.shape[0]).reshape(-1, 4)).ravel()]
100 loops, best of 3: 2.88 ms per loop

# @piRSquared's soln2
In [107]: %%timeit
     ...: d = df.set_index(np.arange(len(df)) // 4, append=True).swaplevel(0, 1)
     ...: pd.concat([d.xs(i) for i in np.random.permutation(range(4))])
100 loops, best of 3: 3.48 ms per loop

# Array based soln-1
In [108]: %timeit array_shuffle(a, n=4)
100 loops, best of 3: 3.38 ms per loop

# Array based soln-2
In [109]: %timeit array_permuted_indexing(a, n=4)
10000 loops, best of 3: 125 µs per loop
</code>```

Body:
Reshape splitting the first axis into two with the later of length same as the group length = 4, giving us a 3D array and then use np.random.shuffle, which shuffles along the first axis. The reshaped version being a view into the original array, assigns back the results directly into it. Being in-situ, this should be pretty efficient (both memory-wise and on performance).

Hence, the implementation would be as simple as this -

def array_shuffle(a, n=4):
    a3D = a.reshape(a.shape[0]//n,n,-1) # a is input array
    np.random.shuffle(a3D)

Another variant of it would be to generate random permutations covering the length of the 3D array, then indexing into it with those and finally reshaping back to 2D.This makes a copy, but seems more performant than in-situ edits as shown in the previous method.

The implementation would be -

def array_permuted_indexing(a, n=4):
    m = a.shape[0]//n
    a3D = a.reshape(m, n, -1)
    return a3D[np.random.permutation(m)].reshape(-1,a3D.shape[-1])

Step-by-step run on shuffling method -

1] Setup random input array and split into a 3D version :

In [2]: np.random.seed(0)

In [3]: a = np.random.randint(11,99,(16,3))

In [4]: a3D = a.reshape(a.shape[0]//4,4,-1)

In [5]: a
Out[5]:
array([[55, 58, 75],
       [78, 78, 20],
       [94, 32, 47],
       [98, 81, 23],
       [69, 76, 50],
       [98, 57, 92],
       [48, 36, 88],
       [83, 20, 31],
       [91, 80, 90],
       [58, 75, 93],
       [60, 40, 30],
       [30, 25, 50],
       [43, 76, 20],
       [68, 43, 42],
       [85, 34, 46],
       [86, 66, 39]])

2] Check the 3D array :

In [6]: a3D
Out[6]:
array([[[55, 58, 75],
        [78, 78, 20],
        [94, 32, 47],
        [98, 81, 23]],

       [[69, 76, 50],
        [98, 57, 92],
        [48, 36, 88],
        [83, 20, 31]],

       [[91, 80, 90],
        [58, 75, 93],
        [60, 40, 30],
        [30, 25, 50]],

       [[43, 76, 20],
        [68, 43, 42],
        [85, 34, 46],
        [86, 66, 39]]])

3] Shuffle it along the first axis (in-situ) :

In [7]: np.random.shuffle(a3D)

In [8]: a3D
Out[8]:
array([[[69, 76, 50],
        [98, 57, 92],
        [48, 36, 88],
        [83, 20, 31]],

       [[43, 76, 20],
        [68, 43, 42],
        [85, 34, 46],
        [86, 66, 39]],

       [[55, 58, 75],
        [78, 78, 20],
        [94, 32, 47],
        [98, 81, 23]],

       [[91, 80, 90],
        [58, 75, 93],
        [60, 40, 30],
        [30, 25, 50]]])

4] Verify the changes back in the original array :

In [9]: a
Out[9]:
array([[69, 76, 50],
       [98, 57, 92],
       [48, 36, 88],
       [83, 20, 31],
       [43, 76, 20],
       [68, 43, 42],
       [85, 34, 46],
       [86, 66, 39],
       [55, 58, 75],
       [78, 78, 20],
       [94, 32, 47],
       [98, 81, 23],
       [91, 80, 90],
       [58, 75, 93],
       [60, 40, 30],
       [30, 25, 50]])

Runtime test

In [102]: a = np.random.randint(11,99,(16000,3))

In [103]: df = pd.DataFrame(a)

# @piRSquared's soln1
In [106]: %timeit df.iloc[np.random.permutation(np.arange(df.shape[0]).reshape(-1, 4)).ravel()]
100 loops, best of 3: 2.88 ms per loop

# @piRSquared's soln2
In [107]: %%timeit
     ...: d = df.set_index(np.arange(len(df)) // 4, append=True).swaplevel(0, 1)
     ...: pd.concat([d.xs(i) for i in np.random.permutation(range(4))])
100 loops, best of 3: 3.48 ms per loop

# Array based soln-1
In [108]: %timeit array_shuffle(a, n=4)
100 loops, best of 3: 3.38 ms per loop

# Array based soln-2
In [109]: %timeit array_permuted_indexing(a, n=4)
10000 loops, best of 3: 125 µs per loop


问:
output parameter
how to get output parameter from stored procedure of one table and by using that value how to insert data in another table which is in realation with that table? </p>

答:
When you create your SqlParameter object, assign Output to its Direction property.  Then after you execute your query, cast out the value of the parameter to a C# variable and use it as you please:

```<code>SqlParameter newId = new SqlParameter();
newId.Direction = ParameterDirection.Output;
SqlCommand cmd = new SqlCommand();
// ... build your cmd...and add your other parameters as required
cmd.Parameters.Add(newId);
cmd.ExecuteNonQuery();
int outValue = (int)newId.Value;
</code>```

Then use outValue to pass it to your next SQL query.

OwnerDisplayName: Amit

Title: output parameter

Body:
When you create your SqlParameter object, assign Output to its Direction property.  Then after you execute your query, cast out the value of the parameter to a C# variable and use it as you please:

SqlParameter newId = new SqlParameter();
newId.Direction = ParameterDirection.Output;
SqlCommand cmd = new SqlCommand();
// ... build your cmd...and add your other parameters as required
cmd.Parameters.Add(newId);
cmd.ExecuteNonQuery();
int outValue = (int)newId.Value;

Then use outValue to pass it to your next SQL query.

OwnerDisplayName: Ricardo Villamil


问:
Which one is better about PHP class for query?
I have PHP class that contain function for query data from database. The first one is

```<code>class x{

  public $var1;
  public $var2;

  function __construct(){ }

  function getX($primkey){
    $sql = mysql_qyery("SELECT * FROM x_table WHERE primkey='$primkey'");
    $row = mysq;_fetch_assoc($sql);
    $this->var1 = $row['var1'];
    $this->var2 = $row['var2'];
  }

}
</code>```

and another on is

```<code>class x{

  public $var1;
  public $var2;

  function __construct(){ }

  function getX($primkey){
    $sql = mysql_qyery("SELECT * FROM x_table WHERE primkey='$primkey'");
    $row = mysq;_fetch_assoc($sql);
    return $row;
  }

}
</code>```

two class has some difference on function getX(). The first class put data from database to class variables but the second one return whole data from database via array.

I would like to know about performance of two class, which one is better. and which one is good for programming or any idea?

Regards.

答:
I would create a Database Adapter, then create a Data Mapper and work with a model that uses the Data Mapper.

In which case a call to $model->find() calls the objects find method, which calls the Data Mapper find method which issues queries to the Database Adapter.

Body:
I have PHP class that contain function for query data from database. The first one is

class x{

  public $var1;
  public $var2;

  function __construct(){ }

  function getX($primkey){
    $sql = mysql_qyery("SELECT * FROM x_table WHERE primkey='$primkey'");
    $row = mysq;_fetch_assoc($sql);
    $this->var1 = $row['var1'];
    $this->var2 = $row['var2'];
  }

}

and another on is

class x{

  public $var1;
  public $var2;

  function __construct(){ }

  function getX($primkey){
    $sql = mysql_qyery("SELECT * FROM x_table WHERE primkey='$primkey'");
    $row = mysq;_fetch_assoc($sql);
    return $row;
  }

}

two class has some difference on function getX(). The first class put data from database to class variables but the second one return whole data from database via array.

I would like to know about performance of two class, which one is better. and which one is good for programming or any idea?

Regards.


问:
Getting Product author id in products permalinks
I am using woo commerce and WC Vendor plugin to make a vendor shop. Now I want the product author ID as well in the permalink of the woo commerce product does anyone have any idea how to do that.

Thanks in advance

答:
I have found the solution by writing a simple function in functions.php file the function that worked for me is</p>

```<code>add_filter('post_type_link', 'add_author_id', 10, 4);

function add_author_id($post_link, $post, $leavename, $sample) {
if ('product' != get_post_type($post))
    return $post_link;
$authordata = get_userdata($post->post_author);
$author = $authordata->id;
$post_link = str_replace('%author%', $author, $post_link);
return $post_link;
 }
</code>```

Body:
I have found the solution by writing a simple function in functions.php file the function that worked for me is

add_filter('post_type_link', 'add_author_id', 10, 4);

function add_author_id($post_link, $post, $leavename, $sample) {
if ('product' != get_post_type($post))
    return $post_link;
$authordata = get_userdata($post->post_author);
$author = $authordata->id;
$post_link = str_replace('%author%', $author, $post_link);
return $post_link;
 }


问:
finding if substring exists in file in python
I have 2 files. One is my "keyfile" and other is "lookupfile". I'am trying to check if line in keyfile is present in lookup.Here's my code snippet

```<code>lookupfile = open("riskeng_recon_e_mso_transact_db_msoinputapplication_t2.txt","r")

with open("1.txt","r") as my_file:
    for line in my_file:
        print "-------------checking for "+line+"-----------"
        for x in lookupfile:
            #print x
            if str(line) in str(x):
                print "Line present"+line
</code>```

My 2 files have records in this format.

```<code>Lookupfile:

1234asfd
32453sdfvs
sfgagss234

keyfile:

123
3245
124
</code>```

My issue here is that after taking first record from key file and comparing it with lookupfile, it is not moving forward with the next record in lookupfile.

答:
Can do the operation while reading too:
Since pair-wise wasn't what you wanted we need to create a list with the rows from lookupfile to reuse it.

```<code>with open("file1.txt", "w") as f:
    f.write("""\
1234asfd
32453sdfvs
sfgagss234""")

with open("file2.txt", "w") as f:
    f.write("""\
123
3245
124
324""")

with open("file1.txt") as f1, open("file2.txt") as f2:
    # Store lookupfile in list
    lookup = f1.read().split("\n")

    # Loop lookupfile for every line in keyfile
    for idx, line in enumerate(f2,1):
        for idy, row in enumerate(lookup,1):
            # Look for match
            if line.strip() in row:
                print("line {} present on line {}".format(idx,idy))
</code>```

Prints

```<code>line 1 present on line 1
line 2 present on line 2
line 4 present on line 2
</code>```

Body:
I have 2 files. One is my "keyfile" and other is "lookupfile". I'am trying to check if line in keyfile is present in lookup.Here's my code snippet

lookupfile = open("riskeng_recon_e_mso_transact_db_msoinputapplication_t2.txt","r")

with open("1.txt","r") as my_file:
    for line in my_file:
        print "-------------checking for "+line+"-----------"
        for x in lookupfile:
            #print x
            if str(line) in str(x):
                print "Line present"+line

My 2 files have records in this format.

Lookupfile:

1234asfd
32453sdfvs
sfgagss234

keyfile:

123
3245
124

My issue here is that after taking first record from key file and comparing it with lookupfile, it is not moving forward with the next record in lookupfile.

Body:
Can do the operation while reading too:
Since pair-wise wasn't what you wanted we need to create a list with the rows from lookupfile to reuse it.

with open("file1.txt", "w") as f:
    f.write("""\
1234asfd
32453sdfvs
sfgagss234""")

with open("file2.txt", "w") as f:
    f.write("""\
123
3245
124
324""")

with open("file1.txt") as f1, open("file2.txt") as f2:
    # Store lookupfile in list
    lookup = f1.read().split("\n")

    # Loop lookupfile for every line in keyfile
    for idx, line in enumerate(f2,1):
        for idy, row in enumerate(lookup,1):
            # Look for match
            if line.strip() in row:
                print("line {} present on line {}".format(idx,idy))

Prints

line 1 present on line 1
line 2 present on line 2
line 4 present on line 2


问:
How to block submission until form gets validated using jQuery Validate plugin?
i have a search button on my form, when i hit on it, the onclick attribute activate and jump it into function which i have mentioned on onclick
this is my button,
<input style="float:right;" type="submit" onclick="getData('search')" id="search" class="btn btn-success" name="searchbtn" value="Search">

i want when i hit on search button first form validate then go to that function but i don't know why before validating it directly goes to that function

```<code>$('#myForm').validate({
    onclick:false,
        rules:{
                name:"required",
                dob:"required",
                email:{
                    required: true,
                    email: true
                },
                age:{
                    required: true,
                    number: true,
                    minlength:2,
                    maxlength:2
                }
              },
              messages:{
              name: "Please Enter Name",
              email: "Please Enter valid Email",
              number: "Please Enter Only Digits",
              min_length:"Please Enter Minimum 2 Digit",
              max_length:"Please Enter Maximum 2 Digit"
              }
        });
</code>```

this is my jquery validation code.

```<code><form id="myForm" method="post">
                Name:<p><input id="name_search" class="form-control" type="text" name="name" placeholder="name" required></p>
                Date of Birth:<p><input class="form-control" id="dob_search" type="text" name="dob" placeholder="dd/mm/yy" required></p>
                Sex:<p> <select id="sex_search" name="sex" class="form-control">
                    <option value="Male">Male</option>
                    <option value="Female">Female</option>
                            </select></p>
                Email:<p><input id="mail_search" type="email" class="form-control" name="email" placeholder="Enter your email" required></p>
                Age: <p><input id="age_search" class="form-control" type="text" name="age" placeholder="Age" required></p><br/>
                <input style="float:right;" type="submit" onclick="getData('search')" id="search" class="btn btn-success" name="searchbtn" value="Search"></form>
</code>```

this is my form

答:
removing the onclick attribute from html markup and calling the function after confirming your form's validity would do, like:</p>

```<code>$('#myForm').validate({
    ....
});

$('#search').click(function() {
    //check if form is valid
    if ( $('#myform').valid() ) {
        //call the function
        getData('search');
    }
});
</code>```

Body:
i have a search button on my form, when i hit on it, the onclick attribute activate and jump it into function which i have mentioned on onclick
this is my button,
<input style="float:right;" type="submit" onclick="getData('search')" id="search" class="btn btn-success" name="searchbtn" value="Search">

i want when i hit on search button first form validate then go to that function but i don't know why before validating it directly goes to that function

$('#myForm').validate({
    onclick:false,
        rules:{
                name:"required",
                dob:"required",
                email:{
                    required: true,
                    email: true
                },
                age:{
                    required: true,
                    number: true,
                    minlength:2,
                    maxlength:2
                }
              },
              messages:{
              name: "Please Enter Name",
              email: "Please Enter valid Email",
              number: "Please Enter Only Digits",
              min_length:"Please Enter Minimum 2 Digit",
              max_length:"Please Enter Maximum 2 Digit"
              }
        });

this is my jquery validation code.

<form id="myForm" method="post">
                Name:
<input id="name_search" class="form-control" type="text" name="name" placeholder="name" required>

                Date of Birth:
<input class="form-control" id="dob_search" type="text" name="dob" placeholder="dd/mm/yy" required>

                Sex:
 <select id="sex_search" name="sex" class="form-control">
                    <option value="Male">Male</option>
                    <option value="Female">Female</option>
                            </select>

                Email:
<input id="mail_search" type="email" class="form-control" name="email" placeholder="Enter your email" required>

                Age:
<input id="age_search" class="form-control" type="text" name="age" placeholder="Age" required>

                <input style="float:right;" type="submit" onclick="getData('search')" id="search" class="btn btn-success" name="searchbtn" value="Search"></form>

this is my form

Body:
removing the onclick attribute from html markup and calling the function after confirming your form's validity would do, like:

$('#myForm').validate({
    ....
});

$('#search').click(function() {
    //check if form is valid
    if ( $('#myform').valid() ) {
        //call the function
        getData('search');
    }
});