问:
Low memory after quitting distributed Tensorflow execution
I am applying machine learning in MNIST through Tensorflow. I do this on a cluster where every nodes runs a distributed execution of Tensorflow. I run the individual executions via a bash script on a master node. This master node connects to a set of nodes from the cluster using ssh, and then runs the Python script running Tensorflow.

While Tensorflow is running on nodes I often get the following error message, causing a node to crash:

```<code>2017-03-29 20:34:02.749498: I tensorflow/core/distributed_runtime/rpc/grpc_server_lib.cc:239] Started server with target: grpc://localhost:8338
Extracting /home/mvo010/.tmp/tensorflow/mnist/input_data/train-images-idx3-ubyte.gz
Extracting /home/mvo010/.tmp/tensorflow/mnist/input_data/train-labels-idx1-ubyte.gz
Extracting /home/mvo010/.tmp/tensorflow/mnist/input_data/t10k-images-idx3-ubyte.gz
Extracting /home/mvo010/.tmp/tensorflow/mnist/input_data/t10k-labels-idx1-ubyte.gz
Traceback (most recent call last):
  File "/home/mvo010/inf3203-1/mnist_softmax.py", line 173, in <module>
    tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
  File "/share/apps/lib/python2.7/site-packages/tensorflow/python/platform/app.py", line 44, in run
    _sys.exit(main(_sys.argv[:1] + flags_passthrough))
  File "/home/mvo010/inf3203-1/mnist_softmax.py", line 24, in main
    mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)
  File "/share/apps/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py", line 256, in read_data_sets
    train = DataSet(train_images, train_labels, dtype=dtype, reshape=reshape)
  File "/share/apps/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py", line 138, in __init__
    images = numpy.multiply(images, 1.0 / 255.0)
MemoryError
</code>```

This is because of low memory. When I log in on a node to check the memory I discover that the free memory is really low. The problem is that memory on the node does not get freed when a node is done (or gets killed by the master bash script when it timeouts).

Is there a trivial way to clean up memory for a node after quitting the Tensorflow application? I do not have any sudo permissions.

答:
I got some inspiration from the example from AWS (https://aws.amazon.com/blogs/compute/distributed-deep-learning-made-easy/).

Running pkill -f python before I run the python script on each worker and parameter server host solved this problem.

Body:
I am applying machine learning in MNIST through Tensorflow. I do this on a cluster where every nodes runs a distributed execution of Tensorflow. I run the individual executions via a bash script on a master node. This master node connects to a set of nodes from the cluster using ssh, and then runs the Python script running Tensorflow.

While Tensorflow is running on nodes I often get the following error message, causing a node to crash:

2017-03-29 20:34:02.749498: I tensorflow/core/distributed_runtime/rpc/grpc_server_lib.cc:239] Started server with target: grpc://localhost:8338
Extracting /home/mvo010/.tmp/tensorflow/mnist/input_data/train-images-idx3-ubyte.gz
Extracting /home/mvo010/.tmp/tensorflow/mnist/input_data/train-labels-idx1-ubyte.gz
Extracting /home/mvo010/.tmp/tensorflow/mnist/input_data/t10k-images-idx3-ubyte.gz
Extracting /home/mvo010/.tmp/tensorflow/mnist/input_data/t10k-labels-idx1-ubyte.gz
Traceback (most recent call last):
  File "/home/mvo010/inf3203-1/mnist_softmax.py", line 173, in <module>
    tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
  File "/share/apps/lib/python2.7/site-packages/tensorflow/python/platform/app.py", line 44, in run
    _sys.exit(main(_sys.argv[:1] + flags_passthrough))
  File "/home/mvo010/inf3203-1/mnist_softmax.py", line 24, in main
    mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)
  File "/share/apps/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py", line 256, in read_data_sets
    train = DataSet(train_images, train_labels, dtype=dtype, reshape=reshape)
  File "/share/apps/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py", line 138, in __init__
    images = numpy.multiply(images, 1.0 / 255.0)
MemoryError

This is because of low memory. When I log in on a node to check the memory I discover that the free memory is really low. The problem is that memory on the node does not get freed when a node is done (or gets killed by the master bash script when it timeouts).

Is there a trivial way to clean up memory for a node after quitting the Tensorflow application? I do not have any sudo permissions.


来源: stackexchange

问:
How to turn off Ripple Animation on Tabs [Android]?
How do I turn Off Ripple Animation only for the Tabs ? I have tried to change this in the Config File

```<code> activator : "highlight"
</code>```

But that sets no highlight to all buttons.

I want to turn off Ripple Animation  just for Tabs ?

EDIT 1:

I wanted to remove the effect for the ion-tabs

```<code><ion-tabs>
 <ion-tab [root]="tab1Root" tabIcon="people"></ion-tab>
 <ion-tab [root]="tab2Root" tabIcon="paper"></ion-tab>
 <ion-tab [root]="tab3Root" tabIcon="settings"></ion-tab>
</ion-tabs>
</code>```

答:
I found a Hacky Solution

```<code>ion-tabs .button-effect {
 display:none !important;
}
</code>```

Looks like the button-effect is what "draws" the Ripple. So I just disabled the effect for all descendants of ion-tabs

I wrote that css in my variables.scss

EDIT 1:
Nope. This too sets the .button-effect class to display:none globally. My Question was to set it only for a single ion-tab element.

ContentLicense: CC BY-SA 3.0

Body:
How do I turn Off Ripple Animation only for the Tabs ? I have tried to change this in the Config File

 activator : "highlight"

But that sets no highlight to all buttons.

I want to turn off Ripple Animation  just for Tabs ?

EDIT 1:

I wanted to remove the effect for the ion-tabs

<ion-tabs>
 <ion-tab [root]="tab1Root" tabIcon="people"></ion-tab>
 <ion-tab [root]="tab2Root" tabIcon="paper"></ion-tab>
 <ion-tab [root]="tab3Root" tabIcon="settings"></ion-tab>
</ion-tabs>

Body:
I found a Hacky Solution

ion-tabs .button-effect {
 display:none !important;
}

Looks like the button-effect is what "draws" the Ripple. So I just disabled the effect for all descendants of ion-tabs

I wrote that css in my variables.scss

EDIT 1:
Nope. This too sets the .button-effect class to display:none globally. My Question was to set it only for a single ion-tab element.


问:
How in IDA can save memory dump with command or script?

IDA, Hex-View

I select with mouse zone of bytes from StartAddress to EndAddress

Right Click -> Save to File

Got memory dump.

How do the same with command?Like:
SaveDump(StartAddress , EndAddress)
SaveDump(0x00001000 , 0x00002000)

答:
Press Shift + F2 in IDA, and paste this script:

```<code>auto file, fname, i, address, size, x;
address = 0x0159ADB0;
size = 0xEA90;
fname = "C:\\dump_mem.bin";
file = fopen(fname, "wb");
for (i=0; i<size; i++, address++)
{
 x = DbgByte(address);
 fputc(x, file);
}
fclose(file);
</code>```

Run script , u ll get dump_mem.bin  file from  0x0159ADB0 and size 0xEA90

ContentLicense: CC BY-SA 4.0

Body:
Press Shift + F2 in IDA, and paste this script:

auto file, fname, i, address, size, x;
address = 0x0159ADB0;
size = 0xEA90;
fname = "C:\\dump_mem.bin";
file = fopen(fname, "wb");
for (i=0; i<size; i++, address++)
{
 x = DbgByte(address);
 fputc(x, file);
}
fclose(file);

Run script , u ll get dump_mem.bin  file from  0x0159ADB0 and size 0xEA90


问:
Laravel disable slug transltions
I'm trying to save my group model with a slug, but it keeps saving my slug with the untranslated version of the name.

is there a way to force it so it uses the input value?

This is the model:

```<code>class Group extends Model
{
    use CrudTrait;
    use Sluggable, SluggableScopeHelpers;
    use HasTranslations;

    protected $table = 'groups';
    protected $primaryKey = 'id';
    protected $fillable = ['name', 'slug'];
    protected $hidden = ['pivot'];
    protected $translatable = ['name'];
    public $timestamps = true;

    */
    public function users()
    {
        return $this->belongsToMany(User::class);
    }

    /**
     * Return the sluggable configuration array for this model.
     *
     * @return array
     */
    public function sluggable()
    {
        return [
            'slug' => [
                'source' => 'name'

            ],
        ];
    }
}
</code>```

And now when I put in a name e.g. test this will save my slug value as {"en":"{\"en\":\"test\"}"}

instead of just normal test anyone know what I might be doing wrong?

I'm also using the Laravel Backpack items

答:
This is how it suppose to work. each translation will has its own slug:

```<code>en/test-slug
ar/تست-سلغ
</code>```

and so on. why you need it to work up normal?
As a work around to you can corp the local from the slug when retrieving it.

Title: Laravel disable slug transltions

Body:
I'm trying to save my group model with a slug, but it keeps saving my slug with the untranslated version of the name.

is there a way to force it so it uses the input value?

This is the model:

class Group extends Model
{
    use CrudTrait;
    use Sluggable, SluggableScopeHelpers;
    use HasTranslations;

    protected $table = 'groups';
    protected $primaryKey = 'id';
    protected $fillable = ['name', 'slug'];
    protected $hidden = ['pivot'];
    protected $translatable = ['name'];
    public $timestamps = true;

    */
    public function users()
    {
        return $this->belongsToMany(User::class);
    }

    /**
     * Return the sluggable configuration array for this model.
     *
     * @return array
     */
    public function sluggable()
    {
        return [
            'slug' => [
                'source' => 'name'

            ],
        ];
    }
}

And now when I put in a name e.g. test this will save my slug value as {"en":"{\"en\":\"test\"}"}

instead of just normal test anyone know what I might be doing wrong?

I'm also using the Laravel Backpack items

Body:
This is how it suppose to work. each translation will has its own slug:

en/test-slug
ar/تست-سلغ

and so on. why you need it to work up normal?
As a work around to you can corp the local from the slug when retrieving it.


问:
Error thrown citing match arms with incompatible types when pattern matching an Option
I am fairly new to Rust and cannot get my head around this confusing error.

I am simply trying to match on an Option returned by the get function of a HashMap. If a value is returned I want to increment it, if not I want to add a new element to the map.

Here is the code:

```<code>let mut map = HashMap::new();
map.insert("a", 0);
let a = "a";
match map.get(&a) {
    Some(count) => *count += 1,
    None => map.insert(a, 0),
}
</code>```

The resulting error:

error[E0308]: match arms have incompatible types
  --> <anon>:7:5
   |
7  |       match map.get(&a) {
   |  _____^ starting here...
8  | |         Some(count) => *count += 1,
9  | |         None => map.insert(a, 0),
10 | |     }
   | |_____^ ...ending here: expected (), found enum `std::option::Option`
   |
   = note: expected type `()`
              found type `std::option::Option<{integer}>`
note: match arm with an incompatible type
  --> <anon>:9:17
   |
9  |         None => map.insert(a, 0),
   |                 ^^^^^^^^^^^^^^^^
