问:
How to convert XML to JSON in node.js without having first two elements from xml file?
I would like to know I can I parse XML to JSON without having the two first elements from the first xml conversion, but rather a result like the second convertion. xml2js gives me the first conversion.

```<code> <?xml version="1.0"?>
     <catalog>
       <book id="bk101">
          <author>Gambardella, Matthew</author>
          <title>XML Developer's Guide</title>
          <genre>Computer</genre>
          <price>44.95</price>
          <publish_date>2000-10-01</publish_date>
          <description>An in-depth look at creating applications
          with XML.</description>
       </book>
       <book id="bk102">
          <author>Ralls, Kim</author>
          <title>Midnight Rain</title>
          <genre>Fantasy</genre>
          <price>5.95</price>
          <publish_date>2000-12-16</publish_date>
          <description>A former architect battles corporate zombies,
          an evil sorceress, and her own childhood to become queen
          of the world.</description>
       </book>
    </catalog>
</code>```

When I convert it with xml2json, I get this output :

```<code>`{
  "catalog": {
    "book": [
      {
        "-id": "bk101",
        "author": "Gambardella, Matthew",
        "title": "XML Developer's Guide",
        "genre": "Computer",
        "price": "44.95",
        "publish_date": "2000-10-01",
        "description": "An in-depth look at creating applications
      with XML."
      },
      {
        "-id": "bk102",
        "author": "Ralls, Kim",
        "title": "Midnight Rain",
        "genre": "Fantasy",
        "price": "5.95",
        "publish_date": "2000-12-16",
        "description": "A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world."
      }
    ]
  }
}`
</code>```

But i would want this output:

```<code>`[
   {
      "@id": "bk101",
      "author": "Gambardella, Matthew",
      "title": "XML Developer's Guide",
      "genre": "Computer",
      "price": "44.95",
      "publish_date": "2000-10-01",
      "description": "An in-depth look at creating applications \n      with XML."
   },
   {
      "@id": "bk102",
      "author": "Ralls, Kim",
      "title": "Midnight Rain",
      "genre": "Fantasy",
      "price": "5.95",
      "publish_date": "2000-12-16",
      "description": "A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world."
   }
]`
</code>```

The reason is I need this to insert in my mongodb, but the first conversion only puts all the json as one entry in my database. Also, I have a csv insertion (that I also converted in JSON) that matches the second format and was inserted correctly in the database. Is there a way to get the 2nd format instead of the first one?

答:
Here you go

```<code>const xml = ` <?xml version="1.0"?>
<catalog>
  <book id="bk101">
     <author>Gambardella, Matthew</author>
     <title>XML Developer's Guide</title>
     <genre>Computer</genre>
     <price>44.95</price>
     <publish_date>2000-10-01</publish_date>
     <description>An in-depth look at creating applications
     with XML.</description>
  </book>
  <book id="bk102">
     <author>Ralls, Kim</author>
     <title>Midnight Rain</title>
     <genre>Fantasy</genre>
     <price>5.95</price>
     <publish_date>2000-12-16</publish_date>
     <description>A former architect battles corporate zombies,
     an evil sorceress, and her own childhood to become queen
     of the world.</description>
  </book>
</catalog>`

const { parseString } = require('xml2js')
const opts = {
    mergeAttrs: true,
    attrNameProcessors: [str => '@' + str],
}

parseString(xml, opts, (err, res) => {
    console.log(JSON.stringify(res, null, 2))
})
</code>```

Result:

```<code>{
  "catalog": {
    "book": [
      {
        "@id": "bk101",
        "author": "Gambardella, Matthew",
        "title": "XML Developer's Guide",
        "genre": "Computer",
        "price": "44.95",
        "publish_date": "2000-10-01",
        "description": "An in-depth look at creating applications \n     with XML."
      },
      {
        "@id": "bk102",
        "author": "Ralls, Kim",
        "title": "Midnight Rain",
        "genre": "Fantasy",
        "price": "5.95",
        "publish_date": "2000-12-16",
        "description": "A former architect battles corporate zombies, \n     an evil sorceress, and her own childhood to become queen \n     of the world."
      }
    ]
  }
}
</code>```

Body:
I would like to know I can I parse XML to JSON without having the two first elements from the first xml conversion, but rather a result like the second convertion. xml2js gives me the first conversion.

 <?xml version="1.0"?>
     <catalog>
       <book id="bk101">
          <author>Gambardella, Matthew</author>
          <title>XML Developer's Guide</title>
          <genre>Computer</genre>
          <price>44.95</price>
          <publish_date>2000-10-01</publish_date>
          <description>An in-depth look at creating applications
          with XML.</description>
       </book>
       <book id="bk102">
          <author>Ralls, Kim</author>
          <title>Midnight Rain</title>
          <genre>Fantasy</genre>
          <price>5.95</price>
          <publish_date>2000-12-16</publish_date>
          <description>A former architect battles corporate zombies,
          an evil sorceress, and her own childhood to become queen
          of the world.</description>
       </book>
    </catalog>

When I convert it with xml2json, I get this output :

`{
  "catalog": {
    "book": [
      {
        "-id": "bk101",
        "author": "Gambardella, Matthew",
        "title": "XML Developer's Guide",
        "genre": "Computer",
        "price": "44.95",
        "publish_date": "2000-10-01",
        "description": "An in-depth look at creating applications
      with XML."
      },
      {
        "-id": "bk102",
        "author": "Ralls, Kim",
        "title": "Midnight Rain",
        "genre": "Fantasy",
        "price": "5.95",
        "publish_date": "2000-12-16",
        "description": "A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world."
      }
    ]
  }
}`

But i would want this output:

`[
   {
      "@id": "bk101",
      "author": "Gambardella, Matthew",
      "title": "XML Developer's Guide",
      "genre": "Computer",
      "price": "44.95",
      "publish_date": "2000-10-01",
      "description": "An in-depth look at creating applications \n      with XML."
   },
   {
      "@id": "bk102",
      "author": "Ralls, Kim",
      "title": "Midnight Rain",
      "genre": "Fantasy",
      "price": "5.95",
      "publish_date": "2000-12-16",
      "description": "A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world."
   }
]`

The reason is I need this to insert in my mongodb, but the first conversion only puts all the json as one entry in my database. Also, I have a csv insertion (that I also converted in JSON) that matches the second format and was inserted correctly in the database. Is there a way to get the 2nd format instead of the first one?

Body:
Here you go

const xml = ` <?xml version="1.0"?>
<catalog>
  <book id="bk101">
     <author>Gambardella, Matthew</author>
     <title>XML Developer's Guide</title>
     <genre>Computer</genre>
     <price>44.95</price>
     <publish_date>2000-10-01</publish_date>
     <description>An in-depth look at creating applications
     with XML.</description>
  </book>
  <book id="bk102">
     <author>Ralls, Kim</author>
     <title>Midnight Rain</title>
     <genre>Fantasy</genre>
     <price>5.95</price>
     <publish_date>2000-12-16</publish_date>
     <description>A former architect battles corporate zombies,
     an evil sorceress, and her own childhood to become queen
     of the world.</description>
  </book>
</catalog>`

const { parseString } = require('xml2js')
const opts = {
    mergeAttrs: true,
    attrNameProcessors: [str => '@' + str],
}

parseString(xml, opts, (err, res) => {
    console.log(JSON.stringify(res, null, 2))
})

Result:

{
  "catalog": {
    "book": [
      {
        "@id": "bk101",
        "author": "Gambardella, Matthew",
        "title": "XML Developer's Guide",
        "genre": "Computer",
        "price": "44.95",
        "publish_date": "2000-10-01",
        "description": "An in-depth look at creating applications \n     with XML."
      },
      {
        "@id": "bk102",
        "author": "Ralls, Kim",
        "title": "Midnight Rain",
        "genre": "Fantasy",
        "price": "5.95",
        "publish_date": "2000-12-16",
        "description": "A former architect battles corporate zombies, \n     an evil sorceress, and her own childhood to become queen \n     of the world."
      }
    ]
  }
}


来源: stackexchange

问:
How to set for loop array values to a bean
I have the following loop in a controller class:

```<code>for (int i = 0; i <= locationArr.length - 1; i++) {
    data.put(idArr[i], locationArr[i]);
    locationBean.setLocation_name(locationArr[i]);
}
</code>```

My Bean looks like :

```<code> public class LocationBean {
     private String region_id;
     private String region_name;
     private String location_id;
     private String location_name;

     //getters and setters
 }
</code>```

I am trying to set location_name as setLocation_name(locationArr[i]);
But only getting last values of the loop [i] is being assigned.

答:
If you like to have multiple location names you can do that by e.g. a List or more general any Collection if order does not matter.

Here an example:

```<code>public class LocationBean {
   private String region_id;
   private String region_name;
   private String location_id;
   private List<String> locationNames = new ArrayList<>();

   //getters and setters
   public List<String> getLocationNames() {
        return locationNames;
   }
}
</code>```

usage in your loop:

```<code>locationBean.getLocationNames().add(locationArr[i]);
</code>```

I did not refactor all your example code to be complient to the java naming convention. You should name your variables in camel case.

ContentLicense: CC BY-SA 3.0

Body:
I have the following loop in a controller class:

for (int i = 0; i <= locationArr.length - 1; i++) {
    data.put(idArr[i], locationArr[i]);
    locationBean.setLocation_name(locationArr[i]);
}

My Bean looks like :

 public class LocationBean {
     private String region_id;
     private String region_name;
     private String location_id;
     private String location_name;

     //getters and setters
 }

I am trying to set location_name as setLocation_name(locationArr[i]);
But only getting last values of the loop [i] is being assigned.

Body:
If you like to have multiple location names you can do that by e.g. a List or more general any Collection if order does not matter.

Here an example:

public class LocationBean {
   private String region_id;
   private String region_name;
   private String location_id;
   private List<String> locationNames = new ArrayList<>();

   //getters and setters
   public List<String> getLocationNames() {
        return locationNames;
   }
}

usage in your loop:

locationBean.getLocationNames().add(locationArr[i]);

