问:
ClassNotFoundException: org.apache.pdfbox.pdmodel.PDDocument
I am getting below error during compilation. I am using Eclipse IDE & working on Ubuntu. I have added the following jar files in the build path 1) pdfbox 1.8.13 & All its dependencies 2) Commons-logging-1.2 .

Please let me know why there is error when the class is in the jar file ?

```<code>Error: java.lang.ClassNotFoundException: org.apache.pdfbox.pdmodel.PDDocument
at java.net.URLClassLoader$1.run(URLClassLoader.java:359)
at java.net.URLClassLoader$1.run(URLClassLoader.java:348)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:347)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:312)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at com.hadoopexpert.PdfRecordReader.initialize(PdfRecordReader.java:41)
at org.apache.hadoop.mapred.MapTask$NewTrackingRecordReader.initialize(MapTask.java:521)
at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:763)
at org.apache.hadoop.mapred.MapTask.run(MapTask.java:364)
at org.apache.hadoop.mapred.Child$4.run(Child.java:255)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:421)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1190)
at org.apache.hadoop.mapred.Child.main(Child.java:249)
</code>```

答: You have the class on the build path, so it compiles, but apparently you don't have it in the classpath of the running binary, which is why it doesn't run. Make sure that your application's classpath includes all the JARs that you have added (or use some build system such as Maven or Gradle which automates that for you).</p>

Body:
I am getting below error during compilation. I am using Eclipse IDE & working on Ubuntu. I have added the following jar files in the build path 1) pdfbox 1.8.13 & All its dependencies 2) Commons-logging-1.2 .

Please let me know why there is error when the class is in the jar file ?

Error: java.lang.ClassNotFoundException: org.apache.pdfbox.pdmodel.PDDocument
at java.net.URLClassLoader$1.run(URLClassLoader.java:359)
at java.net.URLClassLoader$1.run(URLClassLoader.java:348)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:347)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:312)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at com.hadoopexpert.PdfRecordReader.initialize(PdfRecordReader.java:41)
at org.apache.hadoop.mapred.MapTask$NewTrackingRecordReader.initialize(MapTask.java:521)
at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:763)
at org.apache.hadoop.mapred.MapTask.run(MapTask.java:364)
at org.apache.hadoop.mapred.Child$4.run(Child.java:255)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:421)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1190)
at org.apache.hadoop.mapred.Child.main(Child.java:249)


来源: stackexchange

问:
"The behavior of `attribute_changed?` inside of after callbacks" After a basic `save`
This is my hook method called after after_create :set_after_create in a model.

```<code>  def set_after_create
    passphrase = "#{id}+#{Time.zone.now.to_date}#{Rails.application.secrets.secret_key_base}"
    update(
      ref: CryptLib.sha1(passphrase),
      token_key: CryptLib.sha1("#{passphrase}+#{Random.rand(20)}")
    )
  end
</code>```

Now, I get a warning:

DEPRECATION WARNING: The behavior of attribute_changed? inside of
  after callbacks will be changing in the next version of Rails. The new
  return value will reflect the behavior of calling the method after
  save returned (e.g. the opposite of what it returns now). To
  maintain the current behavior, use saved_change_to_attribute?
  instead. (called from set_after_create at
  /app/app/models/project.rb:330)

I don't understand the connection between the alert and the method.

PS: I get no warning using the update_columns method, but I don't think that's the right way.

Config: Rails 5.1.4 and all gems updated.

答:
I think you are using attribute_changed? at some other place in the same model.
Method attribute_changed? will deprecate in rails newer versions. So, instead of using attribute_changed?, use will_save_change_to_attribute?
For more details see here .

ContentLicense: CC BY-SA 3.0

Body:
This is my hook method called after after_create :set_after_create in a model.

  def set_after_create
    passphrase = "#{id}+#{Time.zone.now.to_date}#{Rails.application.secrets.secret_key_base}"
    update(
      ref: CryptLib.sha1(passphrase),
      token_key: CryptLib.sha1("#{passphrase}+#{Random.rand(20)}")
    )
  end

Now, I get a warning:

DEPRECATION WARNING: The behavior of attribute_changed? inside of
  after callbacks will be changing in the next version of Rails. The new
  return value will reflect the behavior of calling the method after
  save returned (e.g. the opposite of what it returns now). To
  maintain the current behavior, use saved_change_to_attribute?
  instead. (called from set_after_create at
  /app/app/models/project.rb:330)

I don't understand the connection between the alert and the method.

PS: I get no warning using the update_columns method, but I don't think that's the right way.

Config: Rails 5.1.4 and all gems updated.


问:
What is a quick way to force CRLF in C# / .NET?
How would you normalize all new-line sequences in a string to one type?

I'm looking to make them all CRLF for the purpose of email (MIME documents).  Ideally this would be wrapped in a static method, executing very quickly, and not using regular expressions (since the variances of line breaks, carriage returns, etc. are limited).  Perhaps there's even a BCL method I've overlooked?

ASSUMPTION: After giving this a bit more thought, I think it's a safe assumption to say that CR's are either stand-alone or part of the CRLF sequence.  That is, if you see CRLF then you know all CR's can be removed.  Otherwise it's difficult to tell how many lines should come out of something like "\r\n\n\r".

答:
This is a quick way to do that, I mean.

It does not use an expensive regex function.
It also does not use multiple replacement functions that each individually did loop over the data with several checks, allocations, etc.

So the search is done directly in one for loop. For the number of times that the capacity of the result array has to be increased, a loop is also used within the Array.Copy function. That are all the loops.
In some cases, a larger page size might be more efficient.

```<code>public static string NormalizeNewLine(this string val)
{
    if (string.IsNullOrEmpty(val))
        return val;

    const int page = 6;
    int a = page;
    int j = 0;
    int len = val.Length;
    char[] res = new char[len];

    for (int i = 0; i < len; i++)
    {
        char ch = val[i];

        if (ch == '\r')
        {
            int ni = i + 1;
            if (ni < len && val[ni] == '\n')
            {
                res[j++] = '\r';
                res[j++] = '\n';
                i++;
            }
            else
            {
                if (a == page) // Ensure capacity
                {
                    char[] nres = new char[res.Length + page];
                    Array.Copy(res, 0, nres, 0, res.Length);
                    res = nres;
                    a = 0;
                }

                res[j++] = '\r';
                res[j++] = '\n';
                a++;
            }
        }
        else if (ch == '\n')
        {
            int ni = i + 1;
            if (ni < len && val[ni] == '\r')
            {
                res[j++] = '\r';
                res[j++] = '\n';
                i++;
            }
            else
            {
                if (a == page) // Ensure capacity
                {
                    char[] nres = new char[res.Length + page];
                    Array.Copy(res, 0, nres, 0, res.Length);
                    res = nres;
                    a = 0;
                }

                res[j++] = '\r';
                res[j++] = '\n';
                a++;
            }
        }
        else
        {
            res[j++] = ch;
        }
    }

    return new string(res, 0, j);
}
</code>```

I now that '\n\r' is not actually used on basic platforms. But who would use two types of linebreaks in succession to indicate two linebreaks?

If you want to know that, then you need to take a look before to know if the \n and \r both are used separately in the same document.

ContentLicense: CC BY-SA 2.5

Body:
This is a quick way to do that, I mean.

It does not use an expensive regex function.
It also does not use multiple replacement functions that each individually did loop over the data with several checks, allocations, etc.

So the search is done directly in one for loop. For the number of times that the capacity of the result array has to be increased, a loop is also used within the Array.Copy function. That are all the loops.
In some cases, a larger page size might be more efficient.

public static string NormalizeNewLine(this string val)
{
    if (string.IsNullOrEmpty(val))
        return val;

    const int page = 6;
    int a = page;
    int j = 0;
    int len = val.Length;
    char[] res = new char[len];

    for (int i = 0; i < len; i++)
    {
        char ch = val[i];

        if (ch == '\r')
        {
            int ni = i + 1;
            if (ni < len && val[ni] == '\n')
            {
                res[j++] = '\r';
                res[j++] = '\n';
                i++;
            }
            else
            {
                if (a == page) // Ensure capacity
                {
                    char[] nres = new char[res.Length + page];
                    Array.Copy(res, 0, nres, 0, res.Length);
                    res = nres;
                    a = 0;
                }

                res[j++] = '\r';
                res[j++] = '\n';
                a++;
            }
        }
        else if (ch == '\n')
        {
            int ni = i + 1;
            if (ni < len && val[ni] == '\r')
            {
                res[j++] = '\r';
                res[j++] = '\n';
                i++;
            }
            else
            {
                if (a == page) // Ensure capacity
                {
                    char[] nres = new char[res.Length + page];
                    Array.Copy(res, 0, nres, 0, res.Length);
                    res = nres;
                    a = 0;
                }

                res[j++] = '\r';
                res[j++] = '\n';
                a++;
            }
        }
        else
        {
            res[j++] = ch;
        }
    }

    return new string(res, 0, j);
}

I now that '\n\r' is not actually used on basic platforms. But who would use two types of linebreaks in succession to indicate two linebreaks?

If you want to know that, then you need to take a look before to know if the \n and \r both are used separately in the same document.

ContentLicense: CC BY-SA 4.0


问:
Repeating values in a column
I have the following values in a column which are separated by comma.

```<code>BHOP23,BHOP23,BHOP24
</code>```

I would like to know whether values are repeating in a column.

How can I do this?

答:
A PL/SQL function which only relies on simple string functions (SUBSTR, INSTR and LENGTH) to remove duplicates from a string list:

SQL Fiddle

Oracle 11g R2 Schema Setup:

```<code>CREATE TABLE your_table ( your_list_column ) AS
  SELECT 'a,a,b,c,d' FROM DUAL UNION ALL -- duplicates both at head
  SELECT 'a,b,a,c,d' FROM DUAL UNION ALL -- duplicates at head and middle
  SELECT 'a,b,c,d,a' FROM DUAL UNION ALL -- duplicates at head and tail
  SELECT 'a,b,b,c,d' FROM DUAL UNION ALL -- duplicates at middle and next item
  SELECT 'a,b,c,b,d' FROM DUAL UNION ALL -- duplicates at middle and middle
  SELECT 'a,b,c,d,b' FROM DUAL UNION ALL -- duplicates at middle and tail
  SELECT 'a,b,c,d,d' FROM DUAL UNION ALL -- duplicates both at tail
  SELECT 'a,b,a,c,b' FROM DUAL UNION ALL -- two pairs of duplicates
  SELECT 'a,b,c,d,e' FROM DUAL           -- no duplicates
/

CREATE OR REPLACE FUNCTION remove_Duplicates_From_List(
  i_str    IN  VARCHAR2,
  i_delim  IN  VARCHAR2 DEFAULT ','
) RETURN VARCHAR2 DETERMINISTIC
AS
  p_result       VARCHAR2(4000) := i_delim;
  p_temp         VARCHAR2(4000);
  p_start        NUMBER(5) := 1;
  p_end          NUMBER(5);
  c_len CONSTANT NUMBER(5) := LENGTH( i_str );
  c_ld  CONSTANT NUMBER(5) := LENGTH( i_delim );
BEGIN
  IF c_len > 0 THEN
    p_end := INSTR( i_str, i_delim, p_start );
    WHILE p_end > 0 LOOP
      p_temp := SUBSTR( i_str, p_start, p_end + c_ld - p_start );
      IF INSTR( p_result, i_delim || p_temp ) = 0 THEN
        p_result := p_result || p_temp;
      END IF;
      p_start := p_end + c_ld;
      p_end := INSTR( i_str, i_delim, p_start );
    END LOOP;
    IF p_start <= c_len + 1 THEN
      p_temp := SUBSTR( i_str, p_start, c_len - p_start + 1 ) || i_delim;
      IF INSTR( p_result, i_delim || p_temp ) = 0 THEN
        p_result := p_result || p_temp;
      END IF;
    END IF;
  END IF;
  RETURN SUBSTR( p_result, c_ld + 1, LENGTH( p_result ) - 2 * c_ld );
END;
/
</code>```