```

I am not really sure what types the compiler is complaining about here, as both Some and None are both part of the same enum type. Can anyone explain what issue the compiler is having with my code?

答:
The compiler is referring to the value the match arm bodies return, not the type of the pattern of each match arm.

```<code>Some(count) => *count += 1,
None => map.insert(a, 0),
</code>```

The expression *count += 1 evaluates to () (called "unit" in Rust, "void" in many other languages). The expression map.insert(a, 0) on the other hand returns Option<V> where V is the value type of the hash map (an integer in your case). Suddenly the error message does make some sense:

= note: expected type `()`
= note:    found type `std::option::Option<{integer}>`
```

<p>I suppose you don't even want to return something from the <code>match</code> block (remember: <code>match</code> blocks are expressions, too, so you could return something from it). To discard the result of any expression, you can convert it to a statement with <code>;</code>. Let's try this:</p>

```match map.get(&a) {
    Some(count) => {
        *count += 1;
    }
    None => {
        map.insert(a, 0);
    }
}
```

<p>Each match arm body is a block now (something between <code>{</code> and <code>}</code>) and each block contains one statement. Note that we technically don't need to change the first match arm, as <code>*count += 1</code> already returns <code>()</code>, but this way it's more consistent.</p>

<hr>

<p>But once you test this, another error related to borrowing will be shown. This is a well known issue and is explained in more detail here. In short: the borrow checker is not smart enough to recognize that your code is fine and therefore you should use the super nice <code>entry</code>-API:</p>

```let map = HashMap::new();
map.insert("a", 0);
let a = "a";
*map.entry(&a).or_insert(0) += 1;
```

Body:
I am fairly new to Rust and cannot get my head around this confusing error.

I am simply trying to match on an Option returned by the get function of a HashMap. If a value is returned I want to increment it, if not I want to add a new element to the map.

Here is the code:

let mut map = HashMap::new();
map.insert("a", 0);
let a = "a";
match map.get(&a) {
    Some(count) => *count += 1,
    None => map.insert(a, 0),
}

The resulting error:

error[E0308]: match arms have incompatible types
  --> <anon>:7:5
   |
7  |       match map.get(&a) {
   |  _____^ starting here...
8  | |         Some(count) => *count += 1,
9  | |         None => map.insert(a, 0),
10 | |     }
   | |_____^ ...ending here: expected (), found enum `std::option::Option`
   |
   = note: expected type `()`
              found type `std::option::Option<{integer}>`
note: match arm with an incompatible type
  --> <anon>:9:17
   |
9  |         None => map.insert(a, 0),
   |                 ^^^^^^^^^^^^^^^^

I am not really sure what types the compiler is complaining about here, as both Some and None are both part of the same enum type. Can anyone explain what issue the compiler is having with my code?

Body:
The compiler is referring to the value the match arm bodies return, not the type of the pattern of each match arm.

Some(count) => *count += 1,
None => map.insert(a, 0),

The expression *count += 1 evaluates to () (called "unit" in Rust, "void" in many other languages). The expression map.insert(a, 0) on the other hand returns Option<V> where V is the value type of the hash map (an integer in your case). Suddenly the error message does make some sense:

= note: expected type `()`
= note:    found type `std::option::Option<{integer}>`

I suppose you don't even want to return something from the match block (remember: match blocks are expressions, too, so you could return something from it). To discard the result of any expression, you can convert it to a statement with ;. Let's try this:

match map.get(&a) {
    Some(count) => {
        *count += 1;
    }
    None => {
        map.insert(a, 0);
    }
}

Each match arm body is a block now (something between { and }) and each block contains one statement. Note that we technically don't need to change the first match arm, as *count += 1 already returns (), but this way it's more consistent.

But once you test this, another error related to borrowing will be shown. This is a well known issue and is explained in more detail here. In short: the borrow checker is not smart enough to recognize that your code is fine and therefore you should use the super nice entry-API:

let map = HashMap::new();
map.insert("a", 0);
let a = "a";
*map.entry(&a).or_insert(0) += 1;


问:
Load array index from .txt file - separator
im trying to load an array from .txt file and success with this code.

```<code>main(){
string nameArr[7];
ifstream file("name.txt");
if(file.is_open()){

    for(int i=0;i<7;++i){
        file >> nameArr[i];
    }
}

for(int i=0;i<7;i++){
    cout << nameArr[i] << endl;
}
}
</code>```

And with this .txt file.

Bosko Alphard Galih Reh Adit Dita Dani

So, the question is.. if i have long string format with space how should i do with the .txt file (what separator should i use) and how should i write the code?

答:
You can use getline() syntax like this, if you want your whole line in one string.

```<code>main(){
string nameArr[7];
ifstream file("name.txt");
if(file.is_open()){

    for(int i=0;i<7;++i){
        getline(file,filenameArr[i]) //if you want to take a full line in a string // this will take 7 lines from your txt
    }
}

for(int i=0;i<7;i++){
    cout << nameArr[i] << endl;
}
}
</code>```

Body:
im trying to load an array from .txt file and success with this code.

main(){
string nameArr[7];
ifstream file("name.txt");
if(file.is_open()){

    for(int i=0;i<7;++i){
        file >> nameArr[i];
    }
}

for(int i=0;i<7;i++){
    cout << nameArr[i] << endl;
}
}

And with this .txt file.

Bosko Alphard Galih Reh Adit Dita Dani

So, the question is.. if i have long string format with space how should i do with the .txt file (what separator should i use) and how should i write the code?

Body:
You can use getline() syntax like this, if you want your whole line in one string.

main(){
string nameArr[7];
ifstream file("name.txt");
if(file.is_open()){

    for(int i=0;i<7;++i){
        getline(file,filenameArr[i]) //if you want to take a full line in a string // this will take 7 lines from your txt
    }
}

for(int i=0;i<7;i++){
    cout << nameArr[i] << endl;
}
}


问:
Why are views not counted if you embed a youtube iframe dynamically using jquery?
In one of my sites I have thousands of visitors daily but after one year, the view count for the main video on the start page is still at only 26 views.

I wanted to save load times, that's why I am providing an image with play icon on the page. As soon as the icon gets clicked, I load the youtube iframe via:

```<code>    $('#introimg').click( function() {
        $(this).replaceWith('<iframe width="759" height="426" src="https://www.youtube.com/embed/fduB8MivQUk?wmode=transparent&rel=0&showinfo=1&iv_load_policy=1&modestbranding=1&controls=2&vq=large&autoplay=1" allowfullscreen></iframe>');
    });
</code>```

I found one note here that says:

Views that originate as a result of clicking on one of the native player UI elements (either the play button in the control bar or on the static player image) will normally count towards incrementing the views for a video.

Is this the reason? Because I embed the iframe with autoplay true, so there is no click event.

Would be a workaround to do a replaceWidth and then do a trigger('click')? (Which probably does not work within the iframe...)

Related, but different on stackoverflow:

Youtube embedded video views do not count

Are YouTube view counts incremented when using the iframe Player?

答:
Views That Don’t Count

There are a few sources of views that don’t count, and a few things that will disqualify a view from counting.

Views from an embedded video set to autoplay may or may not count. This has varied over the years and there are many conflicting reports available. In general, however, a video set to play automatically is an annoyance that drives users away. Allow them to load the video on their own terms; don’t force it on them.
Views from the creator of the content typically count, to a limited extent. YouTube has no way of knowing, for example, whether you’re showing the video to other people on your computer or not. However, refreshing the page dozens of times to inflate the view count will cause those views to not count.
Repeated views from the same user over a short period of time typically don’t count. Repeat views are legitimate in some cases, typically music videos and tutorials, but they often take place in a single session. If the user is reloading the page each time they view the video, they’re probably trying to game the system and their repeat views won’t count.

Read More here

Body:
In one of my sites I have thousands of visitors daily but after one year, the view count for the main video on the start page is still at only 26 views.

I wanted to save load times, that's why I am providing an image with play icon on the page. As soon as the icon gets clicked, I load the youtube iframe via:

    $('#introimg').click( function() {
        $(this).replaceWith('');
    });

I found one note here that says:

Views that originate as a result of clicking on one of the native player UI elements (either the play button in the control bar or on the static player image) will normally count towards incrementing the views for a video.

Is this the reason? Because I embed the iframe with autoplay true, so there is no click event.

Would be a workaround to do a replaceWidth and then do a trigger('click')? (Which probably does not work within the iframe...)

Related, but different on stackoverflow:

Youtube embedded video views do not count

Are YouTube view counts incremented when using the iframe Player?


问:
CSS: 3 divs - Resizing 2 outer divs automatically based on width of inner div/text
My problem is best outlined with this schematic/image which outlines how I want it to look:

!

I have a background image and 2 divs for text over the top of it (headline, and intro-text). I also have 2 divs on either side of the headline - these are for the white horizontal stripes.

My issue is that the headline is changeable in a CMS, and I want the horizontal white stripes to automatically fill up the space to the left and to the right of it, regardless of the headline's width.

I can't figure out how to make those 2 horizontal white stripes resize automatically.

Here's my HTML:

```<code><div id="masthead">
<div id="headline-container">
    <div id="left-stripe"> </div><div id="headline">{headline}</div><div id="right-stripe"> </div>
</div>
<div class="clear-both"> </div>
<div id="intro-text">{intro_text}</div>
</div>
</code>```

And here's my CSS - ignore the widths specified for the left-stripe and right-stripe - they're just placeholders:

```<code>#masthead {
    height: 260px;
}

div#headline-container {
    width:960px;
    padding:none;
}
div#left-stripe{
    float: left;
    background-color:#fff;
    height: 3px;
    width:500px;
    display: inline;
}
div#right-stripe{
    float: right;
    background-color:#fff;
    height: 3px;
    width:100px;
    display: inline;
}
div#headline {
    text-align:right;
    color: #fff;
    font-size: 200%;
    float: left;
    display: inline;
}
div#intro-text {
    text-align: left;
    float: right;
    width: 300px;
    color: #fff;
}
</code>```

Ideas? Please let me know if I can provide more detail.

答:
UPDATE CSS only fluid solution: http://jsfiddle.net/SebastianPataneMasuelli/XnvYw/1/

it uses the same background image twice, on #masthead and on #headline-container.  except ton headline container the background is offset to match its left position relative to its parent element.  then we only need one div.line behind it, which gets covered by the background image under the headline and copy, giving the illusion of a seamless image.

do you mean like this?: http://jsfiddle.net/SebastianPataneMasuelli/XnvYw/

Body:
My problem is best outlined with this schematic/image which outlines how I want it to look:

!

I have a background image and 2 divs for text over the top of it (headline, and intro-text). I also have 2 divs on either side of the headline - these are for the white horizontal stripes.

My issue is that the headline is changeable in a CMS, and I want the horizontal white stripes to automatically fill up the space to the left and to the right of it, regardless of the headline's width.

I can't figure out how to make those 2 horizontal white stripes resize automatically.

Here's my HTML:

{headline}

{intro_text}

And here's my CSS - ignore the widths specified for the left-stripe and right-stripe - they're just placeholders:

