问:
Drupal - custom module - Generate dynamic URL alias
I have a custom drupal module. I have a demo pages for different APIs I have. (Like, host.com/demo/abc or host.com/demo/bcd or host.com/demo/def ...)

hook_menu()

```<code>$items['demo/%'] = array(
        'page callback' => 'xxx',
        'page arguments' => array(1),
        'access callback' => 'xxx',
        ....
    );
</code>```

I want to change the URL to host.com/abc/demo for all the demo pages. Since I cannot a wild card at the beginning of the hook (Like %/demo) I am considering URL alias. But how can I generate url alias dynamically for all the demo pages?

答:
The best solution :
http://www.zyxware.com/articles/3636/drupal-how-to-create-url-alias-for-custom-menu-implementation-of-hook-pathauto

Otherwise :

Before you need to know that all dynamical solution available is not totally safe , take care before using it.

With url_alias you can try this, but you have to restrict by defined path to avoid flood insertion :

```<code>function mymodule_menu(){
  $items= array();
  $items['demo/%'] = array(
    'page callback' => 'xxx',
    'page arguments' => array(1),
    'access callback' => 'xxx',
    );
  return $items;
}
function mymodule_init(){
  global $language;
  $path_allowed = array(
    'abc',
    'dbe'
  ); // restrict to avoid flood
  if(arg(1) == 'demo' && in_array(arg(0), $path_allowed)) { // detect demo mode
    $path = arg(1).'/'.arg(0);
    $alias = arg(0).'/'.arg(1);
    $a = db_query('SELECT alias FROM url_alias WHERE source = :source AND alias = :alias', array(':source' => $path, ':alias' => $alias))->fetchField();
    if($a == null) ) {
      db_insert('url_alias')->fields(array(
        'source' => $path,
        'alias' => $alias,
        'language' => $language->language
      ))->execute();
    }
  }
}
</code>```

Otherwise, I'm not sure but you can try this too , you can handle it from hook_init but it can cause some issue form all module loading init

```<code>function mymodule_init(){
  if(arg(1) == 'demo') { // detect demo mode
    $mycallbacks = array( // define your callback related
      'abc' => 'mymodule_callback1',
      'dbe' => 'mymodule_callback2',
    );
    if(isset($mycallbacks[arg(0)]) && function_exists($mycallbacks[arg(0)])) { // if  callback is available
      call_user_func($mycallbacks[arg(0)]); // call it
    }
  }
}

function mymodule_callback1(){ //do what you want }
function mymodule_callback2(){ //do what you want }
</code>```

So , mysite.com/abc/demo will execute mymodule_callback1() and mysite.com/dbe/demo will execute mymodule_callback2()

Etc..

Clear all caches and see :)

Body:
I have a custom drupal module. I have a demo pages for different APIs I have. (Like, host.com/demo/abc or host.com/demo/bcd or host.com/demo/def ...)

hook_menu()

$items['demo/%'] = array(
        'page callback' => 'xxx',
        'page arguments' => array(1),
        'access callback' => 'xxx',
        ....
    );

I want to change the URL to host.com/abc/demo for all the demo pages. Since I cannot a wild card at the beginning of the hook (Like %/demo) I am considering URL alias. But how can I generate url alias dynamically for all the demo pages?

Body:
The best solution :
http://www.zyxware.com/articles/3636/drupal-how-to-create-url-alias-for-custom-menu-implementation-of-hook-pathauto

Otherwise :

Before you need to know that all dynamical solution available is not totally safe , take care before using it.

With url_alias you can try this, but you have to restrict by defined path to avoid flood insertion :

function mymodule_menu(){
  $items= array();
  $items['demo/%'] = array(
    'page callback' => 'xxx',
    'page arguments' => array(1),
    'access callback' => 'xxx',
    );
  return $items;
}
function mymodule_init(){
  global $language;
  $path_allowed = array(
    'abc',
    'dbe'
  ); // restrict to avoid flood
  if(arg(1) == 'demo' && in_array(arg(0), $path_allowed)) { // detect demo mode
    $path = arg(1).'/'.arg(0);
    $alias = arg(0).'/'.arg(1);
    $a = db_query('SELECT alias FROM url_alias WHERE source = :source AND alias = :alias', array(':source' => $path, ':alias' => $alias))->fetchField();
    if($a == null) ) {
      db_insert('url_alias')->fields(array(
        'source' => $path,
        'alias' => $alias,
        'language' => $language->language
      ))->execute();
    }
  }
}

Otherwise, I'm not sure but you can try this too , you can handle it from hook_init but it can cause some issue form all module loading init

function mymodule_init(){
  if(arg(1) == 'demo') { // detect demo mode
    $mycallbacks = array( // define your callback related
      'abc' => 'mymodule_callback1',
      'dbe' => 'mymodule_callback2',
    );
    if(isset($mycallbacks[arg(0)]) && function_exists($mycallbacks[arg(0)])) { // if  callback is available
      call_user_func($mycallbacks[arg(0)]); // call it
    }
  }
}