Query 1:

```<code>SELECT your_list_column,
       remove_Duplicates_From_List( your_list_column ) AS uniq
FROM   your_table
</code>```

Results:

```<code>| YOUR_LIST_COLUMN |      UNIQ |
|------------------|-----------|
|        a,a,b,c,d |   a,b,c,d |
|        a,b,a,c,d |   a,b,c,d |
|        a,b,c,d,a |   a,b,c,d |
|        a,b,b,c,d |   a,b,c,d |
|        a,b,c,b,d |   a,b,c,d |
|        a,b,c,d,b |   a,b,c,d |
|        a,b,c,d,d |   a,b,c,d |
|        a,b,a,c,b |     a,b,c |
|        a,b,c,d,e | a,b,c,d,e |
</code>```

Title: Repeating values in a column

Body:
I have the following values in a column which are separated by comma.

BHOP23,BHOP23,BHOP24

I would like to know whether values are repeating in a column.

How can I do this?

Body:
A PL/SQL function which only relies on simple string functions (SUBSTR, INSTR and LENGTH) to remove duplicates from a string list:

SQL Fiddle

Oracle 11g R2 Schema Setup:

CREATE TABLE your_table ( your_list_column ) AS
  SELECT 'a,a,b,c,d' FROM DUAL UNION ALL -- duplicates both at head
  SELECT 'a,b,a,c,d' FROM DUAL UNION ALL -- duplicates at head and middle
  SELECT 'a,b,c,d,a' FROM DUAL UNION ALL -- duplicates at head and tail
  SELECT 'a,b,b,c,d' FROM DUAL UNION ALL -- duplicates at middle and next item
  SELECT 'a,b,c,b,d' FROM DUAL UNION ALL -- duplicates at middle and middle
  SELECT 'a,b,c,d,b' FROM DUAL UNION ALL -- duplicates at middle and tail
  SELECT 'a,b,c,d,d' FROM DUAL UNION ALL -- duplicates both at tail
  SELECT 'a,b,a,c,b' FROM DUAL UNION ALL -- two pairs of duplicates
  SELECT 'a,b,c,d,e' FROM DUAL           -- no duplicates
/

CREATE OR REPLACE FUNCTION remove_Duplicates_From_List(
  i_str    IN  VARCHAR2,
  i_delim  IN  VARCHAR2 DEFAULT ','
) RETURN VARCHAR2 DETERMINISTIC
AS
  p_result       VARCHAR2(4000) := i_delim;
  p_temp         VARCHAR2(4000);
  p_start        NUMBER(5) := 1;
  p_end          NUMBER(5);
  c_len CONSTANT NUMBER(5) := LENGTH( i_str );
  c_ld  CONSTANT NUMBER(5) := LENGTH( i_delim );
BEGIN
  IF c_len > 0 THEN
    p_end := INSTR( i_str, i_delim, p_start );
    WHILE p_end > 0 LOOP
      p_temp := SUBSTR( i_str, p_start, p_end + c_ld - p_start );
      IF INSTR( p_result, i_delim || p_temp ) = 0 THEN
        p_result := p_result || p_temp;
      END IF;
      p_start := p_end + c_ld;
      p_end := INSTR( i_str, i_delim, p_start );
    END LOOP;
    IF p_start <= c_len + 1 THEN
      p_temp := SUBSTR( i_str, p_start, c_len - p_start + 1 ) || i_delim;
      IF INSTR( p_result, i_delim || p_temp ) = 0 THEN
        p_result := p_result || p_temp;
      END IF;
    END IF;
  END IF;
  RETURN SUBSTR( p_result, c_ld + 1, LENGTH( p_result ) - 2 * c_ld );
END;
/

Query 1:

SELECT your_list_column,
       remove_Duplicates_From_List( your_list_column ) AS uniq
FROM   your_table

Results:

| YOUR_LIST_COLUMN |      UNIQ |
|------------------|-----------|
|        a,a,b,c,d |   a,b,c,d |
|        a,b,a,c,d |   a,b,c,d |
|        a,b,c,d,a |   a,b,c,d |
|        a,b,b,c,d |   a,b,c,d |
|        a,b,c,b,d |   a,b,c,d |
|        a,b,c,d,b |   a,b,c,d |
|        a,b,c,d,d |   a,b,c,d |
|        a,b,a,c,b |     a,b,c |
|        a,b,c,d,e | a,b,c,d,e |


问:
dropdown Arrow unicode icon static position css small devices
I'm trying to implement an accordion for FAQ. I have problems with the arrow icons in small screens, so each time I press the down arrow it should be switched for the up arrow icon and also located on the same place. But once I click the down arrow the up arrow appears slightly more on the top (on smartphone view). I tried with margin but not success. I would like to know how to keep both icons at the same place each time I switch from one to the other by clicking on it.

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function(){
        /* Toggle between adding and removing the "active" class,
        to highlight the button that controls the panel */
        this.classList.toggle("active");

        /* Toggle between hiding and showing the active panel */
        var panel = this.nextElementSibling;
        if (panel.style.maxHeight) {
            panel.style.maxHeight = null;
        } else {
            panel.style.maxHeight = panel.scrollHeight + "px";
        }
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>button.accordion {

  background-color: #eee;
  color: #444;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  text-align: center;
  border: none;
  outline: none;
  transition: 0.4s;
  font-size: 18px;
}

/* Add a background color to the button if it is clicked on (add the .active class with JS), and when you move the mouse over it (hover) */

button.accordion.active, button.accordion:hover {
  background-color: #ccc;
}

/* Style the accordion panel. Note: hidden by default */

div.panel {
  padding: 0 18px;
  background-color: white;
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.4s ease-out;
}

button.accordion:after {

  font-family: 'Arial Unicode MS', 'Consolas';
  content: "\2304";

  font-size: 60px !important;
  color: #777;
  float: left;
  margin-left: 5px;
  margin-top: -3vh ;
}

button.accordion.active:after {
  content: "\2303";
  max-height: 1vh;

}</code>```

    <button type="button" class="accordion">First Question</button>

Lorem Ipsum es simplemente el texto de relleno de las imprentas y archivos de texto.

    <button type="button" class="accordion">Second Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

    <button type="button" class="accordion">Third Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

    <button type="button" class="accordion">Fourth Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

    <button type="button" class="accordion">Fifth Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

    <button type="button" class="accordion">Sixth Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

```

答:
hi try this: it will work

```<code>button.accordion{
position:relative;
}

button.accordion::after{
position: absolute;
left: 30px;
top: -16px;
}
</code>```

Body:
I'm trying to implement an accordion for FAQ. I have problems with the arrow icons in small screens, so each time I press the down arrow it should be switched for the up arrow icon and also located on the same place. But once I click the down arrow the up arrow appears slightly more on the top (on smartphone view). I tried with margin but not success. I would like to know how to keep both icons at the same place each time I switch from one to the other by clicking on it.

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function(){
        /* Toggle between adding and removing the "active" class,
        to highlight the button that controls the panel */
        this.classList.toggle("active");

        /* Toggle between hiding and showing the active panel */
        var panel = this.nextElementSibling;
        if (panel.style.maxHeight) {
            panel.style.maxHeight = null;
        } else {
            panel.style.maxHeight = panel.scrollHeight + "px";
        }
    }
}

button.accordion {

  background-color: #eee;
  color: #444;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  text-align: center;
  border: none;
  outline: none;
  transition: 0.4s;
  font-size: 18px;
}

/* Add a background color to the button if it is clicked on (add the .active class with JS), and when you move the mouse over it (hover) */

button.accordion.active, button.accordion:hover {
  background-color: #ccc;
}

/* Style the accordion panel. Note: hidden by default */

div.panel {
  padding: 0 18px;
  background-color: white;
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.4s ease-out;
}

button.accordion:after {

  font-family: 'Arial Unicode MS', 'Consolas';
  content: "\2304";

  font-size: 60px !important;
  color: #777;
  float: left;
  margin-left: 5px;
  margin-top: -3vh ;
}

button.accordion.active:after {
  content: "\2303";
  max-height: 1vh;

}

    <button type="button" class="accordion">First Question</button>

Lorem Ipsum es simplemente el texto de relleno de las imprentas y archivos de texto.

    <button type="button" class="accordion">Second Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

    <button type="button" class="accordion">Third Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

    <button type="button" class="accordion">Fourth Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

    <button type="button" class="accordion">Fifth Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

    <button type="button" class="accordion">Sixth Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

Body:
hi try this: it will work

button.accordion{
position:relative;
}

button.accordion::after{
position: absolute;
left: 30px;
top: -16px;
}


问:
problem with tcp server and client
Hii all, I have already created some programs related to client and server. Today it was my sessional[practical exam] of Client-server technology.

Problem was: i was to add two no's at server sent from client and result back to client.

I tried this solution but some strange solution was there:
Server.java

```<code>import java.net.*;
import java.io.*;

public class Server{
    public static void main(String args[]) throws Exception{
        ServerSocket s = new ServerSocket(7896);
        Socket cs = s.accept();
        BufferedReader br = new BufferedReader(new InputStreamReader(cs.getInputStream()));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(cs.getOutputStream()));
        bw.write(br.read() + br.read());
    }
}
</code>```

Client.java

```<code>import java.io.*;
import java.net.*;

public class Client{
public static void main(String args[]) throws Exception{
    Socket s = new Socket("localhost", 7896);
    BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
    bw.write(3);
    bw.write(4);
    System.out.println("Output is: " + br.read());
}
}
</code>```

when i ran it on dos prompt i got two blank screens; one at client site and one at server site(which was a bit surprising). then i closed server then suddenly i got error msg at client something like connection closed.

Then i ran same program on my ubuntu linux with same jdk 1.6 as it was in windows, and here also blank screens but when i closed server i got:

```<code>Output is: -1
</code>```

Although in exam i done this using DataOutputStream and DataInputStream.

But why the above code is not working.

Can Anyone explain what is happening in the code there.

Thanks

答: write() will buffer input so it does not need to do lots of small writes. Since you are not writing much to the buffer, it is probably still there and not written out yet. Calling flush() will force it to write out the buffer.

Title: problem with tcp server and client

Body:
Hii all, I have already created some programs related to client and server. Today it was my sessional[practical exam] of Client-server technology.

Problem was: i was to add two no's at server sent from client and result back to client.

I tried this solution but some strange solution was there:
Server.java

import java.net.*;
import java.io.*;