#masthead {
    height: 260px;
}

div#headline-container {
    width:960px;
    padding:none;
}
div#left-stripe{
    float: left;
    background-color:#fff;
    height: 3px;
    width:500px;
    display: inline;
}
div#right-stripe{
    float: right;
    background-color:#fff;
    height: 3px;
    width:100px;
    display: inline;
}
div#headline {
    text-align:right;
    color: #fff;
    font-size: 200%;
    float: left;
    display: inline;
}
div#intro-text {
    text-align: left;
    float: right;
    width: 300px;
    color: #fff;
}

Ideas? Please let me know if I can provide more detail.

ContentLicense: CC BY-SA 2.5


问:
Setting scheduling policy SCHED_IDLE or SCHED_BATCH fails with EINVAL (22)
I'm trying to create threads which are unlikely to be scheduled (this is for a test case, not production code), so I wanted to create a thread with SCHED_IDLE scheduling policy.

Unfortunately this fails with EINVAL (even if running as root) on every distro/kernel version I tried.

Note that this fails when calling pthread_attr_setschedpolicy(), while usually what fails is the creation of a thread with a non-authorised scheduling policy (for instance if you try to use SCHED_RR as non-root).

This is some code to demostrate the problem:

```<code>#define _GNU_SOURCE

#include <assert.h>
#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>

typedef struct
{
    const char *name;
    int value;
} policy_t;

policy_t policies[] = {
    { "SCHED_OTHER",  SCHED_OTHER },
    { "SCHED_IDLE",   SCHED_IDLE },
    { "SCHED_BATCH",  SCHED_BATCH },
    { "SCHED_FIFO",   SCHED_FIFO },
    { "SCHED_RR",     SCHED_RR },
};

int main(int argc, char *argv[])
{
    for (int i = 0; i < sizeof(policies) / sizeof(policies[0]); i++) {
        policy_t policy = policies[i];

        pthread_attr_t attr;
        pthread_attr_init(&attr);

        int e = pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
        assert(e == 0);

        e = pthread_attr_setschedpolicy(&attr, policy.value);
        if (e != 0)
            printf("Cannot set sched policy %s (%d): %s (%d)\n",
                   policy.name,
                   policy.value,
                   strerror(e),
                   e);
    }

    return 0;
}
</code>```

The output I get is:

```<code>Cannot set sched policy SCHED_IDLE (5): Invalid argument (22)
Cannot set sched policy SCHED_BATCH (3): Invalid argument (22)
</code>```

答:
The glibc code that implements pthread_attr_setschedpolicy() currently rejects the non-POSIX-defined scheduler policies.

You can set the thread's scheduler policy to SCHED_IDLE or SCHED_BATCH once it's running using pthread_setschedparam(), though.  Eg. the first thing the new thread does can be to set its own scheduler policy.

Body:
I'm trying to create threads which are unlikely to be scheduled (this is for a test case, not production code), so I wanted to create a thread with SCHED_IDLE scheduling policy.

Unfortunately this fails with EINVAL (even if running as root) on every distro/kernel version I tried.

Note that this fails when calling pthread_attr_setschedpolicy(), while usually what fails is the creation of a thread with a non-authorised scheduling policy (for instance if you try to use SCHED_RR as non-root).

This is some code to demostrate the problem:

#define _GNU_SOURCE

#include <assert.h>
#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>

typedef struct
{
    const char *name;
    int value;
} policy_t;

policy_t policies[] = {
    { "SCHED_OTHER",  SCHED_OTHER },
    { "SCHED_IDLE",   SCHED_IDLE },
    { "SCHED_BATCH",  SCHED_BATCH },
    { "SCHED_FIFO",   SCHED_FIFO },
    { "SCHED_RR",     SCHED_RR },
};

int main(int argc, char *argv[])
{
    for (int i = 0; i < sizeof(policies) / sizeof(policies[0]); i++) {
        policy_t policy = policies[i];

        pthread_attr_t attr;
        pthread_attr_init(&attr);

        int e = pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
        assert(e == 0);

        e = pthread_attr_setschedpolicy(&attr, policy.value);
        if (e != 0)
            printf("Cannot set sched policy %s (%d): %s (%d)\n",
                   policy.name,
                   policy.value,
                   strerror(e),
                   e);
    }

    return 0;
}

The output I get is:

Cannot set sched policy SCHED_IDLE (5): Invalid argument (22)
Cannot set sched policy SCHED_BATCH (3): Invalid argument (22)


问:
Installing Rmpi on Ubuntu 16.04 VirtualBox
I created a new ubuntu-16.04.2-desktop-amd64 machine on VM VirtualBox and I want to be able to use the R environment with Rmpi.

Both of the below approaches gives a similar error.

Updated simplified pre-build binary approach:

When Ubuntu had installed I opened a terminal and executed the following commands:

```<code>~$ sudo apt-get update
~$ sudo apt-get install openmpi-bin
~$ sudo apt-get install r-base
~$ sudo apt-get install r-cran-rmpi
~$ R
</code>```

This opened the R terminal and I invoking the follow function which resulted in an error:

```<code>> library(Rmpi)
libmpi.so: cannot open shared object file: No such file or directory
Error : .onLoad failed in loadNamespace() for 'Rmpi', details:
call: fun(libname, pkgname)
error: Cannot start MPI_Init(). Exit
Error: package or namespace load failed for ‘Rmpi’
</code>```

Alternative approaches that I have attempted include using a local OpenMPI installation and using the R function install.packages to install the Rmpi package (see below). These all resulted in the same error.

I have also tried using MPICH by substituting ~$ sudo apt-get install mpich as the second command in the above procedure (including using the R function for installing the package) which results in an even more onerous runtime error.

Does anyone know what I have done wrong or what I can do to resolve this installation error?

Or alternatively, have anyone been able to successfully install a VirtualBox machine with Rmpi using any Linux distro or an image with pre-installed components?

Original local installation approach:

I have followed the instructions on this blog to download OpenMPI version 2.1.0, compile and install it. However when I try to install the package in R with:

```<code>> install.packages("Rmpi", configure.args =
  c("--with-Rmpi-include=/home/jormunr/openmpi/include",
    "--with-Rmpi-libpath=/home/jormunr/openmpi/lib",
    "--with-Rmpi-type=OPENMPI",
    "--with-mpi=/home/jormunr/openmpi/"))
</code>```

it gives the following error

```<code>Error: .onLoad failed in loadNamespace() for 'Rmpi', details:
  call: dyn.load(file, DLLpath = DLLpath, ...)
  error: unable to load shared object '/home/jormunr/R/x86_64-pc-linux-gnu-library/3.2/Rmpi/libs/Rmpi.so':
libmpi.so.20: cannot open shared object file: No such file or directory
Error: loading failed
Execution halted
ERROR: loading failed
</code>```

I can see that the 'libmpi.so.20' file is in the /home/jormunr/openmpi/lib that I provided as one of the parameter to the installation.

答:
[Disclaimer: I am not a Linux expert and merely have user level skills. Any contributions or corrections from an expert will be greatly appreciated.]

Pre-build Binary Approach

Although trying various ways to install the prebuilt binaries I did not manage to get this option to work. This involved executing in the terminal the command 'sudo apt-get install r-cran-rmpi' to install the r-cran-rmpi prebuilt packages which also automatically installs the libopenmpi1.10 package that is a listed prerequisite. However, it appears that the file 'libmpi.so' is not included in the libopenmpi1.10 package but expected by the Rmpi library which causes an error in the R environment that it cannot find this file.

Local Installation Approach

The local installation did eventually succeed with a few amendments. I created a new ubuntu-16.04.2-desktop-amd64 VirtualBox image with default settings, except for 2048MB of memory and 32GB of hard drive space. When installed I opened a terminal and executed the commands from the Jovinge Lab website with the inclusion of the penultimate command which amends the run-time link editor's path and enables the install.package() function of R to find the 'libmpi.so' file. (also changed the version to 1.10.6 as this is the latest version release of version 1 – see below for version 2)

```<code>~$ cd /home/jormunr
~$ wget https://www.open-mpi.org/software/ompi/v1.10/downloads/openmpi-1.10.2.tar.gz
~$ tar -zxvf openmpi-1.10.6.tar.gz
~$ cd openmpi-1.10.2
~$ ./configure --prefix=/home/jormunr
~$ make
~$ make install
~$ sudo apt-get install r-base
~$ export LD_LIBRARY_PATH=/home/jormunr/lib:$LD_LIBRARY_PATH
~$ R
</code>```

This opens an R terminal and I invoked the function:

```<code>> install.packages("Rmpi", configure.args =
+ c("--with-Rmpi-include=/home/jormunr/include/",
+   "--with-Rmpi-libpath=/home/jormunr/lib/",
+   "--with-Rmpi-type=OPENMPI",
+   "--with-mpi=/home/jormunr/"))
</code>```

This now executed without errors and I could test it with the following R statements:

```<code>> library("Rmpi")
> mpi.spawn.Rslaves()
master (rank 0, comm. 1) of size 2 is running on: Valhalla
slave1 (rank 1, comm. 1) of size 2 is running on: Valhalla
> mpi.close.Rslaves()
[1] 1
> mpi.quit()
</code>```

When I tried this process with the OpenMPI Version 2.1.0 the installation completed successfully but the above test had issues; the mpi.spawn.Rslaves() function completed but mpi.close.Rslaves() did not complete – it never returned and the terminal was left hanging.

Body:
I created a new ubuntu-16.04.2-desktop-amd64 machine on VM VirtualBox and I want to be able to use the R environment with Rmpi.

Both of the below approaches gives a similar error.

Updated simplified pre-build binary approach:

When Ubuntu had installed I opened a terminal and executed the following commands:

~$ sudo apt-get update
~$ sudo apt-get install openmpi-bin
~$ sudo apt-get install r-base
~$ sudo apt-get install r-cran-rmpi
~$ R

This opened the R terminal and I invoking the follow function which resulted in an error:

> library(Rmpi)
libmpi.so: cannot open shared object file: No such file or directory
Error : .onLoad failed in loadNamespace() for 'Rmpi', details:
call: fun(libname, pkgname)
error: Cannot start MPI_Init(). Exit
Error: package or namespace load failed for ‘Rmpi’

Alternative approaches that I have attempted include using a local OpenMPI installation and using the R function install.packages to install the Rmpi package (see below). These all resulted in the same error.

I have also tried using MPICH by substituting ~$ sudo apt-get install mpich as the second command in the above procedure (including using the R function for installing the package) which results in an even more onerous runtime error.

Does anyone know what I have done wrong or what I can do to resolve this installation error?

Or alternatively, have anyone been able to successfully install a VirtualBox machine with Rmpi using any Linux distro or an image with pre-installed components?

Original local installation approach:

I have followed the instructions on this blog to download OpenMPI version 2.1.0, compile and install it. However when I try to install the package in R with:

> install.packages("Rmpi", configure.args =
  c("--with-Rmpi-include=/home/jormunr/openmpi/include",
    "--with-Rmpi-libpath=/home/jormunr/openmpi/lib",
    "--with-Rmpi-type=OPENMPI",
    "--with-mpi=/home/jormunr/openmpi/"))