I did not refactor all your example code to be complient to the java naming convention. You should name your variables in camel case.


问:
Transform condition to numeric 0 1
My datasheet d contain multiple covariates regarding a specific disease. One of them is "Age on diagnosis", which is coded as d$Age.

I want to make a new variable called "Age10" where Age < 10 (age below 10 years on time of diagnosis) is coded 0 and Age >= (age equal to or higher on time of diagnosis) is coded as 1.

I have tried subsetting without succes

Can you help?

答:
The below should work:</p>

```<code>d$Age10 <- as.numeric(d$Age >= 10)
</code>```

Title: Transform condition to numeric 0 1

Body:
The below should work:

d$Age10 <- as.numeric(d$Age >= 10)


问:
Python3-Pip install issues broken packages
Let me start by saying I have limited experience with Linux and this very well may be an easy to answer question.

My dilemma is I am attempting to install hangups through the terminal
sudo apt-get install python3-pip
upon entering this command I receive this message in error
The following packages have unmet dependencies:
 python3-pip : Depends: python-pip-whl (= 8.1.2-2ubuntu0.1) but 8.1.2-3 is to be installed
E: Unable to correct problems, you have held broken packages.

Prior it was Recommending to install setuptools, dev, and whl, as well within that same error message, but I was able to remedy that by searching through multiple threads, which piggybacking off of that point I have done a solid two to three hours of research on this topic scouring threads on different websites, but nothing seems to be working. If anyone has any suggestions please chime in.

*I am running the most recent version of Kubuntu btw if that accounts for anything.

Thanks in advance.

答:
try this : </p>

```<code>  sudo apt-get install curl
  curl https://bootstrap.pypa.io/get-pip.py | sudo python3
</code>```

Body:
try this :

  sudo apt-get install curl
  curl https://bootstrap.pypa.io/get-pip.py | sudo python3


问:
Storing function pointer in std::function
I'm trying to write a C++0x wrapper around dlopen()/dlsym() to dynamically load functions from shared objects:

```<code>class DynamicLoader
{
  public:
    DynamicLoader(std::string const& filename);

    template<class Signature>
      std::function<Signature> load(std::string const& functionName);

  private:
    void *itsLibraryHandle;
};

DynamicLoader::DynamicLoader(std::string const& filename)
{
  itsLibraryHandle = dlopen(filename.c_str(), RTLD_LAZY);

  if(!itsLibraryHandle)
  { /* Throw Some Error */ }
}

  template<class Signature>
std::function<Signature> DynamicLoader::load(std::string const& functionName)
{
  return <insert magic here> dlsym(itsHandle, functionName.c_str());
}
</code>```

Is there a way to convert the void* function pointer returned by dlsym into a std::function?

答:
You just need to cast result of dlsym() call to a proper type. Here's a complete working example:</p>

```<code>#include <functional>
#include <iostream>
#include <stdexcept>
#include <string>
#include <dlfcn.h>

class DynamicLoader
{
public:
    DynamicLoader(std::string const& filename) :
        m_handle(dlopen(filename.c_str(), RTLD_LAZY))
    {
        if (!m_handle)
        {
            throw std::logic_error("can't load library named \"" + filename + "\"");
        }
    }

    template<class T>
    std::function<T> load(std::string const& functionName) const
    {
        dlerror();
        void* const result = dlsym(m_handle, functionName.c_str());
        if (!result)
        {
            char* const error = dlerror();
            if (error)
            {
                throw std::logic_error("can't find symbol named \"" + functionName + "\": " + error);
            }
        }

        return reinterpret_cast<T*>(result);
    }

private:
    void* const m_handle;
};

int main()
{
    DynamicLoader const loader("/lib64/libz.so.1");
    auto const zlibVersion = loader.load<char const* (void)>("zlibVersion");
    std::cout << "zlib version: " << zlibVersion() << std::endl;
    return 0;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to write a C++0x wrapper around dlopen()/dlsym() to dynamically load functions from shared objects:

class DynamicLoader
{
  public:
    DynamicLoader(std::string const& filename);

    template<class Signature>
      std::function<Signature> load(std::string const& functionName);

  private:
    void *itsLibraryHandle;
};

DynamicLoader::DynamicLoader(std::string const& filename)
{
  itsLibraryHandle = dlopen(filename.c_str(), RTLD_LAZY);

  if(!itsLibraryHandle)
  { /* Throw Some Error */ }
}

  template<class Signature>
std::function<Signature> DynamicLoader::load(std::string const& functionName)
{
  return <insert magic here> dlsym(itsHandle, functionName.c_str());
}

Is there a way to convert the void* function pointer returned by dlsym into a std::function?

Body:
You just need to cast result of dlsym() call to a proper type. Here's a complete working example:

#include <functional>
#include <iostream>
#include <stdexcept>
#include <string>
#include <dlfcn.h>

class DynamicLoader
{
public:
    DynamicLoader(std::string const& filename) :
        m_handle(dlopen(filename.c_str(), RTLD_LAZY))
    {
        if (!m_handle)
        {
            throw std::logic_error("can't load library named \"" + filename + "\"");
        }
    }

    template<class T>
    std::function<T> load(std::string const& functionName) const
    {
        dlerror();
        void* const result = dlsym(m_handle, functionName.c_str());
        if (!result)
        {
            char* const error = dlerror();
            if (error)
            {
                throw std::logic_error("can't find symbol named \"" + functionName + "\": " + error);
            }
        }

        return reinterpret_cast<T*>(result);
    }

private:
    void* const m_handle;
};

int main()
{
    DynamicLoader const loader("/lib64/libz.so.1");
    auto const zlibVersion = loader.load<char const* (void)>("zlibVersion");
    std::cout << "zlib version: " << zlibVersion() << std::endl;
    return 0;
}


问:
Filebeat to logstash connection refused
I'm trying to send log files from filebeat->logstash->elastic search.
filebeat.yml. But I'm getting the following error in filebeat log:

```<code>2017-12-07T16:15:38+05:30 ERR  Failed to connect: dial tcp [::1]:5044: connectex: No connection could be made because the target machine actively refused it.
</code>```

My filebeat and logstash configurations are as follows:

1.filebeat.yml

```<code>filebeat.prospectors:

- input_type: log
  paths:
    - C:\Users\shreya\Data\mylog.log
  document_type: springlog
 multiline.pattern: ^\[[0-9]{4}-[0-9]{2}-[0-9]{2}
  multiline.negate: true
  multiline.match: before
output.logstash:
  hosts: ["localhost:5044"]
</code>```

2.logstash.yml

```<code>    http.host: "127.0.0.1"
    http.port: 5044
</code>```

3.logstash conf file:

```<code>input {
     beats {
        port => 5044
    codec => multiline {
    pattern => "^(%{TIMESTAMP_ISO8601})"
        negate => true
        what => "previous"
    }
  }
}
filter {
    grok{
    id => "myspringlogfilter"
    match => { "message" => "%{TIMESTAMP_ISO8601:timestamp}; [LOG_LEVEL=%{LOGLEVEL:log-level}, CMPNT_NM= %{GREEDYDATA:component}, MESSAGE=%{GREEDYDATA:message}" }
    overwrite => ["message"]

    }

}
output {
    elasticsearch {
        hosts => "localhost:9200"
        manage_template => false
            index => "%{[@metadata][beat]}-%{[@metadata][version]}-%{+YYYY.MM.dd}"
        document_type => "%{[@metadata][type]}"
    }
    stdout {
         codec => rubydebug
  }
}
</code>```

答:
Problem got solved after I commented out the metric settings in logstash.yml as follows:

```<code># ------------ Metrics Settings --------------
#
# Bind address for the metrics REST endpoint
#
#http.host: "127.0.0.1"
#
# Bind port for the metrics REST endpoint, this option also accept a range
# (9600-9700) and logstash will pick up the first available ports.
#
#http.port: 5044
#
</code>```

But still do not know why this solved the issue. as both(filebeat and logstash) were pointing to the same port. If someone could explain the reason,
 then prior Thanks!

Title: Filebeat to logstash connection refused

Body:
I'm trying to send log files from filebeat->logstash->elastic search.
filebeat.yml. But I'm getting the following error in filebeat log:

2017-12-07T16:15:38+05:30 ERR  Failed to connect: dial tcp [::1]:5044: connectex: No connection could be made because the target machine actively refused it.

My filebeat and logstash configurations are as follows:

1.filebeat.yml

filebeat.prospectors:

- input_type: log
  paths:
    - C:\Users\shreya\Data\mylog.log
  document_type: springlog
 multiline.pattern: ^\[[0-9]{4}-[0-9]{2}-[0-9]{2}
  multiline.negate: true
  multiline.match: before
output.logstash:
  hosts: ["localhost:5044"]

2.logstash.yml

    http.host: "127.0.0.1"
    http.port: 5044

3.logstash conf file:

input {
     beats {
        port => 5044
    codec => multiline {
    pattern => "^(%{TIMESTAMP_ISO8601})"
        negate => true
        what => "previous"
    }
  }
}
filter {
    grok{
    id => "myspringlogfilter"
    match => { "message" => "%{TIMESTAMP_ISO8601:timestamp}; [LOG_LEVEL=%{LOGLEVEL:log-level}, CMPNT_NM= %{GREEDYDATA:component}, MESSAGE=%{GREEDYDATA:message}" }
    overwrite => ["message"]

    }

}
output {
    elasticsearch {
        hosts => "localhost:9200"
        manage_template => false
            index => "%{[@metadata][beat]}-%{[@metadata][version]}-%{+YYYY.MM.dd}"
        document_type => "%{[@metadata][type]}"
    }
    stdout {
         codec => rubydebug
  }
}

Body:
Problem got solved after I commented out the metric settings in logstash.yml as follows:

# ------------ Metrics Settings --------------
#
# Bind address for the metrics REST endpoint
#
#http.host: "127.0.0.1"
#
# Bind port for the metrics REST endpoint, this option also accept a range
# (9600-9700) and logstash will pick up the first available ports.
#
#http.port: 5044
#

But still do not know why this solved the issue. as both(filebeat and logstash) were pointing to the same port. If someone could explain the reason,
 then prior Thanks!


问:
fork: child process doesn't stay in an infinite loop
```<code>#include <stdio.h>
#include <unistd.h>

int main()
{
    pid_t pid;

    pid = fork();
    printf("pid : %d\n", getpid());

    if( pid == 0)
    {
        printf("child: pid : %d \n", getpid());
        while(1);
    }
    else
    {
        printf("parent: pid : %d \n", getpid());
        //while(1);
    }
}
</code>```

In the above code snippet inside if statement if we put while(1), it doesn't remains blocked and when enter key is pressed program is exited, but in case of parent if we put while(1), parent remains blocked until we give ctrl+c. Please clarify this behaviour of child.

答:
In the above code snippet inside if statement if we put while(1), it doesn't remains blocked

The child process doesn't exit actually; it just becomes an orphan process because its parent exits. The orphaned chuld process will be adopted by the init process of your system. You can see it via ps command.

But if you put the while(1); in the parent process it remains blocked.

Basically whichever process has while(1); infinite loop, it's still running. When parent exits you get the prompt back and the child becomes orphan. But the child process is still running.

In general, you need to wait(2) for the child process in the parent process to reap child processes.

Body:
#include <stdio.h>
#include <unistd.h>

int main()
{
    pid_t pid;

    pid = fork();
    printf("pid : %d\n", getpid());

    if( pid == 0)
    {
        printf("child: pid : %d \n", getpid());
        while(1);
    }
    else
    {
        printf("parent: pid : %d \n", getpid());
        //while(1);
    }
}

In the above code snippet inside if statement if we put while(1), it doesn't remains blocked and when enter key is pressed program is exited, but in case of parent if we put while(1), parent remains blocked until we give ctrl+c. Please clarify this behaviour of child.


问:
How to eliminate values from list2 (which are common with another list1) in python
Input:

```<code>list1 = ['name', 'age', 'gender', 'location']
list2 = ['name', 'age']
list3
</code>```

Output:

```<code>list3 = ['gender', 'location']
</code>```

How do I subtract common elements from list?

答:
Use sets,</p>

```<code>list3 = list(set(list1)^set(list2))
</code>```

Body:
Input:

list1 = ['name', 'age', 'gender', 'location']
list2 = ['name', 'age']
list3

Output:

list3 = ['gender', 'location']

How do I subtract common elements from list?

Body:
Use sets,

list3 = list(set(list1)^set(list2))


问:
How to set 4 RelativeLayout Horizontally and Adjust automatically according to screen size

Please Refer to screen shot.
Now my Problem is
i have make a xml design that is like in screenshot.
i have 4 relative layout contains imageview and textview.
now i want to set these 4 relative layout horizontally with equal space from right,left,start,end.
In my layout when it go on big screen the start and end showing extra space,i know i have set it like that.
But Is there any solution to set these RLs automatic adjust there size according to screen size.

```<code> <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/one"
    android:id="@+id/RL_MainCat"
    android:background="@color/white"
    android:layout_marginTop="10dp">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true">
<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/RL_UploadPres"
    android:layout_marginLeft="10dp"
    >
<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/upload_pres_icon"
    android:id="@+id/icon_uploadpres"
    android:layout_centerHorizontal="true"
    />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Upload\nPrescription"
        android:textAlignment="center"
        android:textColor="#1f222d"
        android:textSize="11sp"
        android:layout_below="@+id/icon_uploadpres"
        android:layout_marginTop="10dp"
        />
</RelativeLayout>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/RL_UploadPres"
        android:id="@+id/RL_FindPharmacy"
        android:layout_marginLeft="20dp">
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/find_pharma_icon"
            android:id="@+id/icon_findphar"
            android:layout_centerHorizontal="true"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=" Find \n  Pharmacy  "
            android:textAlignment="center"
            android:textColor="#1f222d"
            android:textSize="11sp"
            android:layout_below="@+id/icon_findphar"
            android:layout_marginTop="10dp"
            android:layout_centerHorizontal="true"
            />
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/RL_FindPharmacy"
        android:id="@+id/RL_BuyOTC"
        android:layout_marginLeft="20dp"
        >
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/otc_icon"
            android:id="@+id/icon_findotc"
            android:layout_centerHorizontal="true"

            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="  Buy \n      OTC     "
            android:textAlignment="center"
            android:textColor="#1f222d"
            android:textSize="11sp"
            android:layout_below="@+id/icon_findotc"
            android:layout_marginTop="10dp"
            android:layout_centerHorizontal="true"/>

    </RelativeLayout>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/RL_BuyMedicine"
        android:layout_toRightOf="@+id/RL_BuyOTC"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="10dp"
        >
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/medicine_icon"
            android:id="@+id/icon_findmedi"
            android:layout_centerHorizontal="true"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="  Buy \n Medicines  "
            android:textColor="#1f222d"
            android:textSize="11sp"
            android:textAlignment="center"
            android:layout_marginTop="10dp"
            android:layout_centerHorizontal="true"
            android:layout_below="@+id/icon_findmedi"
            />

    </RelativeLayout>
</RelativeLayout>
</code>```

答:
Use the relative layouts inside a Linear Layout having horizontal Orientation with Weightsum 4 or 1. and give each relative layout a weight of 1 or .25

Inside Relative layout width is set to 0dp so that the Layout will divide the Width equally when the weight is added

Use Scalable SP (ssp) and Scalable DP (sdp) instead of sp and dp so that the Dimenssions will be adjusted automatically too

```<code><LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:weightSum="1"
    android:orientation="horizontal">

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight=".25">

    </RelativeLayout>

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight=".25">

    </RelativeLayout>

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight=".25">

    </RelativeLayout>

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight=".25">

    </RelativeLayout>
</LinearLayout>
</code>```

Body:
Please Refer to screen shot.
Now my Problem is
i have make a xml design that is like in screenshot.
i have 4 relative layout contains imageview and textview.
now i want to set these 4 relative layout horizontally with equal space from right,left,start,end.
In my layout when it go on big screen the start and end showing extra space,i know i have set it like that.
But Is there any solution to set these RLs automatic adjust there size according to screen size.

 <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/one"
    android:id="@+id/RL_MainCat"
    android:background="@color/white"
    android:layout_marginTop="10dp">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true">
<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/RL_UploadPres"
    android:layout_marginLeft="10dp"
    >
<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/upload_pres_icon"
    android:id="@+id/icon_uploadpres"
    android:layout_centerHorizontal="true"
    />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Upload\nPrescription"
        android:textAlignment="center"
        android:textColor="#1f222d"
        android:textSize="11sp"
        android:layout_below="@+id/icon_uploadpres"
        android:layout_marginTop="10dp"
        />
</RelativeLayout>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/RL_UploadPres"
        android:id="@+id/RL_FindPharmacy"
        android:layout_marginLeft="20dp">
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/find_pharma_icon"
            android:id="@+id/icon_findphar"
            android:layout_centerHorizontal="true"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=" Find \n  Pharmacy  "
            android:textAlignment="center"
            android:textColor="#1f222d"
            android:textSize="11sp"
            android:layout_below="@+id/icon_findphar"
            android:layout_marginTop="10dp"
            android:layout_centerHorizontal="true"
            />
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/RL_FindPharmacy"
        android:id="@+id/RL_BuyOTC"
        android:layout_marginLeft="20dp"
        >
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/otc_icon"
            android:id="@+id/icon_findotc"
            android:layout_centerHorizontal="true"

            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="  Buy \n      OTC     "
            android:textAlignment="center"
            android:textColor="#1f222d"
            android:textSize="11sp"
            android:layout_below="@+id/icon_findotc"
            android:layout_marginTop="10dp"
            android:layout_centerHorizontal="true"/>

    </RelativeLayout>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/RL_BuyMedicine"
        android:layout_toRightOf="@+id/RL_BuyOTC"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="10dp"
        >
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/medicine_icon"
            android:id="@+id/icon_findmedi"
            android:layout_centerHorizontal="true"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="  Buy \n Medicines  "
            android:textColor="#1f222d"
            android:textSize="11sp"
            android:textAlignment="center"
            android:layout_marginTop="10dp"
            android:layout_centerHorizontal="true"
            android:layout_below="@+id/icon_findmedi"
            />

    </RelativeLayout>
</RelativeLayout>

Body:
Use the relative layouts inside a Linear Layout having horizontal Orientation with Weightsum 4 or 1. and give each relative layout a weight of 1 or .25

Inside Relative layout width is set to 0dp so that the Layout will divide the Width equally when the weight is added

Use Scalable SP (ssp) and Scalable DP (sdp) instead of sp and dp so that the Dimenssions will be adjusted automatically too

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:weightSum="1"
    android:orientation="horizontal">

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight=".25">

    </RelativeLayout>

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight=".25">

    </RelativeLayout>

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight=".25">

    </RelativeLayout>

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight=".25">

    </RelativeLayout>
</LinearLayout>


问:
How can i make my program run faster: Is using threads a solution?
I've written a program building a huge search tree. Because my tree is too huge i expected that my program will use over 40 % of cpu. instead of this my program uses not over 10 % of cpu even it runs with high priority.

If threads will use more cpu while running parallel, let me please know it; i can divide my program in threads, i need really reduce the search time.

Thanks !

答:
instead of this my program uses not over 10 % of cpu

How many processors do you have, and how is your OS measuring those 10% , i.e. some OS will show 10% usage if you have 10 processors and use 1 of them 100%.

However, in the case you're not utilizing a processor 100%, you need to figure out why. Perhaps it's somehow IO/network bound and you IO in an inefficient manner. You also mention it's "huge", so what does that mean ? If you really mean huge, and you're using up all the memory of your machine and you start swapping, performance goes down the drain, and you need to either find a more efficient algoritmh/memory use or get more ram.

i can divide my program in threads

If your 1 thread doesn't fully utilize the CPU, you'll probably not gain anything from using threads.


问:
Trigger a "ENTER" in programmatically
It is possible to program a "Enter" after a value is added to a input text box?

If yes, I need help on my code below. It does't trigger the "ENTER" keypress.

My code as below:

```<code>$('#clo_cart').click( function () {

/*Save ENTER in variable*/
var eneterKey = jQuery.Event("keydown");
eneterKey.which = 13;
eneterKey.keycode = 13;

$("#scan_char").focus().val('CLOSECTN').trigger(eneterKey);
}//end of button click
</code>```

Pls Help

答:
This code below work fine for me.  </p>

```<code>  $('#clo_cart').click( function () {

     $("#scan_char").focus().val('CLOSECTN').trigger(enterKey());

  }//end of button click

    /* Function to allow program keypress ENTER */
    function enterKey() {

       return $.Event( "keypress", { which: 13 } );

    }
</code>```

Title: Trigger a "ENTER" in programmatically

Body:
It is possible to program a "Enter" after a value is added to a input text box?

If yes, I need help on my code below. It does't trigger the "ENTER" keypress.

My code as below:

$('#clo_cart').click( function () {

/*Save ENTER in variable*/
var eneterKey = jQuery.Event("keydown");
eneterKey.which = 13;
eneterKey.keycode = 13;

$("#scan_char").focus().val('CLOSECTN').trigger(eneterKey);
}//end of button click

Pls Help

Body:
This code below work fine for me.

  $('#clo_cart').click( function () {

     $("#scan_char").focus().val('CLOSECTN').trigger(enterKey());

  }//end of button click

    /* Function to allow program keypress ENTER */
    function enterKey() {

       return $.Event( "keypress", { which: 13 } );

    }


答:
LocationBean with a List

You want to store every location name, not set ONE value. So you want a method addLocationName store it into a Collection

```<code>locationBean.addLocationName(locationArr[i]);
</code>```

That method is simple, it will add every String into a List<String>

```<code>private List<String> locationsName;
private List<String> locationsId;

public LocationBean (){
    locationsName = new ArrayList<String>();
    locationsId= new ArrayList<String>();
}

public boolean addLocationName(string locationName){
    return this.locationsName.add(locationName);
}

public boolean addLocationId(string locationId){
    return this.locationsId.add(locationId);
}
</code>```

Of course, you would need to do the same with location_id, so a Bean would be smarter :

```<code>public class Location{
    private String id;
    private String name;

    public Location(String id, String name){ ... }
    //constructor and getter
}
</code>```

and simply use a List<Location> instead. That way, both id and name are stored together.

```<code>public boolean addLocation(Location location){
    return this.locations.add(location);
}
</code>```

or passing the values

```<code>public boolean addLocation(String id, String name){
    return this.locations.add(new Location(id, name));
}
</code>```

List of LocationBean

Or your bean should only have one location and then this is in your loop that you need to store every instance of LocationBean into a List<LocationBean> (don't forget to create a new instance each time`

```<code>List<LocationBean> locations = new ArrayList<>();
for (int i = 0; i <= locationArr.length - 1; i++) {
    locationBean = new LocationBean(); //new instance each time

    locationBean.setLocation_name(locationArr[i]);

    locations.add(locationBean); //add into the list
}
</code>```

Title: How to set for loop array values to a bean

Body:
LocationBean with a List

You want to store every location name, not set ONE value. So you want a method addLocationName store it into a Collection

locationBean.addLocationName(locationArr[i]);

That method is simple, it will add every String into a List<String>

private List<String> locationsName;
private List<String> locationsId;

public LocationBean (){
    locationsName = new ArrayList<String>();
    locationsId= new ArrayList<String>();
}

public boolean addLocationName(string locationName){
    return this.locationsName.add(locationName);
}

public boolean addLocationId(string locationId){
    return this.locationsId.add(locationId);
}

Of course, you would need to do the same with location_id, so a Bean would be smarter :

public class Location{
    private String id;
    private String name;

    public Location(String id, String name){ ... }
    //constructor and getter
}

and simply use a List<Location> instead. That way, both id and name are stored together.

public boolean addLocation(Location location){
    return this.locations.add(location);
}

or passing the values

public boolean addLocation(String id, String name){
    return this.locations.add(new Location(id, name));
}

List of LocationBean

Or your bean should only have one location and then this is in your loop that you need to store every instance of LocationBean into a List<LocationBean> (don't forget to create a new instance each time`

List<LocationBean> locations = new ArrayList<>();
for (int i = 0; i <= locationArr.length - 1; i++) {
    locationBean = new LocationBean(); //new instance each time

    locationBean.setLocation_name(locationArr[i]);

    locations.add(locationBean); //add into the list
}


问:
JPA (Hibernate): "ORA-02289 Sequence does not exist", but it does
I'm working with JPA entities.

I created a new one like this:

```<code>@Entity
public class Entity {
    @Id
    @GeneratedValue(generator = "Entity_Sequence", strategy = GenerationType.SEQUENCE)
    @SequenceGenerator(name = "Entity_Sequence", sequenceName = "Entity_Seq")
    private Long id;

    // ... other fields
}
</code>```

Generated SQL I used to create DB Objects:

```<code>CREATE SEQUENCE ENTITY_SEQ START WITH 1 INCREMENT BY 50;

CREATE TABLE ENTITY (
  ID     NUMBER(19, 0) NOT NULL,
  -- ... other fields
  PRIMARY KEY (ID)
);
</code>```

Now, I am able to query the nextval of the sequence from SQL Developer and from IntelliJ. But when I try to persist an entity from code, Hibernate throws the following exception:

```<code>15:21:11,022 INFO  [stdout] (EJB default - 2) Hibernate: select ENTITY_SEQ.nextval from dual
15:21:11,037 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (EJB default - 2) SQL Error: 2289, SQLState: 42000
15:21:11,037 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (EJB default - 2) ORA-02289: Sequence ist nicht vorhanden.
</code>```

("Sequence ist nicht vorhanden" translates to "Sequence does not exist".)

Why is Hibernate not able to find the sequence while I am?

EDIT 1 (12-01):

I tried the suggested answer from Olivier, but the error is still the same.

EDIT 2 (12-01):

Since Olivier deleted his answer, he suggested I move the @SequenceGenerator annotation to the class.

答:
I found the error: It was my local setup, so nothing useful to tell you, just check your setup.

I was "configuring" my server in files that aren't actually used by the server, and thus showed no effect.

Body:
I'm working with JPA entities.

I created a new one like this:

@Entity
public class Entity {
    @Id
    @GeneratedValue(generator = "Entity_Sequence", strategy = GenerationType.SEQUENCE)
    @SequenceGenerator(name = "Entity_Sequence", sequenceName = "Entity_Seq")
    private Long id;

    // ... other fields
}

Generated SQL I used to create DB Objects:

CREATE SEQUENCE ENTITY_SEQ START WITH 1 INCREMENT BY 50;

CREATE TABLE ENTITY (
  ID     NUMBER(19, 0) NOT NULL,
  -- ... other fields
  PRIMARY KEY (ID)
);

Now, I am able to query the nextval of the sequence from SQL Developer and from IntelliJ. But when I try to persist an entity from code, Hibernate throws the following exception:

15:21:11,022 INFO  [stdout] (EJB default - 2) Hibernate: select ENTITY_SEQ.nextval from dual
15:21:11,037 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (EJB default - 2) SQL Error: 2289, SQLState: 42000
15:21:11,037 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (EJB default - 2) ORA-02289: Sequence ist nicht vorhanden.

("Sequence ist nicht vorhanden" translates to "Sequence does not exist".)

Why is Hibernate not able to find the sequence while I am?

EDIT 1 (12-01):

I tried the suggested answer from Olivier, but the error is still the same.

EDIT 2 (12-01):

Since Olivier deleted his answer, he suggested I move the @SequenceGenerator annotation to the class.


问:
Calling Activity from Class
In my application, there is an Activity class and a helper class. Activity class has access to a TextView which displays the score. Helper class needs to periodically update score in the activity class.

```<code>public class MainActivity extends Activity
{
  TextView textView;

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

    textView = (TextView) findViewById(R.id.textView);
    Helper helper = new Helper();
  }

  void updateScore(int score)
  {
    textView.setText(score + "");
  }

  /* ... */
}

public class Helper
{
  int score = 0;

  void updateScore()
  {
    // what to do here?
  }
}
</code>```

I found two ways to do this but they are not very good. One way is to pass activity instance to helper class. Other way is to declare TextView static. However, both are susceptible to memory leaks. Is there a better way of doing this?

答:
You can achieve that by using interface

```<code>public class MainActivity extends Activity implements MainActivity.Callback {
    TextView textView;

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

        textView = (TextView) findViewById(R.id.textView);
        Helper helper = new Helper(this);
    }

    @Override
    void updateScore(int score) {
        textView.setText(score + "");
    }

    interface Callback {
        void updateScore(int score);
    }

    /* ... */
}

public class Helper {
    int score = 0;
    Callback callback;

    public Helper(Callback callback){
        this.callback = callback;
    }

    void updateScore() {
        callback.updateScore(score);
    }
}
</code>```

When you call updateScore from helper class, it will call the updateScore from activity and pass the score to it and you can update the TextView inside MainActivity.

Title: Calling Activity from Class

Body:
In my application, there is an Activity class and a helper class. Activity class has access to a TextView which displays the score. Helper class needs to periodically update score in the activity class.

public class MainActivity extends Activity
{
  TextView textView;

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

    textView = (TextView) findViewById(R.id.textView);
    Helper helper = new Helper();
  }

  void updateScore(int score)
  {
    textView.setText(score + "");
  }

  /* ... */
}

public class Helper
{
  int score = 0;

  void updateScore()
  {
    // what to do here?
  }
}

I found two ways to do this but they are not very good. One way is to pass activity instance to helper class. Other way is to declare TextView static. However, both are susceptible to memory leaks. Is there a better way of doing this?

Body:
You can achieve that by using interface

public class MainActivity extends Activity implements MainActivity.Callback {
    TextView textView;

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

        textView = (TextView) findViewById(R.id.textView);
        Helper helper = new Helper(this);
    }

    @Override
    void updateScore(int score) {
        textView.setText(score + "");
    }

    interface Callback {
        void updateScore(int score);
    }

    /* ... */
}

public class Helper {
    int score = 0;
    Callback callback;

    public Helper(Callback callback){
        this.callback = callback;
    }

    void updateScore() {
        callback.updateScore(score);
    }
}

When you call updateScore from helper class, it will call the updateScore from activity and pass the score to it and you can update the TextView inside MainActivity.


问:
What is the difference between io.sockets.emit and socket.emit in io.on('connection', function(socket){})?
I noticed if I want to emit a message like

```<code>io.on('connection', function(socket){
    socket.emit('signal')
})
</code>```

Somehow I have to refresh the HTML page to get the ejs file work on the signal. But If I directly emit it like:

```<code>io.sockets.emit('signal')
</code>```

Then I do not have to refresh the html to get the action work.

How come?

答:
Let me translate the code in plain English.

First case

```<code>io.on('connection', function(socket){
    socket.emit('signal')
})
</code>```

Translation: When io is being connected, instruct the connected socket that triggered the connection event to emit 'signal'.

In this case, the io is attached with an event listener that listens for "connection" event, which is fired whenever a socket connects to the io. Therefore, whenever a socket connects to the io, the io instruct the socket to emit a "signal" event.

Why do I need to refresh for it to fire?

Because when you refresh, your computer acts as a socket and is connected to the io onload. Therefore a "connection" event is fired, and it is only fired when a socket connects to the io.

Note: Actually, you do not need to refresh to fire it. You can simply disconnect your internet connection and then reconnect it.

Second case

```<code>io.sockets.emit('signal')
</code>```

Translation: All sockets that are currently connected to io, emit 'signal' event now!

In this case, you are instructing all currently connected sockets to emit the "signal" event. Your computer is a socket connected to the io, so it emits the event.

Note: If you have another device connecting to the same node server, and you use that command, you will see two "signal" events being emitted.

Body:
I noticed if I want to emit a message like

io.on('connection', function(socket){
    socket.emit('signal')
})

Somehow I have to refresh the HTML page to get the ejs file work on the signal. But If I directly emit it like:

io.sockets.emit('signal')

Then I do not have to refresh the html to get the action work.

How come?

Body:
Let me translate the code in plain English.

First case

io.on('connection', function(socket){
    socket.emit('signal')
})

Translation: When io is being connected, instruct the connected socket that triggered the connection event to emit 'signal'.

In this case, the io is attached with an event listener that listens for "connection" event, which is fired whenever a socket connects to the io. Therefore, whenever a socket connects to the io, the io instruct the socket to emit a "signal" event.

Why do I need to refresh for it to fire?

Because when you refresh, your computer acts as a socket and is connected to the io onload. Therefore a "connection" event is fired, and it is only fired when a socket connects to the io.

Note: Actually, you do not need to refresh to fire it. You can simply disconnect your internet connection and then reconnect it.

Second case

io.sockets.emit('signal')

Translation: All sockets that are currently connected to io, emit 'signal' event now!

In this case, you are instructing all currently connected sockets to emit the "signal" event. Your computer is a socket connected to the io, so it emits the event.

Note: If you have another device connecting to the same node server, and you use that command, you will see two "signal" events being emitted.


问:
How to create an Excel File with Nodejs?
I am a nodejs programmer . Now I have a table of data that I want to save in Excel File format . How do I go about doing this ?

I found a few Node libraries . But most of them are Excel Parsers rather than Excel Writers .I am using a Linux Server . Hence need something that can run on Linux . Please let me know  if there are any helpful libraries that you know of .

Or is there a way I can convert a CSV file to an xls file ( programmatically ) ?

答:
You should check ExcelJS

Works with CSV and XLSX formats.

Great for reading/writing XLSX streams. I've used it to stream an XLSX download to an Express response object, basically like this:

```<code>app.get('/some/route', function(req, res) {
  res.writeHead(200, {
    'Content-Disposition': 'attachment; filename="file.xlsx"',
    'Transfer-Encoding': 'chunked',
    'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  })
  var workbook = new Excel.stream.xlsx.WorkbookWriter({ stream: res })
  var worksheet = workbook.addWorksheet('some-worksheet')
  worksheet.addRow(['foo', 'bar']).commit()
  worksheet.commit()
  workbook.commit()
}
</code>```

Works great for large files, performs much better than excel4node (got huge memory usage & Node process "out of memory" crash after nearly 5 minutes for a file containing 4 million cells in 20 sheets) since its streaming capabilities are much more limited (does not allows to "commit()" data to retrieve chunks as soon as they can be generated)

See also this SO answer.

Body:
You should check ExcelJS

Works with CSV and XLSX formats.

Great for reading/writing XLSX streams. I've used it to stream an XLSX download to an Express response object, basically like this:

app.get('/some/route', function(req, res) {
  res.writeHead(200, {
    'Content-Disposition': 'attachment; filename="file.xlsx"',
    'Transfer-Encoding': 'chunked',
    'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  })
  var workbook = new Excel.stream.xlsx.WorkbookWriter({ stream: res })
  var worksheet = workbook.addWorksheet('some-worksheet')
  worksheet.addRow(['foo', 'bar']).commit()
  worksheet.commit()
  workbook.commit()
}

Works great for large files, performs much better than excel4node (got huge memory usage & Node process "out of memory" crash after nearly 5 minutes for a file containing 4 million cells in 20 sheets) since its streaming capabilities are much more limited (does not allows to "commit()" data to retrieve chunks as soon as they can be generated)

See also this SO answer.


问:
java - Loop optimization on int array
I would like to know, which is fast way to write/read in an int array.

Here my Java code: I have three int arrays, two in read access and one int array in write access.

```<code>for(int j = h20 ; j < h21 ; j++){
    for(int i = w20 ; i < w21 ; i++){
        if( int_color == arr3[j*h31 + i] )  continue; //condition
        arr1[(j+decY)*w11 + i+decX] = arr2[j*w21 + i];
    }
}
</code>```

My code is a classic 2D array loop, there are just one special condition to check.

Is it other way to write this code to decrease processing time?

Thx.

答:
You can reduce the amount of calculations, if you separate them by variables. In your case, any calculation that relies on j alone doesn't have to be inside the inner loop because the result won't change for the rest of the loop. Instead, calculate the values outside and only use the result in the inner loop.

```<code>for(int j = h20 ; j < h21 ; j++){
    int tmp1 = j*h31;
    int tmp2 = (j+decY)*w11 + decX;
    int tmp3 = j*w21;

    // j won't change inside here, so you can simply use the precalculated values
    for(int i = w20 ; i < w21 ; i++){
        if( int_color == arr3[tmp1 + i] )  continue; //condition
        arr1[tmp2 + i] = arr2[tmp3 + i];
    }
}
</code>```

Edit: If you want to reduce this even more, you could rewrite the calculation for tmp2:

```<code>(j+decY)*w11 + decX ==> j*w11 + decY*w11 + decX
</code>```

Then, you could extract the decY*w11 + decX into its own variable outside the first loop.

```<code>int tmp0 = decY*w11 + decX;
for(int j = h20 ; j < h21 ; j++){
    int tmp1 = j*h31;
    int tmp2 = j*w11 + tmp0;
    int tmp3 = j*w21;

    // j won't change inside here, so you can simply use the precalculated values
    for(int i = w20 ; i < w21 ; i++){
        if( int_color == arr3[tmp1 + i] )  continue; //condition
        arr1[tmp2 + i] = arr2[tmp3 + i];
    }
}
</code>```

But this will save you only one addition per iteration, so I don't think it's worth the extra effort.

Title: java - Loop optimization on int array

Body:
I would like to know, which is fast way to write/read in an int array.

Here my Java code: I have three int arrays, two in read access and one int array in write access.

for(int j = h20 ; j < h21 ; j++){
    for(int i = w20 ; i < w21 ; i++){
        if( int_color == arr3[j*h31 + i] )  continue; //condition
        arr1[(j+decY)*w11 + i+decX] = arr2[j*w21 + i];
    }
}

My code is a classic 2D array loop, there are just one special condition to check.

Is it other way to write this code to decrease processing time?

Thx.

Body:
You can reduce the amount of calculations, if you separate them by variables. In your case, any calculation that relies on j alone doesn't have to be inside the inner loop because the result won't change for the rest of the loop. Instead, calculate the values outside and only use the result in the inner loop.

for(int j = h20 ; j < h21 ; j++){
    int tmp1 = j*h31;
    int tmp2 = (j+decY)*w11 + decX;
    int tmp3 = j*w21;

    // j won't change inside here, so you can simply use the precalculated values
    for(int i = w20 ; i < w21 ; i++){
        if( int_color == arr3[tmp1 + i] )  continue; //condition
        arr1[tmp2 + i] = arr2[tmp3 + i];
    }
}

Edit: If you want to reduce this even more, you could rewrite the calculation for tmp2:

(j+decY)*w11 + decX ==> j*w11 + decY*w11 + decX

Then, you could extract the decY*w11 + decX into its own variable outside the first loop.

int tmp0 = decY*w11 + decX;
for(int j = h20 ; j < h21 ; j++){
    int tmp1 = j*h31;
    int tmp2 = j*w11 + tmp0;
    int tmp3 = j*w21;

    // j won't change inside here, so you can simply use the precalculated values
    for(int i = w20 ; i < w21 ; i++){
        if( int_color == arr3[tmp1 + i] )  continue; //condition
        arr1[tmp2 + i] = arr2[tmp3 + i];
    }
}

But this will save you only one addition per iteration, so I don't think it's worth the extra effort.


问:
Exception flow control
I use exceptions to flow control a lot, but I have a strange feeling that I am doing something wrong. Is it a good practice to write something like code shown bellow?</p>

```<code>public static void main(String[] args)
{
    try
    {
        methodA();
    }
    catch (Exception ex)
    {
        handleException(ex);
    }
}

public static methodA()
{
    methodB();
}

public static methodB()
{
    if(someConditionIsNotMet)
    {
        throw new RuntimeException("Some Condition Is Not Met");
    }
}
</code>```

答:
I would separate flow control and exception handling. Flow control is meant for making sure statements are executed in correct sequence and under correct conditions. This must be determined at design time. Exception handling is meant to handle unforeseen situations at run time. Exceptions are almost always due to external factors: time outs, no disk space, data errors...

Just my two cents.

Title: Exception flow control

Body:
I use exceptions to flow control a lot, but I have a strange feeling that I am doing something wrong. Is it a good practice to write something like code shown bellow?

public static void main(String[] args)
{
    try
    {
        methodA();
    }
    catch (Exception ex)
    {
        handleException(ex);
    }
}

public static methodA()
{
    methodB();
}

public static methodB()
{
    if(someConditionIsNotMet)
    {
        throw new RuntimeException("Some Condition Is Not Met");
    }
}


答:
Either u can create a list of LocationBean objects :

```<code>ArrayList <LocationBean> locationBeanList = new ArrayList <LocationBean>)();

for (int i = 0; i <= locationArr.length - 1; i++) {
        data.put(idArr[i], locationArr[i]);
        locationBean = new LocationBean();
        locationBean.setLocation_name(locationArr[i]);
        locationBeanList.add(locationBean);

    }
</code>```

Or, u can create list of locations in single location bean

```<code> public class LocationBean {
 private String region_id;
 private String region_name;
 private String location_id;
 private List<String> location_name_list = new ArrayList<String>();

 //getters and setters
 }

List<String> locationList = new ArrayList <String>();
 for (int i = 0; i <= locationArr.length - 1; i++) {
        data.put(idArr[i], locationArr[i]);

        locationList.add(locationArr[i]);

    }

locationBean.setLocation_name_list(locationList );
</code>```

Body:
I have the following loop in a controller class:

for (int i = 0; i <= locationArr.length - 1; i++) {
    data.put(idArr[i], locationArr[i]);
    locationBean.setLocation_name(locationArr[i]);
}

My Bean looks like :

 public class LocationBean {
     private String region_id;
     private String region_name;
     private String location_id;
     private String location_name;

     //getters and setters
 }

I am trying to set location_name as setLocation_name(locationArr[i]);
But only getting last values of the loop [i] is being assigned.

Body:
Either u can create a list of LocationBean objects :

ArrayList <LocationBean> locationBeanList = new ArrayList <LocationBean>)();

for (int i = 0; i <= locationArr.length - 1; i++) {
        data.put(idArr[i], locationArr[i]);
        locationBean = new LocationBean();
        locationBean.setLocation_name(locationArr[i]);
        locationBeanList.add(locationBean);

    }

Or, u can create list of locations in single location bean

 public class LocationBean {
 private String region_id;
 private String region_name;
 private String location_id;
 private List<String> location_name_list = new ArrayList<String>();

 //getters and setters
 }

List<String> locationList = new ArrayList <String>();
 for (int i = 0; i <= locationArr.length - 1; i++) {
        data.put(idArr[i], locationArr[i]);

        locationList.add(locationArr[i]);

    }

locationBean.setLocation_name_list(locationList );


问:
Semantic UI Selection Dropdown with KnockoutJS
So, anyone ever tried this before? Is there any way to integrate Semantic UI dropdown with KnockoutJS? Preferably selection dropdown using select because I want to integrate that on my form.</p>

答:
Yes you can do  it using select like this HTML

```<code><div class="ui form">
    <div class="field">
        <select data-bind="options: optionsText,
                           value: selectedOption,
                           optionsCaption: 'Select Options'">
        </select>
    </div>
</div>
</code>```

And Knockout View Model

```<code>var ViewModel = function() {
    var self=this;
    self.optionsText=ko.observableArray(['Some','Thing','Like','This']);
    self.selectedOption=ko.observable();
    self.selectedOption.subscribe(function(newValue) {
        alert("Selected value " + newValue);
    });
};
ko.applyBindings(new ViewModel());
</code>```

You can see demo jsFiddle

Body:
Yes you can do  it using select like this HTML

<div class="ui form">
    <div class="field">
        <select data-bind="options: optionsText,
                           value: selectedOption,
                           optionsCaption: 'Select Options'">
        </select>
    </div>
</div>

And Knockout View Model

var ViewModel = function() {
    var self=this;
    self.optionsText=ko.observableArray(['Some','Thing','Like','This']);
    self.selectedOption=ko.observable();
    self.selectedOption.subscribe(function(newValue) {
        alert("Selected value " + newValue);
    });
};
ko.applyBindings(new ViewModel());

You can see demo jsFiddle


问:
ASP.net problem with changing table row visibility
i have a table array dynamically generated from a data query and stored in a session variable. Now i wanna add a textbox to limit how many rows at a time i will display. To test this, i wrote two button methods, one will set some rows to be visible = false, and the second button method will set the same rows back to visible = true.

```<code>protected void limit_btn_Click(object sender, EventArgs e)
{
    for (int i = 0; i < traceTables.Length; i++)
        for (int j = 2; j < traceTables[i].Rows.Count; j++)
            traceTables[i].Rows[j].Visible = false;

    Session["Tables"] = traceTables;
    table_C();
}//end limit_btn_Click()

protected void obo_btn_Click(object sender, EventArgs e)
{
    for (int i = 0; i < traceTables.Length; i++)
        for (int j = 2; j < traceTables[i].Rows.Count; j++)
            traceTables[i].Rows[j].Visible = true;

    Session["Tables"] = traceTables;
    table_C();
}//end obo_btn_Click()

protected void table_C()
{
    String changeTo = log_locations.SelectedValue;
    for (int i = 0; i < sshLoc.Length; i++)
    {
        if (sshLoc[i].CompareTo(changeTo) == 0)
        {
            table_panel.ContentTemplateContainer.Controls.Remove(traceTables[currentTable]);
            System.Diagnostics.Debug.WriteLine("Removing " + sshLoc[currentTable]);
            table_panel.ContentTemplateContainer.Controls.Add(traceTables[i]);
            System.Diagnostics.Debug.WriteLine("Adding " + sshLoc[i]);
            currentTable = i;
            Session["CurrentTable"] = currentTable;
            break;
        }//end if
    }//end for
}//end table_C()
</code>```

table_C() basically removes and adds the table from the panel - i use it when i want to switch between tables from a dropdown list (which works) and in this case it simply removes and adds the same table from the panel content container.

The problem is that setting the rows to be not visible works fine. Setting the rows back to visible never does, and i'm not sure why

答:
Try using display:none and display:visible rather than .visible in ASP
 traceTables[i].Rows[j].Add("style","display:none");

Visible removes it completely from the HTML, so you can only show it again by recreating the page.

Body:
i have a table array dynamically generated from a data query and stored in a session variable. Now i wanna add a textbox to limit how many rows at a time i will display. To test this, i wrote two button methods, one will set some rows to be visible = false, and the second button method will set the same rows back to visible = true.

protected void limit_btn_Click(object sender, EventArgs e)
{
    for (int i = 0; i < traceTables.Length; i++)
        for (int j = 2; j < traceTables[i].Rows.Count; j++)
            traceTables[i].Rows[j].Visible = false;

    Session["Tables"] = traceTables;
    table_C();
}//end limit_btn_Click()

protected void obo_btn_Click(object sender, EventArgs e)
{
    for (int i = 0; i < traceTables.Length; i++)
        for (int j = 2; j < traceTables[i].Rows.Count; j++)
            traceTables[i].Rows[j].Visible = true;

    Session["Tables"] = traceTables;
    table_C();
}//end obo_btn_Click()

protected void table_C()
{
    String changeTo = log_locations.SelectedValue;
    for (int i = 0; i < sshLoc.Length; i++)
    {
        if (sshLoc[i].CompareTo(changeTo) == 0)
        {
            table_panel.ContentTemplateContainer.Controls.Remove(traceTables[currentTable]);
            System.Diagnostics.Debug.WriteLine("Removing " + sshLoc[currentTable]);
            table_panel.ContentTemplateContainer.Controls.Add(traceTables[i]);
            System.Diagnostics.Debug.WriteLine("Adding " + sshLoc[i]);
            currentTable = i;
            Session["CurrentTable"] = currentTable;
            break;
        }//end if
    }//end for
}//end table_C()

table_C() basically removes and adds the table from the panel - i use it when i want to switch between tables from a dropdown list (which works) and in this case it simply removes and adds the same table from the panel content container.

The problem is that setting the rows to be not visible works fine. Setting the rows back to visible never does, and i'm not sure why


问:
Page redirection issue in wordpress
I want to redirect to another page or website in WordPress. I am using below code In which $page variable contains the URL of the website and want to redirect it with a tag href. Problem is the link is appended to localhost current page URL.

the code is here

```<code>$page= get_post_custom_values('projPage');
if($page[0] != ""){
    var_dump($page);?>
    <p>
        <a href="<?php echo $page[0];?>">Project Page</a>
    </p> <?php
} else { ?>
    <p><em>Project Page Unavailable</em></p><?php
}
</code>```

答:
Your URL should have a protocol like HTTP or HTTPS else it is considered as a relative path.

```<code>$page[0]= 'http://www.google.com';
if($page[0] != ""){
    var_dump($page);?>
    <p>
        <a href="<?php echo $page[0];?>">Project Page</a>
    </p> <?php
} else { ?>
    <p><em>Project Page Unavailable</em></p><?php
}
</code>```

this one is works fine for me

Title: Page redirection issue in wordpress

Body:
I want to redirect to another page or website in WordPress. I am using below code In which $page variable contains the URL of the website and want to redirect it with a tag href. Problem is the link is appended to localhost current page URL.

the code is here

$page= get_post_custom_values('projPage');
if($page[0] != ""){
    var_dump($page);?>

        <a href="<?php echo $page[0];?>">Project Page

 <?php
} else { ?>

Project Page Unavailable
<?php
}

Body:
Your URL should have a protocol like HTTP or HTTPS else it is considered as a relative path.

$page[0]= 'http://www.google.com';
if($page[0] != ""){
    var_dump($page);?>
    <p>
        <a href="<?php echo $page[0];?>">Project Page</a>
    </p> <?php
} else { ?>
    <p><em>Project Page Unavailable</em></p><?php
}

this one is works fine for me


问:
How can I simulate $(this)[0].files in JS?
I have a drag and drop container for uploading images. Something like the option that stackoverflow has in the editor. As you know, it works in two ways:

drag and drop an image

click on the container and then a window will be opened to choose an image

Now I'm exactly doing something like that:

```<code>// click
$('.upload_image').on('change', function () {
    file = $(this)[0].files;
    frm = $(this).closest('form');
    addImageToInput();
    return false;
});

// drag and drop
$(".container").on('drop dragdrop', function (e) {
    file = e.originalEvent.dataTransfer.files;
    frm = $(this).closest('form');
    addImageToInput();
    return false;
});
</code>```

Also I have one more function for making a preview:

```<code>function addImageToInput() {
    if ( file !== "" || frm !== "" ) {
        let uploadFormData = new FormData(frm[0]);
        uploadFormData.append("imageToUpload", file[0]);
        readURL(frm.find(".upload_image")[0]);
        formData = uploadFormData;
    } else {
        alert('something went wrong');
    }
}

function readURL(input) {

    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            $('.modal-dropzone-img').html("<img src='" +  e.target.result + "' class='upload_image_preview_img'/>");
        }
        reader.readAsDataURL(input.files[0]);
    }
}
</code>```

Anyway, the preview part works well when I attach an image by using "click" (browse) the image, and the preview part doesn't word (even no error throws) when I use drag and drop approach.

After some tests, I figured out, these aren't equal:

```<code>file = $(this)[0].files;                   // click approach
file = e.originalEvent.dataTransfer.files; // drag and drop approach
</code>```

Any idea how can I make them equal? (in other word, I have to make the second one like the first one, because the first one is the working one)

答:
I have modified the readURL method little bit to accept a file only, it can be drag drop or uploaded . Also addImageToInput() is changed accordingly

```<code>function addImageToInput() {
    if ( file !== "" || frm !== "" ) {
        let uploadFormData = new FormData(frm[0]);
        uploadFormData.append("imageToUpload", file[0]);
        readURL(file[0]);
        formData = uploadFormData;
    } else {
        alert('something went wrong');
    }
}

function readURL(input) {

    if (input) {
        var reader = new FileReader();
        reader.onload = function(e) {
            $('.modal-dropzone-img').html("<img src='" +  e.target.result + "' class='upload_image_preview_img'/>");
        }
        reader.readAsDataURL(input);
    }
}
</code>```

here is a working fiddle

https://jsfiddle.net/153dp05q/

Body:
I have a drag and drop container for uploading images. Something like the option that stackoverflow has in the editor. As you know, it works in two ways:

drag and drop an image

click on the container and then a window will be opened to choose an image

Now I'm exactly doing something like that:

// click
$('.upload_image').on('change', function () {
    file = $(this)[0].files;
    frm = $(this).closest('form');
    addImageToInput();
    return false;
});

// drag and drop
$(".container").on('drop dragdrop', function (e) {
    file = e.originalEvent.dataTransfer.files;
    frm = $(this).closest('form');
    addImageToInput();
    return false;
});

Also I have one more function for making a preview:

function addImageToInput() {
    if ( file !== "" || frm !== "" ) {
        let uploadFormData = new FormData(frm[0]);
        uploadFormData.append("imageToUpload", file[0]);
        readURL(frm.find(".upload_image")[0]);
        formData = uploadFormData;
    } else {
        alert('something went wrong');
    }
}

function readURL(input) {

    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            $('.modal-dropzone-img').html("");
        }
        reader.readAsDataURL(input.files[0]);
    }
}

Anyway, the preview part works well when I attach an image by using "click" (browse) the image, and the preview part doesn't word (even no error throws) when I use drag and drop approach.

After some tests, I figured out, these aren't equal:

file = $(this)[0].files;                   // click approach
file = e.originalEvent.dataTransfer.files; // drag and drop approach

Any idea how can I make them equal? (in other word, I have to make the second one like the first one, because the first one is the working one)

Body:
I have modified the readURL method little bit to accept a file only, it can be drag drop or uploaded . Also addImageToInput() is changed accordingly

function addImageToInput() {
    if ( file !== "" || frm !== "" ) {
        let uploadFormData = new FormData(frm[0]);
        uploadFormData.append("imageToUpload", file[0]);
        readURL(file[0]);
        formData = uploadFormData;
    } else {
        alert('something went wrong');
    }
}

function readURL(input) {

    if (input) {
        var reader = new FileReader();
        reader.onload = function(e) {
            $('.modal-dropzone-img').html("<img src='" +  e.target.result + "' class='upload_image_preview_img'/>");
        }
        reader.readAsDataURL(input);
    }
}

here is a working fiddle

https://jsfiddle.net/153dp05q/


问:
Classify a list of value through a list of thresholds
I have a map of <String,Double> considered as thresholds to classify a list of Doubles

```<code>HashMap<String, Double> map = new Hashmap<>();
map.put(A/B,0.7);
map.put(B/C,0.4);
map.put(C/D,0.3);
map.put(D/E,0.1);
</code>```

The Doubles of the hash is used as threshold to classify a list doubles given, so I want to transform this map into a list of classes A, B, C, D

```<code>Class A : from 0.7
Class B : from 0.4 to 0.7
Class C : from 0.3 to 0.4
Class D : from 0.1 to 0.3
Class E : less than 0.1
</code>```

Do you have any idea on how to perform that as a method StringClassifyByValue(HashMap<String, Double> map, Double value){} returning a String of the class correspondent of the value given as parameter?

ِExample :

this.StringClassifyByValue(map,0.5) have to return B.

答:
```<code>private HashMap<String, HashMap<String, Double>> getMinMaxThreshold(HashMap<String, Double> map) {

        List<Double> threholds = map.values().stream().collect(Collectors.toList());
        HashMap<String,Double >map1= this.sortByValues(map);
        List<String> keys = map1.keySet().stream().collect(Collectors.toList());

        Collections.sort(threholds);
        Collections.reverse(threholds);

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

        for (int i =0;i<=threholds.size();i++){

            if(i==threholds.size()){
                HashMap<String, Double> testmap = new HashMap<>();
                testmap.put("max",threholds.get(i-1));
                testmap.put("min",0.0);
                boudaries.put(keys.get(keys.size()-1).split("/")[1], testmap);
                System.out.println(threholds.get(i-1)+" ->"+0+" : "+keys.get(keys.size()-1).split("/")[1] );
            }

            else if (i==0){
                HashMap<String, Double> testmap = new HashMap<>();
                testmap.put("max",Math.exp(1000));
                testmap.put("min",threholds.get(i));
                boudaries.put(keys.get(0).split("/")[0], testmap);
                System.out.println(Math.exp(100) +" ->"+threholds.get(i)+" : "+keys.get(0).split("/")[0] );}

            else{
                HashMap<String, Double> testmap = new HashMap<>();
                testmap.put("max",threholds.get(i-1));
                testmap.put("min",threholds.get(i));
                boudaries.put(keys.get(i).split("/")[0], testmap);
            System.out.println(threholds.get(i-1)+" ->"+threholds.get(i)+" : "+keys.get(i).split("/")[0]);}
        }

        System.err.println(boudaries);

        return boudaries;
    }
</code>```

The ’keys’ is a ’List’ and represent the Classes A,B,C,D.

The thresholds is a ’List’represent the thresholds. We have
to use this threshold to make the boundaries.

I sort the map of thresholds by values to get the Strings in descending order, and same with the list of Double thresholds to make them in the same order.

I loop foreach element of threshold.. for the first item it's about the last boudaries so I made as boudaries the Exp(1000) and the previous element.. for the last element, it's about a boudaries with min 0 and max the last element of threshold.

I use split to get the first element of splited array except the last item where I use the second element of the array to match the last element. That's it

Test :

If we have as an input this ’Map’

```<code>{ "YELLOW_DARK/RED_LIGHT" : 0.20459770114942527 , "GREEN_DARK/GREEN_LIGHT" : 0.6226151930261519 , "GREEN_LIGHT/YELLOW_LIGHT" : 0.4632936507936508 , "YELLOW_LIGHT/YELLOW_DARK" : 0.3525246305418719 , "RED_LIGHT/RED_DARK" : 0.027777777777777776}
</code>```

My code will transorm it into :

```<code>2.6881171418161356E43 ->0.6226151930261519 : GREEN_DARK
0.6226151930261519 ->0.4632936507936508 : GREEN_LIGHT
0.4632936507936508 ->0.3525246305418719 : YELLOW_LIGHT
0.3525246305418719 ->0.20459770114942527 : YELLOW_DARK
0.20459770114942527 ->0.027777777777777776 : RED_LIGHT
0.027777777777777776 ->0 : RED_DARK
</code>```

and returning as a HashMap<String, HashMap<String, Double>>

```<code>{GREEN_LIGHT={min=0.4632936507936508, max=0.6226151930261519}, YELLOW_DARK={min=0.20459770114942527, max=0.3525246305418719}, YELLOW_LIGHT={min=0.3525246305418719, max=0.4632936507936508}, RED_DARK={min=0.0, max=0.027777777777777776}, RED_LIGHT={min=0.027777777777777776, max=0.20459770114942527}, GREEN_DARK={min=0.6226151930261519, max=Infinity}}
{ "GREEN/LIGHT_YELLOW" : 0.5366379310344828 , "YELLOW_DARK/RED_LIGHT" : 0.18349195937745413 , "YELLOW_LIGHT/YELLOW_DARK" : 0.3571428571428571 , "RED_LIGHT/RED_DARK" : 0.08940809968847352}
</code>```

Body:
I have a map of <String,Double> considered as thresholds to classify a list of Doubles

HashMap<String, Double> map = new Hashmap<>();
map.put(A/B,0.7);
map.put(B/C,0.4);
map.put(C/D,0.3);
map.put(D/E,0.1);

The Doubles of the hash is used as threshold to classify a list doubles given, so I want to transform this map into a list of classes A, B, C, D

Class A : from 0.7
Class B : from 0.4 to 0.7
Class C : from 0.3 to 0.4
Class D : from 0.1 to 0.3
Class E : less than 0.1

Do you have any idea on how to perform that as a method StringClassifyByValue(HashMap<String, Double> map, Double value){} returning a String of the class correspondent of the value given as parameter?

ِExample :

this.StringClassifyByValue(map,0.5) have to return B.

Body:
private HashMap<String, HashMap<String, Double>> getMinMaxThreshold(HashMap<String, Double> map) {

        List<Double> threholds = map.values().stream().collect(Collectors.toList());
        HashMap<String,Double >map1= this.sortByValues(map);
        List<String> keys = map1.keySet().stream().collect(Collectors.toList());

        Collections.sort(threholds);
        Collections.reverse(threholds);

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

        for (int i =0;i<=threholds.size();i++){

            if(i==threholds.size()){
                HashMap<String, Double> testmap = new HashMap<>();
                testmap.put("max",threholds.get(i-1));
                testmap.put("min",0.0);
                boudaries.put(keys.get(keys.size()-1).split("/")[1], testmap);
                System.out.println(threholds.get(i-1)+" ->"+0+" : "+keys.get(keys.size()-1).split("/")[1] );
            }

            else if (i==0){
                HashMap<String, Double> testmap = new HashMap<>();
                testmap.put("max",Math.exp(1000));
                testmap.put("min",threholds.get(i));
                boudaries.put(keys.get(0).split("/")[0], testmap);
                System.out.println(Math.exp(100) +" ->"+threholds.get(i)+" : "+keys.get(0).split("/")[0] );}

            else{
                HashMap<String, Double> testmap = new HashMap<>();
                testmap.put("max",threholds.get(i-1));
                testmap.put("min",threholds.get(i));
                boudaries.put(keys.get(i).split("/")[0], testmap);
            System.out.println(threholds.get(i-1)+" ->"+threholds.get(i)+" : "+keys.get(i).split("/")[0]);}
        }

        System.err.println(boudaries);

        return boudaries;
    }

The ’keys’ is a ’List’ and represent the Classes A,B,C,D.

The thresholds is a ’List’represent the thresholds. We have
to use this threshold to make the boundaries.

I sort the map of thresholds by values to get the Strings in descending order, and same with the list of Double thresholds to make them in the same order.

I loop foreach element of threshold.. for the first item it's about the last boudaries so I made as boudaries the Exp(1000) and the previous element.. for the last element, it's about a boudaries with min 0 and max the last element of threshold.

I use split to get the first element of splited array except the last item where I use the second element of the array to match the last element. That's it

Test :

If we have as an input this ’Map’

{ "YELLOW_DARK/RED_LIGHT" : 0.20459770114942527 , "GREEN_DARK/GREEN_LIGHT" : 0.6226151930261519 , "GREEN_LIGHT/YELLOW_LIGHT" : 0.4632936507936508 , "YELLOW_LIGHT/YELLOW_DARK" : 0.3525246305418719 , "RED_LIGHT/RED_DARK" : 0.027777777777777776}

My code will transorm it into :

2.6881171418161356E43 ->0.6226151930261519 : GREEN_DARK
0.6226151930261519 ->0.4632936507936508 : GREEN_LIGHT
0.4632936507936508 ->0.3525246305418719 : YELLOW_LIGHT
0.3525246305418719 ->0.20459770114942527 : YELLOW_DARK
0.20459770114942527 ->0.027777777777777776 : RED_LIGHT
0.027777777777777776 ->0 : RED_DARK

and returning as a HashMap<String, HashMap<String, Double>>

{GREEN_LIGHT={min=0.4632936507936508, max=0.6226151930261519}, YELLOW_DARK={min=0.20459770114942527, max=0.3525246305418719}, YELLOW_LIGHT={min=0.3525246305418719, max=0.4632936507936508}, RED_DARK={min=0.0, max=0.027777777777777776}, RED_LIGHT={min=0.027777777777777776, max=0.20459770114942527}, GREEN_DARK={min=0.6226151930261519, max=Infinity}}
{ "GREEN/LIGHT_YELLOW" : 0.5366379310344828 , "YELLOW_DARK/RED_LIGHT" : 0.18349195937745413 , "YELLOW_LIGHT/YELLOW_DARK" : 0.3571428571428571 , "RED_LIGHT/RED_DARK" : 0.08940809968847352}


问:
How to keep Sonata Admin menu on left side hidden when browsing
Any help will be more than welcomed.

What are you trying to accomplish?

I have a Sonata Admin panel, and some pages have large amount of data, so I need to hide the left menu. However when I go back to another page (from a Show to a List) or I click on an action button (from a List to Show) for example, then the menu is shown again.

Paste the part of the code that shows the problem.

I was thinking that maybe, in the same way I can keep my form filters applied even when I browse between pages (sonata_admin.persist_filters) maybe there is another way to set-up a global sonata parameter that will "force" the left menu to be shown or hidden for future requests, until I click on the icon to show or hide it again.

What do you expect the result to be?

I just want to keep the left menu hidden between pages.

Sonata Admin with collapsed menu

What is the actual result you get?

Currently, when I click on the icon next to Sonata title the menu hides, but when I browse other pages the menu is shown again.

Sonata Admin with expanded menu

答:
Update: This is now implemented and is the standard behaviour starting from the 3.30.0 release.

There is no such feature currently as far as I know. You can still help us to make Sonata better by providing a PR to implement this feature.

I opened an issue to track this feature here: https://github.com/sonata-project/SonataAdminBundle/issues/4837


答:
I use exceptions to flow control a lot

Throwing specific and functional exceptions to indicate a functional issue during the workflow is not bad itself.

It is not the single way to do it but it is a valid way.

Another way relies on methods that returns boolean and testing the returned value.

Personally, I don't use this way as I found it rather verbose, error-prone (we have not to forget to test the returned boolean) and less expressive (it has only two values: true and false) than an exception (it may have as many as required).

Suppose that method B has to check something and that if the check fails the processing should be stopped and the client notified of the issue, it would be totally valid to use exceptions for this purpose.

Now, it would make more sense to make the exception a specific exception rather than Exception.

Otherwise how the client could interpret the exception meaning ?

The exception could be a workflow exception but it could be also any exception thrown at runtime for another reason such as a NullPointerException.

You want to handle workflow exceptions in a specific way while you will not apply a specific processing to other thrown exceptions.

For example you could write something as :

```<code>public static methodA()
{
    methodB();
}

public static methodB(){
    if (!expectedDataFound()){
      throw new DataNotFoundException("data xxx was not found");
    }
    if (!hasRights()){
      throw new PermissionException("user xxx has not the rights for yyy");
    }
}
</code>```

Then from the client side, you have two ways.

Catching each exception individually or catching them in a common way (that is possible only if they make part of the same hierarchy).

Catching each exception individually :

```<code>public static void main(String[] args)
{
    try
    {
        methodA();
    }
    catch (DataNotFoundException ex)
    {
        handleDataNotFoundException(ex);
    }
    catch (PermissionException ex)
    {
        handlePermissionException(ex);
    }
}
</code>```

Catching exception globally:

```<code>public static void main(String[] args)
{
    try
    {
        methodA();
    }
    catch (WorkflowException ex)
    {
        handleWorkflowException(ex);
    }
}
</code>```

Title: Exception flow control

Body:
I use exceptions to flow control a lot

Throwing specific and functional exceptions to indicate a functional issue during the workflow is not bad itself.

It is not the single way to do it but it is a valid way.

Another way relies on methods that returns boolean and testing the returned value.

Personally, I don't use this way as I found it rather verbose, error-prone (we have not to forget to test the returned boolean) and less expressive (it has only two values: true and false) than an exception (it may have as many as required).

Suppose that method B has to check something and that if the check fails the processing should be stopped and the client notified of the issue, it would be totally valid to use exceptions for this purpose.

Now, it would make more sense to make the exception a specific exception rather than Exception.

Otherwise how the client could interpret the exception meaning ?

The exception could be a workflow exception but it could be also any exception thrown at runtime for another reason such as a NullPointerException.

You want to handle workflow exceptions in a specific way while you will not apply a specific processing to other thrown exceptions.

For example you could write something as :

public static methodA()
{
    methodB();
}

public static methodB(){
    if (!expectedDataFound()){
      throw new DataNotFoundException("data xxx was not found");
    }
    if (!hasRights()){
      throw new PermissionException("user xxx has not the rights for yyy");
    }
}

Then from the client side, you have two ways.

Catching each exception individually or catching them in a common way (that is possible only if they make part of the same hierarchy).

Catching each exception individually :

public static void main(String[] args)
{
    try
    {
        methodA();
    }
    catch (DataNotFoundException ex)
    {
        handleDataNotFoundException(ex);
    }
    catch (PermissionException ex)
    {
        handlePermissionException(ex);
    }
}

Catching exception globally:

public static void main(String[] args)
{
    try
    {
        methodA();
    }
    catch (WorkflowException ex)
    {
        handleWorkflowException(ex);
    }
}


问:
Is there a cachebust variable in mkdocs templates?
Is there anything like {{ time() }} or even more ideally {{ sha1sum('main.js') }} which I could use as a cachebust parameter in my theme templates?

Yes I'm aware of server side caching headers, but I don't have control of those.

Body:
The best I found so far is this {{ build_date_utc.strftime('%S%f') }} based on documentation I found here: http://www.mkdocs.org/user-guide/custom-themes/#template-variables

So now I can do this:
<script src="/static/js/main.js?cb={{ build_date_utc.strftime('%S%f') }}">

Which invalidates the cached file much more than it should, but at least it solves the problem.


问:
Configuration Membership on localhost and real hosting
On localhost use SQLServer Express Edition. When I upload file to real hosting,my hosting use Full SQL Server 2005. How to config the ConnectionString of Membership(aspnetdb.mdf) </p>

答:
How your ConnectionString for your hosting environment is supposed to look like you should probably find out via the FAQs (or a similar section) on your hoster's page.

On this page you will find a reference of all ConnectionStrings and how to use them:

www.connectionstrings.com