public class Server{
    public static void main(String args[]) throws Exception{
        ServerSocket s = new ServerSocket(7896);
        Socket cs = s.accept();
        BufferedReader br = new BufferedReader(new InputStreamReader(cs.getInputStream()));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(cs.getOutputStream()));
        bw.write(br.read() + br.read());
    }
}

Client.java

import java.io.*;
import java.net.*;

public class Client{
public static void main(String args[]) throws Exception{
    Socket s = new Socket("localhost", 7896);
    BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
    bw.write(3);
    bw.write(4);
    System.out.println("Output is: " + br.read());
}
}

when i ran it on dos prompt i got two blank screens; one at client site and one at server site(which was a bit surprising). then i closed server then suddenly i got error msg at client something like connection closed.

Then i ran same program on my ubuntu linux with same jdk 1.6 as it was in windows, and here also blank screens but when i closed server i got:

Output is: -1

Although in exam i done this using DataOutputStream and DataInputStream.

But why the above code is not working.

Can Anyone explain what is happening in the code there.

Thanks


问:
Bootstrap datetimepicker parsing data
I want to parse hours and minutes from selected date&time.

```<code>var datetime = $('#datetimepicker').data('date');
</code>```

gives: 2017-11-01 11:50

If I want to parse hours and minutes :

```<code>time = datetime.getHours()+':'+datetime.getMinutes();
</code>```

error will occure : Uncaught TypeError: datetime.getHours is not a function.

Which functions to use, to parse data from date above?

答:
You can use split on input field data.

```<code>var time = datetime.split(" ")[1];
var hours = time.split(":")[0];
var minutes = time.split(":")[1];
</code>```

Please let me know which library are you using so that I can give you exact solution.

Title: Bootstrap datetimepicker parsing data

Body:
I want to parse hours and minutes from selected date&time.

var datetime = $('#datetimepicker').data('date');

gives: 2017-11-01 11:50

If I want to parse hours and minutes :

time = datetime.getHours()+':'+datetime.getMinutes();

error will occure : Uncaught TypeError: datetime.getHours is not a function.

Which functions to use, to parse data from date above?

Body:
You can use split on input field data.

var time = datetime.split(" ")[1];
var hours = time.split(":")[0];
var minutes = time.split(":")[1];

Please let me know which library are you using so that I can give you exact solution.


问:
spring-boot-jersey with JAX-RS API 2.1 (SSE)
What is the timeline for supporting Spring Boot with JAX-RS 2.1 (using Jersey)?

Jersey added support for JAX-RS 2.1 (JAX-RS API) in Jersey 2.26 (released 2017/09/06). This changed the Jersey support for HTTP Server-Sent Events (SSE) from a Jersey specific implementation to an implementation based on the JAX-RS API.

The Spring Boot Jersey integration (spring-boot-starter-jersey), release 1.5.8, uses Jersey 2.25.1.

Using spring boot 1.5.8 and overriding the jersey versions from spring-boot-starter-jersey to use 2.26 does not seem to work. The Sse and SseEventSink objects do not get injected into the request handlers (when using @Context).

I am not entirely sure if this is an issue with Spring Boot or Jersey. Hence the more general question, when Spring Boot with JAX-RS 2.1 will be supported.

答: JAX-RS 2.1 will be supported via Jersey 2.26 in Spring Boot 2. It has already been merged.</p>


问:
Join two Collections with LINQ with Contains operator
I have following two classes

```<code>Class C
{
public Guid Id{get;set;}
public string Type{get;set;}
}

Class D
{
  public List<Guid> CIds {get;set;}
  public string Type {get;set;}
}

 var D_Collection = new List<D>();
 var C_Collection = new List<C>();

 // SET The C_Collection.Type On the Basis of D_Collection
 // If C.Id exist in D.CIds then C.Type = D.Type
</code>```

I want to Set C.Type bases on the Criteria Given above in Comments

I tried following but it's not working

```<code> var temp = (from x in D_Collection
                        from y in C_Collection
                        where x.CIds.Contains(y.Id)
                        select new {
                               Id = y.Id,
                               Type = x.Type
                }).ToList();
</code>```

答:
This is simple and iterative, and there may well be a better solution. However it will do what you need.</p>

```<code>public void SetTypeOnCList(List<D> dlist, List<C> clist)
{
    clist.ForEach(c =>
    {
        var dobj = dlist.FirstOrDefault(d => d.CIds.Contains(c.Id));
        if (dobj != null)
        {
            c.Type = dobj.Type;
        }
    });
}
</code>```

Body:
I have following two classes

Class C
{
public Guid Id{get;set;}
public string Type{get;set;}
}

Class D
{
  public List<Guid> CIds {get;set;}
  public string Type {get;set;}
}

 var D_Collection = new List<D>();
 var C_Collection = new List<C>();

 // SET The C_Collection.Type On the Basis of D_Collection
 // If C.Id exist in D.CIds then C.Type = D.Type

I want to Set C.Type bases on the Criteria Given above in Comments

I tried following but it's not working

 var temp = (from x in D_Collection
                        from y in C_Collection
                        where x.CIds.Contains(y.Id)
                        select new {
                               Id = y.Id,
                               Type = x.Type
                }).ToList();

Body:
This is simple and iterative, and there may well be a better solution. However it will do what you need.

public void SetTypeOnCList(List<D> dlist, List<C> clist)
{
    clist.ForEach(c =>
    {
        var dobj = dlist.FirstOrDefault(d => d.CIds.Contains(c.Id));
        if (dobj != null)
        {
            c.Type = dobj.Type;
        }
    });
}


问:
Activity is resetting values
I have an activity that sum distance according user walks. The problem is when app goes to background and after something around 50 minutes I resume activity, values start again.
I have tried too many things to solve this problem without success.

Does someone have any idea?

Thanks

答:
You will need to implement the following two methods in your activity:

```<code>public void onRestoreInstanceState(Bundle savedInstanceState)
public void onSaveInstanceState(Bundle outState)
</code>```

In onSaveInstanceState() you persist any relevant data, and in onRestoreInstanceState() you retrieve those persistent values and refresh the data for UI.

Update