it gives the following error

Error: .onLoad failed in loadNamespace() for 'Rmpi', details:
  call: dyn.load(file, DLLpath = DLLpath, ...)
  error: unable to load shared object '/home/jormunr/R/x86_64-pc-linux-gnu-library/3.2/Rmpi/libs/Rmpi.so':
libmpi.so.20: cannot open shared object file: No such file or directory
Error: loading failed
Execution halted
ERROR: loading failed

I can see that the 'libmpi.so.20' file is in the /home/jormunr/openmpi/lib that I provided as one of the parameter to the installation.

Body:
[Disclaimer: I am not a Linux expert and merely have user level skills. Any contributions or corrections from an expert will be greatly appreciated.]

Pre-build Binary Approach

Although trying various ways to install the prebuilt binaries I did not manage to get this option to work. This involved executing in the terminal the command 'sudo apt-get install r-cran-rmpi' to install the r-cran-rmpi prebuilt packages which also automatically installs the libopenmpi1.10 package that is a listed prerequisite. However, it appears that the file 'libmpi.so' is not included in the libopenmpi1.10 package but expected by the Rmpi library which causes an error in the R environment that it cannot find this file.

Local Installation Approach

The local installation did eventually succeed with a few amendments. I created a new ubuntu-16.04.2-desktop-amd64 VirtualBox image with default settings, except for 2048MB of memory and 32GB of hard drive space. When installed I opened a terminal and executed the commands from the Jovinge Lab website with the inclusion of the penultimate command which amends the run-time link editor's path and enables the install.package() function of R to find the 'libmpi.so' file. (also changed the version to 1.10.6 as this is the latest version release of version 1 – see below for version 2)

~$ cd /home/jormunr
~$ wget https://www.open-mpi.org/software/ompi/v1.10/downloads/openmpi-1.10.2.tar.gz
~$ tar -zxvf openmpi-1.10.6.tar.gz
~$ cd openmpi-1.10.2
~$ ./configure --prefix=/home/jormunr
~$ make
~$ make install
~$ sudo apt-get install r-base
~$ export LD_LIBRARY_PATH=/home/jormunr/lib:$LD_LIBRARY_PATH
~$ R

This opens an R terminal and I invoked the function:

> install.packages("Rmpi", configure.args =
+ c("--with-Rmpi-include=/home/jormunr/include/",
+   "--with-Rmpi-libpath=/home/jormunr/lib/",
+   "--with-Rmpi-type=OPENMPI",
+   "--with-mpi=/home/jormunr/"))

This now executed without errors and I could test it with the following R statements:

> library("Rmpi")
> mpi.spawn.Rslaves()
master (rank 0, comm. 1) of size 2 is running on: Valhalla
slave1 (rank 1, comm. 1) of size 2 is running on: Valhalla
> mpi.close.Rslaves()
[1] 1
> mpi.quit()

When I tried this process with the OpenMPI Version 2.1.0 the installation completed successfully but the above test had issues; the mpi.spawn.Rslaves() function completed but mpi.close.Rslaves() did not complete – it never returned and the terminal was left hanging.


问:
C array of pointers to double
I'm getting a memory problem in c++ code, for sure I'm wrong but I don't get the problem. I've declare an array of three pointer to double and allocate memory.

```<code>double *myDoubles[3];

for(int i=0;i<3;i++) {
   myDoubles[i]= (double *) malloc(1000*sizeof(double));
}

myDoubles[2][999]=10.55;
</code>```

Whats wrong?

EDIT

As @EdHeal comments and also @PhilippKiener I should not be using malloc at all. But it's difficult to forget malloc before 25 years with it.
After all my problem was another bug in another place and actually I was writing out of limits :). My fault!

答:
As you are using C++, use std::vector - See here

So the code becomes

```<code>std::vector<std::vector<double>> myDoubles(3);
myDoubles[2].resize(1000);
myDoubles[2][999] = 10.55;
</code>```

Perhaps you need to resize the other entries - I leave that exercise to you.

In addition you have no worries about memory leaks.

Title: C array of pointers to double

Body:
I'm getting a memory problem in c++ code, for sure I'm wrong but I don't get the problem. I've declare an array of three pointer to double and allocate memory.

double *myDoubles[3];

for(int i=0;i<3;i++) {
   myDoubles[i]= (double *) malloc(1000*sizeof(double));
}

myDoubles[2][999]=10.55;

Whats wrong?

EDIT

As @EdHeal comments and also @PhilippKiener I should not be using malloc at all. But it's difficult to forget malloc before 25 years with it.
After all my problem was another bug in another place and actually I was writing out of limits :). My fault!

Body:
As you are using C++, use std::vector - See here

So the code becomes

std::vector<std::vector<double>> myDoubles(3);
myDoubles[2].resize(1000);
myDoubles[2][999] = 10.55;

Perhaps you need to resize the other entries - I leave that exercise to you.

In addition you have no worries about memory leaks.


问:
Java SOAP WebService - How to accept single input parameter
I'm developing a SOAP based Webservice API which would be used by a third party system. WSDL file and endpoint URL would be shared with them and they invoke my Web service by passing an input parameter and get the response back

So far, I have created the Web Service API including WSDL, Services Classes, Helper Classes, DAO, Ibatis) and tested using SOAP UI by passing the input parameter, the request hits the databse and returning the response fine. Attached the WSDL file and SOAP request and response.

I got two questions,

The 3rd Party system is asking for an API documentation and SOAP Envelope. What should I give?

The 3rd party system has to invoke my service by passing the input parameter sQuoteRef. How would they usually do it? I'm not concerned about the client code here but how would the request from 3rd party look like and what changes I should make in my WSDL or Java classes to receive the input parameter and pass on to my service class?

Any inputs would be helpful in completing my task. Many Thanks!

WSDL File

```<code>    <?xml version="1.0" encoding="UTF-8"?><wsdl:definitions name="EmpService" targetNamespace="http://emp.provider.integration.gi.sample.ie/EmpService/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://Emp.provider.integration.gi.sample.ie/EmpService/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <wsdl:types>
        <xsd:schema targetNamespace="http://Emp.provider.integration.gi.sample.ie/EmpService/">

          <xsd:element name="EmpRequestVO">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element maxOccurs="1" minOccurs="1" name="sQuoteRef" type="xsd:string"/>
              </xsd:sequence>
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="EmpResponseVO">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element maxOccurs="1" minOccurs="0" name="sQuoteStatus" type="xsd:string"/>
              </xsd:sequence>
            </xsd:complexType>
          </xsd:element>
        </xsd:schema>
      </wsdl:types>

      <wsdl:message name="GetEmpTransactionSoapIn">
        <wsdl:part element="tns:EmpRequestVO" name="parameters"/>
      </wsdl:message>
      <wsdl:message name="GetEmpTransactionSoapOut">
        <wsdl:part element="tns:EmpResponseVO" name="parameters"/>
      </wsdl:message>

      <wsdl:portType name="EmpServiceSoap">
        <wsdl:operation name="getEmpTransaction">
          <wsdl:input message="tns:GetEmpTransactionSoapIn"/>
          <wsdl:output message="tns:GetEmpTransactionSoapOut"/>
        </wsdl:operation>
      </wsdl:portType>

      <wsdl:binding name="EmpServiceSoap" type="tns:EmpServiceSoap">
        <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
        <wsdl:operation name="getEmpTransaction">
          <soap:operation soapAction="getEmpTransaction" style="document"/>
          <wsdl:input>
            <soap:body use="literal"/>
          </wsdl:input>
          <wsdl:output>
            <soap:body use="literal"/>
          </wsdl:output>
        </wsdl:operation>
      </wsdl:binding>

      <wsdl:service name="PLUSEmpServices">
        <wsdl:port binding="tns:EmpServiceSoap" name="EmpServiceSOAP">
          <soap:address location="http://localhost:9080/WebServices/services/EmpServiceSOAP"/>
        </wsdl:port>
      </wsdl:service>
    </wsdl:definitions>
</code>```

End Point URL
http://localhost:9080/PLUSEmpServices/services/EmpServiceSOAP

```<code>SOAP REQUEST in SOAP UI

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:rtw="http://emp.provider.integration.gi.sample.ie/EmpService/">
   <soapenv:Header/>
   <soapenv:Body>
      <rtw:EmpRequestVO>
         <sQuoteRef>12123118</sQuoteRef>
      </rtw:EmpRequestVO>
   </soapenv:Body>
</soapenv:Envelope>

SOAP RESPONSE in SOAP UI
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:Header/>
   <soapenv:Body>
      <p900:EmpResponseVO xmlns:p900="http://emp.provider.integration.gi.sample.ie/EmpService/">
         <sQuoteStatus>Active</sQuoteStatus>
      </p900:EmpResponseVO>
   </soapenv:Body>
</soapenv:Envelope>
</code>```

答:
The 3rd Party system is asking for an API documentation and SOAP Envelope. What should I give?

To start APIs integration with external parties, your clients require a technical API document that will be a reference to complete APIs integration and a base for any technical communication between the teams. The technical document may includes the following details:

Brief description for different available web-services APIs and their requirements.

APIs communications flow. This will be useful in case the clients need to call more than one services in specific sequence. Including flow diagram will be possible option to explain the system flow.

Test environment details like WSDL URL and access credentials like username, password, agent code, etc.

Detailed description for all fields needed to send a valid request to the server. Fields details may include the following:

a.    Filed name.

b.    Description.

c.    Data Type.

d.    Max length.

e.    Mandatory, Optional or Conditional.

f.    Possible values if any.

All possible response codes a long with their description sent by server API to client API which indicates the successful or failure of transaction process(s). For example (0000 means Success, E001 means validation error, E002 system error, 9999 unknown error, etc.).

Note: Response codes should cover various rejection cases.

Security Section that explain how the data is exchange securely between client and server application.

a.    Mention additional Encryption mechanism for part or all request data if any.

b.    Communication type with the client wither it is over VPN or accessed public
over https URL. Note the URL you mentioned in your question is deployed in your local machine and it will not be available publicly.

Sample SOAP request(s) and response(s) xml format for all available API’s web methods.

Mention any additional rules or constrains on APIs connectivity.

The 3rd party system has to invoke my service by passing the input parameter sQuoteRef. How would they usually do it? I'm not concerned about the client code here but how would the request from 3rd party look like and what changes I should make in my WSDL or Java classes to receive the input parameter and pass on to my service class?

If I understand you correctly your are asking how should I change WSDL or Java classes to accept client request correctly ? Usually the server side API has the upper hand in XML format need to be exchanged and in your case it should be mentioned in WSDL. So the client will create a valid request as per definition mentioned in server WSDL URL.

Further reading that my be useful on how to generate WSDL from Java classes:

Eclipse WSDL generator (from java class)?

SOAP fault handling in java

Body:
I'm developing a SOAP based Webservice API which would be used by a third party system. WSDL file and endpoint URL would be shared with them and they invoke my Web service by passing an input parameter and get the response back