function mymodule_callback1(){ //do what you want }
function mymodule_callback2(){ //do what you want }

So , mysite.com/abc/demo will execute mymodule_callback1() and mysite.com/dbe/demo will execute mymodule_callback2()

Etc..

Clear all caches and see :)


来源: stackexchange

问:
linux : Finding the postgres idle process originator
Actually ,  I am running four daemon program. It makes postgres connection, and it disconnects once through with the stuffs. But When I am putting ps aux , there are lot of postgres idle process being run in my system.  I just want to know , originator of the each idle postres process.  So, that I could find out which process does not close postgres connection properly. </p>

<p>Thanks in  Advance . </p>

答:
See How can you get the active users connected to a postgreSQL database via SQL?

that can get the pid and uid of the connected processes

ContentLicense: CC BY-SA 2.5

Body:
Actually ,  I am running four daemon program. It makes postgres connection, and it disconnects once through with the stuffs. But When I am putting ps aux , there are lot of postgres idle process being run in my system.  I just want to know , originator of the each idle postres process.  So, that I could find out which process does not close postgres connection properly.

Thanks in  Advance .


问:
How does the microservice API gateway pattern work with auto Horizontal scaling?
If I would like to have a high available solution. So, I would have two API gateways in different data center.

Each API gateway is connected to three microservices like billing, users, and account services. Each one has three replica.

So is that true to have 6 copies for one microservice, and if not. How does it work?

答:
The API gateway model is a scalable solution for microservice based architectures.

You have the gateway distributed over 2 data-centres which helps provide High Availability to the gateway - you could even consider spreading it over 3 for full multi-region in the future.

If your microservices each have a replica of 3 and they are distributed into the 2 data-centres then yes you have 6 instances of that microservice running however unless you have the two data-centres sharing resources then it is 3 of each microservice in each data-centre.

ContentLicense: CC BY-SA 3.0


问:
How to enable external request in IIS Express?
How can I enable remote requests in IIS Express? Scott Guthrie wrote that is possible but he didn't say how.</p>

答:
If you're working with Visual Studio then follow these steps to access the IIS-Express over IP-Adress:

Get your host IP-Adress: ipconfig in Windows Command Line

GoTo

```<code>$(SolutionDir)\.vs\config\applicationHost.config
</code>```

Find

```<code><site name="WebApplication3" id="2">
   <application path="/" applicationPool="Clr4IntegratedAppPool">
      <virtualDirectory path="/" physicalPath="C:\Users\user.name\Source\Repos\protoype-one\WebApplication3" />
   </application>
   <bindings>
     <binding protocol="http" bindingInformation="*:62549:localhost" />
   </bindings>
</site>
</code>```

Add:
<binding protocol="http" bindingInformation="*:62549:192.168.178.108"/>

with your IP-Adress

Run your Visual Studio with Administrator rights and everything should work

See post from Andrii how to configure Firewall: here

ContentLicense: CC BY-SA 4.0

Body:
If you're working with Visual Studio then follow these steps to access the IIS-Express over IP-Adress:

Get your host IP-Adress: ipconfig in Windows Command Line

GoTo

$(SolutionDir)\.vs\config\applicationHost.config

Find

<site name="WebApplication3" id="2">
   <application path="/" applicationPool="Clr4IntegratedAppPool">
      <virtualDirectory path="/" physicalPath="C:\Users\user.name\Source\Repos\protoype-one\WebApplication3" />
   </application>
   <bindings>
     <binding protocol="http" bindingInformation="*:62549:localhost" />
   </bindings>
</site>

Add:
<binding protocol="http" bindingInformation="*:62549:192.168.178.108"/>

with your IP-Adress

Run your Visual Studio with Administrator rights and everything should work

See post from Andrii how to configure Firewall: here


问:
What is the difference between `&` and `and` in Clojure Spec?
I seem to have a hard time keeping apart the meaning of the & and and operators of Clojure Spec. They both seem to do sort of the same thing, only one is noted as a regex operator, a difference I'm not sure I understand the importance of.

答:
We can see the difference between the two if we sample some data from them:

(ns playground
  (:require [clojure.spec     :as spec]
            [clojure.spec.gen :as gen]))

(gen/generate (spec/gen (spec/and #{:a :c} #{:b :a :c})))
=> :a
(gen/sample (spec/gen (spec/and #{:a :c} #{:b :a :c})))
=> (:c :a :c :a :a :a :a :a :a :c)
```

<p>As we can see <code>spec/and</code> matches single occurrences of what matches the two predicates <code>#{:a :c}</code> and <code>#{:b :a :c}</code>.</p>

<pre class="lang-clj prettyprint-override"><code>(gen/generate (spec/gen (spec/& #{:a :c} #{:b :a :c})))
=> [:c]
(gen/sample (spec/gen (spec/& #{:a :c} #{:b :a :c})))
=> ([:c] [:a] [:a] [:c] [:c] [:c] [:c] [:a] [:c] [:c])
</code>```

spec/& on the other hand matches what's accepted by the predicates as part of a sequence.

Body:
We can see the difference between the two if we sample some data from them:

(ns playground
  (:require [clojure.spec     :as spec]
            [clojure.spec.gen :as gen]))

(gen/generate (spec/gen (spec/and #{:a :c} #{:b :a :c})))
=> :a
(gen/sample (spec/gen (spec/and #{:a :c} #{:b :a :c})))
=> (:c :a :c :a :a :a :a :a :a :c)

As we can see spec/and matches single occurrences of what matches the two predicates #{:a :c} and #{:b :a :c}.

(gen/generate (spec/gen (spec/& #{:a :c} #{:b :a :c})))
=> [:c]
(gen/sample (spec/gen (spec/& #{:a :c} #{:b :a :c})))
=> ([:c] [:a] [:a] [:c] [:c] [:c] [:c] [:a] [:c] [:c])

spec/& on the other hand matches what's accepted by the predicates as part of a sequence.


问:
Disable IntelliJ SQL Inspections not working
With IntelliJ 2017.1, with the following simple Scala file:

```<code>package demopackage

import slick.jdbc.DerbyProfile.api._

object SqlInspection {
  val query =
    sql"""
         |select my_col
         |from my_table as table_alias
      """.stripMargin
}
</code>```

I get an inspection error: unexpected 'value'.

I get the red error bar on the right scroll bar and the word table_alias has a red squiggle underline.

If I reformat the sql to a single line, the inspection error goes away.

This seems like a completely bogus inspection, so I'd like to disable.

In Preferences -> Editor -> Inspections, I have disabled absolutely everything and I still get this inspection error.

Any ideas?

答: This actually is not an inspection, but SQL parser error, because of a pipe margin characters in multiline string, so it can not be disabled via inspection settings. I've filled the IDEA-170738 request for better handling of such cases. A workaround without modifying the code is to either un-inject SQL language from the string or set highlighting level for the file to None.

Body:
With IntelliJ 2017.1, with the following simple Scala file:

package demopackage

import slick.jdbc.DerbyProfile.api._

object SqlInspection {
  val query =
    sql"""
         |select my_col
         |from my_table as table_alias
      """.stripMargin
}

I get an inspection error: unexpected 'value'.

I get the red error bar on the right scroll bar and the word table_alias has a red squiggle underline.

If I reformat the sql to a single line, the inspection error goes away.

This seems like a completely bogus inspection, so I'd like to disable.

In Preferences -> Editor -> Inspections, I have disabled absolutely everything and I still get this inspection error.

Any ideas?


问:
Is there C++ project manager like NPM?
I used to have NPM to manage my javascript project like npm init command or etc. but I'm curious about there's a C/C++ open source project manager that manage like NPM. If there is, what's name of C++ project manager?

答:
CMake is a good project build management tool, but it does not have the dependency management capabilityies NPM or Maven have. You can check out CPM, but it is not actively maintained anymore.

The Maven Nar Plugin for C/C++ projects is another option, but sadly its not very active either. See also the suggestions in the answer to a similar question regarding Maven.

Title: Is there C++ project manager like NPM?


问:
What's the difference of add methods in TensorFlow?
Three add methods:
+, tf.add, tf.nn.bias_add.
I made test in ipython, here is the test data.

```<code>a = tf.Variable([[1,2],[3,4]])
b = tf.Variable([10,20])
</code>```

All three methods returned array([[11, 22],[13, 24]], dtype=int32).
So what's the difference between them?

Thanks!

答:
From the tensorflow documentation here:

Unlike tf.add, the type of bias is allowed to differ from value in the case where both types are quantized.

tf.add is a general addition operation, while tf.nn.bias_add is to be used specifically for adding bias to the weights, which raises an exception if the dtypes aren't same.

Body:
Three add methods:
+, tf.add, tf.nn.bias_add.
I made test in ipython, here is the test data.

a = tf.Variable([[1,2],[3,4]])
b = tf.Variable([10,20])

All three methods returned array([[11, 22],[13, 24]], dtype=int32).
So what's the difference between them?

Thanks!


问:
Reading from `forkpty` child process: `ls /` output yields `EIO`
I'm trying to use forkpty to execvp a ls /, and then from the parent process read its output and write to stdout.

I got it working, and running it under Valgrind shows no errors either.

EDIT: Valgrind shows no memory errors. The last read still yields EIO under Valgrind.

However, the last read always returns -1 and sets errno to EIO. I've been researching and reading the manual pages, but I still don't understand exactly why that happens:

```<code>  EIO    I/O  error.  This will happen for example when the process is in
         a background process group, tries to read from  its  controlling
         terminal,  and  either it is ignoring or blocking SIGTTIN or its
         process group is orphaned.  It may also occur when  there  is  a
         low-level I/O error while reading from a disk or tape.
</code>```

I've also noticed that if I catch SIGCHLD signals I can know when ls has exited, but if I list a bigger directory such as /usr/bin then I get that signal for the ls child process even when there are many reads following that succeed.

Here's an example output:

```<code>$ ./a.out
bin    dev         initrd.img.old  libx32      opt   sbin  usr
boot   etc         lib             lost+found  proc  srv   var
build  home        lib32           media       root  sys   vmlinuz
core   initrd.img  lib64           mnt         run   tmp   vmlinuz.old
# read: Input/output error
</code>```

Am I missing something obvious?

```<code>#include <pty.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int main(int argc, char* argv[]) {
    int master_fd;
    pid_t child_pid = forkpty(&master_fd, NULL, NULL, NULL);

    if (child_pid == -1) {
        perror("# forkpty");
        return EXIT_FAILURE;
    }
    else if (!child_pid) { /* CHILD */
        char* ls_argv[] = {
            "ls",
            "/",
            NULL,
        };

        execvp(ls_argv[0], ls_argv);
        perror("# execvp");
        abort();
    }
    else { /* PARENT */
        uint8_t buffer[BUFSIZ];
        ssize_t read_count;

        while ((read_count = read(master_fd, buffer, BUFSIZ)) > 0) {
            uint8_t* ptr = buffer;
            size_t ptr_len = (size_t) read_count;

            while (ptr_len > 0) {
                ssize_t write_count = write(STDOUT_FILENO, ptr, ptr_len);

                if (write_count == -1) {
                    perror("# write");
                    return EXIT_FAILURE;
                }

                ptr += write_count;
                ptr_len -= write_count;
            }
        }

        if (read_count == -1) {
            perror("# read");
            return EXIT_FAILURE;
        }

        if (close(master_fd) == -1) {
            perror("# close");
            return EXIT_FAILURE;
        }

        int child_status;

        if (waitpid(child_pid, &child_status, 0) == -1) {
            perror("# waitpid");
            return EXIT_FAILURE;
        }

        if (!WIFEXITED(child_status)) {
            fprintf(stderr, "# main: subprocess did not exit normally\n");
            return EXIT_FAILURE;
        }

        return child_status;
    }
}
</code>```

答:
The pty driver calls a kernel internal function to invalidate the slave pty side, which returns EIO from then on, until the slave side is closed.  This happens always the master side is closed by the controlling process.

This process is standard in all unix variants today. It is a workaround to avoid processes to continue using the device after the master side has gone.  Even if you attach the master side again with a new process, the old slave process is blocked until it closes the open descriptor.

Body:
I'm trying to use forkpty to execvp a ls /, and then from the parent process read its output and write to stdout.

I got it working, and running it under Valgrind shows no errors either.

EDIT: Valgrind shows no memory errors. The last read still yields EIO under Valgrind.

However, the last read always returns -1 and sets errno to EIO. I've been researching and reading the manual pages, but I still don't understand exactly why that happens:

  EIO    I/O  error.  This will happen for example when the process is in
         a background process group, tries to read from  its  controlling
         terminal,  and  either it is ignoring or blocking SIGTTIN or its
         process group is orphaned.  It may also occur when  there  is  a
         low-level I/O error while reading from a disk or tape.

I've also noticed that if I catch SIGCHLD signals I can know when ls has exited, but if I list a bigger directory such as /usr/bin then I get that signal for the ls child process even when there are many reads following that succeed.

Here's an example output:

$ ./a.out
bin    dev         initrd.img.old  libx32      opt   sbin  usr
boot   etc         lib             lost+found  proc  srv   var
build  home        lib32           media       root  sys   vmlinuz
core   initrd.img  lib64           mnt         run   tmp   vmlinuz.old
# read: Input/output error

Am I missing something obvious?

#include <pty.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int main(int argc, char* argv[]) {
    int master_fd;
    pid_t child_pid = forkpty(&master_fd, NULL, NULL, NULL);

    if (child_pid == -1) {
        perror("# forkpty");
        return EXIT_FAILURE;
    }
    else if (!child_pid) { /* CHILD */
        char* ls_argv[] = {
            "ls",
            "/",
            NULL,
        };

        execvp(ls_argv[0], ls_argv);
        perror("# execvp");
        abort();
    }
    else { /* PARENT */
        uint8_t buffer[BUFSIZ];
        ssize_t read_count;

        while ((read_count = read(master_fd, buffer, BUFSIZ)) > 0) {
            uint8_t* ptr = buffer;
            size_t ptr_len = (size_t) read_count;

            while (ptr_len > 0) {
                ssize_t write_count = write(STDOUT_FILENO, ptr, ptr_len);

                if (write_count == -1) {
                    perror("# write");
                    return EXIT_FAILURE;
                }

                ptr += write_count;
                ptr_len -= write_count;
            }
        }

        if (read_count == -1) {
            perror("# read");
            return EXIT_FAILURE;
        }

        if (close(master_fd) == -1) {
            perror("# close");
            return EXIT_FAILURE;
        }

        int child_status;

        if (waitpid(child_pid, &child_status, 0) == -1) {
            perror("# waitpid");
            return EXIT_FAILURE;
        }

        if (!WIFEXITED(child_status)) {
            fprintf(stderr, "# main: subprocess did not exit normally\n");
            return EXIT_FAILURE;
        }

        return child_status;
    }
}


问:
How can we get selected text index in UITextView in IOS
I am having struggle to find out the selected text index of a UITextView. In below picture I have select some text and I am getting selected text but I want to know the that selected text index. Please give any idea. Thanks in advance.

答:
You can get the selected range from the textView and then get the index from there. The code below is not tested but pulled from my memory.</p>

```<code>let textViewRange = myTextView.selectedRange
let startIndex = textViewRange.location
let endIndex = startIndex + textViewRange.length
</code>```

Body:
You can get the selected range from the textView and then get the index from there. The code below is not tested but pulled from my memory.

let textViewRange = myTextView.selectedRange
let startIndex = textViewRange.location
let endIndex = startIndex + textViewRange.length


问:
Open excel file from process.start - filename breaking
My code is:

```<code>string Xlsx_path = @"C:\Program Files (x86)\";
System.Diagnostics.Process.Start("EXCEL.exe", "\"" + Xlsx_path + "/textexcel.xlsx" + "\"");
</code>```

but the result is

'C:\Program Files (x86)\BEB5C000' file not executable'

I guess that

'textexcel.xlsx' value change to 'BEB5C000'

but I cannot find the reason.

答:
Try this:</p>

```<code>string Xlsx_path = @"D:\Test"; // your file path
string fileName = "textexcel.xlsx";
System.Diagnostics.Process.Start(Path.Combine(Xlsx_path, fileName));
</code>```

Body:
My code is:

string Xlsx_path = @"C:\Program Files (x86)\";
System.Diagnostics.Process.Start("EXCEL.exe", "\"" + Xlsx_path + "/textexcel.xlsx" + "\"");

but the result is

'C:\Program Files (x86)\BEB5C000' file not executable'

I guess that

'textexcel.xlsx' value change to 'BEB5C000'

but I cannot find the reason.

Body:
Try this:

string Xlsx_path = @"D:\Test"; // your file path
string fileName = "textexcel.xlsx";
System.Diagnostics.Process.Start(Path.Combine(Xlsx_path, fileName));


问:
Calculate sum of dynamically adding input fields with jquery
I've a form where i am calculating sum of amounts. Rows are dynamically generated with jquery clone();

This code is calculating sum of rendered rows not the new created rows

```<code> $(document).ready(function(){

        $('.datepicker').datepicker();

        var $inst = $('.inst_amount');
            $inst_form = $('.inst_form');
            $total_amount = $('#total_amount');
            $total_price = $('#total_price');
            total = 0;

        $.each($inst, function(index, val) {
            var val = ($(this).val() == "") ? 0 : $(this).val();
            total = total + parseFloat(val);
        });
         $total_price.html(Math.round(total));
         $total_amount.val(Math.round(total));

        $(document).on('blur','.inst_amount', function(){
            var total = 0;
            $.each($inst, function(index, val) {
                var val = ($(this).val() == "") ? 0 : $(this).val();
                total = total + parseFloat(val);
            });
            console.log(total);
            $total_price.html(Math.round(total));
            $total_amount.val(Math.round(total));
        });
});
</code>```

答:
move var $inst = $('.inst_amount'); to where you use it:

var total = 0,$inst = $('.inst_amount'); - actually don't even. See my code

Use commas to separate vars

DRY - Don't Repeat Yourself

give the class correctly and add the field to a container.

function sumIt() {
  var total = 0, val;
  $('.inst_amount').each(function() {
    val = $(this).val();
    val = isNaN(val) || $.trim(val) === "" ? 0 : parseFloat(val);
    total += val;
  });
  $('#total_price').html(Math.round(total));
  $('#total_amount').val(Math.round(total));
}

$(function() {

  // $('.datepicker').datepicker(); // not needed for this test

  $("#add").on("click", function() {
    $("#container input").last()
      .before($("<input />").prop("class","inst_amount").val(0))
      .before("
");
    sumIt();
  });

  $(document).on('input', '.inst_amount', sumIt);
  sumIt() // run when loading
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="add" value="add" /><br/>
<form id="inst_form">
<div id="container">
  <input type="text" class="inst_amount" value="4" /><br/>
  <input type="text" class="inst_amount" value="" /><br/>
  <input type="text" id="total_amount" value="0" />
</form>
</div>
<span id="total_price"></span></code>```

Body:
I've a form where i am calculating sum of amounts. Rows are dynamically generated with jquery clone();

This code is calculating sum of rendered rows not the new created rows

 $(document).ready(function(){

        $('.datepicker').datepicker();

        var $inst = $('.inst_amount');
            $inst_form = $('.inst_form');
            $total_amount = $('#total_amount');
            $total_price = $('#total_price');
            total = 0;

        $.each($inst, function(index, val) {
            var val = ($(this).val() == "") ? 0 : $(this).val();
            total = total + parseFloat(val);
        });
         $total_price.html(Math.round(total));
         $total_amount.val(Math.round(total));

        $(document).on('blur','.inst_amount', function(){
            var total = 0;
            $.each($inst, function(index, val) {
                var val = ($(this).val() == "") ? 0 : $(this).val();
                total = total + parseFloat(val);
            });
            console.log(total);
            $total_price.html(Math.round(total));
            $total_amount.val(Math.round(total));
        });
});

Body:
move var $inst = $('.inst_amount'); to where you use it:

var total = 0,$inst = $('.inst_amount'); - actually don't even. See my code

Use commas to separate vars

DRY - Don't Repeat Yourself

give the class correctly and add the field to a container.

function sumIt() {
  var total = 0, val;
  $('.inst_amount').each(function() {
    val = $(this).val();
    val = isNaN(val) || $.trim(val) === "" ? 0 : parseFloat(val);
    total += val;
  });
  $('#total_price').html(Math.round(total));
  $('#total_amount').val(Math.round(total));
}

$(function() {

  // $('.datepicker').datepicker(); // not needed for this test

  $("#add").on("click", function() {
    $("#container input").last()
      .before($("<input />").prop("class","inst_amount").val(0))
      .before("<br/>");
    sumIt();
  });

  $(document).on('input', '.inst_amount', sumIt);
  sumIt() // run when loading
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="add" value="add" /><br/>
<form id="inst_form">
<div id="container">
  <input type="text" class="inst_amount" value="4" /><br/>
  <input type="text" class="inst_amount" value="" /><br/>
  <input type="text" id="total_amount" value="0" />
</form>
</div>
<span id="total_price"></span>


问:
When does timeout in stream_context_create not work?
I'm trying to extract a small amount of data from another website but I am finding that it is timing out. I've put some coding clauses in place to try and force my code to obtain data from a similar data if trying to obtain it from the first takes too long.

```<code>$ctx = stream_context_create(array('http' => array('timeout' => 2)));

$geo = json_decode(file_get_contents($url, 0, $ctx), true);
</code>```

In principle this should time out after 2 seconds and then I'll know its duff and go for the second URL. But it doesn't work, and tries to get it for 15 seconds. I've tried recplacing the $ctx with

```<code>ini_set('default_socket_timeout', 2);
</code>```

But this doesn't work either. Can anyone please suggest something else I could try?

答: In my case when the URL begins with https the timeout does not work. But when I removed the s from the end of the https it worked. If you can allow your script to use the non secure protocol your problem is solved.</p>

Body:
I'm trying to extract a small amount of data from another website but I am finding that it is timing out. I've put some coding clauses in place to try and force my code to obtain data from a similar data if trying to obtain it from the first takes too long.

$ctx = stream_context_create(array('http' => array('timeout' => 2)));

$geo = json_decode(file_get_contents($url, 0, $ctx), true);

In principle this should time out after 2 seconds and then I'll know its duff and go for the second URL. But it doesn't work, and tries to get it for 15 seconds. I've tried recplacing the $ctx with

ini_set('default_socket_timeout', 2);

But this doesn't work either. Can anyone please suggest something else I could try?


问:
Serving static files Go seems inefficient..or maybe its just me :-)
Over months I've read tons of articles about Go and best practices.  Among those articles are numerous google searches and SOF searches regarding how to and the best way to serve static files.

This is what I currently have

```<code>fs := http.FileServer(http.Dir("static/"))
myRouter.PathPrefix("/static/").Handler(http.StripPrefix("/static/", fs))

myRouter.PathPrefix("/admin/static/").Handler(http.StripPrefix("/admin/static/", fs))
myRouter.PathPrefix("/admin/accounts/static/").Handler(http.StripPrefix("/admin/accounts/static/", fs))
myRouter.PathPrefix("/admin/admin_tools/static/").Handler(http.StripPrefix("/admin/admin_tools/static/", fs))
myRouter.PathPrefix("/admin/audit_tools/static/").Handler(http.StripPrefix("/admin/audit_tools/static/", fs))
myRouter.PathPrefix("/admin/demand/static/").Handler(http.StripPrefix("/admin/demand/static/", fs))
myRouter.PathPrefix("/admin/optimization/static/").Handler(http.StripPrefix("/admin/optimization/static/", fs))
myRouter.PathPrefix("/admin/reports/static/").Handler(http.StripPrefix("/admin/reports/static/", fs))
myRouter.PathPrefix("/admin/setups/static/").Handler(http.StripPrefix("/admin/setups/static/", fs))
myRouter.PathPrefix("/admin/queue/static/").Handler(http.StripPrefix("/admin/queue/static/", fs))
myRouter.PathPrefix("/admin/tagservers/static/").Handler(http.StripPrefix("/admin/tagservers/static/", fs))
myRouter.PathPrefix("/admin/client/static/").Handler(http.StripPrefix("/admin/client/static/", fs))
myRouter.PathPrefix("/client/static/").Handler(http.StripPrefix("/client/static/", fs))
</code>```

My issue with this is that for every path I have to add a new line to cover where the static files come from.  Most examples show how it's done when you have a single landing page with no real navigations built into it. Coming from a Python background I suppose I was bit spoiled with some of the lightweight frameworks, such as Flask and Tornado, where one just points to the static folder once.

Another issue with this current setup is it doesn't play nice with NGINX.  Again with frameworks like Flask and Tornado, all you have to do in NGINX is set the static location once.  With Go I have to set the static location just like the code above (by defining each path).

Has anyone found a better way to serve static files?  I know in theory a function could probably be written to automate it, but it wouldn't really change the fact that each path has to be accounted for on the app level and NGINX level.

UPDATE: In reply to @mkopriva I've attached two screenshots.  The first is of the browser running the app with dev tools open to show the 404s on the static files. The Second is of the server code, to produce those errors all I did was comment out one line.  The line that handles the audit_tools path. If I uncomment it everything routes no problem.

Edit, both @mkopriva and @sberry did a great job. I wish I could pick two correct answers.

答:
If you are using nginx to do this work then you don't need Go to do it too (unless you want to be able to run standalone without nginx).  If that is the case then you can use a Path call instead of PathPrefix so you can do pattern matching.

If you are just trying to do this via nginx then something like this should work:

```<code>server {
    listen 8080;

    location ~* ^/static/ {
        root /path/to/directory/containing_static;
    }

    location  ~* ^.*/static/(.*)$ {
        rewrite "^.*/static/(.*)$" /static/$1 last;
    }

    location @forward_to_app {
       # send to your go app here
    }

  }
</code>```

You can probably do without the rewrite, but that was an easy approach to take.

Body:
Over months I've read tons of articles about Go and best practices.  Among those articles are numerous google searches and SOF searches regarding how to and the best way to serve static files.

This is what I currently have

fs := http.FileServer(http.Dir("static/"))
myRouter.PathPrefix("/static/").Handler(http.StripPrefix("/static/", fs))

myRouter.PathPrefix("/admin/static/").Handler(http.StripPrefix("/admin/static/", fs))
myRouter.PathPrefix("/admin/accounts/static/").Handler(http.StripPrefix("/admin/accounts/static/", fs))
myRouter.PathPrefix("/admin/admin_tools/static/").Handler(http.StripPrefix("/admin/admin_tools/static/", fs))
myRouter.PathPrefix("/admin/audit_tools/static/").Handler(http.StripPrefix("/admin/audit_tools/static/", fs))
myRouter.PathPrefix("/admin/demand/static/").Handler(http.StripPrefix("/admin/demand/static/", fs))
myRouter.PathPrefix("/admin/optimization/static/").Handler(http.StripPrefix("/admin/optimization/static/", fs))
myRouter.PathPrefix("/admin/reports/static/").Handler(http.StripPrefix("/admin/reports/static/", fs))
myRouter.PathPrefix("/admin/setups/static/").Handler(http.StripPrefix("/admin/setups/static/", fs))
myRouter.PathPrefix("/admin/queue/static/").Handler(http.StripPrefix("/admin/queue/static/", fs))
myRouter.PathPrefix("/admin/tagservers/static/").Handler(http.StripPrefix("/admin/tagservers/static/", fs))
myRouter.PathPrefix("/admin/client/static/").Handler(http.StripPrefix("/admin/client/static/", fs))
myRouter.PathPrefix("/client/static/").Handler(http.StripPrefix("/client/static/", fs))

My issue with this is that for every path I have to add a new line to cover where the static files come from.  Most examples show how it's done when you have a single landing page with no real navigations built into it. Coming from a Python background I suppose I was bit spoiled with some of the lightweight frameworks, such as Flask and Tornado, where one just points to the static folder once.

Another issue with this current setup is it doesn't play nice with NGINX.  Again with frameworks like Flask and Tornado, all you have to do in NGINX is set the static location once.  With Go I have to set the static location just like the code above (by defining each path).

Has anyone found a better way to serve static files?  I know in theory a function could probably be written to automate it, but it wouldn't really change the fact that each path has to be accounted for on the app level and NGINX level.

UPDATE: In reply to @mkopriva I've attached two screenshots.  The first is of the browser running the app with dev tools open to show the 404s on the static files. The Second is of the server code, to produce those errors all I did was comment out one line.  The line that handles the audit_tools path. If I uncomment it everything routes no problem.

Edit, both @mkopriva and @sberry did a great job. I wish I could pick two correct answers.

Body:
If you are using nginx to do this work then you don't need Go to do it too (unless you want to be able to run standalone without nginx).  If that is the case then you can use a Path call instead of PathPrefix so you can do pattern matching.

If you are just trying to do this via nginx then something like this should work:

server {
    listen 8080;

    location ~* ^/static/ {
        root /path/to/directory/containing_static;
    }

    location  ~* ^.*/static/(.*)$ {
        rewrite "^.*/static/(.*)$" /static/$1 last;
    }

    location @forward_to_app {
       # send to your go app here
    }

  }

You can probably do without the rewrite, but that was an easy approach to take.


问:
How do I detect if ActiveX is enabled in the browser of client?
How do I detect if ActiveX is enabled in the browser of client?

I tried following code, but it's not working in Firefox.

```<code>window.ActiveXObject not working in Firefox
</code>```

any ideas?

check the example here: http://jsfiddle.net/qXSvQ/2/

I get false when I run this example.

答:
Below code should work, It is working on IE6 & FF 3.6.12 atleast.</p>

```<code>if(typeof(window.ActiveXObject)=="undefined"){
    alert("ActiveX Object not supported");
}else {
    alert("ActiveX Object  supported");
}
</code>```

OwnerDisplayName: twesh

Body:
How do I detect if ActiveX is enabled in the browser of client?

I tried following code, but it's not working in Firefox.

window.ActiveXObject not working in Firefox

any ideas?

check the example here: http://jsfiddle.net/qXSvQ/2/

I get false when I run this example.

Body:
Below code should work, It is working on IE6 & FF 3.6.12 atleast.

if(typeof(window.ActiveXObject)=="undefined"){
    alert("ActiveX Object not supported");
}else {
    alert("ActiveX Object  supported");
}


问:
Getting data periodically from PostgreSQL and sent it to ActiveMQ
Basically, i've a data table in PostgreSQL.
I want to get all the data, and sent it become message to ActiveMQ (1 message for 1 row in table).

But the data table automatically updated every 5 second. So there is some new data in table for every 5 second.

How to sending the new data without double sending the data that was sent?
And i think i must use the Thread.sleep(5000) for made it endless looping?

This all i got:

```<code>package testcode;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

public class ProducerClear2 {

    public static String vardbserver;
    public static String vardbuser;
    public static String vardbpassword;
    public static String vardbname;

    public static void main (String[] args){
        vardbserver = "TestDBtoMQ";
        vardbuser = "postgresql";
        vardbpassword = "admin";

        ConnectionFactory factory = null;
        javax.jms.Connection connection = null;
        Session session = null;
        Destination destination = null;
        MessageProducer producer = null;
        Connection c = null;
        Statement stmt = null;
        try {
            Class.forName("org.postgresql.Driver");
            c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/"+vardbserver, vardbuser, vardbpassword);
            c.setAutoCommit(false);
            System.out.println("----------------------------");

            stmt = c.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM MESSAGES;");
            while (rs.next()) {
                String  message = rs.getString("MESSAGE");
                System.out.println("Message = " + message);
                try {
                    factory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_BROKER_URL);
                    connection = factory.createConnection();
                    connection.start();
                    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                    destination = session.createQueue("TestQueue");
                    producer = session.createProducer(destination);
                    TextMessage mssg = session.createTextMessage(message);
                    System.out.println("Sent: " + mssg.getText());
                    producer.send(mssg);
                }
                catch (JMSException e) {
                    e.printStackTrace();
                }
            }

            rs.close();
            stmt.close();
            c.close();

        }
        catch (Exception e) {
            System.err.println(e.getClass().getName()+": "+ e.getMessage());
        }finally {
            if (session != null) {
                try {
                    session.close();
                } catch (JMSException ex) {
                    // ignore
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (JMSException ex) {
                    // ignore
                }
            }
        }
        System.out.println("----------------------------");
        System.out.println("Message sent successfully");
    }
}
</code>```

The answer check here

答:
To prevent duplicated messages, there are some possible ways such as:

ActiveMQ supports dupplicated message detection and you can leverage this feature.

Use a field(bool) to denote that the row is sent or not.

Regarding the 5 seconds, you can sleep or use a scheduler to do that, for example: Spring Scheduler, Quartz

Body:
Basically, i've a data table in PostgreSQL.
I want to get all the data, and sent it become message to ActiveMQ (1 message for 1 row in table).

But the data table automatically updated every 5 second. So there is some new data in table for every 5 second.

How to sending the new data without double sending the data that was sent?
And i think i must use the Thread.sleep(5000) for made it endless looping?

This all i got:

package testcode;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

public class ProducerClear2 {

    public static String vardbserver;
    public static String vardbuser;
    public static String vardbpassword;
    public static String vardbname;

    public static void main (String[] args){
        vardbserver = "TestDBtoMQ";
        vardbuser = "postgresql";
        vardbpassword = "admin";

        ConnectionFactory factory = null;
        javax.jms.Connection connection = null;
        Session session = null;
        Destination destination = null;
        MessageProducer producer = null;
        Connection c = null;
        Statement stmt = null;
        try {
            Class.forName("org.postgresql.Driver");
            c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/"+vardbserver, vardbuser, vardbpassword);
            c.setAutoCommit(false);
            System.out.println("----------------------------");

            stmt = c.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM MESSAGES;");
            while (rs.next()) {
                String  message = rs.getString("MESSAGE");
                System.out.println("Message = " + message);
                try {
                    factory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_BROKER_URL);
                    connection = factory.createConnection();
                    connection.start();
                    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                    destination = session.createQueue("TestQueue");
                    producer = session.createProducer(destination);
                    TextMessage mssg = session.createTextMessage(message);
                    System.out.println("Sent: " + mssg.getText());
                    producer.send(mssg);
                }
                catch (JMSException e) {
                    e.printStackTrace();
                }
            }

            rs.close();
            stmt.close();
            c.close();

        }
        catch (Exception e) {
            System.err.println(e.getClass().getName()+": "+ e.getMessage());
        }finally {
            if (session != null) {
                try {
                    session.close();
                } catch (JMSException ex) {
                    // ignore
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (JMSException ex) {
                    // ignore
                }
            }
        }
        System.out.println("----------------------------");
        System.out.println("Message sent successfully");
    }
}

The answer check here


问:
watchTransition() is not a function in nv.d3.js with angular.js
I am trying to render a boxplot from nv.d3.js. v.1.8.5 and d3.js v.3.4.4 . I am adding the d3.js file before nv.d3.js file from the index.html .The code breaks saying boxplots.watchTransition is not a function

The following is my code

```<code>d3.selection.prototype.watchTransition = function(renderWatch){
    var args = [this].concat([].slice.call(arguments, 1));
    return renderWatch.transition.apply(renderWatch, args);
};
</code>```

And later in the code

```<code>boxplots.watchTransition(renderWatch, 'nv-boxplot: boxplots')
                .style('stroke-opacity', 1)
                .style('fill-opacity', 0.75)
                .delay(function(d,i) { return i * duration / data.length })
                .attr('transform', function(d,i) {
                    return 'translate(' + (xScale(getX(d,i)) + xScale.rangeBand() * 0.05) + ', 0)';
                });
</code>```

答:
Upgrading npm to latest version worked for me.

Use following command to upgrade npm
npm i -g npm

Body:
I am trying to render a boxplot from nv.d3.js. v.1.8.5 and d3.js v.3.4.4 . I am adding the d3.js file before nv.d3.js file from the index.html .The code breaks saying boxplots.watchTransition is not a function

The following is my code

d3.selection.prototype.watchTransition = function(renderWatch){
    var args = [this].concat([].slice.call(arguments, 1));
    return renderWatch.transition.apply(renderWatch, args);
};

And later in the code

boxplots.watchTransition(renderWatch, 'nv-boxplot: boxplots')
                .style('stroke-opacity', 1)
                .style('fill-opacity', 0.75)
                .delay(function(d,i) { return i * duration / data.length })
                .attr('transform', function(d,i) {
                    return 'translate(' + (xScale(getX(d,i)) + xScale.rangeBand() * 0.05) + ', 0)';
                });


问:
Which method is better when I want to search the min and max result in oracle?
I have a table called student,I want to get the max and min score,so I write the sql in first way:

```<code>select max(score),min(score) from student;
</code>```

and the second way:

```<code>select max(score) from student;
select min(score) from student;
</code>```

I search from the internet and they say that the second way is better because the oracle can not scan the index in the same time.But the second way can not ensure the same datasoure because it do twice searching.How to fix it?

答:
```<code>select ma,mi from
(select max(score) ma from student) a,
(select min(score) mi from student) b
</code>```

Body:
I have a table called student,I want to get the max and min score,so I write the sql in first way:

select max(score),min(score) from student;

and the second way:

select max(score) from student;
select min(score) from student;

I search from the internet and they say that the second way is better because the oracle can not scan the index in the same time.But the second way can not ensure the same datasoure because it do twice searching.How to fix it?


问:
Converting string to byte array in C# (CSV)
I wrote a function to convert byte[] to string, and I add ";" after each byte. Now I want to convert this string to byte[] by splitting the string (similar to a CSV string).

```<code>public string ByteArrayToString(byte[] byteArray,string s)
{
    for (int i = 0; i < byteArray.Length; i++)
    {
        s += byteArray[i].ToString() + ";";
    }
    s = s.Substring(0, s.Length - 1);
    return s;
}
</code>```

How could I write a function to convert this string to that byte array again?

答:
```<code>System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
return encoding.GetBytes(yourStringVariable);
</code>```

Body:
I wrote a function to convert byte[] to string, and I add ";" after each byte. Now I want to convert this string to byte[] by splitting the string (similar to a CSV string).

public string ByteArrayToString(byte[] byteArray,string s)
{
    for (int i = 0; i < byteArray.Length; i++)
    {
        s += byteArray[i].ToString() + ";";
    }
    s = s.Substring(0, s.Length - 1);
    return s;
}

How could I write a function to convert this string to that byte array again?


问:
Remove odd numbers in array
I am trying to come up with another way to remove all of the odd numbers from an array. A friend was able to come up with this solution and I understand what it does, but I am failing to find another solution to it. Do you have any ideas for another solution to do this?

JavaScript

```<code>let myArray = [1,3,5,7,9,2,4,6,8];
let it = myArray.length;

for(let i=0; i<it; i++) {
  for(let j=0; j<myArray.length; j++ )
    if(myArray[j]%2 === 1){
      myArray.splice(j,1)
      break;
    }
  };

  console.log(myArray);
</code>```

答:
Your question asks how to "remove odds", not how to "keep evens" – the result is the same in this case, but the way you derive the answer could vary. There's not always a perfect opposite function that plugs directly into Array.prototype.filter, so all answers here will be in the context of removing elements where we only a way to detect odd values – not keeping elements that are even. I'll detail a wide variety of ways to solve your problem, but first let's review your code

your friend's answer

I added a console.log on your inner loop so you can see each element you're checking. It's easy to see that this solution is doing more work than it has to - there's no need to create more than 1 loop to iterate thru your array of numbers.

let myArray = [1,3,5,7,9,2,4,6,8]
let it = myArray.length

for(let i = 0; i < it; i++) {
  for(let j = 0; j < myArray.length; j++ ) {
    console.log('checking:', myArray[j])
    if(myArray[j] % 2 === 1) {
      myArray.splice(j,1)
      break
    }
  }
}

console.log(myArray)```
</div>
</div>
</p>

<p>Also important, you need to be very mindful when changing the length of an array as you're iterating thru it. For example, if you call <code>arr.splice(i,1)</code>, what effect does that have on your loop?</p>

<ul>
<li>all elements to the right of "i" will shift left 1 place</li>
<li>the length of the array decreases by 1</li>
</ul>

<p>So how should your loop accommodate for that?</p>

<ul>
<li>if all elements shift left after a splice, that means we need to re-check the same <code>i</code> once more because it now points to a new value</li>
<li>if the length decreases by 1, we need to change the loop exit condition to stop 1 iteration sooner</li>
</ul>

<p>The <code>mutRejectOdds</code> answer below addresses these issues</p>

<hr>

<p><strong>recursive function</strong></p>

<p>highly readable and straightforward but not stack-safe</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const isOdd = x => x & 1 === 1

const removeOdds = ([x,...xs]) => {
  if (x === undefined)
    return []
  else if (isOdd(x))
    return removeOdds(xs)
  else
    return [x, ...removeOdds(xs)]
}

let data = [1,2,3,4,5,6,7,8]
console.log(removeOdds(data)) // [2,4,6,8]
console.log(data)             // [1,2,3,4,5,6,7,8]</code>```

linear iterative with accumulator

stack-safe and highly practical

const isOdd = x => x & 1 === 1

const removeOdds = xs => {
  let acc = []
  for (let x of xs)
    if (!isOdd(x))
      acc.push(x)
  return acc
}

let data = [1,2,3,4,5,6,7,8]
console.log(removeOdds(data)) // [2,4,6,8]
console.log(data)             // [1,2,3,4,5,6,7,8]```
</div>
</div>
</p>

<hr>

<p><strong>continuation passing style</strong></p>

<p>brain-twisting but super fun recursive solution that could be put on a trampoline to make stack-safe</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const isOdd = x => x & 1 === 1

const identity = x => x

const removeOdds = xs => {
  const aux = ([x,...xs], k) => {
    if (x === undefined)
      return k([])
    else if (isOdd(x))
      return aux(xs, k)
    else
      return aux(xs, acc => k([x, ...acc]))
  }
  return aux(xs, identity)
}

let data = [1,2,3,4,5,6,7,8]
console.log(removeOdds(data)) // [2,4,6,8]
console.log(data)             // [1,2,3,4,5,6,7,8]</code>```

higher-order function

similar to the recursive function, but instead accepts another argument which is a function of elements to skip - could be written in linear iterative style or continuation passing style too

const isOdd = x => x & 1 === 1

const reject = (f, [x,...xs]) => {
  if (x === undefined)
    return []
  else if (f(x))
    return reject(f, xs)
  else
    return [x, ...reject(f, xs)]
}

let data = [1,2,3,4,5,6,7,8]
console.log(reject(isOdd, data)) // [2,4,6,8]
console.log(data)                // [1,2,3,4,5,6,7,8]```
</div>
</div>
</p>

<hr>

<p><strong>function composition with Array.prototype.filter</strong></p>

<p>uses the highly practical built-in <code>Array.prototype.filter</code> but returns the opposite result using function composition with <code>not</code></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const isOdd = x => x & 1 === 1

const comp = f => g => x => f(g(x))

const not = x => !x

const reject = (f, xs) =>
  xs.filter(comp(not)(f))

let data = [1,2,3,4,5,6,7,8]
console.log(reject(isOdd, data)) // [2,4,6,8]
console.log(data)                // [1,2,3,4,5,6,7,8]</code>```

linear iterative with in-place mutation

all methods I implemented above do not mutate the original data - in some cases, if you had a particularly large array and you did not want to create a copy with odd values removed, you might wish to perform an in-place modification of data

this answer addresses the issues in your original code

const isOdd = x => x & 1 === 1

const mutRejectOdds = xs => {
  for (let i = 0, len = xs.length; i < len; i++)
    if (isOdd(xs[i]))
      (xs.splice(i,1), i--, len--)
}

let data = [1,2,3,4,5,6,7,8]
console.log(mutRejectOdds(data)) // undefined
console.log(data)                // [2,4,6,8]```

Title: Remove odd numbers in array

Body:
I am trying to come up with another way to remove all of the odd numbers from an array. A friend was able to come up with this solution and I understand what it does, but I am failing to find another solution to it. Do you have any ideas for another solution to do this?

JavaScript

let myArray = [1,3,5,7,9,2,4,6,8];
let it = myArray.length;

for(let i=0; i<it; i++) {
  for(let j=0; j<myArray.length; j++ )
    if(myArray[j]%2 === 1){
      myArray.splice(j,1)
      break;
    }
  };

  console.log(myArray);

Body:
Your question asks how to "remove odds", not how to "keep evens" – the result is the same in this case, but the way you derive the answer could vary. There's not always a perfect opposite function that plugs directly into Array.prototype.filter, so all answers here will be in the context of removing elements where we only a way to detect odd values – not keeping elements that are even. I'll detail a wide variety of ways to solve your problem, but first let's review your code

your friend's answer

I added a console.log on your inner loop so you can see each element you're checking. It's easy to see that this solution is doing more work than it has to - there's no need to create more than 1 loop to iterate thru your array of numbers.

let myArray = [1,3,5,7,9,2,4,6,8]
let it = myArray.length

for(let i = 0; i < it; i++) {
  for(let j = 0; j < myArray.length; j++ ) {
    console.log('checking:', myArray[j])
    if(myArray[j] % 2 === 1) {
      myArray.splice(j,1)
      break
    }
  }
}

console.log(myArray)

Also important, you need to be very mindful when changing the length of an array as you're iterating thru it. For example, if you call arr.splice(i,1), what effect does that have on your loop?

all elements to the right of "i" will shift left 1 place

the length of the array decreases by 1

So how should your loop accommodate for that?

if all elements shift left after a splice, that means we need to re-check the same i once more because it now points to a new value

if the length decreases by 1, we need to change the loop exit condition to stop 1 iteration sooner

The mutRejectOdds answer below addresses these issues

recursive function

highly readable and straightforward but not stack-safe

const isOdd = x => x & 1 === 1

const removeOdds = ([x,...xs]) => {
  if (x === undefined)
    return []
  else if (isOdd(x))
    return removeOdds(xs)
  else
    return [x, ...removeOdds(xs)]
}

let data = [1,2,3,4,5,6,7,8]
console.log(removeOdds(data)) // [2,4,6,8]
console.log(data)             // [1,2,3,4,5,6,7,8]

linear iterative with accumulator

stack-safe and highly practical

const isOdd = x => x & 1 === 1

const removeOdds = xs => {
  let acc = []
  for (let x of xs)
    if (!isOdd(x))
      acc.push(x)
  return acc
}

let data = [1,2,3,4,5,6,7,8]
console.log(removeOdds(data)) // [2,4,6,8]
console.log(data)             // [1,2,3,4,5,6,7,8]

continuation passing style

brain-twisting but super fun recursive solution that could be put on a trampoline to make stack-safe

const isOdd = x => x & 1 === 1

const identity = x => x

const removeOdds = xs => {
  const aux = ([x,...xs], k) => {
    if (x === undefined)
      return k([])
    else if (isOdd(x))
      return aux(xs, k)
    else
      return aux(xs, acc => k([x, ...acc]))
  }
  return aux(xs, identity)
}

let data = [1,2,3,4,5,6,7,8]
console.log(removeOdds(data)) // [2,4,6,8]
console.log(data)             // [1,2,3,4,5,6,7,8]

higher-order function

similar to the recursive function, but instead accepts another argument which is a function of elements to skip - could be written in linear iterative style or continuation passing style too

const isOdd = x => x & 1 === 1

const reject = (f, [x,...xs]) => {
  if (x === undefined)
    return []
  else if (f(x))
    return reject(f, xs)
  else
    return [x, ...reject(f, xs)]
}

let data = [1,2,3,4,5,6,7,8]
console.log(reject(isOdd, data)) // [2,4,6,8]
console.log(data)                // [1,2,3,4,5,6,7,8]

function composition with Array.prototype.filter

uses the highly practical built-in Array.prototype.filter but returns the opposite result using function composition with not

const isOdd = x => x & 1 === 1

const comp = f => g => x => f(g(x))

const not = x => !x

const reject = (f, xs) =>
  xs.filter(comp(not)(f))

let data = [1,2,3,4,5,6,7,8]
console.log(reject(isOdd, data)) // [2,4,6,8]
console.log(data)                // [1,2,3,4,5,6,7,8]

linear iterative with in-place mutation

all methods I implemented above do not mutate the original data - in some cases, if you had a particularly large array and you did not want to create a copy with odd values removed, you might wish to perform an in-place modification of data

this answer addresses the issues in your original code

const isOdd = x => x & 1 === 1

const mutRejectOdds = xs => {
  for (let i = 0, len = xs.length; i < len; i++)
    if (isOdd(xs[i]))
      (xs.splice(i,1), i--, len--)
}

let data = [1,2,3,4,5,6,7,8]
console.log(mutRejectOdds(data)) // undefined
console.log(data)                // [2,4,6,8]


问:
Jquery Ajax is neither passing data to PHP nor returning anything on success()
I am trying to pass the jquery variable to PHP with Ajax but the receiving php file is returning error " Undefined index" Code is:

```<code>  <div class="img">
    <a href="ss.php">
       <img id="theme_bg" src="images/themes/theme1.jpg">
    </a></div>

$(document).ready(function($){
    $('.img').on('click','img',function(){
        var imgsrc = $(this).attr('src');
        alert(imgsrc);       //this is returning the img src correctly
$.ajax({
    type: "POST",
    url: 'ss.php',
    dataType: 'json',
    data: {imgpath:imgsrc },
    success: function(response) {
    content.html(response);    // i tried alert here but it shows nothing
    }
});
});});
</code>```

receiving PHP file code is:

```<code> <?php
    $imagepath = $_POST['imgpath'];
    echo $imagepath;
 ?>
</code>```

I tried it with GET also but same error.. I haven't used Ajax before this. I checked other responses here on similar questions but none of them was has anything majorly different from mine code. so dont know what's the error..

updated Screen shots of code both files

updated screen shots of output

答:
Try this one. Add this one to document.ready function

```<code>$(".img").click(function() {
  $.ajax({
    type: "POST",
    url: "ss.php",
    data: {imgpath:imgsrc},
    dataType: "text",
    cache:false,
    success:
        function(data){
          alert(data);
        }
  });// you have missed this bracket
  return false;
});
</code>```

Body:
I am trying to pass the jquery variable to PHP with Ajax but the receiving php file is returning error " Undefined index" Code is:

$(document).ready(function($){
    $('.img').on('click','img',function(){
        var imgsrc = $(this).attr('src');
        alert(imgsrc);       //this is returning the img src correctly
$.ajax({
    type: "POST",
    url: 'ss.php',
    dataType: 'json',
    data: {imgpath:imgsrc },
    success: function(response) {
    content.html(response);    // i tried alert here but it shows nothing
    }
});
});});

receiving PHP file code is:

 <?php
    $imagepath = $_POST['imgpath'];
    echo $imagepath;
 ?>

I tried it with GET also but same error.. I haven't used Ajax before this. I checked other responses here on similar questions but none of them was has anything majorly different from mine code. so dont know what's the error..

updated Screen shots of code both files

updated screen shots of output

Body:
Try this one. Add this one to document.ready function

$(".img").click(function() {
  $.ajax({
    type: "POST",
    url: "ss.php",
    data: {imgpath:imgsrc},
    dataType: "text",
    cache:false,
    success:
        function(data){
          alert(data);
        }
  });// you have missed this bracket
  return false;
});


问:
Spring Roo 2.0.RC1 - Spring Security Provider Default and add Spring Security Configuration
Another Problem.

I can not use Spring Security Provider Springlets_Jpa see (Spring Roo 2.0.RC1: use Mysql DB with springlets authentification)

Then is use the default Provider.
I have default loginin popup with default user and password show in shell.

I want't to have a user and role table an use login view.
I have added Entities User and Role with Roo.

I have no yet spring security configuration.

```<code>entity jpa --class ~.model.User --plural Users --table USER --sequenceName USER_ID_SEQ --identifierStrategy AUTO --identifierColumn USER_ID --versionField version --versionType java.lang.Long --versionColumn VERSION --entityFormatExpression "User: #{firstname} #{lastname} (#{username})"
entity jpa --class ~.model.Role --plural Roles --table ROLE --sequenceName ROLE_ID_SEQ --identifierStrategy AUTO --identifierColumn ROLE_ID --versionField version --versionType java.lang.Long --versionColumn VERSION --entityFormatExpression "#{rolename}"

focus --class ~.model.User
field string --fieldName username --column USERNAME --notNull --unique --comment "Username des Nutzers" --regexp ^[a-zA-Z0-9_]{4,}$
field string --fieldName password --column PASSWORD --notNull --comment "Passwort des Nutzers" --regexp ^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9]{6,}$
field string --fieldName firstname --column FIRST_NAME --notNull --comment "Vorname des Nutzers"
field string --fieldName lastname --column LAST_NAME --notNull  --comment "Nachname des Nutzers"
field string --fieldName email --column EMAIL --notNull --unique --comment "Email des Nutzers" --regexp ^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$
focus --class ~.model.Role
field enum --fieldName rolename --column ROLENAME --type ~.model.restricted.RoleType --notNull --comment "Rollentyp"
field set --fieldName userlst --type ~.model.User --mappedBy role --joinColumnName ROLE_ID --permitReservedWords --comment "Liste der User mit diesem Typ"
</code>```

When i start webapp i acbb create Roles and User. I can select Roles in create User view.

Now i add spring security configuration class (very simple allow all without login)

```<code>import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeRequests().antMatchers("/").permitAll();
    }

}
</code>```

When i now start the webapp and create User i can't select Role from List.
I get WARN

```<code>2017-03-30 09:12:55.088  WARN 6644 --- [nio-8082-exec-7] .w.s.m.s.DefaultHandlerExceptionResolver :
Resolved exception caused by Handler execution: org.springframework.http.converter.HttpMessageNotWri
tableException: Could not write content: No converter found capable of converting from type [de.quin
tra.rechnungspruefung.model.Role] to type [java.lang.String] (through reference chain: io.springlets
.data.web.select2.Select2DataWithConversion["results"]); nested exception is com.fasterxml.jackson.d
atabind.JsonMappingException: No converter found capable of converting from type [de.quintra.rechnun
gspruefung.model.Role] to type [java.lang.String] (through reference chain: io.springlets.data.web.s
elect2.Select2DataWithConversion["results"])
</code>```

And now role show in List.
What is wrong?

答:
Some weeks ago, I detected a problem in Spring Security and I created the following issue in their repository:

https://github.com/spring-projects/spring-security/issues/4202

Seems like if a @Configuration class extends the WebSecurityConfigurerAdapter abstract class (like in the code generated by Spring Roo), some component is trying to @Autowired a ConversionService instance before the formatters have been registered in the Spring context, so the addFormatters method doesn't include any formatters on it.

A simple work-around that will solve your problem and you'll be able to use Spring Security in your project is to @Override the setContentNegotiationStrategy method in the generated SecurityConfiguration class without include the @Autowired annotation.

The following example looks how to override this method correctly. (In this sample the code is commented)

https://github.com/jcagarcia/proofs/blob/master/spring-security-and-formatters/src/main/java/org/springframework/roo/petclinic/config/security/SecurityConfiguration.java#L54

If this solves your problem, will be great that you comment on the issue saying that you have the same problem.

Hope it helps,

Body:
Another Problem.

I can not use Spring Security Provider Springlets_Jpa see (Spring Roo 2.0.RC1: use Mysql DB with springlets authentification)

Then is use the default Provider.
I have default loginin popup with default user and password show in shell.

I want't to have a user and role table an use login view.
I have added Entities User and Role with Roo.

I have no yet spring security configuration.

entity jpa --class ~.model.User --plural Users --table USER --sequenceName USER_ID_SEQ --identifierStrategy AUTO --identifierColumn USER_ID --versionField version --versionType java.lang.Long --versionColumn VERSION --entityFormatExpression "User: #{firstname} #{lastname} (#{username})"
entity jpa --class ~.model.Role --plural Roles --table ROLE --sequenceName ROLE_ID_SEQ --identifierStrategy AUTO --identifierColumn ROLE_ID --versionField version --versionType java.lang.Long --versionColumn VERSION --entityFormatExpression "#{rolename}"

focus --class ~.model.User
field string --fieldName username --column USERNAME --notNull --unique --comment "Username des Nutzers" --regexp ^[a-zA-Z0-9_]{4,}$
field string --fieldName password --column PASSWORD --notNull --comment "Passwort des Nutzers" --regexp ^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9]{6,}$
field string --fieldName firstname --column FIRST_NAME --notNull --comment "Vorname des Nutzers"
field string --fieldName lastname --column LAST_NAME --notNull  --comment "Nachname des Nutzers"
field string --fieldName email --column EMAIL --notNull --unique --comment "Email des Nutzers" --regexp ^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$
focus --class ~.model.Role
field enum --fieldName rolename --column ROLENAME --type ~.model.restricted.RoleType --notNull --comment "Rollentyp"
field set --fieldName userlst --type ~.model.User --mappedBy role --joinColumnName ROLE_ID --permitReservedWords --comment "Liste der User mit diesem Typ"

When i start webapp i acbb create Roles and User. I can select Roles in create User view.

Now i add spring security configuration class (very simple allow all without login)

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeRequests().antMatchers("/").permitAll();
    }

}

When i now start the webapp and create User i can't select Role from List.
I get WARN

2017-03-30 09:12:55.088  WARN 6644 --- [nio-8082-exec-7] .w.s.m.s.DefaultHandlerExceptionResolver :
Resolved exception caused by Handler execution: org.springframework.http.converter.HttpMessageNotWri
tableException: Could not write content: No converter found capable of converting from type [de.quin
tra.rechnungspruefung.model.Role] to type [java.lang.String] (through reference chain: io.springlets
.data.web.select2.Select2DataWithConversion["results"]); nested exception is com.fasterxml.jackson.d
atabind.JsonMappingException: No converter found capable of converting from type [de.quintra.rechnun
gspruefung.model.Role] to type [java.lang.String] (through reference chain: io.springlets.data.web.s
elect2.Select2DataWithConversion["results"])

And now role show in List.
What is wrong?


问:
Look through every items in array(A) and check if it allready exsists in another array(B)
I have two arrays(arrayA & arrayB). I want to check if any of the items in arrayA allready exists in arrayB. if it doesn't I want to add it to arrayB(but that's not the problem). In the exampel I just want to console.log that I'm adding the item to array B.

First I thought this was a good idea:

```<code> for(var i = 0; i < arrayA.length; i++){
        for (var j = 0; j < arrayB.length; j++) {
            if(body[i].id == res[j].name){
                console.log("The article allready exsists")
            }
            else{
                console.log("Adding item to arrayB")
            }

      }

      }
</code>```

Then I realised that this wasn't a verry good way to do it because the array's are pretty big. Also the else-statement will be ran the number of times equal to the length of arrayA. Also It's a problem because the first time this will run the array length of arrayB will be zero and wont even reach the else-statement.

Is their any other ways to achive what I'm trying to do here?

答:
You could use a hash table and a linear approach by iterating first arrayB and collect the name property and then iterate over arrayA and check if the id is in arrayB with the hash table. Add the information to arrayB if not exist.

var arrayA = [{ id: 1 }, { id: 3 }, { id: 4 }, { id: 6 }, { id: 7 }, { id: 9 }, { id: 12 }, { id: 35 }, { id: 22 }, { id: 11 }, { id: 34 }, { id: 90 }, { id: 2 }],
    arrayB = [{ name: 1 }, { name: 7 }, { name: 8 }, { name: 19 }, { name: 25 }, { name: 41 }, { name: 35 }, ],
    hashB = Object.create(null);

arrayB.forEach(function (b) {
    hashB[b.name] = true;
});

arrayA.forEach(function (a) {
    if (!hashB[a.id]) {
        arrayB.push({ name: a.id });
        hashB[a.id] = true;
    }
});

console.log(arrayB);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have two arrays(arrayA & arrayB). I want to check if any of the items in arrayA allready exists in arrayB. if it doesn't I want to add it to arrayB(but that's not the problem). In the exampel I just want to console.log that I'm adding the item to array B.

First I thought this was a good idea:

 for(var i = 0; i < arrayA.length; i++){
        for (var j = 0; j < arrayB.length; j++) {
            if(body[i].id == res[j].name){
                console.log("The article allready exsists")
            }
            else{
                console.log("Adding item to arrayB")
            }

      }

      }

Then I realised that this wasn't a verry good way to do it because the array's are pretty big. Also the else-statement will be ran the number of times equal to the length of arrayA. Also It's a problem because the first time this will run the array length of arrayB will be zero and wont even reach the else-statement.

Is their any other ways to achive what I'm trying to do here?

Body:
You could use a hash table and a linear approach by iterating first arrayB and collect the name property and then iterate over arrayA and check if the id is in arrayB with the hash table. Add the information to arrayB if not exist.

var arrayA = [{ id: 1 }, { id: 3 }, { id: 4 }, { id: 6 }, { id: 7 }, { id: 9 }, { id: 12 }, { id: 35 }, { id: 22 }, { id: 11 }, { id: 34 }, { id: 90 }, { id: 2 }],
    arrayB = [{ name: 1 }, { name: 7 }, { name: 8 }, { name: 19 }, { name: 25 }, { name: 41 }, { name: 35 }, ],
    hashB = Object.create(null);

arrayB.forEach(function (b) {
    hashB[b.name] = true;
});

arrayA.forEach(function (a) {
    if (!hashB[a.id]) {
        arrayB.push({ name: a.id });
        hashB[a.id] = true;
    }
});

console.log(arrayB);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Using XSLT merge 2 XML, which come from PHP transformToXML
I am beginner in PHP, XSLT.  Found solution for transform XML using XSLT:

```<code>$xml = Array2XML::createXML('Document', $result);
$xsl = new DOMDocument;
$xsl->load('Teema.xsl');
$processor = new XSLTProcessor();
$processor->importStyleSheet($xsl);
$results=$processor->transformToXML($xml);
$results=$processor->transformToUri($xml,"NewTeema.xml" );
</code>```

But, what to do if I have 2 or more XMLs?
This $xml is not file, and I dont want to save each xml, like file on server (because it is was converted response json). Any ideas?

答:
Good solution, but I decided to merge 2 json, like this:
  json_encode(array_merge(json_decode($result,
  true),json_decode($resultProducts, true)));
And the use  = Array2XML::createXML('Document', $result);</p>

Body:
I am beginner in PHP, XSLT.  Found solution for transform XML using XSLT:

$xml = Array2XML::createXML('Document', $result);
$xsl = new DOMDocument;
$xsl->load('Teema.xsl');
$processor = new XSLTProcessor();
$processor->importStyleSheet($xsl);
$results=$processor->transformToXML($xml);
$results=$processor->transformToUri($xml,"NewTeema.xml" );

But, what to do if I have 2 or more XMLs?
This $xml is not file, and I dont want to save each xml, like file on server (because it is was converted response json). Any ideas?


问:
Selenium | Java | Can anyone suggest how to select this element?
Need help to select an element that has the following attributes</p>

```<code><a href="" tabindex="-1" ng-bind-html="match.label uibTypeaheadHighlight:query" class="ng-binding ng-scope"><strong>Lantus</strong> 100 iu (Insulin)</a>
</code>```

答:
You can try the below line of code</p>

```<code>WebDriver driver = new FirefoxDriver();
WebElement hyperLink = driver.findElement(By.xpath("//a[contains(text(),'Lantus')]"));
</code>```

Body:
Need help to select an element that has the following attributes

Lantus 100 iu (Insulin)

Body:
You can try the below line of code

WebDriver driver = new FirefoxDriver();
WebElement hyperLink = driver.findElement(By.xpath("//a[contains(text(),'Lantus')]"));


问:
Is it reasonable to synchronize on a local variable?
From the Java memory model, we know that every thread has its own thread stack, and that local variables are placed in each thread's own thread stack.

And that other threads can't access these local variables.

So in which case should we synchronize on local variables?

答:
The point is: synchronization is done for a purpose. You use it to ensure that exactly one thread can do some special protection-worthy activity at any given time.

Thus: if you need synchronization, it is always about more than one thread. And of course, then you need to lock on something that all those threads have access to.

Or in other words: there is no point in you locking the door in order to prevent yourself from entering the building.

But, as the other answer points out: it actually depends on the definition of "local" variable. Lets say you have:

```<code>void foo() {
  final Object lock = new Object();
  Thread a = new Thread() { uses lock
  Thread b = new Thread() { uses lock
</code>```

then sure, that "local" variable can be used as lock for those two threads. And beyond that: that example works because synchronization happens on the monitor of a specific object. And objects reside on the heap. All of them.

Body:
The point is: synchronization is done for a purpose. You use it to ensure that exactly one thread can do some special protection-worthy activity at any given time.

Thus: if you need synchronization, it is always about more than one thread. And of course, then you need to lock on something that all those threads have access to.

Or in other words: there is no point in you locking the door in order to prevent yourself from entering the building.

But, as the other answer points out: it actually depends on the definition of "local" variable. Lets say you have:

void foo() {
  final Object lock = new Object();
  Thread a = new Thread() { uses lock
  Thread b = new Thread() { uses lock

then sure, that "local" variable can be used as lock for those two threads. And beyond that: that example works because synchronization happens on the monitor of a specific object. And objects reside on the heap. All of them.


问:
DNS help, server not responding outside home network
I am aware that this question does not really pertain to programming but I have now resorted to using you guys, so please help!

So I believe my problem resides in the DNS region, I am hosting a web server on my raspberry pi and am trying to use it to host my website(codetendency.com), I bought my domain from godaddy.com and I pointed "@" to my raspberry pi's IP address and when I try to access my website at home through my home network it works out, but when I tried to access it from my phone on my mobile data, the server doesn't respond.

I would greatly appreciate any help you guys could give me.

答: The name codetendency.com resolves to the IP address 192.168.0.201. That address is part of the private address space (see RFC 1918), which is not routed on the public Internet. If you want your server to be visible on the public Internet, you must provide a real IP address.


问:
Construct callable function from string
How to construct and call a function from a string?
For example, consider three different functions and a list of strings, I want to be able to use the items in list of strings to construct and call the appropriate function</p>

```<code>def do_function1():
    return 'done function1'

def do_function2():
    return 'done function2'

def do_function3():
    return 'done function3'

listOfstr = ['function1','function2','function3']

for item in listOfstr:
    result = 'do_'+item()
    print(result)

result = 'do_'+item()
TypeError: 'str' object is not callable
</code>```

答:
The problematic code is

```<code>listOfstr = ['function1','function2','function3']

for item in listOfstr:
    result = 'do_'+item()
</code>```

In the first loop item, will have the value 'function1'. You are calling this string as if it were a function. But strings are not callable and have no code assigned to them!

Then, you go on with the for loop before doing anything.

Simply refer to item, like this:

```<code>for item in listOfstr:
    func_name = 'do_' + item
    func = globals()[func_name]
    func()
</code>```

Title: Construct callable function from string

Body:
How to construct and call a function from a string?
For example, consider three different functions and a list of strings, I want to be able to use the items in list of strings to construct and call the appropriate function

def do_function1():
    return 'done function1'

def do_function2():
    return 'done function2'

def do_function3():
    return 'done function3'

listOfstr = ['function1','function2','function3']

for item in listOfstr:
    result = 'do_'+item()
    print(result)

result = 'do_'+item()
TypeError: 'str' object is not callable

Body:
The problematic code is

listOfstr = ['function1','function2','function3']

for item in listOfstr:
    result = 'do_'+item()

In the first loop item, will have the value 'function1'. You are calling this string as if it were a function. But strings are not callable and have no code assigned to them!

Then, you go on with the for loop before doing anything.

Simply refer to item, like this:

for item in listOfstr:
    func_name = 'do_' + item
    func = globals()[func_name]
    func()


问:
Binary search of a Matrix

Write an efficient algorithm that searches for a value in an m x n
  matrix.

This matrix has the following properties:

-Integers in each row are sorted from left to right.
-The first integer
  of each row is greater than or equal to the last integer of the
  previous row.

Example:

Consider the following matrix:

[

    [1,   3,  5,  7],

[10, 11, 16, 20],
   [23, 30, 34, 50]
]
Given
  target = 3, return 1 ( 1 corresponds to true )

Return 0 / 1 ( 0 if the element is not present, 1 if the element is
  present ) for this problem

My solution works on NetBeans but fails on the website. Any help will be appreciated.
https://www.interviewbit.com/problems/matrix-search/

```<code>public class Solution {

    public int searchMatrix(ArrayList<ArrayList<Integer>> a, int b) {
        int r = a.size();
        int c = a.get(0).size();

        int start = 0;
        int end = r - 1;
        // default value is last row for edge case
        int biRow = r -1; // row to search column

        //binary search 1st value of rows
        while (start <= end) {
            int mid = (start + end) / 2;
            if (b == a.get(mid).get(0)) {
                return 1;
            }

            if (a.get(mid).get(0) < b && b < a.get(end).get(0)) {
                if (mid + 1 >= end) {
                    biRow = mid;
                    break;
                }
            } if (b < a.get(mid).get(0)) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        //binary search column of biRow
        start = 0;
        end = c-1;
        while (start <= end) {
            int mid = (start + end) / 2;
            if (b == a.get(biRow).get(mid)) {
                return 1;
            }
            if (b < a.get(biRow).get(mid)) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        return 0;
    }
}
</code>```

答:
There is logical error in your row search loop. I made a correction and I also added the boundary conditions.Time complexity of this algorithm is O(logN).</p>

```<code>public class Solution {
    public int searchMatrix(ArrayList<ArrayList<Integer>> a, int b) {
        int r = a.size();
        int c = a.get(0).size();

        // return 0 if b is less than 1st element or greater than last element
        if (b < a.get(0).get(0) || b > a.get(r - 1).get(c - 1))
            return 0;
        int start = 0;
        int end = r - 1;
        // default value is last row for edge case
        int biRow = r - 1; // row to search column

        // binary search 1st value of rows
        while (start <= end) {
            int mid = (start + end) / 2;
            if (b == a.get(mid).get(0)) {
                return 1;
            }

            if (b >= a.get(mid).get(0) && b <= a.get(mid).get(c - 1)) {
                {
                    biRow = mid;
                    break;
                }
            }
            if (b < a.get(mid).get(0)) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        // binary search column of biRow
        start = 0;
        end = c - 1;
        while (start <= end) {
            int mid = (start + end) / 2;
            if (b == a.get(biRow).get(mid)) {
                return 1;
            }
            if (b < a.get(biRow).get(mid)) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        return 0;
    }
}
</code>```

Title: Binary search of a Matrix

Body:
Write an efficient algorithm that searches for a value in an m x n
  matrix.

This matrix has the following properties:

-Integers in each row are sorted from left to right.
-The first integer
  of each row is greater than or equal to the last integer of the
  previous row.

Example:

Consider the following matrix:

[

    [1,   3,  5,  7],

[10, 11, 16, 20],
   [23, 30, 34, 50]
]
Given
  target = 3, return 1 ( 1 corresponds to true )

Return 0 / 1 ( 0 if the element is not present, 1 if the element is
  present ) for this problem

My solution works on NetBeans but fails on the website. Any help will be appreciated.
https://www.interviewbit.com/problems/matrix-search/

public class Solution {

    public int searchMatrix(ArrayList<ArrayList<Integer>> a, int b) {
        int r = a.size();
        int c = a.get(0).size();

        int start = 0;
        int end = r - 1;
        // default value is last row for edge case
        int biRow = r -1; // row to search column

        //binary search 1st value of rows
        while (start <= end) {
            int mid = (start + end) / 2;
            if (b == a.get(mid).get(0)) {
                return 1;
            }

            if (a.get(mid).get(0) < b && b = end) {
                    biRow = mid;
                    break;
                }
            } if (b < a.get(mid).get(0)) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        //binary search column of biRow
        start = 0;
        end = c-1;
        while (start <= end) {
            int mid = (start + end) / 2;
            if (b == a.get(biRow).get(mid)) {
                return 1;
            }
            if (b < a.get(biRow).get(mid)) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        return 0;
    }
}

Body:
There is logical error in your row search loop. I made a correction and I also added the boundary conditions.Time complexity of this algorithm is O(logN).

public class Solution {
    public int searchMatrix(ArrayList<ArrayList<Integer>> a, int b) {
        int r = a.size();
        int c = a.get(0).size();

        // return 0 if b is less than 1st element or greater than last element
        if (b < a.get(0).get(0) || b > a.get(r - 1).get(c - 1))
            return 0;
        int start = 0;
        int end = r - 1;
        // default value is last row for edge case
        int biRow = r - 1; // row to search column

        // binary search 1st value of rows
        while (start <= end) {
            int mid = (start + end) / 2;
            if (b == a.get(mid).get(0)) {
                return 1;
            }

            if (b >= a.get(mid).get(0) && b <= a.get(mid).get(c - 1)) {
                {
                    biRow = mid;
                    break;
                }
            }
            if (b < a.get(mid).get(0)) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        // binary search column of biRow
        start = 0;
        end = c - 1;
        while (start <= end) {
            int mid = (start + end) / 2;
            if (b == a.get(biRow).get(mid)) {
                return 1;
            }
            if (b < a.get(biRow).get(mid)) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        return 0;
    }
}


问:
TSQL JSON Parsing
My JSON data has the key with [.  When I try OpenJSON it complains
about the [.  Could you help.

```<code>DECLARE @Json VARCHAR(MAX)

SET @Json = '{"[key]":"val"}'

SELECT *
FROM openjson(@json)
WITH (C1 VARCHAR(200) '$.[key]')
</code>```

Msg 13607, Level 16, State 4, Line 7 JSON path is not properly formatted. Unexpected character '[' is found at position 2.

答:
OPENJSON works with arrays. The JSON string {"[key]":"val"} specifies a single object. In this case you should use JSON_QUERY or JSON_VALUE.

To get the key's value, use [JSON_VALUE] :

```<code>select JSON_VALUE('{"[key]":"val"}','$."[key]"')
</code>```

returns val.

You should investigate why the property's name is [key] instead of key though. This defines defines a property named [key] instead of key.

This is completely unexpected and confusing to everyone. In fact, that's what was wrong with the path expression. This will cause problems for any deserializers that try to generate objects from this data, eg in C# or Javascript. You can't define a property named [key] which means that extra mapping work is needed to use this JSON string.

Whatever process generates this string should be changed to remove the brackets

Title: TSQL JSON Parsing

Body:
My JSON data has the key with [.  When I try OpenJSON it complains
about the [.  Could you help.

DECLARE @Json VARCHAR(MAX)

SET @Json = '{"[key]":"val"}'

SELECT *
FROM openjson(@json)
WITH (C1 VARCHAR(200) '$.[key]')

Msg 13607, Level 16, State 4, Line 7 JSON path is not properly formatted. Unexpected character '[' is found at position 2.

Body:
OPENJSON works with arrays. The JSON string {"[key]":"val"} specifies a single object. In this case you should use JSON_QUERY or JSON_VALUE.

To get the key's value, use [JSON_VALUE] :

select JSON_VALUE('{"[key]":"val"}','$."[key]"')

returns val.

You should investigate why the property's name is [key] instead of key though. This defines defines a property named [key] instead of key.

This is completely unexpected and confusing to everyone. In fact, that's what was wrong with the path expression. This will cause problems for any deserializers that try to generate objects from this data, eg in C# or Javascript. You can't define a property named [key] which means that extra mapping work is needed to use this JSON string.

Whatever process generates this string should be changed to remove the brackets


问:
How can I draw a arrow for showing incoming/ outgoing calls
I'm creating an app that shows Call Log.

In most of the contacts app we see arrows representing incoming/outgoing/missed calls.

where can I get them or can I create them using drawables or something?

答:
https://romannurik.github.io/AndroidAssetStudio/index.html

I got those icons from this website.I think this is very good website to make new icons


问:
homogenization the functions can be compiled into a calculate networks?
Inside of a network, information (package) can be passed to different node(hosts), by modify it's content it can carry different meaning. The final package depends on hosts input via it's given route of network.

Now I want to implement a calculating network model can do small jobs by give different calculate path.

Prototype:

```<code>def a(p): return p + 1
def b(p): return p + 2
def c(p): return p + 3
def d(p): return p + 4
def e(p): return p + 5

def link(p, r):
    p1 = p
    for x in r:
        p1 = x(p1)
    return p1

p = 100
route = [a,c,d]
result = link(p,result)
#========
target_result = 108
if result = target_result:
   # route is OK
</code>```

I think finally I need something like this:

```<code>  p with [init_payload, expected_target, passed_path, actual_calculated_result]
  |
  \/
 [CHAOS of possible of functions networks]
  |
  \/
  px [a,a,b,c,e]  # ok this path is ok and match the target
</code>```

Here is my questions hope may get your help:

can p carry(determin) the route(s) by inspect the function and estmated result？

(1.1 ) for example, if on the route there's a node x()

def x(p): return x / 0        # I suppose it can pass the compile

can p know in somehow this path is not good then avoid select this path?

(1.2) Another confuse is if p is a self-defined class type, the payload inside of this class essentially is a string, when it carry with a path [a,c,d], can p know a() must with a int type then avoid to select this node?'

same as 1.2 when generating the path, can I avoid such oops

def a(p): return p + 1

def b(p): return p + 2

def x(p): return p.append(1)

def y(p): return p.append(2)

full_node_list = [a,b,x,y]

path = random(2,full_node_list) # oops x,y will be trouble for the inttype P and a,b will be trouble to list type.
pls consider if the path is lambda list of functions

PS: as the whole model is not very clear in my mind the any leading and directing will be appreciated.

THANKS!

答:
I'm somewhat confused as to what you're trying to do, but: p cannot "know about" the functions until it is run through them. By design, Python functions don't specify what type of data they operate on: e.g. a*5 is valid whether a is a string, a list, an integer or a float.

If there are some functions that might not be able to operate on p, then you could catch exceptions, for example in your link function:

```<code>def link(p, r):
    try:
        for x in r:
            p = x(p)
    except ZeroDivisionError, AttributeError: # List whatever errors you want to catch
        return None
    return p
</code>```

Body:
Inside of a network, information (package) can be passed to different node(hosts), by modify it's content it can carry different meaning. The final package depends on hosts input via it's given route of network.

Now I want to implement a calculating network model can do small jobs by give different calculate path.

Prototype:

def a(p): return p + 1
def b(p): return p + 2
def c(p): return p + 3
def d(p): return p + 4
def e(p): return p + 5

def link(p, r):
    p1 = p
    for x in r:
        p1 = x(p1)
    return p1

p = 100
route = [a,c,d]
result = link(p,result)
#========
target_result = 108
if result = target_result:
   # route is OK

I think finally I need something like this:

  p with [init_payload, expected_target, passed_path, actual_calculated_result]
  |
  \/
 [CHAOS of possible of functions networks]
  |
  \/
  px [a,a,b,c,e]  # ok this path is ok and match the target

Here is my questions hope may get your help:

can p carry(determin) the route(s) by inspect the function and estmated result？

(1.1 ) for example, if on the route there's a node x()

def x(p): return x / 0        # I suppose it can pass the compile

can p know in somehow this path is not good then avoid select this path?

(1.2) Another confuse is if p is a self-defined class type, the payload inside of this class essentially is a string, when it carry with a path [a,c,d], can p know a() must with a int type then avoid to select this node?'

same as 1.2 when generating the path, can I avoid such oops

def a(p): return p + 1

def b(p): return p + 2

def x(p): return p.append(1)

def y(p): return p.append(2)

full_node_list = [a,b,x,y]

path = random(2,full_node_list) # oops x,y will be trouble for the inttype P and a,b will be trouble to list type.
pls consider if the path is lambda list of functions

PS: as the whole model is not very clear in my mind the any leading and directing will be appreciated.

THANKS!

Body:
I'm somewhat confused as to what you're trying to do, but: p cannot "know about" the functions until it is run through them. By design, Python functions don't specify what type of data they operate on: e.g. a*5 is valid whether a is a string, a list, an integer or a float.

If there are some functions that might not be able to operate on p, then you could catch exceptions, for example in your link function:

def link(p, r):
    try:
        for x in r:
            p = x(p)
    except ZeroDivisionError, AttributeError: # List whatever errors you want to catch
        return None
    return p