After implements this methods, you need to add in your onCreate method

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
  if (savedInstanceState != null) {
        if (savedInstanceState.containsKey(YOUR_KEY_DATA)) {
            long your_long = savedInstanceState.getLong(YOUR_KEY_DATA, 0);
      ......
}
</code>```

Title: Activity is resetting values

Body:
You will need to implement the following two methods in your activity:

public void onRestoreInstanceState(Bundle savedInstanceState)
public void onSaveInstanceState(Bundle outState)

In onSaveInstanceState() you persist any relevant data, and in onRestoreInstanceState() you retrieve those persistent values and refresh the data for UI.

Update

After implements this methods, you need to add in your onCreate method

@Override
protected void onCreate(Bundle savedInstanceState) {
  if (savedInstanceState != null) {
        if (savedInstanceState.containsKey(YOUR_KEY_DATA)) {
            long your_long = savedInstanceState.getLong(YOUR_KEY_DATA, 0);
      ......
}


问:
how to call python module with package name
I want to make a distributable python module, so I want to make users call functions inside of my module via just calling package name.

e.g.

/my_package/

/my_package/__init__.py

/my_package/src/

/my_package/src/__init__.py

/my_package/src/my_module.py

and, the contents of mymodule.py:

def test(): print('hello!')

in this case, I want to let users use my module like:

>>> import mypackage as mp

>>> mp.test()

hello!

just like tensorflow, numpy, etc. !!!

How should I configure __init__.py file and path info??

答:
In the file:

/my_package/__init__.py

add the line:

```<code>from src.my_module import test
</code>```

Body:
In the file:

/my_package/__init__.py

add the line:

from src.my_module import test


问:
Custom function to create an index of results
I’m trying to create a function which creates an index (starting at 100) and then adjust this index according to the results of investments. So, in a nutshell, if the first investment gives an profit of 5%, then the index will stand 105, if the second result is -7%, then the index stands at 97.65. In this question when I use the word "index", I'm not referring to the index function of the zoo package.

Besides creating this index, my goal is also to create an function which can be applied to various subsets of my complete data set (i.e. with the use of sapply and it's friends).

Here’s the function which I have so far (data at end of this question):

```<code>CalculateIndex <- function(x){
    totalAccount <- accountValueStart
    if(x$TradeResult.Currency == head(x$TradeResult.Currency., n = 1)){
        indexedValues <- 100 + ( 100 *((((x$Size.Units. * x$EntryPrice) / totalAccount) * x$TradeResult.Percent.) / 100))
        # Update the accountvalue
        totalAccount <- totalAccount + x$TradeResult.Currency.
    }
    else{ # the value is not the first
        indexedValues <- c(indexedValues,
                indexedValues[-1] + (indexedValues[-1] *(((x$Size.Units. * x$EntryPrice) / totalAccount) * x$TradeResult.Percent.) / 100)
                )
            # Update the accountvalue
            totalAccount <- totalAccount + x$TradeResult.Currency.
    }
    return(indexedValues)
}
</code>```

In words the function does (read: is intended to do) the following:
If the value is the first, use 100 as an starting point for the index. If the value is not the first, use the previous calculated index value as the starting point for calculating the new index value. Besides this, the function also takes the weight of the individual result (compared with the totalAccount value) into account.

The problem:
Using this CalculateIndex function on the theData data frame gives the following incorrect output:

```<code>> CalculateIndex(theData)
 [1]  99.97901  99.94180  99.65632 101.88689 100.89309  98.92878 102.02911 100.49159  98.52955 102.02243  98.43655 100.76502  99.34869 100.76401 101.18014  99.75136  97.90130
[18] 100.39935  99.81311 101.34961
Warning message:
In if (x$TradeResult.Currency == head(x$TradeResult.Currency., n = 1)) { :
  the condition has length > 1 and only the first element will be used
</code>```

Edit:
Wow, I already got an vote down, though I thought my question was already too long. Sorry, I thought/think the problem lay inside my loop, so I didn't want to bore you with the details, which I thought would only give less answers. Sorry, misjudgement on my part.

The problem is, with the above output from CalculateIndex, that the results are wildly different from Excel. Even though this could be resulting from rounding errors (as Joris mentions below), I doubt it. In comparison with the Excel results, the R results differ quite some:

```<code>R output    Excel calculate values
99,9790085700   99,97900857
99,9418035700   99,92081189
99,6563228600   99,57713687
101,8868850000  101,4639947
100,8930864300  102,3570786
98,9287771400   101,2858564
102,0291071400  103,3149664
100,4915864300  103,806556
98,5295542900   102,3361186
102,0224285700  104,3585552
98,4365550000   102,795089
100,7650171400  103,5601228
99,3486857100   102,9087897
100,7640057100  103,6728077
101,1801400000  104,8529634
99,7513600000   104,6043164
97,9013000000   102,5055298
100,3993485700  102,9048999
99,8131085700   102,7179995
101,3496071400  104,0676555
</code>```

I think it would be fair to say that the difference in output isn't the result of R versus Excel problems, but more an error in my function. So, let's focus on the function.

The manual calculation of the function
The function uses different variables:

Size.Units.; this is the number of units which are bought at the EntryPrice.

EntryPrice: the price at which the stocks are bought,

TradeResult.Percent.: the percentage gain or loss resulting from the investment,

TradeResult.Currency.: the currency value ($) of the gain or loss resulting from the investment,

These variables are used in the following section of the function:

```<code>100 + ( 100 *((((x$Size.Units. * x$EntryPrice) / totalAccount) * x$TradeResult.Percent.) / 100))
</code>```

and

```<code>indexedValues[-1] + (indexedValues[-1] *(((x$Size.Units. * x$EntryPrice) / totalAccount) * x$TradeResult.Percent.) / 100)
</code>```

Both of the formula's are essentially the same, with the difference that the the first starts at 100, and the second uses the previous value to calculate the new indexed value.

The formula can be broken down in different steps:

First, x$Size.Units. * x$EntryPrice determines the total position that was taken, in the sense that buying 100 shares at an price of 48.98 gives an position of $4898.

The resulting total position is then divided by the total account size (i.e. totalAccount). This is needed to correct the impact of one position relative to the complete portfolio. For example, if our 100 shares bought at 48.98 drop 10 percent, the calculated index (i.e. the CalculateIndex function) doesn't have to drop 10%, because off course not all the money in totalAccount is invested in one stock. So, by dividing the total position by the totalAccount we get an ratio which tells us how much money is invested. For example, the position with the size of 4898 dollar (on a total account of 14000) results in a total account loss of 3.49% if the stock drops 10%. (i.e. 4898 / 14000 = 0.349857. 0.349857 * 10% = 3.49857%)

This ratio (of invested amount versus total amount) is then in the formula multiplied with x$TradeResult.Percent., so to get the percentage impact on the total account (see calculation example in the previous paragraph).

As an last step, the percentage loss on the total account is applied to the index value (which starts at 100). In this case, the first investment in 100 shares bought at 48.89 dollar let's the index drop from it starting point at 100 to 99.97901, reflecting the losing trade's impact on the total account.

End of Edit

Stripping the function clean and then adding a part of the formula at a time, so to uncover the error, I came to the following step where the error seems to reside:

```<code>CalculateIndex <- function(x){
    totalAccount <- accountValueStart
    if(x$TradeResult.Currency == head(x$TradeResult.Currency., n = 1)){
        indexedValues <- totalAccount
        # Update the accountvalue
        totalAccount <- totalAccount + x$TradeResult.Currency.
    }
    else{ # the value is not the first
        indexedValues <- c(indexedValues, totalAccount)
            # Update the accountvalue
            totalAccount <- totalAccount + x$TradeResult.Currency.
    }
    return(indexedValues)
}
> CalculateIndex(theData)
[1] 14000
Warning message:
In if (x$TradeResult.Currency == head(x$TradeResult.Currency., n = 1)) { :
  the condition has length > 1 and only the first element will be used
</code>```

So, it seems that if I just use the totalAccount variable, the function doesn’t get updated correctly. This seems to suggest there is some error with the basics of the if else statement, because it only outputs the first value.

If I remove the else statement from the function, I do get values for each of the rows in theData. However, these are then wrongly calculated. So, it seems to me that there is some error in how this function updates the totalAccount variable. I don’t see where I made an error, so any suggestion would be highly appreciated. What am I doing wrong?

The Data

Here’s what my data looks like:

```<code>> theData
   Size.Units. EntryPrice TradeResult.Percent. TradeResult.Currency.
1          100      48.98                -0.06                    -3
11         100      32.59                -0.25                    -8
12         100      32.51                -1.48                   -48
2          100      49.01                 5.39                   264
13         100      32.99                 3.79                   125
14         100      34.24                -4.38                  -150
3          100      51.65                 5.50                   284
4          100      48.81                 1.41                    69
15         100      35.74                -5.76                  -206
5          100      49.50                 5.72                   283
6          100      46.67                -4.69                  -219
16         100      33.68                 3.18                   107
7          100      44.48                -2.05                   -91
17         100      32.61                 3.28                   107
8          100      45.39                 3.64                   165
9          100      47.04                -0.74                   -35
10         100      47.39                -6.20                  -294
18         100      33.68                 1.66                    56
19         100      33.12                -0.79                   -26
20         100      32.86                 5.75                   189

theData <- structure(list(X = c(1L, 11L, 12L, 2L, 13L, 14L, 3L, 4L, 15L,
    5L, 6L, 16L, 7L, 17L, 8L, 9L, 10L, 18L, 19L, 20L), Size.Units. = c(100L,
    100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L,
    100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L), EntryPrice = c(48.98,
    32.59, 32.51, 49.01, 32.99, 34.24, 51.65, 48.81, 35.74, 49.5,
    46.67, 33.68, 44.48, 32.61, 45.39, 47.04, 47.39, 33.68, 33.12,
    32.86), TradeResult.Percent. = c(-0.06, -0.25, -1.48, 5.39, 3.79,
    -4.38, 5.5, 1.41, -5.76, 5.72, -4.69, 3.18, -2.05, 3.28, 3.64,
    -0.74, -6.2, 1.66, -0.79, 5.75), TradeResult.Currency. = c(-3L,
    -8L, -48L, 264L, 125L, -150L, 284L, 69L, -206L, 283L, -219L,
    107L, -91L, 107L, 165L, -35L, -294L, 56L, -26L, 189L)), .Names = c("X",
    "Size.Units.", "EntryPrice", "TradeResult.Percent.", "TradeResult.Currency."
    ), class = "data.frame", row.names = c(NA, -20L))

# Set the account start @ 14000
> accountValueStart <- 14000
</code>```

答:
I'm still slightly confused as to what exactly you want to do, but hopefully the following will be helpful.

Your R script gives the same answers as your Excel function for the first value. You see a difference because R doesn't print out all digits.

```<code>> tmp = CalculateIndex(thedata)
Warning message:
In if (x$TradeResult.Currency == head(x$TradeResult.Currency., n = 1)) { :
  the condition has length > 1 and only the first element will be used
> print(tmp, digits=10)
 [1]  99.97900857  99.94180357  99.65632286 101.88688500 100.89308643
 <snip>
</code>```

The reason for the warning message is because x$TradeResult.Currency is a vector that is being compared to a single number.

That warning message is also where your bug lives. In your if statement, you never execute the else part, since only the value of x$TradeResult.Currency is being used. As the warning message states, only the first element of x$TradeResult.Currency is being used.

Body:
I’m trying to create a function which creates an index (starting at 100) and then adjust this index according to the results of investments. So, in a nutshell, if the first investment gives an profit of 5%, then the index will stand 105, if the second result is -7%, then the index stands at 97.65. In this question when I use the word "index", I'm not referring to the index function of the zoo package.

Besides creating this index, my goal is also to create an function which can be applied to various subsets of my complete data set (i.e. with the use of sapply and it's friends).

Here’s the function which I have so far (data at end of this question):

CalculateIndex <- function(x){
    totalAccount <- accountValueStart
    if(x$TradeResult.Currency == head(x$TradeResult.Currency., n = 1)){
        indexedValues <- 100 + ( 100 *((((x$Size.Units. * x$EntryPrice) / totalAccount) * x$TradeResult.Percent.) / 100))
        # Update the accountvalue
        totalAccount <- totalAccount + x$TradeResult.Currency.
    }
    else{ # the value is not the first
        indexedValues <- c(indexedValues,
                indexedValues[-1] + (indexedValues[-1] *(((x$Size.Units. * x$EntryPrice) / totalAccount) * x$TradeResult.Percent.) / 100)
                )
            # Update the accountvalue
            totalAccount <- totalAccount + x$TradeResult.Currency.
    }
    return(indexedValues)
}

In words the function does (read: is intended to do) the following:
If the value is the first, use 100 as an starting point for the index. If the value is not the first, use the previous calculated index value as the starting point for calculating the new index value. Besides this, the function also takes the weight of the individual result (compared with the totalAccount value) into account.

The problem:
Using this CalculateIndex function on the theData data frame gives the following incorrect output:

> CalculateIndex(theData)
 [1]  99.97901  99.94180  99.65632 101.88689 100.89309  98.92878 102.02911 100.49159  98.52955 102.02243  98.43655 100.76502  99.34869 100.76401 101.18014  99.75136  97.90130
[18] 100.39935  99.81311 101.34961
Warning message:
In if (x$TradeResult.Currency == head(x$TradeResult.Currency., n = 1)) { :
  the condition has length > 1 and only the first element will be used

Edit:
Wow, I already got an vote down, though I thought my question was already too long. Sorry, I thought/think the problem lay inside my loop, so I didn't want to bore you with the details, which I thought would only give less answers. Sorry, misjudgement on my part.

The problem is, with the above output from CalculateIndex, that the results are wildly different from Excel. Even though this could be resulting from rounding errors (as Joris mentions below), I doubt it. In comparison with the Excel results, the R results differ quite some:

R output    Excel calculate values
99,9790085700   99,97900857
99,9418035700   99,92081189
99,6563228600   99,57713687
101,8868850000  101,4639947
100,8930864300  102,3570786
98,9287771400   101,2858564
102,0291071400  103,3149664
100,4915864300  103,806556
98,5295542900   102,3361186
102,0224285700  104,3585552
98,4365550000   102,795089
100,7650171400  103,5601228
99,3486857100   102,9087897
100,7640057100  103,6728077
101,1801400000  104,8529634
99,7513600000   104,6043164
97,9013000000   102,5055298
100,3993485700  102,9048999
99,8131085700   102,7179995
101,3496071400  104,0676555

I think it would be fair to say that the difference in output isn't the result of R versus Excel problems, but more an error in my function. So, let's focus on the function.

The manual calculation of the function
The function uses different variables:

Size.Units.; this is the number of units which are bought at the EntryPrice.

EntryPrice: the price at which the stocks are bought,

TradeResult.Percent.: the percentage gain or loss resulting from the investment,

TradeResult.Currency.: the currency value ($) of the gain or loss resulting from the investment,

These variables are used in the following section of the function:

100 + ( 100 *((((x$Size.Units. * x$EntryPrice) / totalAccount) * x$TradeResult.Percent.) / 100))

and

indexedValues[-1] + (indexedValues[-1] *(((x$Size.Units. * x$EntryPrice) / totalAccount) * x$TradeResult.Percent.) / 100)

Both of the formula's are essentially the same, with the difference that the the first starts at 100, and the second uses the previous value to calculate the new indexed value.

The formula can be broken down in different steps:

First, x$Size.Units. * x$EntryPrice determines the total position that was taken, in the sense that buying 100 shares at an price of 48.98 gives an position of $4898.

The resulting total position is then divided by the total account size (i.e. totalAccount). This is needed to correct the impact of one position relative to the complete portfolio. For example, if our 100 shares bought at 48.98 drop 10 percent, the calculated index (i.e. the CalculateIndex function) doesn't have to drop 10%, because off course not all the money in totalAccount is invested in one stock. So, by dividing the total position by the totalAccount we get an ratio which tells us how much money is invested. For example, the position with the size of 4898 dollar (on a total account of 14000) results in a total account loss of 3.49% if the stock drops 10%. (i.e. 4898 / 14000 = 0.349857. 0.349857 * 10% = 3.49857%)

This ratio (of invested amount versus total amount) is then in the formula multiplied with x$TradeResult.Percent., so to get the percentage impact on the total account (see calculation example in the previous paragraph).

As an last step, the percentage loss on the total account is applied to the index value (which starts at 100). In this case, the first investment in 100 shares bought at 48.89 dollar let's the index drop from it starting point at 100 to 99.97901, reflecting the losing trade's impact on the total account.

End of Edit

Stripping the function clean and then adding a part of the formula at a time, so to uncover the error, I came to the following step where the error seems to reside:

CalculateIndex <- function(x){
    totalAccount <- accountValueStart
    if(x$TradeResult.Currency == head(x$TradeResult.Currency., n = 1)){
        indexedValues <- totalAccount
        # Update the accountvalue
        totalAccount <- totalAccount + x$TradeResult.Currency.
    }
    else{ # the value is not the first
        indexedValues <- c(indexedValues, totalAccount)
            # Update the accountvalue
            totalAccount <- totalAccount + x$TradeResult.Currency.
    }
    return(indexedValues)
}
> CalculateIndex(theData)
[1] 14000
Warning message:
In if (x$TradeResult.Currency == head(x$TradeResult.Currency., n = 1)) { :
  the condition has length > 1 and only the first element will be used

So, it seems that if I just use the totalAccount variable, the function doesn’t get updated correctly. This seems to suggest there is some error with the basics of the if else statement, because it only outputs the first value.

If I remove the else statement from the function, I do get values for each of the rows in theData. However, these are then wrongly calculated. So, it seems to me that there is some error in how this function updates the totalAccount variable. I don’t see where I made an error, so any suggestion would be highly appreciated. What am I doing wrong?

The Data

Here’s what my data looks like:

> theData
   Size.Units. EntryPrice TradeResult.Percent. TradeResult.Currency.
1          100      48.98                -0.06                    -3
11         100      32.59                -0.25                    -8
12         100      32.51                -1.48                   -48
2          100      49.01                 5.39                   264
13         100      32.99                 3.79                   125
14         100      34.24                -4.38                  -150
3          100      51.65                 5.50                   284
4          100      48.81                 1.41                    69
15         100      35.74                -5.76                  -206
5          100      49.50                 5.72                   283
6          100      46.67                -4.69                  -219
16         100      33.68                 3.18                   107
7          100      44.48                -2.05                   -91
17         100      32.61                 3.28                   107
8          100      45.39                 3.64                   165
9          100      47.04                -0.74                   -35
10         100      47.39                -6.20                  -294
18         100      33.68                 1.66                    56
19         100      33.12                -0.79                   -26
20         100      32.86                 5.75                   189

theData <- structure(list(X = c(1L, 11L, 12L, 2L, 13L, 14L, 3L, 4L, 15L,
    5L, 6L, 16L, 7L, 17L, 8L, 9L, 10L, 18L, 19L, 20L), Size.Units. = c(100L,
    100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L,
    100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L), EntryPrice = c(48.98,
    32.59, 32.51, 49.01, 32.99, 34.24, 51.65, 48.81, 35.74, 49.5,
    46.67, 33.68, 44.48, 32.61, 45.39, 47.04, 47.39, 33.68, 33.12,
    32.86), TradeResult.Percent. = c(-0.06, -0.25, -1.48, 5.39, 3.79,
    -4.38, 5.5, 1.41, -5.76, 5.72, -4.69, 3.18, -2.05, 3.28, 3.64,
    -0.74, -6.2, 1.66, -0.79, 5.75), TradeResult.Currency. = c(-3L,
    -8L, -48L, 264L, 125L, -150L, 284L, 69L, -206L, 283L, -219L,
    107L, -91L, 107L, 165L, -35L, -294L, 56L, -26L, 189L)), .Names = c("X",
    "Size.Units.", "EntryPrice", "TradeResult.Percent.", "TradeResult.Currency."
    ), class = "data.frame", row.names = c(NA, -20L))

# Set the account start @ 14000
> accountValueStart <- 14000

Body:
I'm still slightly confused as to what exactly you want to do, but hopefully the following will be helpful.

Your R script gives the same answers as your Excel function for the first value. You see a difference because R doesn't print out all digits.

> tmp = CalculateIndex(thedata)
Warning message:
In if (x$TradeResult.Currency == head(x$TradeResult.Currency., n = 1)) { :
  the condition has length > 1 and only the first element will be used
> print(tmp, digits=10)
 [1]  99.97900857  99.94180357  99.65632286 101.88688500 100.89308643
 <snip>

The reason for the warning message is because x$TradeResult.Currency is a vector that is being compared to a single number.

That warning message is also where your bug lives. In your if statement, you never execute the else part, since only the value of x$TradeResult.Currency is being used. As the warning message states, only the first element of x$TradeResult.Currency is being used.


问:
Excel - Text to Rows & Columns?
I have a ugly export string coming from another script and I'm wondering if this is possible: E.g. if you have string:

```<code>row1_c1,row2_c1,row3_c1|row1_c2,row_2_c2,row3_c3
</code>```

whats the easiest way to convert to:

```<code>row1_c1    row1_c2
row2_c1    row2_c2
row3_c1    row3_c2
</code>```

If I copy-paste the string into Excel, the text-to-column conversion happens automatically. But how do I deal with the text-to-rows? Is this possible via UDF?

I tried:

```<code>Public Function SplitEnumbersDown(in_ As String)
  Dim Enumbers() As String
  Enumbers = Split(in_, ";")
  Selection(1).Resize(UBound(Enumbers) + 1) = Application.Transpose(Enumbers)
End Function
</code>```

But if I Change the export string to

 =SplitEnumbersDown("row1_c1,row2_c1,row3_c1")|=SplitEnumbersDown("row1_c2,row_2_c2,row3_c3")
 - this has a circular reference... Do I have a error somewhere?

I am aware of the text-to-column, and then paste Special with transpose, but I would like to have it done automatically.

So the end Goal is to copy paste the export string into Excel and automatically convert it.

答:
This should work:

```<code>Option Explicit

Public Sub SplitString()
    Dim inputRange As Range, outputRange As Range
    Dim s() As String
    Dim al As Object
    Dim i As Long

    Set inputRange = ThisWorkbook.Worksheets("Sheet1").Range("A1")
    Set outputRange = inputRange.Offset(1, 0) 'output to cell(s) below
    Set al = CreateObject("System.Collections.ArrayList")

    s = Split(inputRange.Value, "|")
    For i = LBound(s) To UBound(s)
        al.Add Split(s(i), ",")
    Next i

    outputRange.Resize(UBound(v(0)), UBound(v)).Value = Application.Transpose(al.ToArray)
End Sub
</code>```

Title: Excel - Text to Rows & Columns?

Body:
I have a ugly export string coming from another script and I'm wondering if this is possible: E.g. if you have string:

row1_c1,row2_c1,row3_c1|row1_c2,row_2_c2,row3_c3

whats the easiest way to convert to:

row1_c1    row1_c2
row2_c1    row2_c2
row3_c1    row3_c2

If I copy-paste the string into Excel, the text-to-column conversion happens automatically. But how do I deal with the text-to-rows? Is this possible via UDF?

I tried:

Public Function SplitEnumbersDown(in_ As String)
  Dim Enumbers() As String
  Enumbers = Split(in_, ";")
  Selection(1).Resize(UBound(Enumbers) + 1) = Application.Transpose(Enumbers)
End Function

But if I Change the export string to

 =SplitEnumbersDown("row1_c1,row2_c1,row3_c1")|=SplitEnumbersDown("row1_c2,row_2_c2,row3_c3")
 - this has a circular reference... Do I have a error somewhere?

I am aware of the text-to-column, and then paste Special with transpose, but I would like to have it done automatically.

So the end Goal is to copy paste the export string into Excel and automatically convert it.

Body:
This should work:

Option Explicit

Public Sub SplitString()
    Dim inputRange As Range, outputRange As Range
    Dim s() As String
    Dim al As Object
    Dim i As Long

    Set inputRange = ThisWorkbook.Worksheets("Sheet1").Range("A1")
    Set outputRange = inputRange.Offset(1, 0) 'output to cell(s) below
    Set al = CreateObject("System.Collections.ArrayList")

    s = Split(inputRange.Value, "|")
    For i = LBound(s) To UBound(s)
        al.Add Split(s(i), ",")
    Next i

    outputRange.Resize(UBound(v(0)), UBound(v)).Value = Application.Transpose(al.ToArray)
End Sub


问:
the_content() is not displaying any content
I am having some problems trying to display content from WordPress. the_title() works just fine, but the_content() is always empty even though there is content in WordPress. And yes the_content() is inside a loop. I still can't figure out why it's always empty.</p>

```<code><?php if( get_the_post_thumbnail() ):?>
<?php $backgroundImg = wp_get_attachment_image_src(
        get_post_thumbnail_id($post->ID), 'full'); ?>
    <div class="img-container" style="background: linear-gradient(#1abc9c, transparent 80%),url('<?php echo
    $backgroundImg[0]; ?>') no-repeat; background-size: cover;">

        <div class ="text-wrapper">
            <h1 class="single-blog-title"><?php the_title();?></h1>
            <h3 class="single-blog-subtitle"><?php the_secondary_title(); ?></h3>
            <p></p>
        </div>
        <div>

        </div>
    </div>
<?php endif; ?>

<div id="content" class="site-content">
    <div class ="single-blog-content">
        <?php if( have_posts() ): while( have_posts() ): the_post(); ?>
            <p class="blog-author">by <?php the_field('author'); ?></p>
            <h2><?php the_title();?></h2>
            <div>
                <?php the_content();?>
            </div>
        <?php endwhile; endif; ?>
    </div>
</div>
</code>```

答:
I found the $post->post_content to contain the content I required; however it isn't filtered so you will need to apply the the_content filter to apply HTML formatting:

```<code><?php echo apply_filters('the_content', $post->post_content); ?>
</code>```

Body:
I am having some problems trying to display content from WordPress. the_title() works just fine, but the_content() is always empty even though there is content in WordPress. And yes the_content() is inside a loop. I still can't figure out why it's always empty.

<?php if( get_the_post_thumbnail() ):?>
<?php $backgroundImg = wp_get_attachment_image_src(
        get_post_thumbnail_id($post->ID), 'full'); ?>
    <div class="img-container" style="background: linear-gradient(#1abc9c, transparent 80%),url('<?php echo
    $backgroundImg[0]; ?>') no-repeat; background-size: cover;">

<?php the_title();?>

<?php the_secondary_title(); ?>

<?php endif; ?>

        <?php if( have_posts() ): while( have_posts() ): the_post(); ?>

by <?php the_field('author'); ?>

<?php the_title();?>

                <?php the_content();?>

        <?php endwhile; endif; ?>

Body:
I found the $post->post_content to contain the content I required; however it isn't filtered so you will need to apply the the_content filter to apply HTML formatting:

<?php echo apply_filters('the_content', $post->post_content); ?>


问:
pylint can't find QWidget and QApplication
```<code>import sys
from PyQt5.QtWidgets import (QApplication, QWidget)
app = QApplication(sys.argv)
window = QWidget()
window.setGeometry(50, 50, 500, 300)
window.setWindowTitle('Hello, world')
window.show()
sys.exit(app.exec_())
</code>```

I just started to learn pyqt5. I wrote this hello world app, which works. But pylint gives "E0611:No name 'QWidget' in module 'PyQt5.QtWidgets'" and same for QApplication. Is it some kind of bug in pylint?

```<code>pylint --version
No config file found, using default configuration
pylint 1.7.2,
astroid 1.5.3
Python 3.5.2 (default, Aug 18 2017, 17:48:00)
[GCC 5.4.0 20160609]
</code>```

答:
I found solution in this page:
http://python.6.x6.nabble.com/PyQt-and-pylint-with-quot-no-name-in-module-quot-td5217888.html

so using it in terminal as (for main.py):

```<code>pylint main.py --extension-pkg-whitelist=PyQt5
</code>```

Body:
import sys
from PyQt5.QtWidgets import (QApplication, QWidget)
app = QApplication(sys.argv)
window = QWidget()
window.setGeometry(50, 50, 500, 300)
window.setWindowTitle('Hello, world')
window.show()
sys.exit(app.exec_())

I just started to learn pyqt5. I wrote this hello world app, which works. But pylint gives "E0611:No name 'QWidget' in module 'PyQt5.QtWidgets'" and same for QApplication. Is it some kind of bug in pylint?

pylint --version
No config file found, using default configuration
pylint 1.7.2,
astroid 1.5.3
Python 3.5.2 (default, Aug 18 2017, 17:48:00)
[GCC 5.4.0 20160609]

Body:
I found solution in this page:
http://python.6.x6.nabble.com/PyQt-and-pylint-with-quot-no-name-in-module-quot-td5217888.html

so using it in terminal as (for main.py):

pylint main.py --extension-pkg-whitelist=PyQt5


问:
What should I use for performance sensitive data access?
So I have an application which requires very fast access to large volumes of data and we're at the stage where we're undergoing a large re-design of the database, which gives a good opertunity to re-write the data access layer if nessersary!

Currently in our data access layer we use manually created entities along with plain SQL to fill them. This is pretty fast, but this technology is really getting old, and I'm concerned we're missing out on a newer framework or data access method which could be better in terms of neatness and maintainability.

We've seen the Entity Framework, but after some research it just seems that the benefit of the ORM it gives is not enough to justify the lower performance and as some of our queries are getting complex I'm sure performance with the EF would become more of an issue.

So it is a case of sticking with our current methods of data access, or is there something a bit neater than manually creating and maintaining entities?

I guess the thing that's bugging me is just opening our data layer solution and seeing lots of entities, all of which need to be maintained exactly in line with the database, which sometimes can be a lot of work, but then maybe this is the price we pay for performance?

Any ideas, comments and suggestions are very appreciated! :)

Thanks,

Andy.

** Update **

Forgot to mention that we really need to be able to handle using Azure (client requirements), which currently stops us from using stored procedures. ** Update 2 ** Actually we have an interface layer for our DAL which means we can created an Azure implementation which just override data access methods from the Local implementation which aren't suitable for Azure, so I guess we could just use stored procedures for performance sensitive local databases with EF for the cloud.

答: You could try using mybatis (previously known as ibatis). It allows you to map sql statements to domain objects. This way you keep full control over SQL being executed and get cleanly defined domain model at the same time.</p>


问:
module radio for micro:bit (python)
here is my code for my microbit in python

so i want to know how do i send the target_x and the target_y from the microbit 1 to the second microbit ?

microbit 1 :

```<code>radio.on()
target_x = random.randint(0,4)
target_y = random.randint(0,4)
if button_a.was.pressed():
    radio.send()
</code>```

microbit 2 :

```<code>radio.on()
order = radio.receive()
microbit.display.set_pixel(target_x,target_y,7)
</code>```

so i want to know how do i send the target_x and the target_y from the microbit 1 to the second microbit ?

thanks for your answers

答:
I tested the code below using two microbits. I put in an 'except, try' clause on the receiver in case the message is corrupted. There is more error checking that should be implemented to make a reliable wireless interface, but this answers the question.

radio_send_randints.py

```<code>''' transmit random x and y on button push '''
import random
from microbit import *
import radio

radio.config(group=0)
radio.on()

while True:
    if button_a.was_pressed():
        target_x = random.randint(0,4)
        target_y = random.randint(4)
        message = "{},{}".format(target_x, target_y)
        radio.send(message)
    sleep(100)
</code>```

radio_receive_randints.py

```<code>from microbit import *
import radio

radio.config(group=0)
radio.on()

while True:
    incoming = radio.receive()
    if incoming:
        try:
            target_x, target_y = incoming.split(',')
        except:
            continue
        display.set_pixel(int(target_x), int(target_y), 7)
</code>```

Title: module radio for micro:bit (python)

Body:
here is my code for my microbit in python

so i want to know how do i send the target_x and the target_y from the microbit 1 to the second microbit ?

microbit 1 :

radio.on()
target_x = random.randint(0,4)
target_y = random.randint(0,4)
if button_a.was.pressed():
    radio.send()

microbit 2 :

radio.on()
order = radio.receive()
microbit.display.set_pixel(target_x,target_y,7)

so i want to know how do i send the target_x and the target_y from the microbit 1 to the second microbit ?

thanks for your answers

Body:
I tested the code below using two microbits. I put in an 'except, try' clause on the receiver in case the message is corrupted. There is more error checking that should be implemented to make a reliable wireless interface, but this answers the question.

radio_send_randints.py

''' transmit random x and y on button push '''
import random
from microbit import *
import radio

radio.config(group=0)
radio.on()

while True:
    if button_a.was_pressed():
        target_x = random.randint(0,4)
        target_y = random.randint(4)
        message = "{},{}".format(target_x, target_y)
        radio.send(message)
    sleep(100)

radio_receive_randints.py

from microbit import *
import radio

radio.config(group=0)
radio.on()

while True:
    incoming = radio.receive()
    if incoming:
        try:
            target_x, target_y = incoming.split(',')
        except:
            continue
        display.set_pixel(int(target_x), int(target_y), 7)


问:
What is the HTTP URL to stream the sub-stream channel from Dahua/CP-PLus camera
I got the RTSP equivalent, which is:

```<code>rtsp://my_cam_ip:554/cam/realmonitor?channel=1&subtype=1
</code>```

I came across some equivalents in https://www.ispyconnect.com/man.aspx?n=CP+PLUS, like

```<code>http://my_cam_ip/axis-cgi/mjpg/video.cgi?camera=[CHANNEL]
</code>```

but, it streams only from the main stream.

答:
I've been battling with this for an hour and based on experience with some other makes I've discovered that for the current (2017) Dahua models,  THIS WORKS if you want stream 2 in MJPEG stream:

rtsp://user:pass@:554/cam/realmonitor/channel=1&subtype=2

Subtype=2  not 1,  as indicated by documentation ( subtype=0 gives main and subtype=1 second H264 stream;  Dahua's firmware coder must have considered MJPEG to be a 'tertiary' choice ).

You of course need also to visit the stream configuration pages to put the second stream into MJPEG mode first.

Subtype=2 seems to be undocumented at the moment, I've just had to tell my Dahua dealer to add it to his notes.

Note that the stream wrapper is still RTSP,  it is just the compression payload which is MJPEG.  VLC will display it fine with the URL above.

Note that if you want an mjpeg stream in server-push format (ready for browser) you need to re-wrap it using CVLC or FFMPEG so it's available on a TCP listening socket.

~~~

[  Rudolfs Bundulis - with all respect you missed the point - most decent modern IP cameras can sustain two independent encoding processes so you can run an MJPEG output stream alongside one or more H264 main streams, so it is far more efficient to let the camera do it than to tie up additional hardware in transcoding the stream.  ]

Body:
I got the RTSP equivalent, which is:

rtsp://my_cam_ip:554/cam/realmonitor?channel=1&subtype=1

I came across some equivalents in https://www.ispyconnect.com/man.aspx?n=CP+PLUS, like

http://my_cam_ip/axis-cgi/mjpg/video.cgi?camera=[CHANNEL]

but, it streams only from the main stream.


问:
Loop sizes based on category_id
What's wrong with my code? I have category_id where 1 is for shoe sizes and 2 for apparel sizes. It shows only val for category_id(1) and for category_id(2) it shows only "Large". Thanks.

<select class="sm-form-control" name="product_size" id="product_size">
  <option value="">Size</option>
</select>
```

<pre class="lang-js prettyprint-override"><code>function modal_product_extension(id, category_id) {
    $('#addSize').modal('show');
    $('#addSize').find($('#product_id')).val(id);
    $('#addSize').find($('#categories_id')).val(category_id);
    $('#addSize').find($('#product_price')).val('0');
    $('#addSize').find($('#product_stocks')).val('0');

    var $productSize = $("#product_size")
    if (category_id == "1") {
        var i;
        $productSize.empty()
        for (i = 3; i <= 15; i++) {
            val = i;
            $productSize.append("<option value='"+val+"'>"+ val +"</option>");
        }
    } else if (category_id == "2") {
        $productSize.empty()
        $productSize.append("<option value='S'>Small</option>");
        $productSize.append("<option value='M'>Medium</option>");
        $productSize.append("<option value='L'>Large</option>");
    } else if (category_id == "0") {
        $productSize.empty()
        $productSize.append("<option value=''>Size</option>");
    }
}
</code>```

答:
If I understand correctly, you want to add multiple options to a select element based on the category id. Right now you are changing the html of the select element instead of adding options to it.

In the snippet below I've replaced your html with append so it will actually add the options instead of replace it. An example is given with category_id = 2.

function modal_product_extension(id, category_id) {

  $('#addSize').find($('#product_id')).val(id);
  $('#addSize').find($('#category_id')).val(category_id);
  $('#addSize').find($('#product_price')).val('0');
  $('#addSize').find($('#product_stocks')).val('0');

  if (category_id == "1") {
    var i;
    for (i = 3; i <= 15; i++) {
      val = i;
      $("#product_size").append("<option value='val'>" + val + "</option>");
    }
  } else if (category_id == "2") {
    $("#product_size").append("<option value='S'>Small</option>");
    $("#product_size").append("<option value='M'>Medium</option>");
    $("#product_size").append("<option value='L'>Large</option>");
  } else if (category_id == "0") {
    $("#product_size").append("<option value=''>Size</option>");
  }
}

modal_product_extension(1, 1);```
<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>
<select class="sm-form-control" name="product_size" id="product_size">
</select></code>```

Title: Loop sizes based on category_id

Body:
What's wrong with my code? I have category_id where 1 is for shoe sizes and 2 for apparel sizes. It shows only val for category_id(1) and for category_id(2) it shows only "Large". Thanks.

<select class="sm-form-control" name="product_size" id="product_size">
  <option value="">Size</option>
</select>

function modal_product_extension(id, category_id) {
    $('#addSize').modal('show');
    $('#addSize').find($('#product_id')).val(id);
    $('#addSize').find($('#categories_id')).val(category_id);
    $('#addSize').find($('#product_price')).val('0');
    $('#addSize').find($('#product_stocks')).val('0');

    var $productSize = $("#product_size")
    if (category_id == "1") {
        var i;
        $productSize.empty()
        for (i = 3; i <= 15; i++) {
            val = i;
            $productSize.append("<option value='"+val+"'>"+ val +"</option>");
        }
    } else if (category_id == "2") {
        $productSize.empty()
        $productSize.append("<option value='S'>Small</option>");
        $productSize.append("<option value='M'>Medium</option>");
        $productSize.append("<option value='L'>Large</option>");
    } else if (category_id == "0") {
        $productSize.empty()
        $productSize.append("<option value=''>Size</option>");
    }
}

Body:
If I understand correctly, you want to add multiple options to a select element based on the category id. Right now you are changing the html of the select element instead of adding options to it.

In the snippet below I've replaced your html with append so it will actually add the options instead of replace it. An example is given with category_id = 2.

function modal_product_extension(id, category_id) {

  $('#addSize').find($('#product_id')).val(id);
  $('#addSize').find($('#category_id')).val(category_id);
  $('#addSize').find($('#product_price')).val('0');
  $('#addSize').find($('#product_stocks')).val('0');

  if (category_id == "1") {
    var i;
    for (i = 3; i <= 15; i++) {
      val = i;
      $("#product_size").append("<option value='val'>" + val + "</option>");
    }
  } else if (category_id == "2") {
    $("#product_size").append("<option value='S'>Small</option>");
    $("#product_size").append("<option value='M'>Medium</option>");
    $("#product_size").append("<option value='L'>Large</option>");
  } else if (category_id == "0") {
    $("#product_size").append("<option value=''>Size</option>");
  }
}

modal_product_extension(1, 1);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="sm-form-control" name="product_size" id="product_size">
</select>


答:
The issue is because html() removes the current content and overwrites it. Hence you will only ever see the last content you set.

To fix the problem use append() and empty() in the first condition and a single html() call in the second condition. Also note that you need to concatenate the val variable in the HTML you set in the first condition too. Try this:

```<code>function modal_product_extension(id, category_id) {
  var $addSize = $('#addSize').modal('show');
  $addSize.find('#product_id').val(id);
  $addSize.find('#category_id').val(category_id);
  $addSize.find('#product_price').val('0');
  $addSize.find('#product_stocks').val('0');

  var $productSize = $("#product_size")
  if (category_id == "1") {
    $productSize.empty()
    for (var i = 3; i <= 15; i++) {
      $productSize.append('<option value="' + val + '">' + val + '</option>');
    }
  } else if (category_id == "2") {
    $productSize.html('<option value="S">Small</option><option value="M">Medium</option><option value="L">Large</option>');
  } else if (categories_id == "0") {
    $productSize.html('<option value="">Size</option>');
  }
}
</code>```

Title: Loop sizes based on category_id

Body:
The issue is because html() removes the current content and overwrites it. Hence you will only ever see the last content you set.

To fix the problem use append() and empty() in the first condition and a single html() call in the second condition. Also note that you need to concatenate the val variable in the HTML you set in the first condition too. Try this:

function modal_product_extension(id, category_id) {
  var $addSize = $('#addSize').modal('show');
  $addSize.find('#product_id').val(id);
  $addSize.find('#category_id').val(category_id);
  $addSize.find('#product_price').val('0');
  $addSize.find('#product_stocks').val('0');

  var $productSize = $("#product_size")
  if (category_id == "1") {
    $productSize.empty()
    for (var i = 3; i <= 15; i++) {
      $productSize.append('<option value="' + val + '">' + val + '</option>');
    }
  } else if (category_id == "2") {
    $productSize.html('<option value="S">Small</option><option value="M">Medium</option><option value="L">Large</option>');
  } else if (categories_id == "0") {
    $productSize.html('<option value="">Size</option>');
  }
}


答:
Are you sure that your variable is date type. getHours() is a JS function for getting the hours from a date.

 Double check the type before. If is not, then you just parse the datetime string, using
 let minutes = parseInt(datetime.split(' ')[1].split(':')[0]);

Title: Bootstrap datetimepicker parsing data

Body:
I want to parse hours and minutes from selected date&time.

var datetime = $('#datetimepicker').data('date');

gives: 2017-11-01 11:50

If I want to parse hours and minutes :

time = datetime.getHours()+':'+datetime.getMinutes();

error will occure : Uncaught TypeError: datetime.getHours is not a function.

Which functions to use, to parse data from date above?


答:
Use the Date object:</p>

```<code>var datetime = new Date($('#datetimepicker').data('date'));
var time = datetime.getHours()+':'+datetime.getMinutes();
</code>```

Title: Bootstrap datetimepicker parsing data

Body:
Use the Date object:

var datetime = new Date($('#datetimepicker').data('date'));
var time = datetime.getHours()+':'+datetime.getMinutes();


问:
Angular4/MEAN does not render data on the template
I am learning MEAN stack with Angular4 and got stuck up with a problem.I use a service to get the data from the node.js and it is subscribed by app.component.
Logging the result displays  the right output however, on rendering it on the template doesn't works.There is no warnings or any other errors but data is not displayed on the template.

Here is the Service

```<code>import { Injectable } from '@angular/core';
import { Http,Headers,RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class DataserviceService {
    result:any;
    constructor(private http:Http) { }
    getusers()
       {
           return this.http.get('/users').map( result => this.result = result.json());
       }
    }
</code>```

App.component.ts

```<code>import { Component } from '@angular/core';
import { DataserviceService } from './dataservice.service';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
    users : Array<any> = [];
    constructor(private dataserv : DataserviceService)
     {
        this.dataserv.getusers().subscribe(function(result)
         {
            this.users = result;
            console.log(result);//result is rightly displayed on the console.
        });
    }
}
</code>```

and here is the template

```<code><div *ngIf="users">
  <h2>Results </h2>
  <ul>
    <li *ngFor="let user of users">{{ user.name }}</li>
  </ul>
</div>
</code>```

答:
try like this :

use *ngIf="users.length > 0" instead of *ngIf="users"

```<code><div *ngIf="users.length > 0">
  <h2>Results </h2>
  <ul>
    <li *ngFor="let user of users">{{ user.name }}</li>
  </ul>
</div>
</code>```

Body:
I am learning MEAN stack with Angular4 and got stuck up with a problem.I use a service to get the data from the node.js and it is subscribed by app.component.
Logging the result displays  the right output however, on rendering it on the template doesn't works.There is no warnings or any other errors but data is not displayed on the template.

Here is the Service

import { Injectable } from '@angular/core';
import { Http,Headers,RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class DataserviceService {
    result:any;
    constructor(private http:Http) { }
    getusers()
       {
           return this.http.get('/users').map( result => this.result = result.json());
       }
    }

App.component.ts

import { Component } from '@angular/core';
import { DataserviceService } from './dataservice.service';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
    users : Array<any> = [];
    constructor(private dataserv : DataserviceService)
     {
        this.dataserv.getusers().subscribe(function(result)
         {
            this.users = result;
            console.log(result);//result is rightly displayed on the console.
        });
    }
}

and here is the template

Results

{{ user.name }}

Body:
try like this :

use *ngIf="users.length > 0" instead of *ngIf="users"

<div *ngIf="users.length > 0">
  <h2>Results </h2>
  <ul>
    <li *ngFor="let user of users">{{ user.name }}</li>
  </ul>
</div>


问:
Why is the Parse error is occured in this code? PHP
I am working on Magento project.There I have a controller which is a php file.I want to write a JavaScript function inside that php file.
This is the function which results in the error,

```<code> public function verifyPinAction()
         {
           $data = $this->getRequest()->getPost();
             echo "<script type='text/javascript'>
           var datastring=<?php echo $data['pin'];?>;
           $.ajax({
type: 'POST',
url: 'http://xxxxx.com/xxxxxx/ErrorProcessing1.php',
data : datastring,
//dataType: 'json',

success: function(html) {

   //alert(html);

   if(html=='wrong text entered')
  {
    <?php Mage::getSingleton('core/session')->addError('Invalid Pin Number');
                  $this->_redirect('enterpintoverify'); ?>
  }
  else{
    <?php Mage::getSingleton('core/session')->addSuccess('Your Email is verified');
                $this->_redirect('enterpintoverify');?>
  }

}
});
           </script>
           ";

         }
</code>```

It gives the following error

```<code>Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in /home/xxxxx/public_html/newtradesdev/app/code/local/Customer/Register/controllers/IndexController.php on line 65
</code>```

Line 65 refers to
var datastring=<?php echo $data['pin'];?>;
Can someone tell me where have I gone wrong?

I have used xxxx marks beacause I am working on hosted site.Please skip the urls.

答:
Change your echo to this instead:

```<code>public function verifyPinAction()
{
   $data = $this->getRequest()->getPost();
?>
<!--HTML STARTS HERE-->
<script type='text/javascript'>
           var datastring=<?php echo $data['pin'];?>;
           $.ajax({
type: 'POST',
url: 'http://xxxxx.com/xxxxxx/ErrorProcessing1.php',
data : datastring,
//dataType: 'json',

success: function(html) {

   //alert(html);

   if(html=='wrong text entered')
  {
    <?php Mage::getSingleton('core/session')->addError('Invalid Pin Number');
                  $this->_redirect('enterpintoverify'); ?>
  }
  else{
    <?php Mage::getSingleton('core/session')->addSuccess('Your Email is verified');
                $this->_redirect('enterpintoverify');?>
  }

}
});
           </script>
<!--HTML ENDS HERE-->
<?php

}

?>
</code>```

This presents more readable code and will not cause any errors either.

Body:
I am working on Magento project.There I have a controller which is a php file.I want to write a JavaScript function inside that php file.
This is the function which results in the error,

 public function verifyPinAction()
         {
           $data = $this->getRequest()->getPost();
             echo "
           ";

         }

It gives the following error

Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in /home/xxxxx/public_html/newtradesdev/app/code/local/Customer/Register/controllers/IndexController.php on line 65

Line 65 refers to
var datastring=<?php echo $data['pin'];?>;
Can someone tell me where have I gone wrong?

I have used xxxx marks beacause I am working on hosted site.Please skip the urls.

Body:
Change your echo to this instead:

public function verifyPinAction()
{
   $data = $this->getRequest()->getPost();
?>
<!--HTML STARTS HERE-->
<script type='text/javascript'>
           var datastring=<?php echo $data['pin'];?>;
           $.ajax({
type: 'POST',
url: 'http://xxxxx.com/xxxxxx/ErrorProcessing1.php',
data : datastring,
//dataType: 'json',

success: function(html) {

   //alert(html);

   if(html=='wrong text entered')
  {
    <?php Mage::getSingleton('core/session')->addError('Invalid Pin Number');
                  $this->_redirect('enterpintoverify'); ?>
  }
  else{
    <?php Mage::getSingleton('core/session')->addSuccess('Your Email is verified');
                $this->_redirect('enterpintoverify');?>
  }

}
});
           </script>
<!--HTML ENDS HERE-->
<?php

}

?>

This presents more readable code and will not cause any errors either.


问:
Jasmine calls.length and callCount are undefined
I'm trying to test my chrome extension with Jasmine but I'm having trouble getting calls.length and callCount to behave as expected. Both cases return undefined.

I've included a sample of the code and the spec. Here's the rest of the code if it helps: https://github.com/DruRly/kamikaze/tree/closeIdleTab

How to reproduce:

git clone https://github.com/DruRly/kamikaze/tree/closeIdleTab

cd kamikaze

open SpecRunner.html

spec/kamikazeSpec.js

```<code>describe("kamikaze", function() {
  describe("closeIdleTabs", function(){
    it("calls closeIdleTab for each tab received", function(){
      spyOn(kamikaze, 'closeIdleTab');

      kamikaze.closeIdleTabs([1,2,3]);
      expect(kamikaze.closeIdleTab.calls.length).toBe(3);
    })
  })
})
</code>```

src/kamikaze.js

```<code>kamikaze = {
  ...

  closeIdleTabs: function(tabs){
    tabs.forEach(function(tab){
      test.closeIdleTab(tab);
    })
  },

  closeIdleTab: function(tab){
    if(tabTimeStamps[tab.id]){
      var secondsSinceUpdated = getSecondsSinceUpdated(tab.id)
      if(secondsSinceUpdated > (minutesUntilIdle * 60)){
        chrome.tabs.remove(tab.id)
      }
    }
  },

  ...
}
</code>```

答:
Alternative syntax (with a bit nicer output on failure) would be

```<code>expect(kamikaze.closeIdleTab).toHaveBeenCalledTimes(3);
</code>```

Here is some documentation.

Body:
I'm trying to test my chrome extension with Jasmine but I'm having trouble getting calls.length and callCount to behave as expected. Both cases return undefined.

I've included a sample of the code and the spec. Here's the rest of the code if it helps: https://github.com/DruRly/kamikaze/tree/closeIdleTab

How to reproduce:

git clone https://github.com/DruRly/kamikaze/tree/closeIdleTab

cd kamikaze

open SpecRunner.html

spec/kamikazeSpec.js

describe("kamikaze", function() {
  describe("closeIdleTabs", function(){
    it("calls closeIdleTab for each tab received", function(){
      spyOn(kamikaze, 'closeIdleTab');

      kamikaze.closeIdleTabs([1,2,3]);
      expect(kamikaze.closeIdleTab.calls.length).toBe(3);
    })
  })
})

src/kamikaze.js

kamikaze = {
  ...

  closeIdleTabs: function(tabs){
    tabs.forEach(function(tab){
      test.closeIdleTab(tab);
    })
  },

  closeIdleTab: function(tab){
    if(tabTimeStamps[tab.id]){
      var secondsSinceUpdated = getSecondsSinceUpdated(tab.id)
      if(secondsSinceUpdated > (minutesUntilIdle * 60)){
        chrome.tabs.remove(tab.id)
      }
    }
  },

  ...
}

Body:
Alternative syntax (with a bit nicer output on failure) would be

expect(kamikaze.closeIdleTab).toHaveBeenCalledTimes(3);

Here is some documentation.


问:
Create a variable in a makefile by reading contents of another file
How can I create a variable on-the-fly from makefile, the value of which would be the entire contents of another data file.</p>

答:
GNU make version 4.2 supports file reading operation, so with respect to Maxim Egorushkin's great answer there is an optional way to solve this problem now:</p>

```<code>FILE     := test.txt
variable :=$(file < $(FILE))
</code>```

Body:
GNU make version 4.2 supports file reading operation, so with respect to Maxim Egorushkin's great answer there is an optional way to solve this problem now:

FILE     := test.txt
variable :=$(file < $(FILE))


问:
replace url using preg_replace php
Hi all i know preg_replace can be used for formatting string but
i need help in that concerned area
my url will be like this

```<code>www.example.com/en/index.php
</code>```

or

```<code>www.example.com/fr/index.php
</code>```

what i want is to get

result as

```<code>www.example.com/index.php
</code>```

i need it in php code so as to set in a session

can anyone please explain how ?

答:
Finally i got a method my thanks to Purpletoucan

```<code>$newurl = preg_replace('/\/(en|esp|fr)\//', '/', $url);
</code>```

it's working now i think!

Title: replace url using preg_replace php

Body:
Hi all i know preg_replace can be used for formatting string but
i need help in that concerned area
my url will be like this

www.example.com/en/index.php

or

www.example.com/fr/index.php

what i want is to get

result as

www.example.com/index.php

i need it in php code so as to set in a session

can anyone please explain how ?

Body:
Finally i got a method my thanks to Purpletoucan

$newurl = preg_replace('/\/(en|esp|fr)\//', '/', $url);

it's working now i think!


问:
What is the procedure for installing graylog 2.x on windows..?
I have requirement to setup graylog and elasticsearch on windows.

Version: 2.3.2

答:
Running Graylog on Windows is not supported, see System Requirements.

If you absolutely have to run Graylog on a Windows-based system, you have to use the virtual appliance (OVA) and run it in HyperV/VMWare/VirtualBox.

See Virtual Machine Appliances for details.


问:
Why is the counter decrementing correctly but the countdown is not?
Here is my angular code to define a countdown timer for my website:

function AlbumCtrl($scope, $timeout) {
  $scope.counter = new Date("Nov 30, 2017 09:00:00").getTime() - new Date().getTime();
  $scope.onTimeout = function() {
    $scope.counter--;
    var distance = $scope.counter;
    $scope.countdown = Math.floor(distance / (1000 * 60 * 60 * 24)) + "d " +
      Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)) + "h " +
      Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)) + "m " +
      Math.floor(((distance % (1000 * 60)) / 1000)) + "s ";
    if ($scope.counter > 0) {
      mytimeout = $timeout($scope.onTimeout, 1000);
    } else {
      alert("Time is up!");
    }
  }

  var mytimeout = $timeout($scope.onTimeout, 1000);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <!-- added for a working snippet -->

<!doctype html>
<html ng-app>

<head>
  <script src="http://code.angularjs.org/angular-1.0.0rc11.min.js"></script>
  <script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
</head>

<body>
  <div ng-controller="AlbumCtrl">
    {{counter}} {{countdown}}
  </div>
</body>

</html></code>```

The 'counter' appears to decrement correctly on my page but the 'countdown' stays fixed and shows the correct value only on page load or refresh. For example, I get the following output as time passes:

```<code>    1115148833 12d 21h 45m 48s
    1115148745 12d 21h 45m 48s
    1115148693 12d 21h 45m 48s
</code>```

What exactly is going wrong? Thanks for your help.

答:
For demonstration purposes(to simplify correctness of answer checking) I set destination date to 1 day and 2 hours later from now:

function AlbumCtrl($scope, $timeout) {
  var date = new Date();
  date.setHours(date.getHours() + 2);
  date.setDate(date.getDate() + 1);

  $scope.counter = date.getTime() - new Date().getTime();
  $scope.onTimeout = function() {
    $scope.counter = $scope.counter - 1000;
    var ost = $scope.counter;

    function GetPart(koef) {
      koef *= 1000;
      var res = Math.floor(ost / koef);
      ost = ost - res * koef;
      return res;
    }

    var days = GetPart(60 * 60 * 24);
    var hours = GetPart(60 * 60);
    var min = GetPart(60);
    var sec = GetPart(1);

    $scope.countdown = days + "d " + hours + "h " + min + "m " + sec + "s ";

    if ($scope.counter > 0)
      mytimeout = $timeout($scope.onTimeout, 1000);
    else
      alert("Time is up!");
  }

  var mytimeout = $timeout($scope.onTimeout, 1000);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!-- added for a working snippet -->

<!doctype html>
<html ng-app>

<head>
  <script src="http://code.angularjs.org/angular-1.0.0rc11.min.js"></script>
  <script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
</head>

<body>
  <div ng-controller="AlbumCtrl">
    {{countdown}}
  </div>
</body>

</html></code>```

Body:
Here is my angular code to define a countdown timer for my website:

function AlbumCtrl($scope, $timeout) {
  $scope.counter = new Date("Nov 30, 2017 09:00:00").getTime() - new Date().getTime();
  $scope.onTimeout = function() {
    $scope.counter--;
    var distance = $scope.counter;
    $scope.countdown = Math.floor(distance / (1000 * 60 * 60 * 24)) + "d " +
      Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)) + "h " +
      Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)) + "m " +
      Math.floor(((distance % (1000 * 60)) / 1000)) + "s ";
    if ($scope.counter > 0) {
      mytimeout = $timeout($scope.onTimeout, 1000);
    } else {
      alert("Time is up!");
    }
  }

  var mytimeout = $timeout($scope.onTimeout, 1000);
}

<!doctype html>

    {{counter}} {{countdown}}

The 'counter' appears to decrement correctly on my page but the 'countdown' stays fixed and shows the correct value only on page load or refresh. For example, I get the following output as time passes:

    1115148833 12d 21h 45m 48s
    1115148745 12d 21h 45m 48s
    1115148693 12d 21h 45m 48s

What exactly is going wrong? Thanks for your help.

Body:
For demonstration purposes(to simplify correctness of answer checking) I set destination date to 1 day and 2 hours later from now:

function AlbumCtrl($scope, $timeout) {
  var date = new Date();
  date.setHours(date.getHours() + 2);
  date.setDate(date.getDate() + 1);

  $scope.counter = date.getTime() - new Date().getTime();
  $scope.onTimeout = function() {
    $scope.counter = $scope.counter - 1000;
    var ost = $scope.counter;

    function GetPart(koef) {
      koef *= 1000;
      var res = Math.floor(ost / koef);
      ost = ost - res * koef;
      return res;
    }

    var days = GetPart(60 * 60 * 24);
    var hours = GetPart(60 * 60);
    var min = GetPart(60);
    var sec = GetPart(1);

    $scope.countdown = days + "d " + hours + "h " + min + "m " + sec + "s ";

    if ($scope.counter > 0)
      mytimeout = $timeout($scope.onTimeout, 1000);
    else
      alert("Time is up!");
  }

  var mytimeout = $timeout($scope.onTimeout, 1000);
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!-- added for a working snippet -->

<!doctype html>
<html ng-app>

<head>
  <script src="http://code.angularjs.org/angular-1.0.0rc11.min.js"></script>
  <script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
</head>

<body>
  <div ng-controller="AlbumCtrl">
    {{countdown}}
  </div>
</body>

</html>


问:
canDeactivate method of angular2 router, changing router state even if I select cancel from confirmation popUp
I am using canDeactivate method to block browser navigation in angular2. I am calling a confirmation popup, if user select cancel it doesn't move to another page but the state of the router is being changed. Using angular router version 4.4.4.</p>

答:
Try this:

```<code>export class DeactivateComponent implements CanDeactivate<MyComponent> {
    canDeactivate(component: MyComponent,
                  currentRoute: ActivatedRouteSnapshot,
                  currentState: RouterStateSnapshot,
                  nextState: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

        return component.canDeactivate() || window.confirm("Proceed?");
    }
}
</code>```

Typical path:

```<code>{path: ':id', component: MyComponent, canDeactivate: [DeactivateComponent]},
</code>```

Body:
Try this:

export class DeactivateComponent implements CanDeactivate<MyComponent> {
    canDeactivate(component: MyComponent,
                  currentRoute: ActivatedRouteSnapshot,
                  currentState: RouterStateSnapshot,
                  nextState: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

        return component.canDeactivate() || window.confirm("Proceed?");
    }
}

Typical path:

{path: ':id', component: MyComponent, canDeactivate: [DeactivateComponent]},