So far, I have created the Web Service API including WSDL, Services Classes, Helper Classes, DAO, Ibatis) and tested using SOAP UI by passing the input parameter, the request hits the databse and returning the response fine. Attached the WSDL file and SOAP request and response.

I got two questions,

The 3rd Party system is asking for an API documentation and SOAP Envelope. What should I give?

The 3rd party system has to invoke my service by passing the input parameter sQuoteRef. How would they usually do it? I'm not concerned about the client code here but how would the request from 3rd party look like and what changes I should make in my WSDL or Java classes to receive the input parameter and pass on to my service class?

Any inputs would be helpful in completing my task. Many Thanks!

WSDL File

    <?xml version="1.0" encoding="UTF-8"?><wsdl:definitions name="EmpService" targetNamespace="http://emp.provider.integration.gi.sample.ie/EmpService/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://Emp.provider.integration.gi.sample.ie/EmpService/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <wsdl:types>
        <xsd:schema targetNamespace="http://Emp.provider.integration.gi.sample.ie/EmpService/">

          <xsd:element name="EmpRequestVO">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element maxOccurs="1" minOccurs="1" name="sQuoteRef" type="xsd:string"/>
              </xsd:sequence>
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="EmpResponseVO">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element maxOccurs="1" minOccurs="0" name="sQuoteStatus" type="xsd:string"/>
              </xsd:sequence>
            </xsd:complexType>
          </xsd:element>
        </xsd:schema>
      </wsdl:types>

      <wsdl:message name="GetEmpTransactionSoapIn">
        <wsdl:part element="tns:EmpRequestVO" name="parameters"/>
      </wsdl:message>
      <wsdl:message name="GetEmpTransactionSoapOut">
        <wsdl:part element="tns:EmpResponseVO" name="parameters"/>
      </wsdl:message>

      <wsdl:portType name="EmpServiceSoap">
        <wsdl:operation name="getEmpTransaction">
          <wsdl:input message="tns:GetEmpTransactionSoapIn"/>
          <wsdl:output message="tns:GetEmpTransactionSoapOut"/>
        </wsdl:operation>
      </wsdl:portType>

      <wsdl:binding name="EmpServiceSoap" type="tns:EmpServiceSoap">
        <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
        <wsdl:operation name="getEmpTransaction">
          <soap:operation soapAction="getEmpTransaction" style="document"/>
          <wsdl:input>
            <soap:body use="literal"/>
          </wsdl:input>
          <wsdl:output>
            <soap:body use="literal"/>
          </wsdl:output>
        </wsdl:operation>
      </wsdl:binding>

      <wsdl:service name="PLUSEmpServices">
        <wsdl:port binding="tns:EmpServiceSoap" name="EmpServiceSOAP">
          <soap:address location="http://localhost:9080/WebServices/services/EmpServiceSOAP"/>
        </wsdl:port>
      </wsdl:service>
    </wsdl:definitions>

End Point URL
http://localhost:9080/PLUSEmpServices/services/EmpServiceSOAP

SOAP REQUEST in SOAP UI

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:rtw="http://emp.provider.integration.gi.sample.ie/EmpService/">
   <soapenv:Header/>
   <soapenv:Body>
      <rtw:EmpRequestVO>
         <sQuoteRef>12123118</sQuoteRef>
      </rtw:EmpRequestVO>
   </soapenv:Body>
</soapenv:Envelope>

SOAP RESPONSE in SOAP UI
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:Header/>
   <soapenv:Body>
      <p900:EmpResponseVO xmlns:p900="http://emp.provider.integration.gi.sample.ie/EmpService/">
         <sQuoteStatus>Active</sQuoteStatus>
      </p900:EmpResponseVO>
   </soapenv:Body>
</soapenv:Envelope>


问:
How to store post values of page 1 form in database when user submits in page 2?
There are two pages. IN page 1 user enters a number and accordingly the data is fetched from db. In page 2 the user performs some action on data and presses submit in page2 then the id or the value submitted by the user in the first page is to be stored with data changed in page 2.I should store the changed data i page 2 with id in page1. I am unable to store the input of page one. I am new to php. Here is the code

Page 1:

```<code><form name="VAL" action="ty.php" method="POST">
<?php
echo  "<input type=\"number\" name=\"j\" value=\"j\"class=\"input\" min=\"1\" max =\"2000\">
echo  "<input type=\"submit\" name=\"submit1\" value=\"choice1\"class=\"button\">

?>
</code>```

Page 2:

```<code><?php
 $ytr=$_post['j'];//The value of number entered by user in page 1 this is not saving in db
  $wer=$_POST['hi'];
 if($_SERVER['REQUEST_METHOD'] == 'POST'&& $_POST['submit2']=='choice2')
 {
 $con = mysql_connect("localhost","root","");

 if (!$con){
      die('Could not connect: ' . mysql_error());
 }

mysql_select_db("ram", $con);
$sqlCmd = sprintf("INSERT INTO outp (tweet,Mtweet) VALUES ('%s','%s')",
    mysql_real_escape_string($ytr),
    mysql_real_escape_string($wer));
mysql_query($sqlCmd);
mysql_close($con);
    }
?>`
</code>```

答: You can use  SESSION variable of php which stores data which is accessible throughout the application.</p>

Body:
There are two pages. IN page 1 user enters a number and accordingly the data is fetched from db. In page 2 the user performs some action on data and presses submit in page2 then the id or the value submitted by the user in the first page is to be stored with data changed in page 2.I should store the changed data i page 2 with id in page1. I am unable to store the input of page one. I am new to php. Here is the code

Page 1:

<form name="VAL" action="ty.php" method="POST">
<?php
echo  "<input type=\"number\" name=\"j\" value=\"j\"class=\"input\" min=\"1\" max =\"2000\">
echo  "<input type=\"submit\" name=\"submit1\" value=\"choice1\"class=\"button\">

?>

Page 2:

<?php
 $ytr=$_post['j'];//The value of number entered by user in page 1 this is not saving in db
  $wer=$_POST['hi'];
 if($_SERVER['REQUEST_METHOD'] == 'POST'&& $_POST['submit2']=='choice2')
 {
 $con = mysql_connect("localhost","root","");

 if (!$con){
      die('Could not connect: ' . mysql_error());
 }

mysql_select_db("ram", $con);
$sqlCmd = sprintf("INSERT INTO outp (tweet,Mtweet) VALUES ('%s','%s')",
    mysql_real_escape_string($ytr),
    mysql_real_escape_string($wer));
mysql_query($sqlCmd);
mysql_close($con);
    }
?>`


问:
Loop for this particular summation
Given a pattern... (1 / 2)^2 + (2 / 3)^2 + (3 / 4)^2 + ...

Input is n; which becomes the highest denominator used in the summation of these fractions.

When a user enters n = 2; the sum is simply (1 / 2)^2.

When a user enters n = 3; the sum is (1 / 2)^2 + (2 / 3)^2

I believe I've solved this problem (we assume the user enters an integer greater than or equal to 2)...

```<code>int n;
double sum = 0, counter = 2;

n = console.nextInt();

while(counter <= n) {
sum = sum + Math.pow(--counter/++counter, 2);
counter++;
}

System.out.println("Sum is " + sum);
</code>```

Is there any "obvious" way to simplify my solution to this problem (whilst remaining as a while-loop)? This is one of the first loops I've ever written. I'm not sure if less variables can be used to solve this problem.

答:
Try</p>

```<code>int n;
double sum = 0, counter=1;

n = console.nextInt();

   while((counter+1) <= n) {
    sum = sum + Math.pow(counter/(counter+1), 2);
    counter++;
    }

System.out.println("Sum is " + sum);
</code>```

Title: Loop for this particular summation

Body:
Given a pattern... (1 / 2)^2 + (2 / 3)^2 + (3 / 4)^2 + ...

Input is n; which becomes the highest denominator used in the summation of these fractions.

When a user enters n = 2; the sum is simply (1 / 2)^2.

When a user enters n = 3; the sum is (1 / 2)^2 + (2 / 3)^2

I believe I've solved this problem (we assume the user enters an integer greater than or equal to 2)...

int n;
double sum = 0, counter = 2;

n = console.nextInt();

while(counter <= n) {
sum = sum + Math.pow(--counter/++counter, 2);
counter++;
}

System.out.println("Sum is " + sum);

Is there any "obvious" way to simplify my solution to this problem (whilst remaining as a while-loop)? This is one of the first loops I've ever written. I'm not sure if less variables can be used to solve this problem.

Body:
Try

int n;
double sum = 0, counter=1;

n = console.nextInt();

   while((counter+1) <= n) {
    sum = sum + Math.pow(counter/(counter+1), 2);
    counter++;
    }

System.out.println("Sum is " + sum);


问:
How to handle Empty PFFile objects (Parse backend, Swift)
I have a list of users stored on Parse (backend), with a column called "profile_picture" that stores the user's profile picture. However, there are certain users without a profile picture, thus their profile_picture column is "undefined" (has no value).

I am using a searchbar to query through all the users and update the tableview with the user's profile pic and username. I do this by appending the username to var searchResults = String , and the profile pic to var searchImages = PFFile after the query like so:

```<code>            let query = PFQuery.orQuery(withSubqueries: [usernameQuery!,fbUsername!, firstnameQuery!, lastnameQuery!]);

        searchActive = true;

        query.findObjectsInBackground { (objects, error) in

            if error != nil {

                print("There was an error getting userlist");

            }

            else {

                if let users = objects {

                    self.searchResults.removeAll(keepingCapacity: false);

                    for object in users {

                        if let user = object.object(forKey: "username") as? String {

                            self.searchResults.append(user);
                        }

                        if let picture = object.object(forKey: "profile_picture") as? PFFile {

                            self.searchImages.append(picture);

                        }

                        self.searchTableView.reloadData();

                    }
</code>```

The problem is that when the "profile_picture" column is empty, it does not append anything, which then means that the searchResults array (containing usernames) and the searchImages array (containing the PFFiles) have different sizes, which results in uncoordinated assignments of values. They are supposed to parallel arrays. And I'm using values in these arrays to assign values in a table cell.

Hope you guys understand my problem! Thanks in advance

答:
So your username field is definitely not empty. I think you can add an else after you check whether profile_picture is nil or not. Like:

```<code>if let picture = object.object(forKey: "profile_picture") as? PFFile {
    self.searchImages.append(picture);
} else {
    self.searchImages.append(UIImage(named:"placeholder"))
}
</code>```

Body:
I have a list of users stored on Parse (backend), with a column called "profile_picture" that stores the user's profile picture. However, there are certain users without a profile picture, thus their profile_picture column is "undefined" (has no value).

