问:
cakephp query with conditions limit and order
I want to retrieve the last 3 registered users in cakephp using the field created in table Users.

In my controller I have:

```<code>$this->User->recursive = 1;
    $this->set('users',
        $this->User->find('all',
             array('conditions'=> array(
                  'limit' => 3,
                  'order' => array(
                  'created' => 'asc'
                  )
             )
         )
    )
);
</code>```

The code above when run returns this error:

```<code>Syntax error or access violation: 1064 You have an error in your SQL
syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near 'order = ('asc')' at line
</code>```

What must I do to resolve the error?

答:
When you limit the data first you should order DESC or ASC. Another easy way that works fine

```<code>$this->set('datas',
    $this->Your_Model_Name->find('all',
        array (
            'conditions'    => array('Site_id' => $site_name),   //conditions here
            'fields'        => array('Date_time','Ac_1_Status','Tempin'),
            'order'         => array('id' => 'desc'),  // id desc or asc
            'limit'         => 15
        )
    )
);
</code>```

Body:
I want to retrieve the last 3 registered users in cakephp using the field created in table Users.

In my controller I have:

$this->User->recursive = 1;
    $this->set('users',
        $this->User->find('all',
             array('conditions'=> array(
                  'limit' => 3,
                  'order' => array(
                  'created' => 'asc'
                  )
             )
         )
    )
);

The code above when run returns this error:

Syntax error or access violation: 1064 You have an error in your SQL
syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near 'order = ('asc')' at line

What must I do to resolve the error?

Body:
When you limit the data first you should order DESC or ASC. Another easy way that works fine

$this->set('datas',
    $this->Your_Model_Name->find('all',
        array (
            'conditions'    => array('Site_id' => $site_name),   //conditions here
            'fields'        => array('Date_time','Ac_1_Status','Tempin'),
            'order'         => array('id' => 'desc'),  // id desc or asc
            'limit'         => 15
        )
    )
);


来源: stackexchange

问:
how pass data from activity to custom adapter
hi guys i need to pass arraylist from activity to custom adapter class but with my code it doesn't passed...i don't know why!

i use intent to pass data:

ACTIVITY:

```<code>private void azz() {
    int a=0;
    String status="";
    boolean statuss = false;
    String intenttt= path;

    System.out.println("INTENT:"+intenttt);

    file = new File(intenttt);
    System.out.println("FILE:"+file);

    FileInputStream is = null;
    try {
        is = new FileInputStream(file);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = null;
    try {
        dBuilder = dbFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    Document doc = null;
    try {
        doc = dBuilder.parse(is);
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    Element element = doc.getDocumentElement();
    element.normalize();

    NodeList nList = doc.getElementsByTagName("checkboxes_pizza");

    for (int i = 0; i < nList.getLength(); i++) {
        Node node = nList.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element element2 = (Element) node;
            //tv1.setText(tv1.getText()+"\nName : " + getValue("name", element2)+"\n");
            String id = getValue("id", element2);
            a = Integer.parseInt(id);
            status = getValue("status", element2);

            statuss= Boolean.parseBoolean(status);

            System.out.println("XML:" + a);

            hm.add(a);

            System.out.println("AZZ:" + hm);

        }

    }

    Intent intent = new Intent(ScrollableTabsActivity.this,PlanetAdapter.class) ;
    intent.putIntegerArrayListExtra("a", hm);
    startActivity(intent);

     // ok();

}
</code>```

CUSTOM ADAPTER TO GET INTENT:

```<code> Intent intent = getIntent();
        Arraylist<Integer> email=intent.getIntegerArrayListExtra("a");
</code>```

moreover getIntent() is written in red by IDE...

答:
That is because getIntent() is not available in adapter class unless you declare a function named getIntent() in it. Add a function in the adapter to receive the data in the adapter and call notifyDataSetChanged() to refresh the list. for example:

```<code>class DataAdapter extends ArrayAdapter<String> {

    private ArrayList<String> items = new ArrayList<>();

    public DataAdapter(@NonNull Context context, @LayoutRes int resource) {
        super(context, resource);
    }

    public void setItems(ArrayList<String> items) {
        this.items = items;
        notifyDataSetChanged();
    }
    //some more code
}
</code>```

in your activity create an instance of the adapter and bind it to the list/spinner and then call the function to add data in the adapter.

ContentLicense: CC BY-SA 3.0

Body:
hi guys i need to pass arraylist from activity to custom adapter class but with my code it doesn't passed...i don't know why!

i use intent to pass data:

ACTIVITY:

private void azz() {
    int a=0;
    String status="";
    boolean statuss = false;
    String intenttt= path;

    System.out.println("INTENT:"+intenttt);

    file = new File(intenttt);
    System.out.println("FILE:"+file);

    FileInputStream is = null;
    try {
        is = new FileInputStream(file);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = null;
    try {
        dBuilder = dbFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    Document doc = null;
    try {
        doc = dBuilder.parse(is);
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    Element element = doc.getDocumentElement();
    element.normalize();

    NodeList nList = doc.getElementsByTagName("checkboxes_pizza");

    for (int i = 0; i < nList.getLength(); i++) {
        Node node = nList.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element element2 = (Element) node;
            //tv1.setText(tv1.getText()+"\nName : " + getValue("name", element2)+"\n");
            String id = getValue("id", element2);
            a = Integer.parseInt(id);
            status = getValue("status", element2);

            statuss= Boolean.parseBoolean(status);

            System.out.println("XML:" + a);

            hm.add(a);

            System.out.println("AZZ:" + hm);

        }

    }

    Intent intent = new Intent(ScrollableTabsActivity.this,PlanetAdapter.class) ;
    intent.putIntegerArrayListExtra("a", hm);
    startActivity(intent);

     // ok();

}

CUSTOM ADAPTER TO GET INTENT:

 Intent intent = getIntent();
        Arraylist<Integer> email=intent.getIntegerArrayListExtra("a");

moreover getIntent() is written in red by IDE...

Body:
That is because getIntent() is not available in adapter class unless you declare a function named getIntent() in it. Add a function in the adapter to receive the data in the adapter and call notifyDataSetChanged() to refresh the list. for example:

class DataAdapter extends ArrayAdapter<String> {

    private ArrayList<String> items = new ArrayList<>();

    public DataAdapter(@NonNull Context context, @LayoutRes int resource) {
        super(context, resource);
    }

    public void setItems(ArrayList<String> items) {
        this.items = items;
        notifyDataSetChanged();
    }
    //some more code
}

in your activity create an instance of the adapter and bind it to the list/spinner and then call the function to add data in the adapter.


问:
Printing last name + first name - but it shows error (Java)
So I have made a code for user to enter their first and last name; then exhanging the two position.

for example. Bulota Babi becomes Babi, Bulota

this is my code

```<code>public class trial {
    public static void main(String [] args) {
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();

        String fname = input.substring(0, input.indexOf(0));
        String lname = input.substring(1, input.indexOf(input.length()));

        System.out.println(lname +","+ fname);
    }

}
</code>```

im not sure whats wrong with it, this is the error message

```<code>Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.substring(String.java:1967)
    at trial.main(trial.java:11)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
</code>```

答:
The String.indexOf function works on the ASCII value. As you are passing 0 in indexOf function it  returns value -1.

After that you are doing subString on input string having range (0,-1).

As Mentioned in java docs for java.lang.StringIndexOutOfBoundsException , java.lang.StringIndexOutOfBoundsException
  Exception will come to indicate that an index is either negative or
  greater than the size of the string.

So your exception is coming from  input.substring function

Body:
So I have made a code for user to enter their first and last name; then exhanging the two position.

for example. Bulota Babi becomes Babi, Bulota

this is my code

public class trial {
    public static void main(String [] args) {
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();

        String fname = input.substring(0, input.indexOf(0));
        String lname = input.substring(1, input.indexOf(input.length()));

        System.out.println(lname +","+ fname);
    }

}

im not sure whats wrong with it, this is the error message

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.substring(String.java:1967)
    at trial.main(trial.java:11)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)


问:
Firebase React Native build error after linking module
I'm attempting to use the firestack module to implement social media signin into my React Native project: https://github.com/fullstackreact/react-native-firestack

However after linking the module, I am receiving the following error during the build:

```<code>Execution failed for task ':app:processDebugResources'.
java.io.IOException: Could not delete path 'C:\Users\######\project\android\app\build\generated\source\r\debug\android'.
</code>```

答: Delete build directory in android/app and try react-native run-android

Body:
I'm attempting to use the firestack module to implement social media signin into my React Native project: https://github.com/fullstackreact/react-native-firestack

However after linking the module, I am receiving the following error during the build:

Execution failed for task ':app:processDebugResources'.
java.io.IOException: Could not delete path 'C:\Users\######\project\android\app\build\generated\source\r\debug\android'.


问:
Day difference coming wrong
We have to do some security check for which we are getting some date from some part of our code and then we are calculating the difference in days

```<code>String userDate = EncryptUtil.getInstance().decrypt(Constants.USER_DATE);
String currentDate = new SimpleDateFormat("dd/MM/yyyy").format(calendar.getTime());

long startTime = new Date(userDate).getTime();
long presentTime = new Date(currentDate).getTime();
long diffTime = presentTime - startTime;
long diffDays = diffTime / (1000 * 60 * 60 * 24);
</code>```

The userDate value is coming 03/06/2017 and currentDate is 07/06/2017, both are correct, but when I'm calculating day difference (diffDays) it is giving a difference of 122, where it should be actually 4. I don't understand why? Can anybody help.

答:
Avoid the use the of the old Date API.

```<code>public static void main(String args[]) throws Exception {
    final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
    LocalDate userDate = LocalDate.parse("03/06/2017", formatter);
    LocalDate currentDate = LocalDate.parse("07/06/2017", formatter);

    long days = ChronoUnit.DAYS.between(userDate, currentDate);

    System.out.printf("%s days have passed%n", days);
}
</code>```

Your actual issue is that you are assuming that Date parses ddMMyyyy which is not correct, that's the European date format rather than then US one.

From the JavaDoc for Date.parse (which is used by the Deprecated(!!) String constructor):

If the number is followed by a slash, it is regarded as a month (it is decreased by 1 to produce a number in the range 0 to 11), unless a month has already been recognized, in which case it is regarded as a day of the month.

i.e. it tries to parse a month first, then a day.

Title: Day difference coming wrong

Body:
We have to do some security check for which we are getting some date from some part of our code and then we are calculating the difference in days

String userDate = EncryptUtil.getInstance().decrypt(Constants.USER_DATE);
String currentDate = new SimpleDateFormat("dd/MM/yyyy").format(calendar.getTime());

long startTime = new Date(userDate).getTime();
long presentTime = new Date(currentDate).getTime();
long diffTime = presentTime - startTime;
long diffDays = diffTime / (1000 * 60 * 60 * 24);

The userDate value is coming 03/06/2017 and currentDate is 07/06/2017, both are correct, but when I'm calculating day difference (diffDays) it is giving a difference of 122, where it should be actually 4. I don't understand why? Can anybody help.

Body:
Avoid the use the of the old Date API.

public static void main(String args[]) throws Exception {
    final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
    LocalDate userDate = LocalDate.parse("03/06/2017", formatter);
    LocalDate currentDate = LocalDate.parse("07/06/2017", formatter);

    long days = ChronoUnit.DAYS.between(userDate, currentDate);

    System.out.printf("%s days have passed%n", days);
}

Your actual issue is that you are assuming that Date parses ddMMyyyy which is not correct, that's the European date format rather than then US one.

From the JavaDoc for Date.parse (which is used by the Deprecated(!!) String constructor):

If the number is followed by a slash, it is regarded as a month (it is decreased by 1 to produce a number in the range 0 to 11), unless a month has already been recognized, in which case it is regarded as a day of the month.

i.e. it tries to parse a month first, then a day.


问:
Exiftool - modify metadata format
Suppose I have 5000 images with following metadata in the LABEL field.

```<code>0001 ELEPHANT
0002 ELEPHANT
0003 ELEPHANT
...
4999 ELEPHANT
5000 ELEPHANT
</code>```

I wish to change the format to:

```<code>ELEPHANT-0001
ELEPHANT-0002
ELEPHANT-0003
…
ELEPHANT-4999
ELEPHANT-5000
</code>```

In other words, I want to do the following for a metadata field of multiple images:

#### NAME     —>     NAME-####

From what I can gather there could be two ways of doing this

Ignore the current metadata in the images, and reference a (plain text? csv?) file that I prepare separately; or

Read the file's metadata as a string, identify the space and the number preceding the space, save that number, and finally make a new string by concatenating the number and space, and adding a hyphen in between!

Any suggestions?

答:
Expanding upon the answer I gave in the exiftool forums.

The basic command would be

exiftool "-LABEL<${LABEL;s/(\d{4}) (.*)/$2-$1/}" <FileOrDir>

You basically want to copy a tag into the same tag, with some modifications.  The option to copy a tag is the less than (or greater than) symbol < or >.  A common mistake is to use the equal sign = which is used to assign a static value to a tag.

To do the modification to the tag, it takes the Advance Formatting option, which is actually some in-line perl code.  In this example, the tag is treated as a perl string and a regex substitution is used.  It matches and captures the first four digits (\d{4}), matches the space (but doesn't capture it), then matches and captures the rest of the tag (.*).  The two captures are assigned to the variables $1 and $2, respectively.  In the replace half of the substitution $2-$1, the two captures are reversed with the hyphen between them.

To take full advantage of the advance formatting, some basic perl and regex knowledge is helpful.

Once you are sure of the command, you can add -overwrite_original to suppress the generation of backup files and -r to recurse into subdirectories.

ContentLicense: CC BY-SA 4.0

Title: Exiftool - modify metadata format

Body:
Suppose I have 5000 images with following metadata in the LABEL field.

0001 ELEPHANT
0002 ELEPHANT
0003 ELEPHANT
...
4999 ELEPHANT
5000 ELEPHANT

I wish to change the format to:

ELEPHANT-0001
ELEPHANT-0002
ELEPHANT-0003
…
ELEPHANT-4999
ELEPHANT-5000

In other words, I want to do the following for a metadata field of multiple images:

#### NAME     —>     NAME-####

From what I can gather there could be two ways of doing this

Ignore the current metadata in the images, and reference a (plain text? csv?) file that I prepare separately; or

Read the file's metadata as a string, identify the space and the number preceding the space, save that number, and finally make a new string by concatenating the number and space, and adding a hyphen in between!

Any suggestions?


问:
Liferay 6.2 - Duplicate web pages
noob question. My site looks like this:

```<code>- Public pages
   - Home
      - My site
           - A
              - A 1
                   - A 1.1
                   - A 1.2
              - A 2
           - B
              - B 1
                   - B 1.1
                   - B 1.2
              - B 2
</code>```

And now I have to create C, D, E, etc. web page trees. So, how can I do it without doing it manually? I've tried to export the "A" tree and import again but it doesn't work because it is imported to the same place "A" tree was. Is there any way to import as a copy or something similar?

Thanks in advance.

答:
The simplest close match I can find is:-

You have an option to copy a page while you create the page.
The proper way is to create a resource importer in a theme and initialize the whole site. Like it is already done by Liferay for their default site and theme.

Title: Liferay 6.2 - Duplicate web pages

Body:
noob question. My site looks like this:

- Public pages
   - Home
      - My site
           - A
              - A 1
                   - A 1.1
                   - A 1.2
              - A 2
           - B
              - B 1
                   - B 1.1
                   - B 1.2
              - B 2

And now I have to create C, D, E, etc. web page trees. So, how can I do it without doing it manually? I've tried to export the "A" tree and import again but it doesn't work because it is imported to the same place "A" tree was. Is there any way to import as a copy or something similar?

Thanks in advance.


问:
unable to understand ruby method call
I have a method definition in ruby file (get_java_opts)-
Then one more method calls this "get_java_opts" method with below syntax-
What is this line doing?-

```<code>get_java_opts ? my_java_opts = get_java_opts : my_java_opts = @java_opts
</code>```

Code from my ruby file-

```<code>def start
  appdir = "#{@rootdir}/mydir"
  wo_prop = "#{@rootdir}/app.properties"
  get_java_opts ? my_java_opts = get_java_opts : my_java_opts = @java_opts
</code>```

Method definition-

```<code>def get_java_opts
  yml = "#{@rootdir}/#{@test}.yaml"
  y = YAML.load_file(yml) if File.exists?(yml)
  java_opts = y[@app]['java_opts'] rescue "No YAML found"
end
</code>```

答:
The Ternary Operator syntax is like condition ? true : false

Lets understand its working using get_java_opts ? my_java_opts = get_java_opts : my_java_opts = @java_opts as example

Let us divide our expression in parts PART A ? PART B : PART C

Now ,
in PART A you've get_java_opts,

in PART B you've my_java_opts = get_java_opts, and

in PART C you've my_java_opts = @java_opts

So Now,

let's assume your PART A is returning either true or false.

If PART A return true then then the PART B will execute which is my_java_opts = get_java_opts

and if PART A return false then the PART C will execute which is my_java_opts = @java_opts.

Title: unable to understand ruby method call

Body:
I have a method definition in ruby file (get_java_opts)-
Then one more method calls this "get_java_opts" method with below syntax-
What is this line doing?-

get_java_opts ? my_java_opts = get_java_opts : my_java_opts = @java_opts

Code from my ruby file-

def start
  appdir = "#{@rootdir}/mydir"
  wo_prop = "#{@rootdir}/app.properties"
  get_java_opts ? my_java_opts = get_java_opts : my_java_opts = @java_opts

Method definition-

def get_java_opts
  yml = "#{@rootdir}/#{@test}.yaml"
  y = YAML.load_file(yml) if File.exists?(yml)
  java_opts = y[@app]['java_opts'] rescue "No YAML found"
end


问:
How to order by custom time format in laravel?
I have to order a database table with a custom time format.
 The time format used in the table is like this:

1:30:PM

8:35:PM

5:50:PM

7:00 PM

I tried the following, but it does not sort them all in the correct order.

```<code>            ->orderBy('time_schedule.start_time', 'asc');
</code>```

After sorting the with the above method the result comes like

1:30:PM

5:50:PM

8:35:PM

7:00 PM

I'm not able to change the format saved, as i'm not working on that part of the application.

Also the data have to come sorted form laravel, cannot use front end sorting in my situation.

Please let me know whether there is a way to sort this with laravel.

答:
you can't add timestamp to database in custom format like 01:00 AM .all you to do is u need to format it to 24 hr then store it to database

so during retrieve order by clause will give you sorted order

```<code>    $time = '01:00 PM';
    $date = date_format(date_create($time),'H:i:s');
    \App\TableModel::insert(['start_time'=>$date]);
    or
    DB::table('tablename')->insert(['start_time'=>$date]);

    retrive by order.......
    DB::table('tablename')->orderBy('start_time')->get();
</code>```

for more information check ref:Insert h:mm pm/am time format into database using MYSQL

Body:
I have to order a database table with a custom time format.
 The time format used in the table is like this:

1:30:PM

8:35:PM

5:50:PM

7:00 PM

I tried the following, but it does not sort them all in the correct order.

            ->orderBy('time_schedule.start_time', 'asc');

After sorting the with the above method the result comes like

1:30:PM

5:50:PM

8:35:PM

7:00 PM

I'm not able to change the format saved, as i'm not working on that part of the application.

Also the data have to come sorted form laravel, cannot use front end sorting in my situation.

Please let me know whether there is a way to sort this with laravel.

Body:
you can't add timestamp to database in custom format like 01:00 AM .all you to do is u need to format it to 24 hr then store it to database

so during retrieve order by clause will give you sorted order

    $time = '01:00 PM';
    $date = date_format(date_create($time),'H:i:s');
    \App\TableModel::insert(['start_time'=>$date]);
    or
    DB::table('tablename')->insert(['start_time'=>$date]);

    retrive by order.......
    DB::table('tablename')->orderBy('start_time')->get();

for more information check ref:Insert h:mm pm/am time format into database using MYSQL


问:
ibatis to mybatis migration
ibatis conversion of <isNotEmpty property="A"> is <if test='A != null and A != "" '>

the above conversion works fine for string. But how to compare the list along with null check to check if the list is notEmpty

I tried following things

```<code><if test='List != null and List.size() > 0'>
<if test='List != null and List.isNotEmpty()'>(because isEmpty() worked fine)
<if test='List != null and !(List.isEmpty())'>
<if test='List != null and !List.isEmpty()'>
</code>```

But if I use isEmpty() along with null check for alternative to isNotEmpty work fine, Im bit confused on this part

Any explanation on this would be great!

答:
You can validate the condition List is Empty or not in many ways in myBatis.

Choose the suitable answer from below which matches your requirement.

Basic Check

```<code><if test="list != null and list.size()>0">
    <foreach item="item" index="index" collection="list"
      open="(" separator="," close=")">
        #{item}
    </foreach>
</if>
</code>```

If you are doing the same in some SQL where statements you can do the below.

```<code>WHERE
    <choose>
        <when test="list==null || list.isEmpty()">
            1 = 0 <!-- a test returning false, to adapt depending on you DB vendor -->
        </when>
        <otherwise>
            ID IN <foreach item="item" collection="list" open="(" separator="," close=")">#{item}</foreach>
        </otherwise>
    </choose>
</code>```

Using Dynamic SQL

```<code>WHERE <*condition1*>
<dynamic>
<isNotEmpty prepend="AND" property="list">
    yourTbl.pk_ID IN
    <iterate property="list" open="(" close=")" conjunction=",">
        #list[]#
    </iterate>
</isNotEmpty>
</dynamic>
</code>```

Title: ibatis to mybatis migration

Body:
ibatis conversion of <isNotEmpty property="A"> is <if test='A != null and A != "" '>

the above conversion works fine for string. But how to compare the list along with null check to check if the list is notEmpty

I tried following things

<if test='List != null and List.size() > 0'>
<if test='List != null and List.isNotEmpty()'>(because isEmpty() worked fine)
<if test='List != null and !(List.isEmpty())'>
<if test='List != null and !List.isEmpty()'>

But if I use isEmpty() along with null check for alternative to isNotEmpty work fine, Im bit confused on this part

Any explanation on this would be great!

Body:
You can validate the condition List is Empty or not in many ways in myBatis.

Choose the suitable answer from below which matches your requirement.

Basic Check

<if test="list != null and list.size()>0">
    <foreach item="item" index="index" collection="list"
      open="(" separator="," close=")">
        #{item}
    </foreach>
</if>

If you are doing the same in some SQL where statements you can do the below.

WHERE
    <choose>
        <when test="list==null || list.isEmpty()">
            1 = 0 <!-- a test returning false, to adapt depending on you DB vendor -->
        </when>
        <otherwise>
            ID IN <foreach item="item" collection="list" open="(" separator="," close=")">#{item}</foreach>
        </otherwise>
    </choose>

Using Dynamic SQL

WHERE <*condition1*>
<dynamic>
<isNotEmpty prepend="AND" property="list">
    yourTbl.pk_ID IN
    <iterate property="list" open="(" close=")" conjunction=",">
        #list[]#
    </iterate>
</isNotEmpty>
</dynamic>


问:
Getting expression text
I want to pass the name of a property of a model to a method. Instead of using the name as string, I am using lambda expression as it is easy to make a typo, and also property names may be changed. Now if the property is a simple property (e.g: model.Name) I can get the name from the expression. But if it is a nested property (e.g: model.AnotherModel.Name) then how can I get full text ("AnotherModel.Name") from the expression. For example, I have the following classes:</p>

```<code>public class BaseModel
{
    public ChildModel Child { get; set; }
    public List<ChildModel> ChildList { get; set; }

    public BaseModel()
    {
        Child = new ChildModel();
        ChildList = new List<ChildModel>();
    }
}

public class ChildModel
{
    public string Name { get;set; }
}

public void GetExpressionText<T>(Expression<Func<T, object>> expression)
{
    string expText;
    //what to do??
    return expText;
}

GetExpressionText<BaseModel>(b => b.Child); //should return "Child"
GetExpressionText<BaseModel>(b => b.Child.Name); //should return "Child.Name"
GetExpressionText<BaseModel>(b => b.ChildList[0].Name); //should return "ChildList[0].Name"
</code>```

答:
You could use the C# 6.0 feature:  nameof(b.Child) "Used to obtain the simple (unqualified) string name of a variable, type, or member."
which will also change on renaming. But this will only return the propertyname and not the complete path. Returning a complete path will be difficult, because only one instance is passed.

Title: Getting expression text

Body:
I want to pass the name of a property of a model to a method. Instead of using the name as string, I am using lambda expression as it is easy to make a typo, and also property names may be changed. Now if the property is a simple property (e.g: model.Name) I can get the name from the expression. But if it is a nested property (e.g: model.AnotherModel.Name) then how can I get full text ("AnotherModel.Name") from the expression. For example, I have the following classes:

public class BaseModel
{
    public ChildModel Child { get; set; }
    public List<ChildModel> ChildList { get; set; }

    public BaseModel()
    {
        Child = new ChildModel();
        ChildList = new List<ChildModel>();
    }
}

public class ChildModel
{
    public string Name { get;set; }
}

public void GetExpressionText<T>(Expression<Func<T, object>> expression)
{
    string expText;
    //what to do??
    return expText;
}

GetExpressionText<BaseModel>(b => b.Child); //should return "Child"
GetExpressionText<BaseModel>(b => b.Child.Name); //should return "Child.Name"
GetExpressionText<BaseModel>(b => b.ChildList[0].Name); //should return "ChildList[0].Name"


问:
UiPath wont recognize textbox and other controls within userform
I have been working on UiPath for quite some time and I have a form where I need to input certain details.

UiPath won't recognize the controls within the form. This form is designed using power builder and the selector looks something as below

```<code><wnd app='pcemain.exe' cls='FNWNS390' title='Open' />
<wnd cls='pbdw90' />
</code>```

答:
Since the items and their order in the list won't change; you should be able to use the Send Hotkey activity or Type into activity, or a combination of the two.

In some dropdowns, you can type the whole name of the item.

My tip for these kinds of situations, where the (mouse) controls are
  challenging, is to try to do the action manually without using the
  mouse (or use it as little as possible). When finding a solution, do
  it in UiPath

Body:
I have been working on UiPath for quite some time and I have a form where I need to input certain details.

UiPath won't recognize the controls within the form. This form is designed using power builder and the selector looks something as below

<wnd app='pcemain.exe' cls='FNWNS390' title='Open' />
<wnd cls='pbdw90' />


问:
Angular2 - Routing for file download not working
I have a set of files under following path:

/assets/myFolder

I have to make them downloadable from the application.

Now I'm trying to implement the download link like this :

```<code><a href="/assets/myFolder/file.pdf" download>click here to download the file</a>
</code>```

When I click on the link, I get the file but the content is the homepage html file.

I think that I have to customize something in the app.routing but I don't know how.

答:
Actually the problem was not a real problem...
All works properly, I was just testing the download with a file that contains white spaces...
Those are not allowed in web...</p>

Body:
I have a set of files under following path:

/assets/myFolder

I have to make them downloadable from the application.

Now I'm trying to implement the download link like this :

click here to download the file

When I click on the link, I get the file but the content is the homepage html file.

I think that I have to customize something in the app.routing but I don't know how.


问:
Typescript type assertions in parameters
I'm liking typescript so far, but find that i need to do type assertion a lot. For example casting an EventTarget to an HTMLAnchorElement is a common use case for me. However to get that, i need to use something like the following:

```<code>getTabID(eventTarget: EventTarget) : string {
    // without the following variable, the compiler tells me that .hash
    // is not a property of EventTarget, which according to the interface, it isn't.
    // So thats fine, i'll cast it to an Element
    let mEventTarget: HTMLAnchorElement = <HTMLAnchorElement>eventTarget
    let mTabID: string
    if(mEventTarget.hash){
        mTabID = mEventTarget.hash.split('#')[1]
    }
    return mTabID
}
</code>```

However this means that if I don't want the compiler to throw errors I need to create variables in my functions JUST to do type assertions. I don't mind the extra typing, but these end up in the JS as well and ends up wasting bytes in my js files.

I would like to be able to the following:

```<code>getTabID(eventTarget: EventTarget) : string {
    let mTabID: string
    // Do the type assertion in the parameter
    if(<HTMLAnchorElement> eventTarget.hash){
        mTabID = mEventTarget.hash.split('#')[1]
    } else {
        mTabID = mEventTarget.dataset.tabId
    }
    return mTabID
}
</code>```

I've had a good look in the docs and SO and can't seem to find any way to do this. Anyone have any ideas?

答:
You can use type guards to implement this.

An example would be:

function isAnchor(eventTarget: EventTarget): eventTarget is HTMLAnchorElement {
  return (<HTMLAnchorElement>eventTarget).hash != undefined;
}

function getTabID(eventTarget: EventTarget): string {
  let mTabID: string
  // Do the type assertion in the parameter
  if (isAnchor(eventTarget)) {
    mTabID = eventTarget.hash.split('#')[1]
  } else {
    mTabID = eventTarget.dataset.tabId
  }
  return mTabID
}
```

Note: I didn't know what interface dataset was part of but you can make a type guard for it as well.

You can learn more about type guards in the handbook here.

Body:
I'm liking typescript so far, but find that i need to do type assertion a lot. For example casting an EventTarget to an HTMLAnchorElement is a common use case for me. However to get that, i need to use something like the following:

getTabID(eventTarget: EventTarget) : string {
    // without the following variable, the compiler tells me that .hash
    // is not a property of EventTarget, which according to the interface, it isn't.
    // So thats fine, i'll cast it to an Element
    let mEventTarget: HTMLAnchorElement = <HTMLAnchorElement>eventTarget
    let mTabID: string
    if(mEventTarget.hash){
        mTabID = mEventTarget.hash.split('#')[1]
    }
    return mTabID
}

However this means that if I don't want the compiler to throw errors I need to create variables in my functions JUST to do type assertions. I don't mind the extra typing, but these end up in the JS as well and ends up wasting bytes in my js files.

I would like to be able to the following:

getTabID(eventTarget: EventTarget) : string {
    let mTabID: string
    // Do the type assertion in the parameter
    if(<HTMLAnchorElement> eventTarget.hash){
        mTabID = mEventTarget.hash.split('#')[1]
    } else {
        mTabID = mEventTarget.dataset.tabId
    }
    return mTabID
}

I've had a good look in the docs and SO and can't seem to find any way to do this. Anyone have any ideas?

Body:
You can use type guards to implement this.

An example would be:

function isAnchor(eventTarget: EventTarget): eventTarget is HTMLAnchorElement {
  return (<HTMLAnchorElement>eventTarget).hash != undefined;
}

function getTabID(eventTarget: EventTarget): string {
  let mTabID: string
  // Do the type assertion in the parameter
  if (isAnchor(eventTarget)) {
    mTabID = eventTarget.hash.split('#')[1]
  } else {
    mTabID = eventTarget.dataset.tabId
  }
  return mTabID
}

Note: I didn't know what interface dataset was part of but you can make a type guard for it as well.

You can learn more about type guards in the handbook here.


问:
Service not running in background after swiping out application
I am using service for sending current location of device to server continuously in background, but service is also getting killed when I swipe out the application on some phones. It's working if I remove restriction of running background services from Phone settings to the app. I will be thankful, If someone provide solution of removing this restriction  programatically.</p>

答: Every Phone manufacturer has it's own settings for background processing apps. As there are many android device manufacturers it will be difficult to check for every device group. I'm facing the same issue for my app. It will be better if you ask to check is there any setting regarding background services in their device.</p>


问:
How to get the internal table data in excel format if the report runs in background?
Could you please tell me the way to get internal table data in excel file to be saved in local desktop (presentation server). Remember that the report runs in background.</p>

答:
Both requirements a contradictionary because a backround job does not have any connection to any SAPGui. I.e. there is no SAPGui connection linked to a background job ans thus it is not possible to determine onto which local desktop the excel file should be saved.

A possibility would be to store the results that are created in the backround job somehow and externalize the save to a local desktop into another program. When creating files on the SAP AS you should keep in mind what happens with these file after they are not needed any longer. I.e. you need to do the file maintenance (deletion of files after they are not needed any longer) your self.


问:
Equals method for data class in Kotlin
I have the following data class

```<code>data class PuzzleBoard(val board: IntArray) {
    val dimension by lazy { Math.sqrt(board.size.toDouble()).toInt() }
}
</code>```

I read that data classes in Kotlin get equals()/hashcode() method for free.

I instantiated two objects.

```<code>val board1 = PuzzleBoard(intArrayOf(1,2,3,4,5,6,7,8,0))
val board2 = PuzzleBoard(intArrayOf(1,2,3,4,5,6,7,8,0))
</code>```

But still, the following statements return false.

```<code>board1 == board2
board1.equals(board2)
</code>```

答:
For Data classes in Kotlin, hashcode() method will generate and return the same integer if parameters values are same for both objects.

```<code>val user = User("Alex", 1)
val secondUser = User("Alex", 1)
val thirdUser = User("Max", 2)

println(user.hashCode().equals(secondUser.hashCode()))
println(user.hashCode().equals(thirdUser.hashCode()))
</code>```

Running this code will return True and False as when we created secondUser object we have passed same argument as object user, so hashCode() integer generated for both of them will be same.

also if you will check this:

```<code>println(user.equals(thirdUser))
</code>```

It will return false.

As per hashCode() method docs

```<code>open fun hashCode(): Int (source)
</code>```

Returns a hash code value for the object. The general contract of
hashCode is:

Whenever it is invoked on the same object more than once, the hashCode
method must consistently return the same integer, provided no
information used in equals comparisons on the object is modified.

If two objects are equal according to the equals() method, then calling
the hashCode method on each of the two objects must produce the same
integer result.

For more details see this discussion here

Title: Equals method for data class in Kotlin

Body:
I have the following data class

data class PuzzleBoard(val board: IntArray) {
    val dimension by lazy { Math.sqrt(board.size.toDouble()).toInt() }
}

I read that data classes in Kotlin get equals()/hashcode() method for free.

I instantiated two objects.

val board1 = PuzzleBoard(intArrayOf(1,2,3,4,5,6,7,8,0))
val board2 = PuzzleBoard(intArrayOf(1,2,3,4,5,6,7,8,0))

But still, the following statements return false.

board1 == board2
board1.equals(board2)

Body:
For Data classes in Kotlin, hashcode() method will generate and return the same integer if parameters values are same for both objects.

val user = User("Alex", 1)
val secondUser = User("Alex", 1)
val thirdUser = User("Max", 2)

println(user.hashCode().equals(secondUser.hashCode()))
println(user.hashCode().equals(thirdUser.hashCode()))

Running this code will return True and False as when we created secondUser object we have passed same argument as object user, so hashCode() integer generated for both of them will be same.

also if you will check this:

println(user.equals(thirdUser))

It will return false.

As per hashCode() method docs

open fun hashCode(): Int (source)

Returns a hash code value for the object. The general contract of
hashCode is:

Whenever it is invoked on the same object more than once, the hashCode
method must consistently return the same integer, provided no
information used in equals comparisons on the object is modified.

If two objects are equal according to the equals() method, then calling
the hashCode method on each of the two objects must produce the same
integer result.

For more details see this discussion here


问:
Data is not saved if use custom property editor in Umbraco
I create custom property editor which takes all available languages in Umbraco like:

```<code>angular.module("umbraco").controller("MyLanguageController", function ($scope, myLanguageService) {
   $scope.items = [];

   myLanguageService.getAll().then( function( result ) {
      if( result && result.data && result.data.length ) {
         $scope.items = result.data;
      }
   } );
});
</code>```

and

```<code>angular.module("umbraco.resources")
   .factory("myLanguageService", function ($http) {

      return {
         getAll: function () {
            return $http.get("/umbraco/backoffice/MyControllerSide/GetAll", { "dataType": "json" });
         }
      };
});
</code>```

The view:

```<code><div ng-controller="MyLanguageController" id="language">
   <ul>
      <li ng-repeat="item in items" class="checkbox">
         <label>
            <input type="checkbox" value="{{item.IsoCode}}"> {{item.CultureName}}
         </label>
      </li>
   </ul>
</div>
</code>```

The package manifest contains:

```<code>{
    propertyEditors: [
        {
            alias: "MyLanguageAlias",
            name: "Language Selector",
            icon: "icon-umb-translation",
            hideLabel: true,
            valueType: "JSON",
            editor: {
                view: "~/App_Plugins/MyLanguageSelector/backoffice/view.html"
            }
        }
    ],
  ...
</code>```

and C# code:

```<code>  [HttpGet]
  public JsonResult GetAll()
  {
     IEnumerable<ILanguage> languages = ApplicationContext.Services.LocalizationService.GetAllLanguages() ?? new List<ILanguage>(0);
     IEnumerable<TranslationLanguageModel> model =
        languages.Select(s => new MyLanguageModel { CultureName = s.CultureInfo.DisplayName, IsoCode = s.IsoCode });

     return Json(model, JsonRequestBehavior.AllowGet);
  }
</code>```

I created new data type in Umbraco/Developer section, and I add it in document type:

When I save document, the value for that property is null. I don't understand why.

And when come back to content, then nothing is checked.

What should I do ?

Update 1

If I put:

```<code><input type="checkbox" value="{{item.IsoCode}}"  ng-model="models[item.IsoCode]"/> {{item.CultureName}}
</code>```

then I receive always True instead of object/json.

Update 2

I succeeded to do by adding ng-change for checkbox and modify $scope.model.value value

<input type="checkbox" value="item.IsoCode" ng-change="change()" ng-model="models[item.IsoCode]"/> {{item.CultureName}}

and

```<code>$scope.models = {};

$scope.change = function () {
  $scope.model.value = $scope.models;
}
</code>```

then it works !

答: Your checkboxes have no model to save their state to, so Umbraco has nothing to save. Try adding ng-model="model.value" (or something thereabout) to your checkbox and see if that does something more :-) </p>

Body:
I create custom property editor which takes all available languages in Umbraco like:

angular.module("umbraco").controller("MyLanguageController", function ($scope, myLanguageService) {
   $scope.items = [];

   myLanguageService.getAll().then( function( result ) {
      if( result && result.data && result.data.length ) {
         $scope.items = result.data;
      }
   } );
});

and

angular.module("umbraco.resources")
   .factory("myLanguageService", function ($http) {

      return {
         getAll: function () {
            return $http.get("/umbraco/backoffice/MyControllerSide/GetAll", { "dataType": "json" });
         }
      };
});

The view:

            <input type="checkbox" value="{{item.IsoCode}}"> {{item.CultureName}}

The package manifest contains:

{
    propertyEditors: [
        {
            alias: "MyLanguageAlias",
            name: "Language Selector",
            icon: "icon-umb-translation",
            hideLabel: true,
            valueType: "JSON",
            editor: {
                view: "~/App_Plugins/MyLanguageSelector/backoffice/view.html"
            }
        }
    ],
  ...

and C# code:

  [HttpGet]
  public JsonResult GetAll()
  {
     IEnumerable<ILanguage> languages = ApplicationContext.Services.LocalizationService.GetAllLanguages() ?? new List<ILanguage>(0);
     IEnumerable<TranslationLanguageModel> model =
        languages.Select(s => new MyLanguageModel { CultureName = s.CultureInfo.DisplayName, IsoCode = s.IsoCode });

     return Json(model, JsonRequestBehavior.AllowGet);
  }

I created new data type in Umbraco/Developer section, and I add it in document type:

When I save document, the value for that property is null. I don't understand why.

And when come back to content, then nothing is checked.

What should I do ?

Update 1

If I put:

<input type="checkbox" value="{{item.IsoCode}}"  ng-model="models[item.IsoCode]"/> {{item.CultureName}}

then I receive always True instead of object/json.

Update 2

I succeeded to do by adding ng-change for checkbox and modify $scope.model.value value

<input type="checkbox" value="item.IsoCode" ng-change="change()" ng-model="models[item.IsoCode]"/> {{item.CultureName}}

and

$scope.models = {};

$scope.change = function () {
  $scope.model.value = $scope.models;
}

then it works !


问:
Pyspark pyspark.rdd.PipelinedRDD not working with model
I am not able to pass a RDD object to PySpark logistic regression model. I am using Spark 2.0.1. Any help will be greatly appreciated..

>>> from pyspark import SparkContext, HiveContext
>>> from pyspark.mllib.regression import LabeledPoint
>>> from pyspark.mllib.classification import LogisticRegressionWithLBFGS
>>> from pyspark.mllib.util import MLUtils
>>>
>>> table_name = "api_model"
>>> target_col = "dv"
>>>
>>>
>>> hc = HiveContext(sc)
>>>
>>> # get the table from the hive context
... df = hc.table(table_name)
>>> df = df.select(target_col, *[col for col in df.columns if col != target_col])
>>>
>>> # map through the data to produce an rdd of labeled points
... rdd_of_labeled_points = df.rdd.map(lambda row: LabeledPoint(row[0], row[1:]))
>>> print (rdd_of_labeled_points.take(3))
[LabeledPoint(1.0, [0.0,2.520784472,0.0,0.0,0.0,2.004684436,2.000347299,0.0,2.228387043,2.228387043,0.0,0.0,0.0,0.0,0.0,0.0]), LabeledPoint(0.0, [2.857738033,0.0,0.0,2.619965104,0.0,2.004684436,2.000347299,0.0,2.228387043,2.228387043,0.0,0.0,0.0,0.0,0.0,0.0]), LabeledPoint(0.0, [2.857738033,0.0,2.061393767,0.0,0.0,2.004684436,0.0,0.0,2.228387043,2.228387043,0.0,0.0,0.0,0.0,0.0,0.0])]
>>>
>>> from pyspark.ml.classification import LogisticRegression
>>> lr = LogisticRegression(maxIter=10, regParam=0.3, elasticNetParam=0.8)
>>> lrModel = lr.fit(sc.parallelize(rdd_of_labeled_points))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/hdp/current/spark2-client/python/pyspark/context.py", line 432, in parallelize
    c = list(c)    # Make it a list so we can compute its length
TypeError: 'PipelinedRDD' object is not iterable
```

答:
That's because you are using sc.parallelize on an RDD. The following is wrong :

```<code>sc.parallelize(rdd_of_labeled_points)
</code>```

You are also mixing spark-ml and spark-mllib :

```<code>from pyspark.mllib.classification import LogisticRegressionWithLBFGS
</code>```

and

```<code>from pyspark.ml.classification import LogisticRegression

lrModel = lr.fit(sc.parallelize(rdd_of_labeled_points))
</code>```

In the first case, you'll need to train the model using the RDD as I stated above, example :

```<code>model = LinearRegressionWithSGD.train(rdd_of_labeled_points, iterations=100, step=0.00000001)
</code>```

In the second case, you'll need to convert your RDD into a DataFrame to feed it to your model.

I strongly advice you to read the official documentation. There is also plenty of examples to help you start.

Remember :

spark-mllib uses RDDs.

spark-mll uses DataFrames.

Body:
That's because you are using sc.parallelize on an RDD. The following is wrong :

sc.parallelize(rdd_of_labeled_points)

You are also mixing spark-ml and spark-mllib :

from pyspark.mllib.classification import LogisticRegressionWithLBFGS

and

from pyspark.ml.classification import LogisticRegression

lrModel = lr.fit(sc.parallelize(rdd_of_labeled_points))

In the first case, you'll need to train the model using the RDD as I stated above, example :

model = LinearRegressionWithSGD.train(rdd_of_labeled_points, iterations=100, step=0.00000001)

In the second case, you'll need to convert your RDD into a DataFrame to feed it to your model.

I strongly advice you to read the official documentation. There is also plenty of examples to help you start.

Remember :

spark-mllib uses RDDs.

spark-mll uses DataFrames.


问:
HOG + Linear SVM + Python
Can someone give some references for extracting HOG features (both positive and negative) from folders, saving these in two .xml files and using these in a Linear SVM for classification in Python?</p>

答:
For people with similar problems, I found this tutorial for beginners

http://www.learnopencv.com/histogram-of-oriented-gradients/

http://www.learnopencv.com/handwritten-digits-classification-an-opencv-c-python-tutorial/

Title: HOG + Linear SVM + Python


问:
Switch Axis of Pandas Data frame
If we used 100 observations in the training dataset to fit the model, then the index of the next time step for making a prediction would be specified to the prediction function as start=101, end=101. This would return an array with one element containing the prediction.

We also would prefer the forecasted values to be in the original scale, in case we performed any differencing (d>0 when configuring the model). This can be specified by setting the typ argument to the value ‘levels’: typ=’levels’.

Alternately, we can avoid all of these specifications by using the forecast() function, which performs a one-step forecast using the model.

We can split the training dataset into train and test sets, use the train set to fit the model, and generate a prediction for each element on the test set.

Title: Switch Axis of Pandas Data frame

Body:
I think you need select column, transpose by T with rename_axis:

df = df[['NA_Sales']].T.rename_axis(None, axis=1)
print (df)
          Action  Adventure  Fighting    Misc  Platform  Puzzle  Racing  \
NA_Sales  871.96     105.46    221.99  410.02    446.26  123.78  359.09

          Role-Playing  Shooter  Simulation  Sports  Strategy
NA_Sales        325.89   575.16      183.31  678.78     68.59

If need transpose all columns:

df = df.T.rename_axis(None, axis=1)
print (df)
               Action  Adventure  Fighting    Misc  Platform  Puzzle  Racing  \
NA_Sales       871.96     105.46    221.99  410.02    446.26  123.78  359.09
EU_Sales       518.64      63.74    100.17  215.89    200.76   50.78  237.25
JP_Sales       154.15      51.10     86.71  106.95    130.66   57.31   56.68
Other_Sales    185.55      16.70     36.22   75.29     51.28   12.55   77.08
Global_Sales  1731.26     237.23    445.05  808.79    829.30  244.95  730.40

              Role-Playing  Shooter  Simulation   Sports  Strategy
NA_Sales            325.89   575.16      183.31   678.78     68.59
EU_Sales            186.77   305.57      113.29   369.49     45.02
JP_Sales            348.64    37.67       63.40   134.59     49.41
Other_Sales          59.17   100.27       31.52   133.05     11.32
Global_Sales        920.57  1019.15      391.81  1316.33    174.62


问:
How to include custom JS files in to React create app
I had js files under public folder i want to include these js files in to react components which are under src component folder in react create application?</p>

答:
Put them in the same folder as your react components and simply import them to you react components like so:

// importing your js file called jslibrary.js
// make sure that the file path is correct!
import { function1 } from './jslibrary.js'```
</div>
</div>
</p>

<p>You also have to make sure that you are exporting your function / variables in your jslibrary file, like so:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>export function function1() {
  //... do stuff
}

let myVar = 1234;
export myVar;</code>```

If you use export default on a function or a variable, you don't need to use the brackets like in the above.

For more info, I highly recommend the documentation on import and export.

Body:
Put them in the same folder as your react components and simply import them to you react components like so:

// importing your js file called jslibrary.js
// make sure that the file path is correct!
import { function1 } from './jslibrary.js'

You also have to make sure that you are exporting your function / variables in your jslibrary file, like so:

export function function1() {
  //... do stuff
}

let myVar = 1234;
export myVar;

If you use export default on a function or a variable, you don't need to use the brackets like in the above.

For more info, I highly recommend the documentation on import and export.


问:
Different ways about Passing 2D array of pointer to function C
I met some problems when passing 2d-array to functions today, later I found some solutions like A and B.
I knew that 2d-array is stored in a continuous memory as 1d. So in my opinion, there is no 2 dimensional points in fact, compiler split this continuous numbers and made '2 dimensional' concept.

My question is: in C after I explicitly told compiler the parameter is a 'int**', why it did not pass a '2 dimensional' point?

Someone may point out "in C you did not told compiler the group-length", I think it knew this information because if you try to reexplain the 12 elements' plain memory into arr[2][6] it will be error like "void printArr(int _arr[][6], int _columns, int _rows)".

A little confused please help...

```<code>int arr[][3]={{1,2,3},{5,6,7},{9,10,11},{13,14,15}};

void printArr(int _arr[][3], int _columns, int _rows){ //----->A
void printArr(int (* _arr)[3], int _columns, int _rows){//---->B
void printArr(int** _arr, int _columns, int _rows){//--------->C
    for(int r=0; r< _rows; r++){
        for (int c=0; c<_columns; c++)
            //printf("%4d,", _arr[r][c]);
            printf("%4d,", *(*(_arr+r)+c));
    }
}
int main(){
    printArr(arr, columns, rows);
}
</code>```

答:
Style note: don't use leading underscores for your identifiers; such names are reserved for the implementation.

Solution B explicitly captures what is happening; in the call to printArr, the expression arr is implicitly converted from "4-element array of 3-element array of int" to "pointer to 3-element array of int".

However, in the context of a function parameter declaration, the notation T a[] is synonymous with T *a; therefore, solution A is effectively the same as solution B.

ContentLicense: CC BY-SA 2.5

Body:
I met some problems when passing 2d-array to functions today, later I found some solutions like A and B.
I knew that 2d-array is stored in a continuous memory as 1d. So in my opinion, there is no 2 dimensional points in fact, compiler split this continuous numbers and made '2 dimensional' concept.

My question is: in C after I explicitly told compiler the parameter is a 'int**', why it did not pass a '2 dimensional' point?

Someone may point out "in C you did not told compiler the group-length", I think it knew this information because if you try to reexplain the 12 elements' plain memory into arr[2][6] it will be error like "void printArr(int _arr[][6], int _columns, int _rows)".

A little confused please help...

int arr[][3]={{1,2,3},{5,6,7},{9,10,11},{13,14,15}};

void printArr(int _arr[][3], int _columns, int _rows){ //----->A
void printArr(int (* _arr)[3], int _columns, int _rows){//---->B
void printArr(int** _arr, int _columns, int _rows){//--------->C
    for(int r=0; r< _rows; r++){
        for (int c=0; c<_columns; c++)
            //printf("%4d,", _arr[r][c]);
            printf("%4d,", *(*(_arr+r)+c));
    }
}
int main(){
    printArr(arr, columns, rows);
}


问:
Regex split string by spaces taking into account nested brackets
I know that this has been asked/answered several times but unfortunately none of the solutions I've tried so far works in my case.
I need to split something like this:

```<code>contrast(200%) drop-shadow(rgba(0, 0, 0, 0.5) 0px 0px 10px)
</code>```

into this:

```<code>contrast(200%)
drop-shadow(0px 0px 10px rgba(0,0,0,.5))
</code>```

By following this solution, I'm currently doing this:

```<code>myString = "contrast(200%) drop-shadow(rgba(0, 0, 0, 0.5) 0px 0px 10px)"
myString.match(/[^\(\s]+(\(.*?\)+)?/g)
</code>```

but this gives me:

```<code>contrast(200%)
drop-shadow(rgba(0, 0, 0, 0.5)  <== notice the missing second ) here
0px    <== unwanted, should go with previous one
0px    <== unwanted, should go with previous one
10px)  <== unwanted, should go with previous one
</code>```

as the regexp does not capture all closing brackets...

答:
You may split a string on spaces/tabs that are outside of nested parentheses using the code below:

function splitOnWhitespaceOutsideBalancedParens() {
  var item = '', result = [], stack = 0, whitespace = /\s/;
  for (var i=0; i < text.length; i++) {
    if ( text[i].match(whitespace) && stack == 0 ) {
        result.push(item);
        item = '';
        continue;
    } else if ( text[i] == '(' ) {
        stack++;
    } else if ( text[i] == ')' ) {
        stack--;
    }
    item += text[i];
  }
  result.push(item);
  return result;
}

var text = "contrast(200%) drop-shadow(rgba(0, 0, 0, 0.5) 0px 0px 10px)";
console.log(splitOnWhitespaceOutsideBalancedParens(text));```

Body:
I know that this has been asked/answered several times but unfortunately none of the solutions I've tried so far works in my case.
I need to split something like this:

contrast(200%) drop-shadow(rgba(0, 0, 0, 0.5) 0px 0px 10px)

into this:

contrast(200%)
drop-shadow(0px 0px 10px rgba(0,0,0,.5))

By following this solution, I'm currently doing this:

myString = "contrast(200%) drop-shadow(rgba(0, 0, 0, 0.5) 0px 0px 10px)"
myString.match(/[^\(\s]+(\(.*?\)+)?/g)

but this gives me:

contrast(200%)
drop-shadow(rgba(0, 0, 0, 0.5)  <== notice the missing second ) here
0px    <== unwanted, should go with previous one
0px    <== unwanted, should go with previous one
10px)  <== unwanted, should go with previous one

as the regexp does not capture all closing brackets...


问:
Only Alphabet and whitespace allowed in UITextField Swift
I want to validate my textField that check only Alphabet & whitespace allowed, If number was given then it will return warning error.

```<code>//First I declare my value to variable
var nameValue: String = mainView.nameTextField.text!

//Then I declare this
 let set = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ")

//And this is the validation
if(nameValue.rangeOfCharacter(from: set.inverted) != nil ){
    self.showAlert(message: "Must not contain Number in Name")
   } else {
      //other code
   }

ex: nameValue : "abcd" it works, but
if nameValue : "ab cd" whitespace included, it returns the showAlert message.
</code>```

This code works but only for alphabets, What I need now is alphabets and a whitespace. and what I declare was a hardcode I guess. Maybe you guys have better code and options for this case.

Thank you .

答:
The easiest way will be to add new line to the character set like

```<code>let set = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ ")
</code>```

i.e, adding white space character at the end of the included character set" "

Rather than hardcoding you can use regular expression like

```<code>   do {
    let regex = try NSRegularExpression(pattern: ".*[^A-Za-z ].*", options: [])
    if regex.firstMatch(in: nameValue, options: [], range: NSMakeRange(0, nameValue.characters.count)) != nil {
         self.showAlert(message: "Must not contain Number in Name")

    } else {

    }
}
catch {

}
</code>```

Body:
I want to validate my textField that check only Alphabet & whitespace allowed, If number was given then it will return warning error.

//First I declare my value to variable
var nameValue: String = mainView.nameTextField.text!

//Then I declare this
 let set = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ")

//And this is the validation
if(nameValue.rangeOfCharacter(from: set.inverted) != nil ){
    self.showAlert(message: "Must not contain Number in Name")
   } else {
      //other code
   }

ex: nameValue : "abcd" it works, but
if nameValue : "ab cd" whitespace included, it returns the showAlert message.

This code works but only for alphabets, What I need now is alphabets and a whitespace. and what I declare was a hardcode I guess. Maybe you guys have better code and options for this case.

Thank you .

Body:
The easiest way will be to add new line to the character set like

let set = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ ")

i.e, adding white space character at the end of the included character set" "

Rather than hardcoding you can use regular expression like

   do {
    let regex = try NSRegularExpression(pattern: ".*[^A-Za-z ].*", options: [])
    if regex.firstMatch(in: nameValue, options: [], range: NSMakeRange(0, nameValue.characters.count)) != nil {
         self.showAlert(message: "Must not contain Number in Name")

    } else {

    }
}
catch {

}


问:
How do you add markers to the legend of a Plots.jl plot?
The code

```<code>using Plots
pyplot(markershape = :auto)
for i in 1:4
  plot!(rand(10), label = "Series " * string(i))
end
savefig("Plot.png")
</code>```

produces the following plot:

The markers do not appear in the legend, only the data series's line color.  This makes it significantly harder to match the lines up with the labels in the legend, especially for those who are colorblind or reading off of a black-and-white printout.  Is there a way to display the plot markers as well as line colors in the legend?

答:
There's probably a more efficient, straightforward way but you can try plotting the line / markers separately:

```<code>using Plots
pyplot(markershape = :auto)
for i in 1:4
    x = rand(10)
    plot!(x, color=i, marker=false, label="")
    scatter!(x, color=i, markersize=10, label = "Series " * string(i))
end
savefig("Plot.png")
</code>```

label="" suppresses the legend entry for the line

color=i ensures that the color of the lines/markers are the same

Body:
The code

using Plots
pyplot(markershape = :auto)
for i in 1:4
  plot!(rand(10), label = "Series " * string(i))
end
savefig("Plot.png")

produces the following plot:

The markers do not appear in the legend, only the data series's line color.  This makes it significantly harder to match the lines up with the labels in the legend, especially for those who are colorblind or reading off of a black-and-white printout.  Is there a way to display the plot markers as well as line colors in the legend?

Body:
There's probably a more efficient, straightforward way but you can try plotting the line / markers separately:

using Plots
pyplot(markershape = :auto)
for i in 1:4
    x = rand(10)
    plot!(x, color=i, marker=false, label="")
    scatter!(x, color=i, markersize=10, label = "Series " * string(i))
end
savefig("Plot.png")

label="" suppresses the legend entry for the line

color=i ensures that the color of the lines/markers are the same


问:
Issue in 'View source' of artifactory 5.2 and 5.1 version
I am facing issue in 'View Source ' option of the artifactory.

The .drl file I want to view is in a jar and I have added mimetypes for some extensions that I need.

```<code><mimetype type="application/drools" extensions="drl, drt" viewable="true" syntax="java" />
</code>```

What happens is that sometimes I am able to see the content of the file and sometimes it just shows an empty textarea and nothing else.

In 4.16.1 version there is no such issue.

Sometimes if I relaod the page or open in incognito then the description appears but if I reload again then there is nothing except the textarea. Means this is actually non predictable and generally it shows blank textarea instead of content.

I have faced similar issue in 5.1 versions as well.

Should I use 4.16.1 or there is something that i am missing in the configurations or settings or in mimetypes?

Snapshot for 4.16.1 version

Snapshot for 5.2.1 version

答:
Ok so we've identified the bug you reported (thanks by the way) - it'll be included in our upcoming release 5.4.0 (around 2 weeks I think).

You can follow the issue here

Body:
I am facing issue in 'View Source ' option of the artifactory.

The .drl file I want to view is in a jar and I have added mimetypes for some extensions that I need.

<mimetype type="application/drools" extensions="drl, drt" viewable="true" syntax="java" />

What happens is that sometimes I am able to see the content of the file and sometimes it just shows an empty textarea and nothing else.

In 4.16.1 version there is no such issue.

Sometimes if I relaod the page or open in incognito then the description appears but if I reload again then there is nothing except the textarea. Means this is actually non predictable and generally it shows blank textarea instead of content.

I have faced similar issue in 5.1 versions as well.

Should I use 4.16.1 or there is something that i am missing in the configurations or settings or in mimetypes?

Snapshot for 4.16.1 version

Snapshot for 5.2.1 version


问:
Append .png image to a pdf using reportlab in Django framework
I'm using Django and reportlab to generate a PDF report
I already can generate the pdf, but I Wanted to append a logo.png to it.
these were the lines I added in

views.py:

```<code>from reportlab.platypus import Image

logo = Image("/cdss/static/cdss/img/logo.png")

exam.append(logo)
</code>```

But it isn't working, Am I exporting the Image() method wrong? Or is Path to the file wrong?

Hope you can help me, thanks  ;)

答:
This Worked For me....

```<code>def PrintImage(request,std_id):
    response = HttpResponse(content_type='application/pdf')
    doc = SimpleDocTemplate(response,topMargin=2)

    doc.pagesize = landscape(A6)
    elements = []
    I = Image('http://demoschoolzen.educationzen.com/images/tia.png')
    I.drawHeight =  0.7*inch
    I.drawWidth = 0.7*inch
    elements.append(I)
    doc.build(elements)
    return response
</code>```

and Call it from your URLs

Body:
I'm using Django and reportlab to generate a PDF report
I already can generate the pdf, but I Wanted to append a logo.png to it.
these were the lines I added in

views.py:

from reportlab.platypus import Image

logo = Image("/cdss/static/cdss/img/logo.png")

exam.append(logo)

But it isn't working, Am I exporting the Image() method wrong? Or is Path to the file wrong?

Hope you can help me, thanks  ;)

Body:
This Worked For me....

def PrintImage(request,std_id):
    response = HttpResponse(content_type='application/pdf')
    doc = SimpleDocTemplate(response,topMargin=2)

    doc.pagesize = landscape(A6)
    elements = []
    I = Image('http://demoschoolzen.educationzen.com/images/tia.png')
    I.drawHeight =  0.7*inch
    I.drawWidth = 0.7*inch
    elements.append(I)
    doc.build(elements)
    return response

and Call it from your URLs


问:
how to pass query param in graphql
Is that possible to pass data inside the body query in graphql??  Like this

```<code>    var name = formData.get('name');
    var email = formData.get('email');
    var message = formData.get('message');

    const resp = await fetch('/graphql', {
        method: 'post',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            query: '{createPost (name: '+ name +' , email: '+ email +' , message: '+ message +') {id, statut}}',

        }),
        credentials: 'include',
    });
    const { data } = await resp.json();
    if (!data || !data.createPost) throw new Error('Error');

    console.log(data.createPost)
</code>```

In the query line i want to pass all the var that i get from a submit form.
When i try this , i got this error

```<code>{

"errors": [
    {
      "message": "Syntax Error GraphQL request (1:29) Expected :, found Name \"email\"\n\n1: {createPost(name: John Doe , email: JD@test.com , message: blablabla) {id, statut}}\n                               ^\n",
      "locations": [
        {
          "line": 1,
          "column": 29
        }
      ]
    }
  ]
}
</code>```

Thank you for the help

答:
Here's what worked for me;</p>

```<code>const graphqlQuery = `{
      products {
        id
        title
        images
      }
    }`

const params = encodeURI(graphqlQuery)

fetch('http://localhost:3001/?raw&query=' + params, {
  method: 'post',
  headers: {
    "Content-Type": 'text/plain'
  }
}).then(function(response) {
  console.log('response', response);
  return response.json()
})
</code>```

Title: how to pass query param in graphql

Body:
Is that possible to pass data inside the body query in graphql??  Like this

    var name = formData.get('name');
    var email = formData.get('email');
    var message = formData.get('message');

    const resp = await fetch('/graphql', {
        method: 'post',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            query: '{createPost (name: '+ name +' , email: '+ email +' , message: '+ message +') {id, statut}}',

        }),
        credentials: 'include',
    });
    const { data } = await resp.json();
    if (!data || !data.createPost) throw new Error('Error');

    console.log(data.createPost)

In the query line i want to pass all the var that i get from a submit form.
When i try this , i got this error

{

"errors": [
    {
      "message": "Syntax Error GraphQL request (1:29) Expected :, found Name \"email\"\n\n1: {createPost(name: John Doe , email: JD@test.com , message: blablabla) {id, statut}}\n                               ^\n",
      "locations": [
        {
          "line": 1,
          "column": 29
        }
      ]
    }
  ]
}

Thank you for the help

Body:
Here's what worked for me;

const graphqlQuery = `{
      products {
        id
        title
        images
      }
    }`

const params = encodeURI(graphqlQuery)

fetch('http://localhost:3001/?raw&query=' + params, {
  method: 'post',
  headers: {
    "Content-Type": 'text/plain'
  }
}).then(function(response) {
  console.log('response', response);
  return response.json()
})


问:
Order by field in cakephp
I am doing project in cakephp .

I want to write below query in cakephp Style. I've written 50% . Please help me

$this->Login->find('all')

```<code>SELECT * FROM login
ORDER BY FIELD(profile_type, 'Basic', 'Premium') DESC;
</code>```

答:
This one is more easy way to order and limit that works fine</p>
```<code>$this->set('users',
    $this->User->find('all',
        array(
            'limit' => 3,
            'order' => 'User.created DESC'
       )
   )
);
</code>```

Title: Order by field in cakephp

Body:
I am doing project in cakephp .

I want to write below query in cakephp Style. I've written 50% . Please help me

$this->Login->find('all')

SELECT * FROM login
ORDER BY FIELD(profile_type, 'Basic', 'Premium') DESC;

Body:
This one is more easy way to order and limit that works fine

$this->set('users',
    $this->User->find('all',
        array(
            'limit' => 3,
            'order' => 'User.created DESC'
       )
   )
);


问:
Java get First and Last duplicate elements of List

In my application i want to get first and repetitive elements from array
eg,

```<code>String[] strings = {"one", "one", "one", "one", "one", "one", "one", "one", "one", "one", "one", "one"
                , "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two"
                , "three", "three", "three", "three", "three", "three", "three", "three", "three", "three", "three"
                , "four", "four", "four", "four", "four", "four", "four", "four", "four", "four"
                , "five", "five", "five", "five", "five", "five"
                , "six", "six", "six", "six", "six", "six", "six", "six", "six"
                , "seven", "seven", "seven", "seven", "seven", "seven", "seven", "seven"
                , "eight", "eight", "eight", "eight", "eight", "eight"
                , "nine", "nine", "nine", "nine", "nine", "nine", "nine", "nine", "nine"
                , "ten", "ten", "ten", "ten", "ten", "ten", "ten", "ten", "ten"};
</code>```

for the above list i want to get output like

one

one

two

two

three

three

four

four

five

five

six

six

seven

seven

eight

eight

nine

nine

ten

ten

答:
you can try this </p>

```<code>public static void main(String[] args) {

    String[] strings = {"one", "one", "one", "one", "one", "one", "one", "one", "one", "one", "one", "one"
            , "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two"
            , "three", "three", "three", "three", "three", "three", "three", "three", "three", "three", "three"
            , "four", "four", "four", "four", "four", "four", "four", "four", "four", "four"
            , "five", "five", "five", "five", "five", "five"
            , "six", "six", "six", "six", "six", "six", "six", "six", "six"
            , "seven", "seven", "seven", "seven", "seven", "seven", "seven", "seven"
            , "eight", "eight", "eight", "eight", "eight", "eight"
            , "nine", "nine", "nine", "nine", "nine", "nine", "nine", "nine", "nine"
            , "ten", "ten", "ten", "ten", "ten", "ten", "ten", "ten", "ten"};

    Map<String,Integer> itemMap=new LinkedHashMap<>();
    for (String item:strings){
        if(!itemMap.containsKey(item)){
            itemMap.put(item,1);
        }else{
            itemMap.put(item, itemMap.get(item)+1);
        }
    }

    for(Map.Entry<String, Integer> mapEntry:itemMap.entrySet()){
        if(mapEntry.getValue()>1){
            System.out.println(mapEntry.getKey()+"\n"+mapEntry.getKey());
        }
    }
}
</code>```

Body:
In my application i want to get first and repetitive elements from array
eg,

String[] strings = {"one", "one", "one", "one", "one", "one", "one", "one", "one", "one", "one", "one"
                , "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two"
                , "three", "three", "three", "three", "three", "three", "three", "three", "three", "three", "three"
                , "four", "four", "four", "four", "four", "four", "four", "four", "four", "four"
                , "five", "five", "five", "five", "five", "five"
                , "six", "six", "six", "six", "six", "six", "six", "six", "six"
                , "seven", "seven", "seven", "seven", "seven", "seven", "seven", "seven"
                , "eight", "eight", "eight", "eight", "eight", "eight"
                , "nine", "nine", "nine", "nine", "nine", "nine", "nine", "nine", "nine"
                , "ten", "ten", "ten", "ten", "ten", "ten", "ten", "ten", "ten"};

for the above list i want to get output like

one

one

two

two

three

three

four

four

five

five

six

six

seven

seven

eight

eight

nine

nine

ten

ten

Body:
you can try this

public static void main(String[] args) {

    String[] strings = {"one", "one", "one", "one", "one", "one", "one", "one", "one", "one", "one", "one"
            , "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two"
            , "three", "three", "three", "three", "three", "three", "three", "three", "three", "three", "three"
            , "four", "four", "four", "four", "four", "four", "four", "four", "four", "four"
            , "five", "five", "five", "five", "five", "five"
            , "six", "six", "six", "six", "six", "six", "six", "six", "six"
            , "seven", "seven", "seven", "seven", "seven", "seven", "seven", "seven"
            , "eight", "eight", "eight", "eight", "eight", "eight"
            , "nine", "nine", "nine", "nine", "nine", "nine", "nine", "nine", "nine"
            , "ten", "ten", "ten", "ten", "ten", "ten", "ten", "ten", "ten"};

    Map<String,Integer> itemMap=new LinkedHashMap<>();
    for (String item:strings){
        if(!itemMap.containsKey(item)){
            itemMap.put(item,1);
        }else{
            itemMap.put(item, itemMap.get(item)+1);
        }
    }

    for(Map.Entry<String, Integer> mapEntry:itemMap.entrySet()){
        if(mapEntry.getValue()>1){
            System.out.println(mapEntry.getKey()+"\n"+mapEntry.getKey());
        }
    }
}


问:
Which are the "must follow" FxCop rules for any C# developer?
I'm planning to start using FxCop in one of our ongoing project. But, when i tried it with selecting all available rules, it looks like I have to make lots of changes in my code. Being a "team member" I can't right away start making these changes, like naming convention change etc. anyway i would like to start using FxCop with a minimal rule set and would gradually increase the rule set as we goes on. Can you suggest me some must have FxCop rules which i should start following. Or do you suggest any better approach?

Note: Most of my code is in C#.

答: The minimal fxcop and also code analysis (if using VS2010 Premium or Ultimate) is the following: http://msdn.microsoft.com/en-us/library/dd264893.aspx</p>

OwnerDisplayName: Vijesh

LastEditorDisplayName: Vijesh


问:
Dragging back to fire an arrow in SpriteKit/Swift?
I am creating an iOS application using SpriteKit in which two archers are placed at random x-positions in the GameScene. After the scene loads, the camera focuses on the archer places to the left side of the scene. From here, I want the user to be able to press down on the screen, "pull back", and release their finger in order to fire an arrow at an angle and level of power relative to how far back and at what angle the user moved their finger and ultimately let go (think the firing action in Angry Birds in which the player drags their finger back and releases, firing the bird in the opposite direction). I am curious how to derive an angle (opposite of the pulled-back direction) and level of power from the touch the user made within my application. I do not need a full explanation, but maybe a few tips or resources which may speak on a similar function in SpriteKit, or maybe point me to a method which deals with this sort of user interaction. My experience with SpriteKit has been limited mostly to simple touches but not anything as advanced as dragging to create said firing data. Any tips/help is appreciated. Thanks.

-David

答:
Use the touchesBegan and touchesEnded methods to determine the 'line' that the player dragged their finger over. Use these start and end points and some basic trigomonetry to determine the angle and length of the line.

These form your angle and strength of firing. You can then add some simple graphics effects (e.g. if you continually re-calculate the current line in touchesMoved, you can rotate the sprite for the bow to the current angle etc).


问:
HTML removing all events from element
I have some javascript functions in my main program(im not able to modify this code) and some of them are not needed. I want to add new javascript and disable unnecessary events(for example onClick).
I tried someething like this:

```<code>function disableClickEvent(){
    var elems = document.body.getElementsByTagName("a");
    for (i = 0; i < elems.length; i++) {
        for (var key in toDisableMap) {
             if(elems[i].innerHTML == key ){
                 elems[i].unbind();
                 break;
             }
         }
    }
}
</code>```

but there is an error (in console):

```<code>jQuery.Deferred exception: a[i].unbind is not a function disableClickEvent
</code>```

I am not sure that unbind is right way for disable events. How is it possible to solve this problem?

答:
$(document).ready(function(){
  $('a').click(function(){
    alert($(this).attr('id'));
  });
});
function disableClickEvent(){
    var elems = document.body.getElementsByTagName("a");
    for (i = 0; i < elems.length; i++) {
    $(elems[i]).off('click');
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Test1
<br>
Test2
<br>
<button onclick="disableClickEvent()" value="Disable">Disable</button></code>```

When using .Off() you have to use Jquery object $(elems[i]).off('click');

Title: HTML removing all events from element

Body:
I have some javascript functions in my main program(im not able to modify this code) and some of them are not needed. I want to add new javascript and disable unnecessary events(for example onClick).
I tried someething like this:

function disableClickEvent(){
    var elems = document.body.getElementsByTagName("a");
    for (i = 0; i < elems.length; i++) {
        for (var key in toDisableMap) {
             if(elems[i].innerHTML == key ){
                 elems[i].unbind();
                 break;
             }
         }
    }
}

but there is an error (in console):

jQuery.Deferred exception: a[i].unbind is not a function disableClickEvent

I am not sure that unbind is right way for disable events. How is it possible to solve this problem?

Body:
$(document).ready(function(){
  $('a').click(function(){
    alert($(this).attr('id'));
  });
});
function disableClickEvent(){
    var elems = document.body.getElementsByTagName("a");
    for (i = 0; i < elems.length; i++) {
    $(elems[i]).off('click');
    }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="test1" style="cursor:pointer">Test1</a>
<br>
<a id="test2"  style="cursor:pointer">Test2</a>
<br>
<button onclick="disableClickEvent()" value="Disable">Disable</button>

When using .Off() you have to use Jquery object $(elems[i]).off('click');


问:
how to display formatted String from console.log to an html div
Say I have a formatted string str written in my backend java code like this :

```<code>name    : xxx       company : qwe
address : yyy       age     : asd
country : zzz
</code>```

now I managed to display it on the browser console via

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

and when I checked it is also formatted just the way it is

```<code>name    : xxx       company : qwe
address : yyy       age     : asd
country : zzz
</code>```

but when I use Jquery to show it in a div in my html file, say for example

```<code>$('.divclass').text(str);
</code>```

it will just be one line

```<code>name    : xxx       company : qweaddress : yyy       age     : asdcountry : zzz
</code>```

this is all expected, but I was wondering if there is an implementation where I could possibly display the console.log to my html tag and still keep the format that I had before, instead of having to format it again, I guess my question is if there is a way to present console.log to the html in my case.

答:
You can either use the ```</code>-tag or (recommended): You can replace every <code>\n</code> in the string with <code><br /></code>.</p>

```str = str.replace("\n", "
");
```

<p>You have to do that, because web browsers don't display normal line-breaks by themselves. You either have to use the <code><br /></code>-tag or a special tag like <code>```.

Body:
Say I have a formatted string str written in my backend java code like this :

name    : xxx       company : qwe
address : yyy       age     : asd
country : zzz

now I managed to display it on the browser console via

console.log(str);

and when I checked it is also formatted just the way it is

name    : xxx       company : qwe
address : yyy       age     : asd
country : zzz

but when I use Jquery to show it in a div in my html file, say for example

$('.divclass').text(str);

it will just be one line

name    : xxx       company : qweaddress : yyy       age     : asdcountry : zzz

this is all expected, but I was wondering if there is an implementation where I could possibly display the console.log to my html tag and still keep the format that I had before, instead of having to format it again, I guess my question is if there is a way to present console.log to the html in my case.

Body:
You can either use the <pre>-tag or (recommended): You can replace every \n in the string with <br />.

str = str.replace("\n", "<br />");

You have to do that, because web browsers don't display normal line-breaks by themselves. You either have to use the <br />-tag or a special tag like <pre>.


问:
Magento installation issue
Am getting below error before installing magento could any one help me on this

There has been an error processing your request

  Exception printing is disabled by default for security reasons.

  Error log record number: 67392566

答: Go to var/report and open file with this number 67392566 and see the exact error then send me so I can help you exactly with your query.</p>

Title: Magento installation issue


问:
Retrieving Entity Metadata using web api
we have a requirement where we have to retrieve an Entity's Metadata.
Exact requirement: Im reading a field value on a form which ia having "entity schema name". With that I need to get that Entity's primary key schema name. Is it possible? If so please help me.
Eg: in that field if I enter "lead" , that web api should fetch me "leadid" and store it in another field.
2. If I enter "incident" , that web api should get me "incidentid" </p>

答:
You don't need do retrieve entity metadata for that, primary key is always "entity schema name" + "id", for entities other than activities. If you want a generic solution though, you should be able to get this info from metadata:

```<code>https://crmaddress/api/data/v9.1/EntityDefinitions(LogicalName='account')
</code>```

and simply getting the "PrimaryIdAttribute" of the result, so the example code would be:

```<code>fetch("/api/data/v9.1/EntityDefinitions(LogicalName='account')")
   .then(response => response.json())
   .then(data => console.log(data.PrimaryIdAttribute));
</code>```

Body:
You don't need do retrieve entity metadata for that, primary key is always "entity schema name" + "id", for entities other than activities. If you want a generic solution though, you should be able to get this info from metadata:

https://crmaddress/api/data/v9.1/EntityDefinitions(LogicalName='account')

and simply getting the "PrimaryIdAttribute" of the result, so the example code would be:

fetch("/api/data/v9.1/EntityDefinitions(LogicalName='account')")
   .then(response => response.json())
   .then(data => console.log(data.PrimaryIdAttribute));


问:
Self-join Query
Is it possible to do parent-child query just using join without looping through temporary table?

Database sample :

```<code>menuid  name                parent  url
----------------------------------------------------------
A0000   Master              A0000   #
A0001   Rekening            A0000   /master/rekening.aspx
A0002   Master Nominal      A0001   /master/nominal.aspx
A0003   Master Satuan Other A0001   /master/satuan.aspx
A0004   Master Kondisi      A0000   /master/kondisi.aspx
A0005   Master Tujuan       A0003   /master/tujuan.aspx
A0006   Master Item         A0003   /master/item.aspx
A0007   Master Warehouse    A0000   /master/warehouse.aspx
A0008   Master Kapal        A0006   /master/kapal.aspx
</code>```

Desired result if choosed uri = '/master/kapal.aspx' :

```<code>menuid  name                parent  url
----------------------------------------------------------
A0000   Master              A0000   #
A0001   Rekening            A0000   /master/rekening.aspx
A0003   Master Satuan Other A0001   /master/satuan.aspx
A0006   Master Item         A0003   /master/item.aspx
A0008   Master Kapal        A0006   /master/kapal.aspx
</code>```

Desired result if choosed uri = /master/tujuan.aspx' :

```<code>menuid  name                parent  url
----------------------------------------------------------
A0000   Master              A0000   #
A0001   Rekening            A0000   /master/rekening.aspx
A0005   Master Tujuan       A0003   /master/tujuan.aspx
</code>```

Sample query :

```<code>declare @menuid varchar(255) = 'menuid'
declare @parent varchar(255) = 'parent'
declare @temp_parent varchar(255)
declare @i smallint = 0

delete from temp_menu
while (@menuid <> @parent)
begin
  if(@i = 0)
  begin
    insert into temp_menu
    select * from menu where uri = '/master/kapal.aspx'
    select @menuid = menuid, @parent = parent from menu where uri = '/master/kapal.aspx'
    set @i = 1;
    end
  else
  begin
    insert into temp_menu
    select * from menu where menuid = @parent
    select @menuid = menuid, @temp_parent = parent from menu where menuid = @parent
    set @parent = @temp_parent;
    end
end
select * from temp_menu
</code>```

Sample with hieararchy :

```<code>A0000
|_______________________
|               |       |
A0001           A0004   A0007
|________
|       |
A0002   A0003
        |_______
        |       |
        A0005   A0006
                |
                A0008
</code>```

UPDATED :
I want to get all rows from  the longest branch possible from nodes parent to menuid and stopped if the parent same with menuid or there is no menuid match with parent.

ADDED WITH SCRIPT AND SAMPLES

```<code>IF OBJECT_ID('dbo.menu', 'U') IS NOT NULL
  DROP TABLE dbo.menu
GO

IF OBJECT_ID('dbo.temp_menu', 'U') IS NOT NULL
  DROP TABLE dbo.temp_menu
GO

IF OBJECTPROPERTY(object_id('dbo.sp_get_parent'), N'IsProcedure') = 1
  DROP PROCEDURE dbo.sp_get_parent
GO

create table dbo.menu (
menuid varchar(255)
, name varchar(255)
, parent varchar(255)
, uri varchar(255)
);

insert into dbo.menu (menuid, name, parent, uri)
values ('A0000', 'Master', 'A0000', '#')
, ('A0001', 'Rekening', 'A0000', '/master/rekening.aspx')
, ('A0002', 'Master Nominal', 'A0001', '/master/nominal.aspx')
, ('A0003', 'Master Satuan Other', 'A0001', '/master/satuan.aspx')
, ('A0004', 'Master Kondisi', 'A0000', '/master/kondisi.aspx')
, ('A0005', 'Master Tujuan', 'A0003', '/master/tujuan.aspx')
, ('A0006', 'Master Item', 'A0003', '/master/item.aspx')
, ('A0007', 'Master Warehouse', 'A0000', '/master/warehouse.aspx')
, ('A0008', 'Master Kapal', 'A0006', '/master/kapal.aspx');

create table dbo.temp_menu (
menuid varchar(255)
, name varchar(255)
, parent varchar(255)
, uri varchar(255)
);

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

Create PROCEDURE [dbo].[sp_get_parent]
@uri VARCHAR (255)
AS

declare @menuid varchar(255) = 'menuid'
declare @parent varchar(255) = 'parent'
declare @temp_parent varchar(255)
declare @i smallint = 0

delete from temp_menu
while (@menuid <> @parent)
begin
  if(@i = 0)
  begin
    insert into temp_menu
    select * from menu where uri = @uri
    select @menuid = menuid, @parent = parent from menu where uri = @uri
    set @i = 1;
  end
  else
  begin
    insert into temp_menu
    select * from menu where menuid = @parent
    select @menuid = menuid, @temp_parent = parent from menu where menuid = @parent
    set @parent = @temp_parent;
  end
end
select * from temp_menu order by menuid asc
GO
</code>```

For desired sample above can try this query :

```<code>sp_get_parent '/master/kapal.aspx'
</code>```

AND

```<code>sp_get_parent '/master/tujuan.aspx'
</code>```

答:
```<code>drop table if exists dbo.Menu;

create table dbo.Menu (
menuid varchar(100)
, name varchar(100)
, parent varchar(100)
, url varchar(100)
);

insert into dbo.Menu (menuid, name, parent, url)
values ('A0000', 'Master', 'A0000', '#')
, ('A0001', 'Rekening', 'A0000', '/master/rekening.aspx')
, ('A0002', 'Master Nominal', 'A0001', '/master/nominal.aspx')
, ('A0003', 'Master Satuan Other', 'A0001', '/master/satuan.aspx')
, ('A0004', 'Master Kondisi', 'A0000', '/master/kondisi.aspx')
, ('A0005', 'Master Tujuan', 'A0003', '/master/tujuan.aspx')
, ('A0006', 'Master Item', 'A0003', '/master/item.aspx')
, ('A0007', 'Master Warehouse', 'A0000', '/master/warehouse.aspx')
, ('A0008', 'Master Kapal', 'A0006', '/master/kapal.aspx');

with cteMenu as (
select
    m.menuid, m.name, m.parent, m.url
    , convert(varchar(max), '.' + m.menuid + '.') as Hierarchy
    , 0 as Lvl
from dbo.Menu m
where m.menuid = m.parent

union all

select
    m.menuid, m.name, m.parent, m.url
    , cm.Hierarchy + m.menuid + '.' as Hierarchy
    , cm.Lvl + 1 as Lvl
from dbo.Menu m
    inner join cteMenu cm on m.parent = cm.menuid
where m.menuid <> m.parent
)
select
cm.menuid, cm.name, cm.parent, cm.url
from (
select
    top(1)
    cm.*
from cteMenu cm
order by cm.Lvl desc
) t
    inner join cteMenu cm on t.Hierarchy like cm.Hierarchy + '%'
</code>```

Title: Self-join Query

Body:
Is it possible to do parent-child query just using join without looping through temporary table?

Database sample :

menuid  name                parent  url
----------------------------------------------------------
A0000   Master              A0000   #
A0001   Rekening            A0000   /master/rekening.aspx
A0002   Master Nominal      A0001   /master/nominal.aspx
A0003   Master Satuan Other A0001   /master/satuan.aspx
A0004   Master Kondisi      A0000   /master/kondisi.aspx
A0005   Master Tujuan       A0003   /master/tujuan.aspx
A0006   Master Item         A0003   /master/item.aspx
A0007   Master Warehouse    A0000   /master/warehouse.aspx
A0008   Master Kapal        A0006   /master/kapal.aspx

Desired result if choosed uri = '/master/kapal.aspx' :

menuid  name                parent  url
----------------------------------------------------------
A0000   Master              A0000   #
A0001   Rekening            A0000   /master/rekening.aspx
A0003   Master Satuan Other A0001   /master/satuan.aspx
A0006   Master Item         A0003   /master/item.aspx
A0008   Master Kapal        A0006   /master/kapal.aspx

Desired result if choosed uri = /master/tujuan.aspx' :

menuid  name                parent  url
----------------------------------------------------------
A0000   Master              A0000   #
A0001   Rekening            A0000   /master/rekening.aspx
A0005   Master Tujuan       A0003   /master/tujuan.aspx

Sample query :

declare @menuid varchar(255) = 'menuid'
declare @parent varchar(255) = 'parent'
declare @temp_parent varchar(255)
declare @i smallint = 0

delete from temp_menu
while (@menuid <> @parent)
begin
  if(@i = 0)
  begin
    insert into temp_menu
    select * from menu where uri = '/master/kapal.aspx'
    select @menuid = menuid, @parent = parent from menu where uri = '/master/kapal.aspx'
    set @i = 1;
    end
  else
  begin
    insert into temp_menu
    select * from menu where menuid = @parent
    select @menuid = menuid, @temp_parent = parent from menu where menuid = @parent
    set @parent = @temp_parent;
    end
end
select * from temp_menu

Sample with hieararchy :

A0000
|_______________________
|               |       |
A0001           A0004   A0007
|________
|       |
A0002   A0003
        |_______
        |       |
        A0005   A0006
                |
                A0008

UPDATED :
I want to get all rows from  the longest branch possible from nodes parent to menuid and stopped if the parent same with menuid or there is no menuid match with parent.

ADDED WITH SCRIPT AND SAMPLES

IF OBJECT_ID('dbo.menu', 'U') IS NOT NULL
  DROP TABLE dbo.menu
GO

IF OBJECT_ID('dbo.temp_menu', 'U') IS NOT NULL
  DROP TABLE dbo.temp_menu
GO

IF OBJECTPROPERTY(object_id('dbo.sp_get_parent'), N'IsProcedure') = 1
  DROP PROCEDURE dbo.sp_get_parent
GO

create table dbo.menu (
menuid varchar(255)
, name varchar(255)
, parent varchar(255)
, uri varchar(255)
);

insert into dbo.menu (menuid, name, parent, uri)
values ('A0000', 'Master', 'A0000', '#')
, ('A0001', 'Rekening', 'A0000', '/master/rekening.aspx')
, ('A0002', 'Master Nominal', 'A0001', '/master/nominal.aspx')
, ('A0003', 'Master Satuan Other', 'A0001', '/master/satuan.aspx')
, ('A0004', 'Master Kondisi', 'A0000', '/master/kondisi.aspx')
, ('A0005', 'Master Tujuan', 'A0003', '/master/tujuan.aspx')
, ('A0006', 'Master Item', 'A0003', '/master/item.aspx')
, ('A0007', 'Master Warehouse', 'A0000', '/master/warehouse.aspx')
, ('A0008', 'Master Kapal', 'A0006', '/master/kapal.aspx');

create table dbo.temp_menu (
menuid varchar(255)
, name varchar(255)
, parent varchar(255)
, uri varchar(255)
);

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

Create PROCEDURE [dbo].[sp_get_parent]
@uri VARCHAR (255)
AS

declare @menuid varchar(255) = 'menuid'
declare @parent varchar(255) = 'parent'
declare @temp_parent varchar(255)
declare @i smallint = 0

delete from temp_menu
while (@menuid <> @parent)
begin
  if(@i = 0)
  begin
    insert into temp_menu
    select * from menu where uri = @uri
    select @menuid = menuid, @parent = parent from menu where uri = @uri
    set @i = 1;
  end
  else
  begin
    insert into temp_menu
    select * from menu where menuid = @parent
    select @menuid = menuid, @temp_parent = parent from menu where menuid = @parent
    set @parent = @temp_parent;
  end
end
select * from temp_menu order by menuid asc
GO

For desired sample above can try this query :

sp_get_parent '/master/kapal.aspx'

AND

sp_get_parent '/master/tujuan.aspx'