I am using a searchbar to query through all the users and update the tableview with the user's profile pic and username. I do this by appending the username to var searchResults = String , and the profile pic to var searchImages = PFFile after the query like so:

            let query = PFQuery.orQuery(withSubqueries: [usernameQuery!,fbUsername!, firstnameQuery!, lastnameQuery!]);

        searchActive = true;

        query.findObjectsInBackground { (objects, error) in

            if error != nil {

                print("There was an error getting userlist");

            }

            else {

                if let users = objects {

                    self.searchResults.removeAll(keepingCapacity: false);

                    for object in users {

                        if let user = object.object(forKey: "username") as? String {

                            self.searchResults.append(user);
                        }

                        if let picture = object.object(forKey: "profile_picture") as? PFFile {

                            self.searchImages.append(picture);

                        }

                        self.searchTableView.reloadData();

                    }

The problem is that when the "profile_picture" column is empty, it does not append anything, which then means that the searchResults array (containing usernames) and the searchImages array (containing the PFFiles) have different sizes, which results in uncoordinated assignments of values. They are supposed to parallel arrays. And I'm using values in these arrays to assign values in a table cell.

Hope you guys understand my problem! Thanks in advance

Body:
So your username field is definitely not empty. I think you can add an else after you check whether profile_picture is nil or not. Like:

if let picture = object.object(forKey: "profile_picture") as? PFFile {
    self.searchImages.append(picture);
} else {
    self.searchImages.append(UIImage(named:"placeholder"))
}


问:
Complex List Comprehension slower than straight loop
I saw an interesting solution for a programming exercise on leetcode  It's not even about the problem/solution itself, so you can read it up on the link provided if you wish. However a high voted solution is this one liner:

Snippet 1

```<code>def fizzBuzz2(n):
    return  ["Fizz" * (not i%3) + "Buzz" * (not i%5) or str(i) for i in range(1, n+1)]
</code>```

Snippet 2

```<code>def fizzBuzz(n):
    out = []
    for i in range(1, n+1):
        if i % 3 == 0 and i % 5 == 0:
            out.append("FizzBuzz")
        elif i % 3 == 0:
            out.append("Fizz")
        elif i % 5 == 0:
            out.append("Buzz")
        else:
            out.append(str(i))

    return out
</code>```

However, I've expected that the list comprehension is going to beat the common loop, but when I've timed it and it wasn't the case. Even doing a dis, Snippet 2 has more instructions.

What is making Snippet 1 slow?

答:
A lot of people already answered your question, but I want to add that there are still faster solutions. To me it seems wrong to test the numbers in hindsight, although you already know at which places "Fizz", "Buzz" and "FizzBuzz" will occur. Try this instead:

```<code>def fizz_buzz(n):
    result = []
    for i in range(1, n + 1, 15):
        result += [str(i), str(i + 1), 'Fizz',
                   str(i + 3), 'Buzz', 'Fizz',
                   str(i + 6), str(i + 7), 'Fizz', 'Buzz',
                   str(i + 10), 'Fizz', str(i + 12), str(i + 13),
                   'FizzBuzz']
    return result[:n - len(result)]

start_time = time()
for i in range(10000):
    fizz_buzz(1000)
print("fizz_buzz:", time() - start_time)
</code>```

Compared to the previous answers:

```<code>your comp: 3.3942723274230957
my listcomp: 2.586350202560425
classical: 3.879168748855591
fizz_buzz: 1.6374053955078125
</code>```

Body:
I saw an interesting solution for a programming exercise on leetcode  It's not even about the problem/solution itself, so you can read it up on the link provided if you wish. However a high voted solution is this one liner:

Snippet 1

def fizzBuzz2(n):
    return  ["Fizz" * (not i%3) + "Buzz" * (not i%5) or str(i) for i in range(1, n+1)]

Snippet 2

def fizzBuzz(n):
    out = []
    for i in range(1, n+1):
        if i % 3 == 0 and i % 5 == 0:
            out.append("FizzBuzz")
        elif i % 3 == 0:
            out.append("Fizz")
        elif i % 5 == 0:
            out.append("Buzz")
        else:
            out.append(str(i))

    return out

However, I've expected that the list comprehension is going to beat the common loop, but when I've timed it and it wasn't the case. Even doing a dis, Snippet 2 has more instructions.

What is making Snippet 1 slow?

Body:
A lot of people already answered your question, but I want to add that there are still faster solutions. To me it seems wrong to test the numbers in hindsight, although you already know at which places "Fizz", "Buzz" and "FizzBuzz" will occur. Try this instead:

def fizz_buzz(n):
    result = []
    for i in range(1, n + 1, 15):
        result += [str(i), str(i + 1), 'Fizz',
                   str(i + 3), 'Buzz', 'Fizz',
                   str(i + 6), str(i + 7), 'Fizz', 'Buzz',
                   str(i + 10), 'Fizz', str(i + 12), str(i + 13),
                   'FizzBuzz']
    return result[:n - len(result)]

start_time = time()
for i in range(10000):
    fizz_buzz(1000)
print("fizz_buzz:", time() - start_time)

Compared to the previous answers:

your comp: 3.3942723274230957
my listcomp: 2.586350202560425
classical: 3.879168748855591
fizz_buzz: 1.6374053955078125


问:
please explain me. 'Plugin with id not found', 'Android NDK undefined modules'
I downloaded 'Tess-two' library.
After project was ndk-builded&ant release in cmd, I import library in my project.

here was one error.

```<code>'Plugin with id 'com.github.dcendents.android-maven' not found.'
</code>```

I had solved, just add 2 line in my app module gradle.
-like this

```<code>classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'
classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3'
</code>```

The error was completely solved, however another error appeared.

```<code>C:/android-ndk-r14/build//../build/core/build-binary.mk:687: Android NDK: Module
 pngt depends on undefined modules: z
C:/android-ndk-r14/build//../build/core/build-binary.mk:700: *** Android NDK: Ab
orting (set APP_ALLOW_MISSING_DEPS=true to allow missing dependencies).Stop.
</code>```

At this time, I just added one line in tess-two\jni\Application.mk.

```<code>APP_ALLOW_MISSING_DEPS=true
</code>```

Now, my project can build very well.
But I can't understand what I did.

Somebody please explain to me. What mean that error and how that codes could solve that error.

答:
Module builds will now fail if they have any missing dependencies.
https://github.com/android-ndk/ndk/wiki/Changelog-r14-beta1</p>

Body:
I downloaded 'Tess-two' library.
After project was ndk-builded&ant release in cmd, I import library in my project.

here was one error.

'Plugin with id 'com.github.dcendents.android-maven' not found.'

I had solved, just add 2 line in my app module gradle.
-like this

classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'
classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3'

The error was completely solved, however another error appeared.

C:/android-ndk-r14/build//../build/core/build-binary.mk:687: Android NDK: Module
 pngt depends on undefined modules: z
C:/android-ndk-r14/build//../build/core/build-binary.mk:700: *** Android NDK: Ab
orting (set APP_ALLOW_MISSING_DEPS=true to allow missing dependencies).Stop.

At this time, I just added one line in tess-two\jni\Application.mk.

APP_ALLOW_MISSING_DEPS=true

Now, my project can build very well.
But I can't understand what I did.

Somebody please explain to me. What mean that error and how that codes could solve that error.


问:
jQuery 101 - Change CSS not working with advanced selectors
This is across IE and Firefox.

I have an unordered list of 5 items within li tags.

```<code><script type="text/javascript">
$(function() //when doc is ready
    {
                $("li:first").css('color', 'red');

    });

</script>
</code>```

That does absolutely nothing, however if I leave out the :first part, it makes all li's red, unsure of why since I'm following a tutorial.

Here is the html:

```<code><div id="container">
<script type="text/javascript"><!--
$(function() //when doc is ready
{
    $("li:first").css('color', 'red');
});//--></script>

<div id="leftcontent">
<center><img src="http://www.dmu.com/5f/images/thiszis.png"></center>
<div id="hoastdears">
<ul>

<li>item1</li>
<li>item2</li>
<li>item3</li>
<li>item4</li>
<li>item5</li>
</ul>
</code>```

With

in the header.

答:
Try this

```<code>$(document).ready(function(){
        $("li:first").css('color', 'red');
});
</code>```

Here is a link to the jQuery API http://api.jquery.com/ready/

Body:
This is across IE and Firefox.

I have an unordered list of 5 items within li tags.

That does absolutely nothing, however if I leave out the :first part, it makes all li's red, unsure of why since I'm following a tutorial.

Here is the html:

item1

item2

item3

item4

item5

With

in the header.

Body:
Try this

$(document).ready(function(){
        $("li:first").css('color', 'red');
});

Here is a link to the jQuery API http://api.jquery.com/ready/


问:
CSS - Applying a gradient to a sloped body
Is it possible to apply a vertical linear gradient to the resulting shape for html tag body using only CSS?

Thank you very much in advance..

答:
    .grad2 {
        height: 100px;
        background: linear-gradient(135deg, rgba(18,18,18,1) 0%, rgba(28,28,28,1) 9%, rgba(43,43,43,1) 24%, rgba(18,18,18,1) 40%, rgba(0,0,0,1) 49%, rgba(43,43,43,1) 50%, rgba(71,71,71,1) 61%, rgba(102,102,102,1) 75%, rgba(89,89,89,1) 88%, rgba(77,77,77,1) 100%);
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div class="grad2"></div></code>```

Check this tool, it will help you very much: http://www.cssmatic.com/gradient-generator#

Body:
    .grad2 {
        height: 100px;
        background: linear-gradient(135deg, rgba(18,18,18,1) 0%, rgba(28,28,28,1) 9%, rgba(43,43,43,1) 24%, rgba(18,18,18,1) 40%, rgba(0,0,0,1) 49%, rgba(43,43,43,1) 50%, rgba(71,71,71,1) 61%, rgba(102,102,102,1) 75%, rgba(89,89,89,1) 88%, rgba(77,77,77,1) 100%);
    }

    <div class="grad2"></div>

Check this tool, it will help you very much: http://www.cssmatic.com/gradient-generator#


问:
android studio sdk v23 webview get geolocation
yet another question regarding this issue.  Sorry to be redundant, but I've looked everwhere and still I can't get this to work.  My webpage navigator.geolocation function returns this error: The application does not have sufficient geolocation permissions.  It doesn't ever ask the user if they'll allow permission.  Everything works in different browsers on my desktop (chrome, ff, safari, ie 10 +).

I'm running an emulator in android studio... the phone type is a nexus 5 api 23 (android 6.0).

Here's the hodgpodge of code I have for this by now:

//my mainActivity.java file:

```<code>  @Override
   protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mWebView = (WebView) findViewById(R.id.activity_main_webview);
    WebSettings mWebSettings = mWebView.getSettings();
    mWebSettings.setJavaScriptEnabled(true);
    String userAgent = mWebView.getSettings().getUserAgentString() ;
    mWebSettings.setUserAgentString(userAgent);

    mWebSettings.setBuiltInZoomControls(true);
    mWebSettings.setAppCacheEnabled(true);
    mWebSettings.setDatabaseEnabled(true);
    mWebSettings.setDomStorageEnabled(true);
    mWebSettings.setAllowFileAccess(true);
    mWebSettings.setAllowContentAccess(true);
    mWebSettings.setGeolocationEnabled(true);
    mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

    mWebView.clearCache(true);
    mWebView.clearHistory();
    mWebView.clearView();
    mWebView.loadUrl("https://mywebsite.com");

    mWebView.setWebChromeClient(new WebChromeClient()
    {
        @Override
        public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
        }

etc...
</code>```

//my android manifest file:

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.CAMERA"></uses-permission>
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
</code>```

I'm stuck stuck stuck.  Starting to wonder if this is even possible... how to people get this to work?!?!?!?

答:
Assuming you use AppCompatActivity, not plain activity, this does the trick:

```<code>@Override
   protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
//your code
        ActivityCompat.requestPermissions(getActivity(), new String[]{
                android.Manifest.permission.ACCESS_COARSE_LOCATION,
                android.Manifest.permission.ACCESS_FINE_LOCATION
        }, 0);
//your code
}
</code>```

Starting from Android 6, API level 23, permission handling has changed. You should ask permission for critical functionalities (like location) from user explicitly in runtime.

Body:
yet another question regarding this issue.  Sorry to be redundant, but I've looked everwhere and still I can't get this to work.  My webpage navigator.geolocation function returns this error: The application does not have sufficient geolocation permissions.  It doesn't ever ask the user if they'll allow permission.  Everything works in different browsers on my desktop (chrome, ff, safari, ie 10 +).

I'm running an emulator in android studio... the phone type is a nexus 5 api 23 (android 6.0).

Here's the hodgpodge of code I have for this by now:

//my mainActivity.java file:

  @Override
   protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mWebView = (WebView) findViewById(R.id.activity_main_webview);
    WebSettings mWebSettings = mWebView.getSettings();
    mWebSettings.setJavaScriptEnabled(true);
    String userAgent = mWebView.getSettings().getUserAgentString() ;
    mWebSettings.setUserAgentString(userAgent);

    mWebSettings.setBuiltInZoomControls(true);
    mWebSettings.setAppCacheEnabled(true);
    mWebSettings.setDatabaseEnabled(true);
    mWebSettings.setDomStorageEnabled(true);
    mWebSettings.setAllowFileAccess(true);
    mWebSettings.setAllowContentAccess(true);
    mWebSettings.setGeolocationEnabled(true);
    mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

    mWebView.clearCache(true);
    mWebView.clearHistory();
    mWebView.clearView();
    mWebView.loadUrl("https://mywebsite.com");

    mWebView.setWebChromeClient(new WebChromeClient()
    {
        @Override
        public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
        }

etc...

//my android manifest file:

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.CAMERA"></uses-permission>
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

I'm stuck stuck stuck.  Starting to wonder if this is even possible... how to people get this to work?!?!?!?

Body:
Assuming you use AppCompatActivity, not plain activity, this does the trick:

@Override
   protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
//your code
        ActivityCompat.requestPermissions(getActivity(), new String[]{
                android.Manifest.permission.ACCESS_COARSE_LOCATION,
                android.Manifest.permission.ACCESS_FINE_LOCATION
        }, 0);
//your code
}

Starting from Android 6, API level 23, permission handling has changed. You should ask permission for critical functionalities (like location) from user explicitly in runtime.


问:
QWebSocketServer won't accept SSL connections from Windows Firefox
I have a Qt application that runs a QWebSocketServer in secure mode (SSL) with certificates from Letsencrypt. Everything works fine when I connect from Chrome or Edge on my Windows 10 machine.

I'm using this facility for testing: https://www.websocket.org/echo.html

But it doesn't work when I connect from Firefox in Windows 10. However, it does work when connecting from Firefox running on Linux in VMware on the same machine. When it doesn't work, I mean that none of the callbacks of QWebSocketServer gets called: neither newConnection, nor acceptError, peerVerifyError, sslErrors, or serverError (I implemented all these callbacks to try to debug it). Also, on the websocket side, I get some error message after a few seconds:

```<code>ERROR: undefined
DISCONNECTED
</code>```

I also tried to connect from my Windows 10 machine from a different network location. And it worked! But only for a while. After several trials, it failed repeatedly and systematically.

Also, I tried from a different Windows 10 machine and it worked. But again, only for a few trials and afterwards it failed repeatedly and systematically.

I tried the following with no success:

clear the Firefox cache.

uninstall and re-install Firefox (I'm using version 52).

run Firefox Developer Edition.

run Firefox from a different user account.

restart the server machine (Ubuntu 16.04).

restart the client machines (Windows 10).

When I remove the Secure mode in my QWebSocketServer everything works with non-secure WebSockets.

On the server machine, tcptrack displays the Firefox connection, as "ESTABLISHED", but QWebSocketServer apparently receives nothing (no callback method gets called).

It seems QWebSocketServer is receiving the connection request, but failing to answer and to call any error callback method (via Qt signals).

I am running out of ideas to understand what's the problem.

What could I try next?

答: Answering my own question: the issue was indeed a bug in Qt 5.8.0 as reported here: bugreports.qt.io/browse/QTBUG-57665. The fix proposed in the discussion of this bug report actually fixed the problem.</p>

Body:
I have a Qt application that runs a QWebSocketServer in secure mode (SSL) with certificates from Letsencrypt. Everything works fine when I connect from Chrome or Edge on my Windows 10 machine.

I'm using this facility for testing: https://www.websocket.org/echo.html

But it doesn't work when I connect from Firefox in Windows 10. However, it does work when connecting from Firefox running on Linux in VMware on the same machine. When it doesn't work, I mean that none of the callbacks of QWebSocketServer gets called: neither newConnection, nor acceptError, peerVerifyError, sslErrors, or serverError (I implemented all these callbacks to try to debug it). Also, on the websocket side, I get some error message after a few seconds:

ERROR: undefined
DISCONNECTED

I also tried to connect from my Windows 10 machine from a different network location. And it worked! But only for a while. After several trials, it failed repeatedly and systematically.

Also, I tried from a different Windows 10 machine and it worked. But again, only for a few trials and afterwards it failed repeatedly and systematically.

I tried the following with no success:

clear the Firefox cache.

uninstall and re-install Firefox (I'm using version 52).

run Firefox Developer Edition.

run Firefox from a different user account.

restart the server machine (Ubuntu 16.04).

restart the client machines (Windows 10).

When I remove the Secure mode in my QWebSocketServer everything works with non-secure WebSockets.

On the server machine, tcptrack displays the Firefox connection, as "ESTABLISHED", but QWebSocketServer apparently receives nothing (no callback method gets called).

It seems QWebSocketServer is receiving the connection request, but failing to answer and to call any error callback method (via Qt signals).

I am running out of ideas to understand what's the problem.

What could I try next?


问:
Why does my original array gets changed when i only change copied array?
here i want to make duplicate array "arr" for my tile array and make some changes to it, the problem is when i make the changes (in method neighbors) it applies to the original array "tiles" too

```<code>public class Board {
    private final int [][] tiles;
    // construct a board from an n-by-n array of blocks
    // (where blocks[i][j] = block in row i, column j)
    public Board(int[][] blocks) {
        tiles = blocks;
    }// all neighboring boards
    public Iterable<Board> neighbors() {
        Queue<Board> q = new LinkedList<>();
        int [][] arr = tiles;
        // do stuff
        if (y+1 < n) {
            int t = arr[x][y];
            arr[x][y] = arr[x][y+1];
            arr[x][y+1] = t;
            Board br = new Board(arr);
            if(!this.equals(br)) {
                q.add(new Board(arr));
            }
        }
        return q;
    }
}
</code>```

thanks for your time

答:
Arrays are objects in Java. Oracle doc

And objects are not duplicated in that manner. Your variables "tiles" and "arr" are just pointing at the same array now, you haven't copied it.

To copy an array try System.arraycopy:

```<code>System.arraycopy( tiles, 0, arr, 0, tiles.length );
</code>```

See more about System copy here: https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#arraycopy(java.lang.Object,%20int,%20java.lang.Object,%20int,%20int)

Body:
here i want to make duplicate array "arr" for my tile array and make some changes to it, the problem is when i make the changes (in method neighbors) it applies to the original array "tiles" too

public class Board {
    private final int [][] tiles;
    // construct a board from an n-by-n array of blocks
    // (where blocks[i][j] = block in row i, column j)
    public Board(int[][] blocks) {
        tiles = blocks;
    }// all neighboring boards
    public Iterable<Board> neighbors() {
        Queue<Board> q = new LinkedList<>();
        int [][] arr = tiles;
        // do stuff
        if (y+1 < n) {
            int t = arr[x][y];
            arr[x][y] = arr[x][y+1];
            arr[x][y+1] = t;
            Board br = new Board(arr);
            if(!this.equals(br)) {
                q.add(new Board(arr));
            }
        }
        return q;
    }
}

thanks for your time

Body:
Arrays are objects in Java. Oracle doc

And objects are not duplicated in that manner. Your variables "tiles" and "arr" are just pointing at the same array now, you haven't copied it.

To copy an array try System.arraycopy:

System.arraycopy( tiles, 0, arr, 0, tiles.length );

See more about System copy here: https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#arraycopy(java.lang.Object,%20int,%20java.lang.Object,%20int,%20int)


问:
Browserify document is undefined
i just found browserify, which sounds really cool. However i try to append a canvas element to the body(filename : Renderer.js):

```<code>  window.document.body.appendChild(this.canvas)
  module.exports = Renderer
</code>```

And i also have a main.js

```<code>var Renderer = require("Renderer.js")
var r = new Renderer();
</code>```

So i build the bundle like this:

```<code>browserify main.js -o bundle.js
</code>```

And when i start the project:

```<code>node server.js
</code>```

I get the following error message

ReferenceError : document is not defined (if only document.body)

And window is not defined (when window.document.body)

Can someone explain this behaviour and how to fix it?

答:
Did you try to run that browserify code on the server? Please do not, as in the server there is not window element, whereas node only has global. Instead, you need to use your browser to download the browserified code and execute on your browser.

Note that, browserify library is mainly to bundle packages for client to use require styled call.

Title: Browserify document is undefined

Body:
i just found browserify, which sounds really cool. However i try to append a canvas element to the body(filename : Renderer.js):

  window.document.body.appendChild(this.canvas)
  module.exports = Renderer

And i also have a main.js

var Renderer = require("Renderer.js")
var r = new Renderer();

So i build the bundle like this:

browserify main.js -o bundle.js

And when i start the project:

node server.js

I get the following error message

ReferenceError : document is not defined (if only document.body)

And window is not defined (when window.document.body)

Can someone explain this behaviour and how to fix it?


问:
Loading JSON data into hive tables
I've tried loading simple JSON records from a file into hive tables like as shown below. Each JSON record is in a separate line.

```<code>{"Industry":"Manufacturing","Phone":null,"Id":null,"type":"Account","Name":"Manufacturing"}
{"Industry":null,"Phone":"(738) 244-5566","Id":null,"type":"Account","Name":"Sales"}
{"Industry":"Government","Phone":null,"Id":null,"type":"Account","Name":"Kansas City Brewery & Co"}
</code>```

But I couldn't find any serde to load the array of comma (,) separated JSON records into the hive table. Input is a file containing JSON records as shown below...

```<code>[{"Industry":"Manufacturing","Phone":null,"Id":null,"type":"Account","Name":"Manufacturing"},{"Industry":null,"Phone":"(738) 244-5566","Id":null,"type":"Account","Name":"Sales"},{"Industry":"Government","Phone":null,"Id":null,"type":"Account","Name":"Kansas City Brewery & Co"}]
</code>```

Can someone suggest me a serde which can parse this JSON file?

Thanks

答:
You can check this serde : https://github.com/rcongiu/Hive-JSON-Serde

Another related post : Parse json arrays using HIVE

Title: Loading JSON data into hive tables

Body:
I've tried loading simple JSON records from a file into hive tables like as shown below. Each JSON record is in a separate line.

{"Industry":"Manufacturing","Phone":null,"Id":null,"type":"Account","Name":"Manufacturing"}
{"Industry":null,"Phone":"(738) 244-5566","Id":null,"type":"Account","Name":"Sales"}
{"Industry":"Government","Phone":null,"Id":null,"type":"Account","Name":"Kansas City Brewery & Co"}

But I couldn't find any serde to load the array of comma (,) separated JSON records into the hive table. Input is a file containing JSON records as shown below...

[{"Industry":"Manufacturing","Phone":null,"Id":null,"type":"Account","Name":"Manufacturing"},{"Industry":null,"Phone":"(738) 244-5566","Id":null,"type":"Account","Name":"Sales"},{"Industry":"Government","Phone":null,"Id":null,"type":"Account","Name":"Kansas City Brewery & Co"}]

Can someone suggest me a serde which can parse this JSON file?

Thanks


问:
Comparing function of binary_search
I am trying to run binary_search on vector of custom objects.

```<code>struct T{
    string name;
    T(string n):name(n){};
    bool operator < (   T * n  ) const {
        return name < n ->  name;
    }
    bool operator == ( T * n ) const {
      return name == n -> name;
    }
};

    vector<T *> t;
    t.push_back(new T("one"));
    t.push_back(new T("two"));
    t.push_back(new T("three"));

bool has_3 = binary_search( t.begin(), t.end(), new T("two") ) ;
    if( has_3 ){
        cout <<"Its there" << endl;
    }
</code>```

The comparation function should be just fine yet when i run the code has_3 equals to 0 = the element isnt present in vector. Is this problem caused by my overloading of < ? I see no reason why this shouldnt find the value. Considering the order of insertion into vector it should be sorted

Thanks for help.

答:
There are several reasons why this shouldn't find the value:

The range must be sorted; your range is out of alphabetical order

Your comparison functionality is defined between T and T*, while you search a vector of T* for a T*.

You can fix the first problem by swapping "two" and "three", and the second problem by making a vector of T:

```<code>struct T{
    string name;
    T(string n):name(n){};
    bool operator < (   const T &n  ) const {
        return name < n.name;
    }
    // operator == is not necessary for binary_search
};
int main() {
    vector<T> t;
    t.push_back(T("one"));
    t.push_back(T("three"));
    t.push_back(T("two"));
    bool has_3 = binary_search( t.begin(), t.end(), T("two") ) ;
    if( has_3 ){
        cout <<"Its there" << endl;
    }
    return 0;
}
</code>```

Demo 1.

If you do have no way but to construct a vector of pointers, you have this ugly work-around available (I strongly recommend against it):

```<code>struct T{
    string name;
    T(string n):name(n){};
};
bool operator < (const T& l, const T *r) {
    return l.name < r->name;
}
bool operator < (const T *l, const T &r) {
    return l->name < r.name;
}
</code>```

Now you can search like this:

```<code>bool has_3 = binary_search( t.begin(), t.end(), T("two") ) ;
if( has_3 ){
    cout <<"Its there" << endl;
}
</code>```

Demo 2.

Title: Comparing function of binary_search

Body:
I am trying to run binary_search on vector of custom objects.

struct T{
    string name;
    T(string n):name(n){};
    bool operator < (   T * n  ) const {
        return name < n ->  name;
    }
    bool operator == ( T * n ) const {
      return name == n -> name;
    }
};

    vector<T *> t;
    t.push_back(new T("one"));
    t.push_back(new T("two"));
    t.push_back(new T("three"));

bool has_3 = binary_search( t.begin(), t.end(), new T("two") ) ;
    if( has_3 ){
        cout <<"Its there" << endl;
    }

The comparation function should be just fine yet when i run the code has_3 equals to 0 = the element isnt present in vector. Is this problem caused by my overloading of < ? I see no reason why this shouldnt find the value. Considering the order of insertion into vector it should be sorted

Thanks for help.

Body:
There are several reasons why this shouldn't find the value:

The range must be sorted; your range is out of alphabetical order

Your comparison functionality is defined between T and T*, while you search a vector of T* for a T*.

You can fix the first problem by swapping "two" and "three", and the second problem by making a vector of T:

struct T{
    string name;
    T(string n):name(n){};
    bool operator < (   const T &n  ) const {
        return name < n.name;
    }
    // operator == is not necessary for binary_search
};
int main() {
    vector<T> t;
    t.push_back(T("one"));
    t.push_back(T("three"));
    t.push_back(T("two"));
    bool has_3 = binary_search( t.begin(), t.end(), T("two") ) ;
    if( has_3 ){
        cout <<"Its there" << endl;
    }
    return 0;
}

Demo 1.

If you do have no way but to construct a vector of pointers, you have this ugly work-around available (I strongly recommend against it):

struct T{
    string name;
    T(string n):name(n){};
};
bool operator < (const T& l, const T *r) {
    return l.name < r->name;
}
bool operator < (const T *l, const T &r) {
    return l->name < r.name;
}

Now you can search like this:

bool has_3 = binary_search( t.begin(), t.end(), T("two") ) ;
if( has_3 ){
    cout <<"Its there" << endl;
}

Demo 2.


问:
Sending UDP from one computer to another in python
I have a pretty standard simple demo for udp packets but I get an error when trying to send to another IP address and I don't really understand why.

socketerror: [Errno 22] Invalid argument

The code that I thought would work is basically....

Server

```<code>def Main():
    host = '0.0.0.0'
    port = 20030

    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind((host,port))

    #Then it prints incoming data and sends it back to client.
    data,addr = s.recvfrom(1024)
    s.close()
</code>```

Client

```<code>def Main():
    host = '127.0.0.1'
    port = 20020

    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind((host,port))
    server = ('10.20.64.115', 20030)

    #loop for input to send to server.
    s.sendto(message, server)
    s.close()
</code>```

If I run them both on the same computer and host = 127.0.0.1 on both, both are bound to 127.0.0.1 and s.sendto(message, server) is sending to 127.0.0.1 they can send messages back and for without problems.

If I run them on different computers I believe I'm supposed to use the client to sendto the IP address of the server's IP address but I get the [Errno 22].

So I tried binding the client to 192.0.0.1 that gave an [Errno 99] cannot assign requested address.

I tried binding the client to 0.0.0.0 and the sendto address to 10.20.64.115 but the client just returns to a new line and the server doesn't see anything.

All the tutorials say to bind and sendto 127.0.0.1 so I set both computers to that and it also doesn't show up in the server.

So I'm all confused now. Correct any misunderstandings...

bind(ip address you want to listen to, port you want to listen to)

sendto(message, ip address you want to send to, port you want to send to)

0.0.0.0 is listening to everything.

192.0.0.1 is listening to the router.

127.0.0.1 is listening to just the computer.

If so what ip address do I need to sendto to avoid an errno 22 and successfully send the message to the server? Or am I missing something with the sockets?

答:
bind(ip address you want to listen to, port you want to listen to)

While sending UDP packets, on the client side, it does not require bind() to attach its socket to an address, you can directly use sendto() and recvfrom() to send and receive messages from the server. Refer here for more details

Body:
I have a pretty standard simple demo for udp packets but I get an error when trying to send to another IP address and I don't really understand why.

socketerror: [Errno 22] Invalid argument

The code that I thought would work is basically....

Server

def Main():
    host = '0.0.0.0'
    port = 20030

    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind((host,port))

    #Then it prints incoming data and sends it back to client.
    data,addr = s.recvfrom(1024)
    s.close()

Client

def Main():
    host = '127.0.0.1'
    port = 20020

    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind((host,port))
    server = ('10.20.64.115', 20030)

    #loop for input to send to server.
    s.sendto(message, server)
    s.close()

If I run them both on the same computer and host = 127.0.0.1 on both, both are bound to 127.0.0.1 and s.sendto(message, server) is sending to 127.0.0.1 they can send messages back and for without problems.

If I run them on different computers I believe I'm supposed to use the client to sendto the IP address of the server's IP address but I get the [Errno 22].

So I tried binding the client to 192.0.0.1 that gave an [Errno 99] cannot assign requested address.

I tried binding the client to 0.0.0.0 and the sendto address to 10.20.64.115 but the client just returns to a new line and the server doesn't see anything.

All the tutorials say to bind and sendto 127.0.0.1 so I set both computers to that and it also doesn't show up in the server.

So I'm all confused now. Correct any misunderstandings...

bind(ip address you want to listen to, port you want to listen to)

sendto(message, ip address you want to send to, port you want to send to)

0.0.0.0 is listening to everything.

192.0.0.1 is listening to the router.

127.0.0.1 is listening to just the computer.

If so what ip address do I need to sendto to avoid an errno 22 and successfully send the message to the server? Or am I missing something with the sockets?


问:
Hide start time in FullCalendar
On FullCalendar, in the month view, is there a way to hide an event's start time?</p>

答: Just remove allDay: false, from your fullCalendar function

Title: Hide start time in FullCalendar


问:
Using alpha from texture to draw solid color
How can I use OpenGLES 1.1 (iPhone) to draw a texture, but only using the alpha to draw some color?

The result should be the exact same alpha mask from the original texture, with a single solid color inside instead of the original colors.

I am using glDrawArrays with glCoordPointer and glVertexPointer.

I think doing two passes, one with the texture and one with a solid color to to this. I just can't seem to find the invert of glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_ALPHA);.

Edit: after some more looking around, I thinks this should be possible to achieve using glTexEnvf. It's just a matter of finding the right arguments.

答:
glBlendFunc(source_factor, dest_factor) translates to:

```<code>dest= source*source_factor + dest*dest_factor
</code>```

So glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_ALPHA) is:

```<code>dest= source*0 + dest*(1 - source.alpha)
</code>```

The second pass (which isn't the inverse) should be glBlendFunc(GL_SRC_ALPHA, GL_ONE):

```<code>dest= source*source.alpha + dest
</code>```

since you already applied the alpha mask in the first pass. Although you still need to figure out how to apply a constant color with alpha instead of the source texture.

Body:
glBlendFunc(source_factor, dest_factor) translates to:

dest= source*source_factor + dest*dest_factor

So glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_ALPHA) is:

dest= source*0 + dest*(1 - source.alpha)

The second pass (which isn't the inverse) should be glBlendFunc(GL_SRC_ALPHA, GL_ONE):

dest= source*source.alpha + dest

since you already applied the alpha mask in the first pass. Although you still need to figure out how to apply a constant color with alpha instead of the source texture.