问:
Convert 4 level nested JSON file to 1 level nested with Python
I have the 4 level nested JSON file below, that I would like to normalize to a one level nesting:

Input file is like this:

```<code>{
    "@index": "40",
    "row": [
      {
        "column": [
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "663.12",
              "@width": "250.01",
              "@height": "12.00",
              "#text": "text 1"
            }
          }
        ]
      },
      {
        "column": [
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "8.0",
              "@x": "121.10",
              "@y": "675.36",
              "@width": "348.98",
              "@height": "8.04",
              "#text": "text 2"
            }
          },
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "473.30",
              "@y": "676.92",
              "@width": "42.47",
              "@height": "12.00",
              "#text": "text 3"
            }
          }
        ]
      },
      {
        "column": [
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "690.72",
              "@width": "433.61",
              "@height": "12.00",
              "#text": "text 4"
            }
          }
        ]
      }
    ]
  }
</code>```

Desired output is like this:

```<code>{
    "@index": "40",
    "row": [
          {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "663.12",
              "@width": "250.01",
              "@height": "12.00",
              "#text": "Text 1"
          },
          {
              "@fontName": "Times New Roman",
              "@fontSize": "8.0",
              "@x": "121.10",
              "@y": "675.36",
              "@width": "348.98",
              "@height": "8.04",
              "#text": "Text 2"
          },
          {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "473.30",
              "@y": "676.92",
              "@width": "42.47",
              "@height": "12.00",
              "#text": "Text 3"
          },
          {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "690.72",
              "@width": "433.61",
              "@height": "12.00",
              "#text": "Text 4"
          }
    ]
  }
</code>```

The code I have so far is this using pandas is below, but I don´t know how to continue to normalize to one level.

```<code>import json
import pandas as pd
from pandas.io.json import json_normalize #package for flattening json in pandas df

#load json object
with open('D:\Files\JSON\4Level.json') as f:
    d = json.load(f)

nycphil = json_normalize(d['row'])
print (nycphil.head(4))
</code>```

This is the current output tabulated, where shows that column is a nested element:

```<code>                                            column
0  [{'text': {'@fontName': 'Times New Roman', '@f...
1  [{'text': {'@fontName': 'Times New Roman', '@f...
2  [{'text': {'@fontName': 'Times New Roman', '@f...
</code>```

The print with one level nesting would be:

```<code>text.#text   text.@fontName text.@fontSize   ...   text.@width text.@x text.@y
0     Text 1  Times New Roman           12.0   ...        250.01   85.10  663.12
1     Text 2  Times New Roman            8.0   ...        348.98  121.10  675.36
2     Text 3  Times New Roman           12.0   ...         42.47  473.30  676.92
3     Text 4  Times New Roman           12.0   ...        433.61   85.10  690.72
</code>```

The Input/Output comparison is like this:

Maybe someone could help me with this. Thanks for any help.

UPDATE

In order to make a small sample in first sample input I showed, I removed some elements that seems to be are needed in your scripts to work. So now I show exactly the same structure as real file but with this input your scripts don't work. I think they need a little tweak but I've been trying and I don't know how to change them to get the same output with this new input. Maybe you can help me and sorry for not show the correct input from beginning.

```<code>{
   "document":{
      "page":[
         {
            "@index":"0",
            "image":{
               "@data":"ABC",
               "@format":"png",
               "@height":"620.00",
               "@type":"base64encoded",
               "@width":"450.00",
               "@x":"85.00",
               "@y":"85.00"
            }
         },
         {
            "@index":"1",
            "row":[
               {
                  "column":[
                     {
                        "text":""
                     },
                     {
                        "text":{
                           "#text":"Text1",
                           "@fontName":"Arial",
                           "@fontSize":"12.0",
                           "@height":"12.00",
                           "@width":"71.04",
                           "@x":"121.10",
                           "@y":"83.42"
                        }
                     }
                  ]
               },
               {
                  "column":[
                     {
                        "text":""
                     },
                     {
                        "text":{
                           "#text":"Text2",
                           "@fontName":"Arial",
                           "@fontSize":"12.0",
                           "@height":"12.00",
                           "@width":"101.07",
                           "@x":"121.10",
                           "@y":"124.82"
                        }
                     }
                  ]
               }
            ]
         },
         {
            "@index":"2",
            "row":[
               {
                  "column":{
                     "text":{
                        "#text":"Text3",
                        "@fontName":"Arial",
                        "@fontSize":"12.0",
                        "@height":"12.00",
                        "@width":"363.44",
                        "@x":"85.10",
                        "@y":"69.62"
                     }
                  }
               },
               {
                  "column":{
                     "text":{
                        "#text":"Text4",
                        "@fontName":"Arial",
                        "@fontSize":"12.0",
                        "@height":"12.00",
                        "@width":"382.36",
                        "@x":"85.10",
                        "@y":"83.42"
                     }
                  }
               },
               {
                  "column":{
                     "text":{
                        "#text":"Text5",
                        "@fontName":"Arial",
                        "@fontSize":"12.0",
                        "@height":"12.00",
                        "@width":"435.05",
                        "@x":"85.10",
                        "@y":"97.22"
                     }
                  }
               }
            ]
         },
         {
            "@index":"3"
         }
      ]
   }
}
</code>```

答:
Below is a working code:

(56336255.json is the sample data you have posted)

```<code>import json
import pprint

flat_data = dict()
with open('56336255.json') as f:
    data = json.load(f)
    for k, v in data.items():
        if k == '@index':
            flat_data[k] = data[k]
        else:
            flat_data[k] = []
            for row in v:
                for cell in row['column']:
                    flat_data[k].append(cell['text'])

    pprint.pprint(flat_data)
</code>```

output

```<code>{'@index': '40',
 'row': [{'#text': 'text 1',
          '@fontName': 'Times New Roman',
          '@fontSize': '12.0',
          '@height': '12.00',
          '@width': '250.01',
          '@x': '85.10',
          '@y': '663.12'},
         {'#text': 'text 2',
          '@fontName': 'Times New Roman',
          '@fontSize': '8.0',
          '@height': '8.04',
          '@width': '348.98',
          '@x': '121.10',
          '@y': '675.36'},
         {'#text': 'text 3',
          '@fontName': 'Times New Roman',
          '@fontSize': '12.0',
          '@height': '12.00',
          '@width': '42.47',
          '@x': '473.30',
          '@y': '676.92'},
         {'#text': 'text 4',
          '@fontName': 'Times New Roman',
          '@fontSize': '12.0',
          '@height': '12.00',
          '@width': '433.61',
          '@x': '85.10',
          '@y': '690.72'}]}
</code>```

Body:
I have the 4 level nested JSON file below, that I would like to normalize to a one level nesting:

Input file is like this:

{
    "@index": "40",
    "row": [
      {
        "column": [
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "663.12",
              "@width": "250.01",
              "@height": "12.00",
              "#text": "text 1"
            }
          }
        ]
      },
      {
        "column": [
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "8.0",
              "@x": "121.10",
              "@y": "675.36",
              "@width": "348.98",
              "@height": "8.04",
              "#text": "text 2"
            }
          },
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "473.30",
              "@y": "676.92",
              "@width": "42.47",
              "@height": "12.00",
              "#text": "text 3"
            }
          }
        ]
      },
      {
        "column": [
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "690.72",
              "@width": "433.61",
              "@height": "12.00",
              "#text": "text 4"
            }
          }
        ]
      }
    ]
  }

Desired output is like this:

{
    "@index": "40",
    "row": [
          {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "663.12",
              "@width": "250.01",
              "@height": "12.00",
              "#text": "Text 1"
          },
          {
              "@fontName": "Times New Roman",
              "@fontSize": "8.0",
              "@x": "121.10",
              "@y": "675.36",
              "@width": "348.98",
              "@height": "8.04",
              "#text": "Text 2"
          },
          {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "473.30",
              "@y": "676.92",
              "@width": "42.47",
              "@height": "12.00",
              "#text": "Text 3"
          },
          {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "690.72",
              "@width": "433.61",
              "@height": "12.00",
              "#text": "Text 4"
          }
    ]
  }

The code I have so far is this using pandas is below, but I don´t know how to continue to normalize to one level.

import json
import pandas as pd
from pandas.io.json import json_normalize #package for flattening json in pandas df

#load json object
with open('D:\Files\JSON\4Level.json') as f:
    d = json.load(f)

nycphil = json_normalize(d['row'])
print (nycphil.head(4))

This is the current output tabulated, where shows that column is a nested element:

                                            column
0  [{'text': {'@fontName': 'Times New Roman', '@f...
1  [{'text': {'@fontName': 'Times New Roman', '@f...
2  [{'text': {'@fontName': 'Times New Roman', '@f...

The print with one level nesting would be:

text.#text   text.@fontName text.@fontSize   ...   text.@width text.@x text.@y
0     Text 1  Times New Roman           12.0   ...        250.01   85.10  663.12
1     Text 2  Times New Roman            8.0   ...        348.98  121.10  675.36
2     Text 3  Times New Roman           12.0   ...         42.47  473.30  676.92
3     Text 4  Times New Roman           12.0   ...        433.61   85.10  690.72

The Input/Output comparison is like this:

Maybe someone could help me with this. Thanks for any help.

UPDATE

In order to make a small sample in first sample input I showed, I removed some elements that seems to be are needed in your scripts to work. So now I show exactly the same structure as real file but with this input your scripts don't work. I think they need a little tweak but I've been trying and I don't know how to change them to get the same output with this new input. Maybe you can help me and sorry for not show the correct input from beginning.

{
   "document":{
      "page":[
         {
            "@index":"0",
            "image":{
               "@data":"ABC",
               "@format":"png",
               "@height":"620.00",
               "@type":"base64encoded",
               "@width":"450.00",
               "@x":"85.00",
               "@y":"85.00"
            }
         },
         {
            "@index":"1",
            "row":[
               {
                  "column":[
                     {
                        "text":""
                     },
                     {
                        "text":{
                           "#text":"Text1",
                           "@fontName":"Arial",
                           "@fontSize":"12.0",
                           "@height":"12.00",
                           "@width":"71.04",
                           "@x":"121.10",
                           "@y":"83.42"
                        }
                     }
                  ]
               },
               {
                  "column":[
                     {
                        "text":""
                     },
                     {
                        "text":{
                           "#text":"Text2",
                           "@fontName":"Arial",
                           "@fontSize":"12.0",
                           "@height":"12.00",
                           "@width":"101.07",
                           "@x":"121.10",
                           "@y":"124.82"
                        }
                     }
                  ]
               }
            ]
         },
         {
            "@index":"2",
            "row":[
               {
                  "column":{
                     "text":{
                        "#text":"Text3",
                        "@fontName":"Arial",
                        "@fontSize":"12.0",
                        "@height":"12.00",
                        "@width":"363.44",
                        "@x":"85.10",
                        "@y":"69.62"
                     }
                  }
               },
               {
                  "column":{
                     "text":{
                        "#text":"Text4",
                        "@fontName":"Arial",
                        "@fontSize":"12.0",
                        "@height":"12.00",
                        "@width":"382.36",
                        "@x":"85.10",
                        "@y":"83.42"
                     }
                  }
               },
               {
                  "column":{
                     "text":{
                        "#text":"Text5",
                        "@fontName":"Arial",
                        "@fontSize":"12.0",
                        "@height":"12.00",
                        "@width":"435.05",
                        "@x":"85.10",
                        "@y":"97.22"
                     }
                  }
               }
            ]
         },
         {
            "@index":"3"
         }
      ]
   }
}

Body:
Below is a working code:

(56336255.json is the sample data you have posted)

import json
import pprint

flat_data = dict()
with open('56336255.json') as f:
    data = json.load(f)
    for k, v in data.items():
        if k == '@index':
            flat_data[k] = data[k]
        else:
            flat_data[k] = []
            for row in v:
                for cell in row['column']:
                    flat_data[k].append(cell['text'])

    pprint.pprint(flat_data)

output

{'@index': '40',
 'row': [{'#text': 'text 1',
          '@fontName': 'Times New Roman',
          '@fontSize': '12.0',
          '@height': '12.00',
          '@width': '250.01',
          '@x': '85.10',
          '@y': '663.12'},
         {'#text': 'text 2',
          '@fontName': 'Times New Roman',
          '@fontSize': '8.0',
          '@height': '8.04',
          '@width': '348.98',
          '@x': '121.10',
          '@y': '675.36'},
         {'#text': 'text 3',
          '@fontName': 'Times New Roman',
          '@fontSize': '12.0',
          '@height': '12.00',
          '@width': '42.47',
          '@x': '473.30',
          '@y': '676.92'},
         {'#text': 'text 4',
          '@fontName': 'Times New Roman',
          '@fontSize': '12.0',
          '@height': '12.00',
          '@width': '433.61',
          '@x': '85.10',
          '@y': '690.72'}]}


来源: stackexchange

问:
How to install Nexus 3 on Windows?
I downloaded an unpacked Sonatype Nexus OSS. But have no clue how to install it. There is a readme file. All tutorials get outdated.

nexus.exe just immediately finishes without a message. No logs appears. The same with nexus.exe install and nexus.exe start - URL http://localhost:8081/ stays unavailable. There is no jsw directory anymore also.

My directory structure:

D:\java\nexus\nexus-3.1.0-04

D:\java\nexus\sonatype-work

Java:

```<code>>java -version
java version "1.8.0_77"
Java(TM) SE Runtime Environment (build 1.8.0_77-b03)
Java HotSpot(TM) 64-Bit Server VM (build 25.77-b03, mixed mode)
</code>```

Windows 7 x64

答:
I had this problem in windows 10

open PowerShell go to your extracted place of your nexus oss bin folder

.. \nexus-3.16.1-02-win64\nexus-3.16.1-02\bin

and run your command like this

.\nexus.exe /run

it works and after a while tells

```<code>-------------------------------------------------

Started Sonatype Nexus OSS 3.16.1-02

-------------------------------------------------
</code>```

now go to http://localhost:8081

ContentLicense: CC BY-SA 3.0

Title: How to install Nexus 3 on Windows?

Body:
I downloaded an unpacked Sonatype Nexus OSS. But have no clue how to install it. There is a readme file. All tutorials get outdated.

nexus.exe just immediately finishes without a message. No logs appears. The same with nexus.exe install and nexus.exe start - URL http://localhost:8081/ stays unavailable. There is no jsw directory anymore also.

My directory structure:

D:\java\nexus\nexus-3.1.0-04

D:\java\nexus\sonatype-work

Java:

>java -version
java version "1.8.0_77"
Java(TM) SE Runtime Environment (build 1.8.0_77-b03)
Java HotSpot(TM) 64-Bit Server VM (build 25.77-b03, mixed mode)

Windows 7 x64

Body:
I had this problem in windows 10

open PowerShell go to your extracted place of your nexus oss bin folder

.. \nexus-3.16.1-02-win64\nexus-3.16.1-02\bin

and run your command like this

.\nexus.exe /run

it works and after a while tells

-------------------------------------------------

Started Sonatype Nexus OSS 3.16.1-02

-------------------------------------------------

now go to http://localhost:8081

ContentLicense: CC BY-SA 4.0


问:
Fullscreen android
When i click a button, i have to set my activity fullscreen.
searching in internet i found the code for do this.

```<code>container.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                                | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                                | View.SYSTEM_UI_FLAG_IMMERSIVE);
</code>```

But i do something wrong because status bar and navigation bar disappears and my activity ramain with the same height.

before

after

This is the video.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".VideoActivity">

    <include layout="@layout/content_video" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/close"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center_horizontal"
        android:layout_marginBottom="70dp"
        android:layout_marginRight="80dp"
        android:src="@drawable/phone"
        app:elevation="0dp"
        app:backgroundTint="#44FF0000" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/screen"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center_horizontal"
        android:layout_marginBottom="70dp"
        android:layout_marginLeft="80dp"
        android:src="@drawable/fullscreen"
        app:elevation="0dp"
        app:backgroundTint="#44000000"/>

</android.support.design.widget.CoordinatorLayout>
</code>```

And this content_video.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".VideoActivity"
    tools:showIn="@layout/video"
    android:id="@+id/layout"
    android:orientation="horizontal">

    <RelativeLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#000000">
    </RelativeLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="@string/string_video_id"
        android:id="@+id/conference_id"
        android:textColor="@android:color/white"
        android:enabled="false"
        android:focusable="false"
        android:alpha="0.5"
        android:background="@color/button_background"
        android:paddingLeft="10dip"
        android:paddingTop="5dip"
        android:paddingRight="10dip"
        android:paddingBottom="5dip"
        android:layout_marginBottom="20dp"
        android:layout_marginLeft="10dp"
        android:gravity="bottom"
        android:layout_alignParentBottom="true"/>

</RelativeLayout>
</code>```

Can someone help me plase?
Thanks

答:
```<code> getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
</code>```

Check this source.

Title: Fullscreen android

Body:
When i click a button, i have to set my activity fullscreen.
searching in internet i found the code for do this.

container.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                                | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                                | View.SYSTEM_UI_FLAG_IMMERSIVE);

But i do something wrong because status bar and navigation bar disappears and my activity ramain with the same height.

before

after

This is the video.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".VideoActivity">

    <include layout="@layout/content_video" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/close"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center_horizontal"
        android:layout_marginBottom="70dp"
        android:layout_marginRight="80dp"
        android:src="@drawable/phone"
        app:elevation="0dp"
        app:backgroundTint="#44FF0000" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/screen"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center_horizontal"
        android:layout_marginBottom="70dp"
        android:layout_marginLeft="80dp"
        android:src="@drawable/fullscreen"
        app:elevation="0dp"
        app:backgroundTint="#44000000"/>

</android.support.design.widget.CoordinatorLayout>

And this content_video.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".VideoActivity"
    tools:showIn="@layout/video"
    android:id="@+id/layout"
    android:orientation="horizontal">

    <RelativeLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#000000">
    </RelativeLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="@string/string_video_id"
        android:id="@+id/conference_id"
        android:textColor="@android:color/white"
        android:enabled="false"
        android:focusable="false"
        android:alpha="0.5"
        android:background="@color/button_background"
        android:paddingLeft="10dip"
        android:paddingTop="5dip"
        android:paddingRight="10dip"
        android:paddingBottom="5dip"
        android:layout_marginBottom="20dp"
        android:layout_marginLeft="10dp"
        android:gravity="bottom"
        android:layout_alignParentBottom="true"/>

</RelativeLayout>

Can someone help me plase?
Thanks

Body:
 getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

Check this source.


问:
How to cancel retrofit request in model while using mvp pattern
enter image description herei want to cancel request in model implementation using mvp pattern in android
iam using retrofit2 .in this method i sent file path and state to check on it because button action make (upload,cancel)in the same function.

```<code>this snipet of class
</code>```

{public class ModelImpl implements UploadInterface.Interactor, ProgressRequestBody.UploadCallbacks {enter image description here
    //another way we can use retrofit call here to upload file and
    //return result in OnFinishedListener interface inside model interface
    //we use here service to upload to run in background service
    // this way we can cancel request and retry
    //but using intent service in service difficult to stop because it designed to
    //run long task and stop it self with caller.

```<code>private OnProgressListener listener;

public ModelImpl(OnProgressListener listener) {
    this.listener = listener;
}

@Override
public void uploadImage(String status, String filePath, OnFinishedListener onFinishedListener) {
    // call servce to start upload throw service

    /*Intent mIntent = new Intent(context, FileUploadService.class);
    mIntent.putExtra("mFilePath", filePath);
    FileUploadService.enqueueWork(context, mIntent);*/

    // starting http service upload

    if (!filePath.isEmpty()) {

        File file = new File(filePath.trim());
        ProgressRequestBody fileBody = new ProgressRequestBody(file, "image", this);
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("fileUpload", file.getName(), fileBody);

        RestApiService apiService = RetrofitInstance.getApiService();

        Call<PojoResponse> callUpload = apiService.onFileUpload2(filePart);
        if (status.equals("upload")) {
            callUpload.enqueue(new Callback<PojoResponse>() {

                @Override
                public void onResponse(Call<PojoResponse> call, Response<PojoResponse> response) {
                    Log.d("ResponseData", "" + response.body().getUrl());
                    onFinishedListener.onFinished(response.body());

                }

                @Override
                public void onFailure(Call<PojoResponse> call, Throwable t) {
                    if (call != null && !call.isCanceled()) {
                        // Call is not cancelled, Handle network failure

                        onFinishedListener.onFailure(call, t);
                    } else if (call != null && call.isCanceled()) {

                        // Call is CANCELLED. IGNORE THIS SINCE IT WAS CANCELLED.
                        onFinishedListener.onFailure(call, t);
                    }

                    //onFinishedListener.onFailure(call, t);

                }
            });
        } else {
            if (callUpload != null && callUpload.isExecuted()) {
              callUpload.cancel();
            }

        }
    }

}
</code>```

}

答:
```<code>    package com.example.mvp2.ui.main.model;

import android.util.Log;

import com.example.mvp2.ui.main.network.RestApiService;
import com.example.mvp2.ui.main.network.RetrofitInstance;
import com.example.mvp2.ui.main.utils.ProgressRequestBody;
import com.example.mvp2.ui.main.views.upload.UploadInterface;

import java.io.File;

import okhttp3.MultipartBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ModelImpl implements UploadInterface.Interactor, ProgressRequestBody.UploadCallbacks {
    //another way we can use retrofit call here to upload file and
    //return result in OnFinishedListener interface inside model interface
    //we use here service to upload to run in background service
    // this way we can cancel request and retry
    //but using intent service in service difficult to stop because it designed to
    //run long task and stop it self with caller.

    private OnProgressListener listener;
    private Call < PojoResponse > callUpload;

    public ModelImpl(OnProgressListener listener) {
        this.listener = listener;
    }

    @Override
    public void uploadImage(String status, String filePath, OnFinishedListener onFinishedListener) {
        if (!filePath.isEmpty()) {

            File file = new File(filePath.trim());
            ProgressRequestBody fileBody = new ProgressRequestBody(file,
                "image", this);
            MultipartBody.Part filePart =
                MultipartBody.Part.createFormData("fileUpload", file.getName(), fileBody);

            RestApiService apiService = RetrofitInstance.getApiService();

            callUpload = apiService.onFileUpload2(filePart);
            //     if (status.equals("upload")) {
            callUpload.enqueue(new Callback < PojoResponse > () {
                @Override
                public void onResponse(Call < PojoResponse > call, Response < PojoResponse > response) {
                    Log.d("ResponseData", "" + response.body().getUrl());
                    onFinishedListener.onFinished(response.body());
                }
                @Override
                public void onFailure(Call < PojoResponse > call, Throwable t) {
                    if (call != null && !call.isCanceled()) {
                        // Call is not cancelled, Handle network failure

                        onFinishedListener.onFailure(call, t);
                    } else if (call != null && call.isCanceled()) {

                        // Call is CANCELLED. IGNORE THIS SINCE IT WAS CANCELLED.
                        onFinishedListener.onFailure(call, t);
                    }
                }
            });
            // }
            /* else {
                if (callUpload != null && callUpload.isExecuted()) {
                    callUpload.cancel();
                    // this will go to presenter
                    onFinishedListener.onCancel();
                }

            }*/
        }

    }

    public void cancelUpload() {
        if (callUpload != null && callUpload.isExecuted()) {
            callUpload.cancel();
            // this will go to presenter
            onFinishedListener.onCancel();
        }
    }

    @Override
    public void onProgressUpdate(int percentage) {
        Log.d("percent", "" + percentage);
        listener.onProgressChange(percentage);

    }

    @Override
    public void onError() {

    }

    @Override
    public void onFinish() {
        Log.d("percent", "" + "finishedddddd");
        listener.onProgressFinished();

    }

}
</code>```

UploadActivityPresenter .java

```<code>   package com.example.mvp2.ui.main.views.upload;

import android.util.Log;

import com.example.mvp2.ui.main.model.ModelImpl;
import com.example.mvp2.ui.main.model.PojoResponse;

import retrofit2.Call;

public class UploadActivityPresenter implements UploadInterface.Presenter, UploadInterface.Interactor.OnFinishedListener, UploadInterface.Interactor.OnProgressListener {
    private UploadInterface.View view;
    private UploadInterface.Interactor model;

    public UploadActivityPresenter(UploadInterface.View view) {
        this.view = view;
  model = new ModelImpl(this);
    }

    @Override
    public void uploadBtnClicked(String status, String filePath) {
        // this interface call method upload without know about logic about it
        // model = new ModelImpl(this);
        if (view != null) {
            if (filePath.length() > 0) {
                Log.d("filepath", "" + filePath.trim());
                view.setStatus(status);
                if (model != null) {
                    if (status.equals("upload")) {
                        model.uploadImage(status, filePath, this);
                    } else {
                        model.cancelUpload()
                    }
                }
                Log.d("ss", "ssssss");
            } else {
                view.selectFileFirst();
            }

        }

    }

    @Override
    public void imageClicked() {
        if (view != null) {
            view.showFullImageInFragment();
        }
    }

    @Override
    public void onFinished(PojoResponse obj) {
        if (view != null) {
            view.getResponse(obj);
            view.setStatus("Done");
        }

    }

    @Override
    public void onFailure(Call < PojoResponse > call, Throwable t) {
        if (view != null) {
            view.errorUploading(call, t);
        }
    }

    @Override
    public void onCancel() {
        if (view != null) {

        }
    }

    @Override
    public void onProgressChange(int percent) {
        Log.d("aaaaa", "" + percent);
        if (view != null) {
            view.setProgressPercent(percent);
        }
    }

    @Override
    public void onProgressFinished() {
        if (view != null) {
            view.setProgressFinished();
        }
    }

}
</code>```

this should work , u were creating new Model object everytime you upload image or cancel upload image in presenter ,similarly in modelImpl call object was instantiated on every call .

Make sure your presenter class is instantiated one time only .

Body:
enter image description herei want to cancel request in model implementation using mvp pattern in android
iam using retrofit2 .in this method i sent file path and state to check on it because button action make (upload,cancel)in the same function.

this snipet of class

{public class ModelImpl implements UploadInterface.Interactor, ProgressRequestBody.UploadCallbacks {enter image description here
    //another way we can use retrofit call here to upload file and
    //return result in OnFinishedListener interface inside model interface
    //we use here service to upload to run in background service
    // this way we can cancel request and retry
    //but using intent service in service difficult to stop because it designed to
    //run long task and stop it self with caller.

private OnProgressListener listener;

public ModelImpl(OnProgressListener listener) {
    this.listener = listener;
}

@Override
public void uploadImage(String status, String filePath, OnFinishedListener onFinishedListener) {
    // call servce to start upload throw service

    /*Intent mIntent = new Intent(context, FileUploadService.class);
    mIntent.putExtra("mFilePath", filePath);
    FileUploadService.enqueueWork(context, mIntent);*/

    // starting http service upload

    if (!filePath.isEmpty()) {

        File file = new File(filePath.trim());
        ProgressRequestBody fileBody = new ProgressRequestBody(file, "image", this);
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("fileUpload", file.getName(), fileBody);

        RestApiService apiService = RetrofitInstance.getApiService();

        Call<PojoResponse> callUpload = apiService.onFileUpload2(filePart);
        if (status.equals("upload")) {
            callUpload.enqueue(new Callback<PojoResponse>() {

                @Override
                public void onResponse(Call<PojoResponse> call, Response<PojoResponse> response) {
                    Log.d("ResponseData", "" + response.body().getUrl());
                    onFinishedListener.onFinished(response.body());

                }

                @Override
                public void onFailure(Call<PojoResponse> call, Throwable t) {
                    if (call != null && !call.isCanceled()) {
                        // Call is not cancelled, Handle network failure

                        onFinishedListener.onFailure(call, t);
                    } else if (call != null && call.isCanceled()) {

                        // Call is CANCELLED. IGNORE THIS SINCE IT WAS CANCELLED.
                        onFinishedListener.onFailure(call, t);
                    }

                    //onFinishedListener.onFailure(call, t);

                }
            });
        } else {
            if (callUpload != null && callUpload.isExecuted()) {
              callUpload.cancel();
            }

        }
    }

}

}

Body:
    package com.example.mvp2.ui.main.model;

import android.util.Log;

import com.example.mvp2.ui.main.network.RestApiService;
import com.example.mvp2.ui.main.network.RetrofitInstance;
import com.example.mvp2.ui.main.utils.ProgressRequestBody;
import com.example.mvp2.ui.main.views.upload.UploadInterface;

import java.io.File;

import okhttp3.MultipartBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ModelImpl implements UploadInterface.Interactor, ProgressRequestBody.UploadCallbacks {
    //another way we can use retrofit call here to upload file and
    //return result in OnFinishedListener interface inside model interface
    //we use here service to upload to run in background service
    // this way we can cancel request and retry
    //but using intent service in service difficult to stop because it designed to
    //run long task and stop it self with caller.

    private OnProgressListener listener;
    private Call < PojoResponse > callUpload;

    public ModelImpl(OnProgressListener listener) {
        this.listener = listener;
    }

    @Override
    public void uploadImage(String status, String filePath, OnFinishedListener onFinishedListener) {
        if (!filePath.isEmpty()) {

            File file = new File(filePath.trim());
            ProgressRequestBody fileBody = new ProgressRequestBody(file,
                "image", this);
            MultipartBody.Part filePart =
                MultipartBody.Part.createFormData("fileUpload", file.getName(), fileBody);

            RestApiService apiService = RetrofitInstance.getApiService();

            callUpload = apiService.onFileUpload2(filePart);
            //     if (status.equals("upload")) {
            callUpload.enqueue(new Callback < PojoResponse > () {
                @Override
                public void onResponse(Call < PojoResponse > call, Response < PojoResponse > response) {
                    Log.d("ResponseData", "" + response.body().getUrl());
                    onFinishedListener.onFinished(response.body());
                }
                @Override
                public void onFailure(Call < PojoResponse > call, Throwable t) {
                    if (call != null && !call.isCanceled()) {
                        // Call is not cancelled, Handle network failure

                        onFinishedListener.onFailure(call, t);
                    } else if (call != null && call.isCanceled()) {

                        // Call is CANCELLED. IGNORE THIS SINCE IT WAS CANCELLED.
                        onFinishedListener.onFailure(call, t);
                    }
                }
            });
            // }
            /* else {
                if (callUpload != null && callUpload.isExecuted()) {
                    callUpload.cancel();
                    // this will go to presenter
                    onFinishedListener.onCancel();
                }

            }*/
        }

    }

    public void cancelUpload() {
        if (callUpload != null && callUpload.isExecuted()) {
            callUpload.cancel();
            // this will go to presenter
            onFinishedListener.onCancel();
        }
    }

    @Override
    public void onProgressUpdate(int percentage) {
        Log.d("percent", "" + percentage);
        listener.onProgressChange(percentage);

    }

    @Override
    public void onError() {

    }

    @Override
    public void onFinish() {
        Log.d("percent", "" + "finishedddddd");
        listener.onProgressFinished();

    }

}

UploadActivityPresenter .java

   package com.example.mvp2.ui.main.views.upload;

import android.util.Log;

import com.example.mvp2.ui.main.model.ModelImpl;
import com.example.mvp2.ui.main.model.PojoResponse;

import retrofit2.Call;

public class UploadActivityPresenter implements UploadInterface.Presenter, UploadInterface.Interactor.OnFinishedListener, UploadInterface.Interactor.OnProgressListener {
    private UploadInterface.View view;
    private UploadInterface.Interactor model;

    public UploadActivityPresenter(UploadInterface.View view) {
        this.view = view;
  model = new ModelImpl(this);
    }

    @Override
    public void uploadBtnClicked(String status, String filePath) {
        // this interface call method upload without know about logic about it
        // model = new ModelImpl(this);
        if (view != null) {
            if (filePath.length() > 0) {
                Log.d("filepath", "" + filePath.trim());
                view.setStatus(status);
                if (model != null) {
                    if (status.equals("upload")) {
                        model.uploadImage(status, filePath, this);
                    } else {
                        model.cancelUpload()
                    }
                }
                Log.d("ss", "ssssss");
            } else {
                view.selectFileFirst();
            }

        }

    }

    @Override
    public void imageClicked() {
        if (view != null) {
            view.showFullImageInFragment();
        }
    }

    @Override
    public void onFinished(PojoResponse obj) {
        if (view != null) {
            view.getResponse(obj);
            view.setStatus("Done");
        }

    }

    @Override
    public void onFailure(Call < PojoResponse > call, Throwable t) {
        if (view != null) {
            view.errorUploading(call, t);
        }
    }

    @Override
    public void onCancel() {
        if (view != null) {

        }
    }

    @Override
    public void onProgressChange(int percent) {
        Log.d("aaaaa", "" + percent);
        if (view != null) {
            view.setProgressPercent(percent);
        }
    }

    @Override
    public void onProgressFinished() {
        if (view != null) {
            view.setProgressFinished();
        }
    }

}

this should work , u were creating new Model object everytime you upload image or cancel upload image in presenter ,similarly in modelImpl call object was instantiated on every call .

Make sure your presenter class is instantiated one time only .


问:
Why int type is convert to Integer?
I faced to a problem I don't understand.
I still use int type but code crashed because int is convert to Integer.

Can you explain me what is the problem ? Thanks.

Code

Caller

```<code>int excelIndex = 2
String number = CustomKeywords.'getInfo'('test', 'test', 'test', excelIndex)
</code>```

Callee

```<code>@Keyword
public String getInfo(String dataTest, String dataSheet, String columnName, int excelIndex) {
    String cellContent = getValueToExcel(dataTest, dataSheet, columnName, excelIndex)
    ...
    return cellContent
}

@Keyword
def getValueFromExcel(String testDataFile, String sheet, String columnName, int rowNumber) {
    ExcelData data = initialiseDataDriven(testDataFile, sheet)
    return data.getValue(columnName, rowNumber)
}
</code>```

Error

```<code>number = CustomKeywords.getInfo("test", "test", "test", excelIndex) FAILED.

Reason:
org.codehaus.groovy.runtime.InvokerInvocationException: groovy.lang.MissingMethodException: No signature of method: getValueFromExcel is applicable for argument types: (java.lang.String, java.lang.String, java.lang.String, java.lang.Integer) values: [test, test, test, 2]
Possible solutions: getValueFromExcel(java.lang.String, java.lang.String, java.lang.String, int)
</code>```

答:
You are calling a member method getInfo in a static style

Either make getInfo static:

```<code>public static String getInfo(String dataTest, String dataSheet, String columnName, int excelIndex) {
</code>```

Or, make an instance of CustomKeywords, and call getInfo on that:

```<code>int excelIndex = 2
def keywords = new CustomKeywords()
String number = keywords.getInfo('test', 'test', 'test', excelIndex)
</code>```

Title: Why int type is convert to Integer?

Body:
I faced to a problem I don't understand.
I still use int type but code crashed because int is convert to Integer.

Can you explain me what is the problem ? Thanks.

Code

Caller

int excelIndex = 2
String number = CustomKeywords.'getInfo'('test', 'test', 'test', excelIndex)

Callee

@Keyword
public String getInfo(String dataTest, String dataSheet, String columnName, int excelIndex) {
    String cellContent = getValueToExcel(dataTest, dataSheet, columnName, excelIndex)
    ...
    return cellContent
}

@Keyword
def getValueFromExcel(String testDataFile, String sheet, String columnName, int rowNumber) {
    ExcelData data = initialiseDataDriven(testDataFile, sheet)
    return data.getValue(columnName, rowNumber)
}

Error

number = CustomKeywords.getInfo("test", "test", "test", excelIndex) FAILED.

Reason:
org.codehaus.groovy.runtime.InvokerInvocationException: groovy.lang.MissingMethodException: No signature of method: getValueFromExcel is applicable for argument types: (java.lang.String, java.lang.String, java.lang.String, java.lang.Integer) values: [test, test, test, 2]
Possible solutions: getValueFromExcel(java.lang.String, java.lang.String, java.lang.String, int)

Body:
You are calling a member method getInfo in a static style

Either make getInfo static:

public static String getInfo(String dataTest, String dataSheet, String columnName, int excelIndex) {

Or, make an instance of CustomKeywords, and call getInfo on that:

int excelIndex = 2
def keywords = new CustomKeywords()
String number = keywords.getInfo('test', 'test', 'test', excelIndex)


问:
pure javascript, filter box doesn't filter properly
I have an array of devices, each device has own unique id, I wish to make searchBox which will filter by this id. So far I managed it partly, so it checks if character from input match character from device-id. However not in way I would want that, example below:

id =35678; input.value = 5

it shouldn't work as first character is 3

id = 35679; input.value= 35

it should work as first character is same

Problem is in match/include function, but no really idea how to replace it to make it work

```<code>input_box.addEventListener('keyup', function(){
  var search_result = this.value;
  var device = document.querySelectorAll('[device_id]')
  var array_of_devices = [];
  for (var i = 0; i < device.length; i++) {
       array_of_devices.push(device[i].getAttribute('device_id'))
  }
  array_of_devices.forEach(el => {
         if (!el.match(search_result)) {
           var not_matched = document.querySelector(`[device_id="${el}"]`)
           not_matched.style.display = "none"
         } else {
          var matched = document.querySelector(`[device_id="${el}"]`)
          matched.style.display = "block"
        }
     })
 })
</code>```

答:
Instead of using .match you can simply use .indexOf and check the index, if it 0 then the entered string is matching the device name from the begining.

```<code>array_of_devices.forEach(el => {
  // Condition below is changed to use indexOf
  if (el.indexOf(search_result) === 0) {
    var not_matched = document.querySelector(`[device_id="${el}"]`)
    not_matched.style.display = "none"
  } else {
    var matched = document.querySelector(`[device_id="${el}"]`)
    matched.style.display = "block"
  }
});
</code>```

I would suggest you to build a string of device elements based on the search string and add it to your DOM instead of modifying the display properties. This is costing you a bunch of DOM operations which is computationally heavy.

Body:
I have an array of devices, each device has own unique id, I wish to make searchBox which will filter by this id. So far I managed it partly, so it checks if character from input match character from device-id. However not in way I would want that, example below:

id =35678; input.value = 5

it shouldn't work as first character is 3

id = 35679; input.value= 35

it should work as first character is same

Problem is in match/include function, but no really idea how to replace it to make it work

input_box.addEventListener('keyup', function(){
  var search_result = this.value;
  var device = document.querySelectorAll('[device_id]')
  var array_of_devices = [];
  for (var i = 0; i < device.length; i++) {
       array_of_devices.push(device[i].getAttribute('device_id'))
  }
  array_of_devices.forEach(el => {
         if (!el.match(search_result)) {
           var not_matched = document.querySelector(`[device_id="${el}"]`)
           not_matched.style.display = "none"
         } else {
          var matched = document.querySelector(`[device_id="${el}"]`)
          matched.style.display = "block"
        }
     })
 })

Body:
Instead of using .match you can simply use .indexOf and check the index, if it 0 then the entered string is matching the device name from the begining.

array_of_devices.forEach(el => {
  // Condition below is changed to use indexOf
  if (el.indexOf(search_result) === 0) {
    var not_matched = document.querySelector(`[device_id="${el}"]`)
    not_matched.style.display = "none"
  } else {
    var matched = document.querySelector(`[device_id="${el}"]`)
    matched.style.display = "block"
  }
});

I would suggest you to build a string of device elements based on the search string and add it to your DOM instead of modifying the display properties. This is costing you a bunch of DOM operations which is computationally heavy.


问:
Handling soft keyboard events in appium-android
How to handle soft keyboard and hide it using appium android.

Below is my scenario :

Open the flipkart app

Click on search icon

type some text [eg: cars]

Click search icon from the device keyboard

Below is the code I implemented:

```<code>driver.findElement(By.className(properties.getProperty("home_menu_className"))).click();
        System.out.println("clicked fist cross mark");
        driver.findElement(By.className(properties.getProperty("home_menu_className"))).click();
        System.out.println("click menu options");
        driver.findElementByName(properties.getProperty("home_menu_back_name")).click();
        System.out.println("clicked home back button");
        //WebElement search = driver.findElement(By.xpath(properties.getProperty("search_xpath")));
        //taction.tap(search);
        driver.rotate(ScreenOrientation.LANDSCAPE);
        driver.findElementByName(properties.getProperty("search_name")).click();
        System.out.println("clicked search icon");
        WebElement search_item = driver.findElementByName(properties.getProperty("search_edit_field_name"));
        search_item.sendKeys("cars");
        search_item.sendkeys(KEYS.ENTER);
        System.out.println("entered search text");
        delay(8000);
</code>```

I used "driver.rotate(ScreenOrientation.LANDSCAPE);" in the code but
  got error as  org.openqa.selenium.WebDriverException: An unknown
  server-side error occurred while processing the command. (WARNING: The
  server did not provide any stacktrace information)

And am getting error on using driver.hideKeyboard();

Can anyone please let me know it ?

Thanks in advance.

答:
To hide keyboard, You can use :

```<code>//To hide keyboard.
driver.hideKeyboard();
</code>```

OR
to enter some key events use :

```<code>driver.press_keycode(KEY_CODE);    #KEY_CODE = 66 for ENTER
</code>```

Refer below the URL to find KEY_CODES :
https://developer.android.com/reference/android/view/KeyEvent

Body:
How to handle soft keyboard and hide it using appium android.

Below is my scenario :

Open the flipkart app

Click on search icon

type some text [eg: cars]

Click search icon from the device keyboard

Below is the code I implemented:

driver.findElement(By.className(properties.getProperty("home_menu_className"))).click();
        System.out.println("clicked fist cross mark");
        driver.findElement(By.className(properties.getProperty("home_menu_className"))).click();
        System.out.println("click menu options");
        driver.findElementByName(properties.getProperty("home_menu_back_name")).click();
        System.out.println("clicked home back button");
        //WebElement search = driver.findElement(By.xpath(properties.getProperty("search_xpath")));
        //taction.tap(search);
        driver.rotate(ScreenOrientation.LANDSCAPE);
        driver.findElementByName(properties.getProperty("search_name")).click();
        System.out.println("clicked search icon");
        WebElement search_item = driver.findElementByName(properties.getProperty("search_edit_field_name"));
        search_item.sendKeys("cars");
        search_item.sendkeys(KEYS.ENTER);
        System.out.println("entered search text");
        delay(8000);

I used "driver.rotate(ScreenOrientation.LANDSCAPE);" in the code but
  got error as  org.openqa.selenium.WebDriverException: An unknown
  server-side error occurred while processing the command. (WARNING: The
  server did not provide any stacktrace information)

And am getting error on using driver.hideKeyboard();

Can anyone please let me know it ?

Thanks in advance.

Body:
To hide keyboard, You can use :

//To hide keyboard.
driver.hideKeyboard();

OR
to enter some key events use :

driver.press_keycode(KEY_CODE);    #KEY_CODE = 66 for ENTER

Refer below the URL to find KEY_CODES :
https://developer.android.com/reference/android/view/KeyEvent


问:
How can I set a click listener only for Button in angular application
I just want to implement a event (click) listner into my angular application, which is only for button. buttons will be created dynamically.

the code looks like this:

```<code>  constructor(
    private companyService: CompanyService,
    elementRef: ElementRef,
    renderer: Renderer,
    private router: Router
  ) {
    renderer.listen(elementRef.nativeElement, "onclick", event => {
      // if (event.target.innerHTML) {
      //   this.searchByVin(event.target.innerHTML);
      // }
    });
  }

private setCustomValueFunction() {
    this.customValueFunction = (
      elemValue: string,
      elemKey: string,
      elem: {}
    ) => {
      if (elemKey === "vin") {
        elemValue = `<div class="gridster-item-content"><button (click)="searchByVin(${elemValue})">${elemValue}</button></div>`;
      }
      if (elemKey === "status") {
        elemValue = `
        <mat-icon>done</mat-icon>`;
      }
      return elemValue;
    };
  }

</code>```

this 2 functions, which can create a button dynamically and in constructor will set a click event listner, but this listner is for all click event, the question is, how can I set this listner only for buttons.

Best Regards,

Leo

答:
The most straight forward method is to do it via html like so:

```<code><button id="button1" (click)="myFunction()"> Button text </button>
</code>```

You have to implement the myFunction() in your javascript file.

Another way is to find that button on your javascript file like this:

```<code>document.getElementById('button1')
</code>```

and add an event listener.

Body:
I just want to implement a event (click) listner into my angular application, which is only for button. buttons will be created dynamically.

the code looks like this:

  constructor(
    private companyService: CompanyService,
    elementRef: ElementRef,
    renderer: Renderer,
    private router: Router
  ) {
    renderer.listen(elementRef.nativeElement, "onclick", event => {
      // if (event.target.innerHTML) {
      //   this.searchByVin(event.target.innerHTML);
      // }
    });
  }

private setCustomValueFunction() {
    this.customValueFunction = (
      elemValue: string,
      elemKey: string,
      elem: {}
    ) => {
      if (elemKey === "vin") {
        elemValue = `<div class="gridster-item-content"><button (click)="searchByVin(${elemValue})">${elemValue}</button></div>`;
      }
      if (elemKey === "status") {
        elemValue = `
        <mat-icon>done</mat-icon>`;
      }
      return elemValue;
    };
  }

this 2 functions, which can create a button dynamically and in constructor will set a click event listner, but this listner is for all click event, the question is, how can I set this listner only for buttons.

Best Regards,

Leo

Body:
The most straight forward method is to do it via html like so:

<button id="button1" (click)="myFunction()"> Button text </button>

You have to implement the myFunction() in your javascript file.

Another way is to find that button on your javascript file like this:

document.getElementById('button1')

and add an event listener.


问:
PHP: compare substrings
Really quick noob question with php:

I'm trying to create a conditional statement where I can check if a variable partially matches a substring.

More specific in my case:

$cal is the name of a file, I want it so if $cal contains ".cfg" it echos some text.

pseudocode:

```<code><?php if ($cal == "*.cfg")
 {
    echo "Hello ";
 }
?>
</code>```

答:
```<code>if (strpos($cal, ".cfg") !== false)
{
  echo "some text";
}
</code>```

EDIT

My proposal for matching exactly "*.cfg":

```<code>$cal = "abc.cfgxyz";
$ext = "cfg";

if (strrpos($cal, ".".$ext) === strlen($cal)-strlen($ext)-1)
{
    echo "matched";
}
</code>```

Title: PHP: compare substrings

Body:
Really quick noob question with php:

I'm trying to create a conditional statement where I can check if a variable partially matches a substring.

More specific in my case:

$cal is the name of a file, I want it so if $cal contains ".cfg" it echos some text.

pseudocode:

<?php if ($cal == "*.cfg")
 {
    echo "Hello ";
 }
?>

Body:
if (strpos($cal, ".cfg") !== false)
{
  echo "some text";
}

EDIT

My proposal for matching exactly "*.cfg":

$cal = "abc.cfgxyz";
$ext = "cfg";

if (strrpos($cal, ".".$ext) === strlen($cal)-strlen($ext)-1)
{
    echo "matched";
}


问:
Update records that can be retrieved by multiple joins in x++
So I have a complete x++ script that aims to update records based on the retrieved result set made with select query with multiple joins and using crosscompany

As I have been told, it is not a good idea to update records when there is crosscompany. Can you give expert advice on how to do it the best practice way considering my current script.

here is the script

```<code>static void UpdateSample(Args _args)
{

   InventTable  a;
   InventTableModule b;
   EcoResProduct c;
   EcoResProductCategory d;
   EcoResCategory e;
   EcoResCategoryHierarchy f;
   int i = 0;

    while select crossCompany  a
    exists join b where a.ItemId  == b.ItemId
    exists  join c where a.Product  == c.RecId
    exists join d where c.RecId  == d.Product
    exists join e where d.Category  == e.RecId
    exists join f where d.CategoryHierarchy  == f.RecId
    && a.dataAreaId == 'DAT' && b.ModuleType  == 2
    && b.LineDisc  == ''
    && f.name == 'EXAMPLE'
    &&(e.name == 'sample1' || e.name == 'sample2' || e.name == 'sample3')

       {
        if (a)
             {
              i = i + 1;
              ttsBegin;
              b.LineDisc= 'something';
              b.update();
              ttscommit;
             }
        }
     info(strfmt("total record/s updated : %1",i));
}
</code>```

When I run above,  am having this error

"Cannot edit a record in Inventory module parameters (InventTableModule).
The record has never been selected."

As solution, based on this link How to Update/Insert/Delete CrossCompany, i tried following the same, this is the modified script

```<code>static void UpdateSample(Args _args)
{
   InventTable  a;
   InventTableModule b;
   EcoResProduct c;
   EcoResProductCategory d;
   EcoResCategory e;
   EcoResCategoryHierarchy f;
   int i = 0;

    while select crossCompany  a
    exists join b where a.ItemId  == b.ItemId
    exists  join c where a.Product  == c.RecId
    exists join d where c.RecId  == d.Product
    exists join e where d.Category  == e.RecId
    exists join f where d.CategoryHierarchy  == f.RecId
    && a.dataAreaId == 'DAT' && b.ModuleType  == 2
    && b.LineDisc  == ''
    && f.name == 'EXAMPLE'
    &&(e.name == 'sample1' || e.name == 'sample2' || e.name == 'sample3')

       {
       if (a)
             {
              i = i + 1;
              b.LineDisc= 'something';
              b.selectForUpdate(true);
              ttsBegin;
              b.update();
              ttsCommit;
             }
        }
     info(strfmt("total record/s updated : %1",i));
}
</code>```

But I am having SYNTAX ERROR on this line

```<code> b.selectForUpdate(true);
</code>```

I am new to x++, hope i can get expert advice about the best practice in doing this.

Thanks in advance.

答:
First off, do not try to do update cross company, it is bound to fail.
Make the update work in current company, then apply the script to other relevant companies.

Fixed a few things:

Trying to update a record found with exists join will not work, hence your error.

Testing on record found is redundant, the loop will not be entered if none is found

Use a large transaction

Also put the update in an inner function, this will make it easy to update in more than one company. See this answer on how to do in all companies.

```<code>static void UpdateSample(Args _args)
{
    void doIt()
    {
        InventTable  a;
        InventTableModule b;
        EcoResProduct c;
        EcoResProductCategory d;
        EcoResCategory e;
        EcoResCategoryHierarchy f;
        int i;
        ttsBegin;
        while select a
            join forUpdate b where a.ItemId  == b.ItemId
            exists join c where a.Product  == c.RecId
            exists join d where c.RecId  == d.Product
            exists join e where d.Category  == e.RecId
            exists join f where d.CategoryHierarchy  == f.RecId
            && b.ModuleType  == 2
            && b.LineDisc  == ''
            && f.name == 'EXAMPLE'
            &&(e.name == 'sample1' || e.name == 'sample2' || e.name == 'sample3')
        {
            ++i;
            b.LineDisc= 'something';
            b.update();
        }
        ttsCommit;
        info(strfmt("total record/s updated : %1", i));
    }
    changecompany ('XXX')
        doIt();
}
</code>```

Body:
So I have a complete x++ script that aims to update records based on the retrieved result set made with select query with multiple joins and using crosscompany

As I have been told, it is not a good idea to update records when there is crosscompany. Can you give expert advice on how to do it the best practice way considering my current script.

here is the script

static void UpdateSample(Args _args)
{

   InventTable  a;
   InventTableModule b;
   EcoResProduct c;
   EcoResProductCategory d;
   EcoResCategory e;
   EcoResCategoryHierarchy f;
   int i = 0;

    while select crossCompany  a
    exists join b where a.ItemId  == b.ItemId
    exists  join c where a.Product  == c.RecId
    exists join d where c.RecId  == d.Product
    exists join e where d.Category  == e.RecId
    exists join f where d.CategoryHierarchy  == f.RecId
    && a.dataAreaId == 'DAT' && b.ModuleType  == 2
    && b.LineDisc  == ''
    && f.name == 'EXAMPLE'
    &&(e.name == 'sample1' || e.name == 'sample2' || e.name == 'sample3')

       {
        if (a)
             {
              i = i + 1;
              ttsBegin;
              b.LineDisc= 'something';
              b.update();
              ttscommit;
             }
        }
     info(strfmt("total record/s updated : %1",i));
}

When I run above,  am having this error

"Cannot edit a record in Inventory module parameters (InventTableModule).
The record has never been selected."

As solution, based on this link How to Update/Insert/Delete CrossCompany, i tried following the same, this is the modified script

static void UpdateSample(Args _args)
{
   InventTable  a;
   InventTableModule b;
   EcoResProduct c;
   EcoResProductCategory d;
   EcoResCategory e;
   EcoResCategoryHierarchy f;
   int i = 0;

    while select crossCompany  a
    exists join b where a.ItemId  == b.ItemId
    exists  join c where a.Product  == c.RecId
    exists join d where c.RecId  == d.Product
    exists join e where d.Category  == e.RecId
    exists join f where d.CategoryHierarchy  == f.RecId
    && a.dataAreaId == 'DAT' && b.ModuleType  == 2
    && b.LineDisc  == ''
    && f.name == 'EXAMPLE'
    &&(e.name == 'sample1' || e.name == 'sample2' || e.name == 'sample3')

       {
       if (a)
             {
              i = i + 1;
              b.LineDisc= 'something';
              b.selectForUpdate(true);
              ttsBegin;
              b.update();
              ttsCommit;
             }
        }
     info(strfmt("total record/s updated : %1",i));
}

But I am having SYNTAX ERROR on this line

 b.selectForUpdate(true);

I am new to x++, hope i can get expert advice about the best practice in doing this.

Thanks in advance.

Body:
First off, do not try to do update cross company, it is bound to fail.
Make the update work in current company, then apply the script to other relevant companies.

Fixed a few things:

Trying to update a record found with exists join will not work, hence your error.

Testing on record found is redundant, the loop will not be entered if none is found

Use a large transaction

Also put the update in an inner function, this will make it easy to update in more than one company. See this answer on how to do in all companies.

static void UpdateSample(Args _args)
{
    void doIt()
    {
        InventTable  a;
        InventTableModule b;
        EcoResProduct c;
        EcoResProductCategory d;
        EcoResCategory e;
        EcoResCategoryHierarchy f;
        int i;
        ttsBegin;
        while select a
            join forUpdate b where a.ItemId  == b.ItemId
            exists join c where a.Product  == c.RecId
            exists join d where c.RecId  == d.Product
            exists join e where d.Category  == e.RecId
            exists join f where d.CategoryHierarchy  == f.RecId
            && b.ModuleType  == 2
            && b.LineDisc  == ''
            && f.name == 'EXAMPLE'
            &&(e.name == 'sample1' || e.name == 'sample2' || e.name == 'sample3')
        {
            ++i;
            b.LineDisc= 'something';
            b.update();
        }
        ttsCommit;
        info(strfmt("total record/s updated : %1", i));
    }
    changecompany ('XXX')
        doIt();
}


问:
Bootstrap col is adding extra height instead of wrapping img tightly
I have an img nested in a col. However, the col is larger than the image. It's as if there is padding at the bottom, but I don't see any. Here is a screenshot: https://imgur.com/a/K8iRWLf

There is another img nested within a separate col in the same row, but that img is the exact same size.

EDIT* I tried two fixes per a suggestion: display: block and vertical-align: bottom (separately), neither of which worked.

```<code> .img-shrink {
    max-width: 80%;
    max-height: 80%;
  }
</code>```

```<code> <div class="row justify-content-center">
                <div class="col-3 body-padding text-center">
                    <img class="img-fluid img-shrink" src="img/dog-beer.jpg" alt="beer">
                </div>
                <div class="col-3 body-padding text-center">
                    <img class="img-fluid img-shrink" src="img/dog-treats.jpg" alt="treats">
                </div>
            </div>
            <div class="row justify-content-center">
                <div class="col-2 align-text-top">
                    <h4 class="product-header">Lorem Ipsum</h4>
                </div>
                <div class="col-2 align-text-top">
                    <h4 class="product-header">Lorem Ipsum</h4>
                </div>
            </div>
</code>```

答:
Try this once and see if it works </p>

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <title>CSS Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
  <style>
  </style>
</head>
<body>
    <div class="row justify-content-center">
        <div class="col-3">
            <img class="img-fluid" src="img.jpg" alt="beer">
        </div>
        <div class="col-3">
            <img class="img-fluid" src="image.jpg" alt="treats">
        </div>
    </div>
    <div class="row justify-content-center">
        <div class="col-3 align-text-top text-center">
            <h4 class="product-header">Lorem Ipsum</h4>
        </div>
        <div class="col-3 align-text-top text-center">
            <h4 class="product-header">Lorem Ipsum</h4>
        </div>
    </div>
</body>
</html>
</code>```

Body:
I have an img nested in a col. However, the col is larger than the image. It's as if there is padding at the bottom, but I don't see any. Here is a screenshot: https://imgur.com/a/K8iRWLf

There is another img nested within a separate col in the same row, but that img is the exact same size.

EDIT* I tried two fixes per a suggestion: display: block and vertical-align: bottom (separately), neither of which worked.

 .img-shrink {
    max-width: 80%;
    max-height: 80%;
  }

Lorem Ipsum

Lorem Ipsum

Body:
Try this once and see if it works

<!DOCTYPE html>
<html lang="en">
<head>
  <title>CSS Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
  <style>
  </style>
</head>
<body>
    <div class="row justify-content-center">
        <div class="col-3">
            <img class="img-fluid" src="img.jpg" alt="beer">
        </div>
        <div class="col-3">
            <img class="img-fluid" src="image.jpg" alt="treats">
        </div>
    </div>
    <div class="row justify-content-center">
        <div class="col-3 align-text-top text-center">
            <h4 class="product-header">Lorem Ipsum</h4>
        </div>
        <div class="col-3 align-text-top text-center">
            <h4 class="product-header">Lorem Ipsum</h4>
        </div>
    </div>
</body>
</html>


问:
How to iterate through complex Json object and do something on each property which equals a certain value
I got the following problem,

I need to iterate through a big Json object ( child nodes consist of array's, strings and objects with at least 4-5 layers of depth in terms of nested properties ).

In some parts across the big Json file there is a specific object structure, it has a property named "erpCode". I need to scan the Json and find all the objects with that property, take the value use that code to ask a different API for details and once I get the details insert them into the object with the current 'erpCode'.

Just to clarify, in my case the parent node property name in the Json always equals the value in 'typeSysname' field which located on the same 'level' as the erpCode property.
A simple example :

```<code>{
   "cars": [
    {
      "name": "X222",
      "carType": {
         "erpCode": "skoda",
         "value": null,
         "typeSysName": "carType"
       }
    }
    ],
    "model": {
       "year": 1999,
       "details": {
           "erpCode": "112"
           "value": null,
           "typeSysName": "details"
        }
     }
}
</code>```

In this example I need to find 2 properties get the values skoda and 112 out of them and get the value and description data from a different API and set it into this Json in the right location.

P.S. Any chance there is a good npm package which can help me with that?

Edit:
I got a solution in C# from a few months ago which runs in a generic way on the Json and handles the complexity of the structure in a generic way.
But I now need to convert this into Javascript and I am a bit lost.

```<code>public static string TranslateDocErpCodes(string jsonString, string topRetailerSysName)
        {

            try
            {
                var doc = JObject.Parse(jsonString);
                var erpCodeList = doc.SelectTokens("$..erpCode").ToList();

                foreach (var erpCodeJToken in erpCodeList)
                {
                    var value = erpCodeJToken?.Value<string>();
                    var erpCodeParent = erpCodeJToken?.Parent.Parent;
                    var erpCodeProperty = erpCodeParent?.Path.Split(".").Last();

                    var result =
                        _dataService.GetLovFromErpCode(topRetailerSysName, erpCodeProperty, value);

                    if (result == null)//reset lov obj
                    {
                        if (erpCodeParent?.Parent is JProperty prop)
                            prop.Value = JObject.FromObject(new LovObject { ErpCode = value });
                    }
                    else//set lov obj
                    {
                        result.ErpCode = value;
                        if (erpCodeParent?.Parent is JProperty prop)
                            prop.Value = JObject.FromObject(result);
                    }

                }
                return JsonConvert.SerializeObject(doc);
            }
            catch (Exception e)
            {
                throw new Exception("ErpConvert.TranslateDocErpCodes() : " + e);
            }
        }
</code>```

答:
I took the answer from Aravindh as a starting point and managed to reach what seems to be a complete solution.
I will share it here,

```<code>async function convertErpCodes(jsonData, orgName, parentPropertyName){
        for (let prop in jsonData) {
          if (jsonData.hasOwnProperty(prop)) {
              if (prop === 'erpCode') {
                  const erpCodeValue = jsonData[prop]
                  const req = {"query": {"erpCode": erpCodeValue, "orgName": orgName, "typeSysName": parentPropertyName}};
                  const result = await viewLookupErpService.findOne(req);
                  if(result)
                    return result;
              }
              const curValue = jsonData[prop];
              if (Array.isArray(curValue)) {
                  for(let i in curValue){
                    const res = await convertErpCodes(curValue[i], orgName, prop);
                  }
              } else if (curValue && typeof curValue === 'object') {
                const response = await convertErpCodes(curValue, orgName, prop);
                if(response){
                    jsonData[prop] = response;
                }
              }
          }
      }
}
</code>```

P.S.
I set up the values only if I get a response from the third party API ( this is the reason for the result and response logic in the recursion.

Body:
I got the following problem,

I need to iterate through a big Json object ( child nodes consist of array's, strings and objects with at least 4-5 layers of depth in terms of nested properties ).

In some parts across the big Json file there is a specific object structure, it has a property named "erpCode". I need to scan the Json and find all the objects with that property, take the value use that code to ask a different API for details and once I get the details insert them into the object with the current 'erpCode'.

Just to clarify, in my case the parent node property name in the Json always equals the value in 'typeSysname' field which located on the same 'level' as the erpCode property.
A simple example :

{
   "cars": [
    {
      "name": "X222",
      "carType": {
         "erpCode": "skoda",
         "value": null,
         "typeSysName": "carType"
       }
    }
    ],
    "model": {
       "year": 1999,
       "details": {
           "erpCode": "112"
           "value": null,
           "typeSysName": "details"
        }
     }
}

In this example I need to find 2 properties get the values skoda and 112 out of them and get the value and description data from a different API and set it into this Json in the right location.

P.S. Any chance there is a good npm package which can help me with that?

Edit:
I got a solution in C# from a few months ago which runs in a generic way on the Json and handles the complexity of the structure in a generic way.
But I now need to convert this into Javascript and I am a bit lost.

public static string TranslateDocErpCodes(string jsonString, string topRetailerSysName)
        {

            try
            {
                var doc = JObject.Parse(jsonString);
                var erpCodeList = doc.SelectTokens("$..erpCode").ToList();

                foreach (var erpCodeJToken in erpCodeList)
                {
                    var value = erpCodeJToken?.Value<string>();
                    var erpCodeParent = erpCodeJToken?.Parent.Parent;
                    var erpCodeProperty = erpCodeParent?.Path.Split(".").Last();

                    var result =
                        _dataService.GetLovFromErpCode(topRetailerSysName, erpCodeProperty, value);

                    if (result == null)//reset lov obj
                    {
                        if (erpCodeParent?.Parent is JProperty prop)
                            prop.Value = JObject.FromObject(new LovObject { ErpCode = value });
                    }
                    else//set lov obj
                    {
                        result.ErpCode = value;
                        if (erpCodeParent?.Parent is JProperty prop)
                            prop.Value = JObject.FromObject(result);
                    }

                }
                return JsonConvert.SerializeObject(doc);
            }
            catch (Exception e)
            {
                throw new Exception("ErpConvert.TranslateDocErpCodes() : " + e);
            }
        }

Body:
I took the answer from Aravindh as a starting point and managed to reach what seems to be a complete solution.
I will share it here,

async function convertErpCodes(jsonData, orgName, parentPropertyName){
        for (let prop in jsonData) {
          if (jsonData.hasOwnProperty(prop)) {
              if (prop === 'erpCode') {
                  const erpCodeValue = jsonData[prop]
                  const req = {"query": {"erpCode": erpCodeValue, "orgName": orgName, "typeSysName": parentPropertyName}};
                  const result = await viewLookupErpService.findOne(req);
                  if(result)
                    return result;
              }
              const curValue = jsonData[prop];
              if (Array.isArray(curValue)) {
                  for(let i in curValue){
                    const res = await convertErpCodes(curValue[i], orgName, prop);
                  }
              } else if (curValue && typeof curValue === 'object') {
                const response = await convertErpCodes(curValue, orgName, prop);
                if(response){
                    jsonData[prop] = response;
                }
              }
          }
      }
}

P.S.
I set up the values only if I get a response from the third party API ( this is the reason for the result and response logic in the recursion.


问:
Initialize Array of Objects using NSArray
I'm pretty new to Objective-C and iOS so I've been playing around with the Picker View. I've defined a Person Class so that when you create a new Person it automatically gives that person a name and age.

```<code>#import "Person.h"

@implementation Person

@synthesize personName, age;

-(id)init
{
    self = [super init];
    if(self)
    {
        personName = [self randomName];
        age = [self randomAge];
    }

    return self;
}

-(NSString *) randomName
{
    NSString* name;
    NSArray* nameArr = [NSArray arrayWithObjects: @"Jill Valentine", @"Peter Griffin", @"Meg Griffin", @"Jack Lolwut",
                            @"Mike Roflcoptor", @"Cindy Woods", @"Jessica Windmill", @"Alexander The Great",
                            @"Sarah Peterson", @"Scott Scottland", @"Geoff Fanta", @"Amanda Pope", @"Michael Meyers",
                            @"Richard Biggus", @"Montey Python", @"Mike Wut", @"Fake Person", @"Chair",
                            nil];
    NSUInteger randomIndex = arc4random() % [nameArr count];
    name = [nameArr objectAtIndex: randomIndex];
    return name;
}

-(NSInteger *) randomAge
{
    //lowerBound + arc4random() % (upperBound - lowerBound);
    NSInteger* num = (NSInteger*)(1 + arc4random() % (99 - 1));

    return num;
}

@end
</code>```

Now I want to make an array of Persons so I can throw a bunch into the picker, pick one Person and show their age. First though I need to make an array of Persons. How do I make an array of objects, initialize and allocate them?

答:
This might not really answer the question, but just in case someone just need to quickly send a string value to a function that require a NSArray parameter.

```<code>NSArray *data = @[@"The String Value"];
</code>```

if you need to send more than just 1 string value, you could also use

```<code>NSArray *data = @[@"The String Value", @"Second String", @"Third etc"];
</code>```

then you can send it to the function like below

```<code>theFunction(data);
</code>```

Body:
I'm pretty new to Objective-C and iOS so I've been playing around with the Picker View. I've defined a Person Class so that when you create a new Person it automatically gives that person a name and age.

#import "Person.h"

@implementation Person

@synthesize personName, age;

-(id)init
{
    self = [super init];
    if(self)
    {
        personName = [self randomName];
        age = [self randomAge];
    }

    return self;
}

-(NSString *) randomName
{
    NSString* name;
    NSArray* nameArr = [NSArray arrayWithObjects: @"Jill Valentine", @"Peter Griffin", @"Meg Griffin", @"Jack Lolwut",
                            @"Mike Roflcoptor", @"Cindy Woods", @"Jessica Windmill", @"Alexander The Great",
                            @"Sarah Peterson", @"Scott Scottland", @"Geoff Fanta", @"Amanda Pope", @"Michael Meyers",
                            @"Richard Biggus", @"Montey Python", @"Mike Wut", @"Fake Person", @"Chair",
                            nil];
    NSUInteger randomIndex = arc4random() % [nameArr count];
    name = [nameArr objectAtIndex: randomIndex];
    return name;
}

-(NSInteger *) randomAge
{
    //lowerBound + arc4random() % (upperBound - lowerBound);
    NSInteger* num = (NSInteger*)(1 + arc4random() % (99 - 1));

    return num;
}

@end

Now I want to make an array of Persons so I can throw a bunch into the picker, pick one Person and show their age. First though I need to make an array of Persons. How do I make an array of objects, initialize and allocate them?

Body:
This might not really answer the question, but just in case someone just need to quickly send a string value to a function that require a NSArray parameter.

NSArray *data = @[@"The String Value"];

if you need to send more than just 1 string value, you could also use

NSArray *data = @[@"The String Value", @"Second String", @"Third etc"];

then you can send it to the function like below

theFunction(data);


问:
get value using jquery
i want to get value of h:outputText label using jquery,
for</p>

```<code><h:outputText id="cal_att_to_date"
  binding="#{Attendance_Calculation.cal_att_to_date}">
     <f:convertDateTime type="date" pattern="dd-MMM-yyyy" timeZone="GMT+5:30"/>    </h:outputText>
</code>```

答: var value = $('#cal_att_to_date').text();

Title: get value using jquery

Body:
i want to get value of h:outputText label using jquery,
for

<h:outputText id="cal_att_to_date"
  binding="#{Attendance_Calculation.cal_att_to_date}">
     <f:convertDateTime type="date" pattern="dd-MMM-yyyy" timeZone="GMT+5:30"/>    </h:outputText>


问:
HTML nested lists only first element of sublist hoverable
I have a simple nested ul, the sublists are displayed right to their parent. However, if I hover other sublist elements than the first one (which is directly right to the parents list item), the hover of the parent ul is lost.  Here is a snippet where you can see the problem:

#btn {
    position: fixed;
    z-index: 5;
    top: 15px;
    left: 15px;
    cursor: pointer;
    transition: left 500ms cubic-bezier(0.6, 0.05, 0.28, 0.91);
}
#btn div {
    width: 35px;
    height: 2px;
    margin-bottom: 8px;
    background-color: #00dffc;
    transition: transform 500ms cubic-bezier(0.6, 0.05, 0.28, 0.91), opacity 500ms, background-color 250ms;
}
#btn.active {
    left: 230px;
}
#btn.active div {
    background-color: #343838;
}
#btn.active #top {
    transform: translateY(10px) rotate(-135deg);
}
#btn.active #middle {
    opacity: 0;
    transform: rotate(135deg);
}
#btn.active #bottom {
    transform: translateY(-10px) rotate(-45deg);
}
#box {
    position: fixed;
    z-index: 4;
    overflow: auto;
    top: 0px;
    left: 0px;
    width: 500px;
    opacity: 1;
    padding: 20px 0px;
    height: 100%;
    background-color: lightblue;
    color: white;
    transition: all 350ms cubic-bezier(0.6, 0.05, 0.28, 0.91);
}
#box.active {
    left: 0px;
    opacity: 1;
}
#items {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    list-style-type: none;
    padding-left: 0;
}
#items .item {
    position: relative;
    cursor: pointer;
    font-size: 2em;
    padding: 15px 30px;
    transition: all 250ms;
}
#items .item:hover {
    padding: 15px 45px;
    background-color: rgba(52, 56, 56, 0.2);
}
#items > li > ul{
    display: none;
    top: 0px;
}
#items > li:hover > ul {
    list-style-type: none;
    margin-left: 25px;
    position: absolute;
    display: inline;
}
#items > li > ul:hover {
    list-style-type: none;
    margin-left: 25px;
    position: absolute;
    display: inline;
}
#items > li > ul > li{
    border: 1px solid;
    transition: all 250ms;
    padding: 15px 30px;

}
#items > li:hover > ul > li:hover{
    padding: 15px 45px;
    background-color: rgba(52, 56, 56, 0.2);
}
#btn, #btn * {
    will-change: transform;
}
#box {
    will-change: transform, opacity;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="box">
    <ul id="items">
            <li class="item">Item 1</li>
            <li class="item">Item 2</li>
            <li class="item">Item 3
                <ul>
                <li>Subitem 1</li>
                <li>Subitem 2</li>
                <li>Subitem 3</li>
            </ul>
            </li>
            <li class="item">Item 4
                <ul>
                <li>Subitem 1</li>
                <li>Subitem 2</li>
                <li>Subitem 3</li>
                </ul>
            </li>
            <li class="item">Item 5
                <ul>
                <li>Subitem 1</li>
                <li>Subitem 2</li>
            </ul>
            </li>
            <li class="item">Item</li>
            <li class="item">Item</li>
            <li class="item">Item</li>
    </ul>
</div></code>```

I gave the sublists boxes so you can see their limits. As you see, you can only hover the first subitem. How can I fix this?

答:
You only have to set the z-index to your nested
. otherwise you will trigger the hover of the next
.

To learn more about z-index take a look at its
  documentation

#btn {
    position: fixed;
    z-index: 5;
    top: 15px;
    left: 15px;
    cursor: pointer;
    transition: left 500ms cubic-bezier(0.6, 0.05, 0.28, 0.91);
}
#btn div {
    width: 35px;
    height: 2px;
    margin-bottom: 8px;
    background-color: #00dffc;
    transition: transform 500ms cubic-bezier(0.6, 0.05, 0.28, 0.91), opacity 500ms, background-color 250ms;
}
#btn.active {
    left: 230px;
}
#btn.active div {
    background-color: #343838;
}
#btn.active #top {
    transform: translateY(10px) rotate(-135deg);
}
#btn.active #middle {
    opacity: 0;
    transform: rotate(135deg);
}
#btn.active #bottom {
    transform: translateY(-10px) rotate(-45deg);
}
#box {
    position: fixed;
    z-index: 4;
    overflow: auto;
    top: 0px;
    left: 0px;
    width: 500px;
    opacity: 1;
    padding: 20px 0px;
    height: 100%;
    background-color: lightblue;
    color: white;
    transition: all 350ms cubic-bezier(0.6, 0.05, 0.28, 0.91);
}
#box.active {
    left: 0px;
    opacity: 1;
}
#items {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    list-style-type: none;
    padding-left: 0;
}
#items .item {
    position: relative;
    cursor: pointer;
    font-size: 2em;
    padding: 15px 30px;
    transition: all 250ms;
}
#items .item:hover {
    padding: 15px 45px;
    background-color: rgba(52, 56, 56, 0.2);
}
#items > li > ul{
    display: none;
    top: 0px;
}
#items > li:hover > ul {
    list-style-type: none;
    margin-left: 25px;
    position: absolute;
    display: inline;
    z-index: 10;
}
#items > li > ul:hover {
    list-style-type: none;
    margin-left: 25px;
    position: absolute;
    display: inline;
    z-index: 10;
}
#items > li > ul > li{
    border: 1px solid;
    transition: all 250ms;
    padding: 15px 30px;

}
#items > li:hover > ul > li:hover{
    padding: 15px 45px;
    background-color: rgba(52, 56, 56, 0.2);
}
#btn, #btn * {
    will-change: transform;
}
#box {
    will-change: transform, opacity;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="box">
    <ul id="items">
            <li class="item">Item 1</li>
            <li class="item">Item 2</li>
            <li class="item">Item 3
                <ul>
                <li>Subitem 1</li>
                <li>Subitem 2</li>
                <li>Subitem 3</li>
            </ul>
            </li>
            <li class="item">Item 4
                <ul>
                <li>Subitem 1</li>
                <li>Subitem 2</li>
                <li>Subitem 3</li>
                </ul>
            </li>
            <li class="item">Item 5
                <ul>
                <li>Subitem 1</li>
                <li>Subitem 2</li>
            </ul>
            </li>
            <li class="item">Item</li>
            <li class="item">Item</li>
            <li class="item">Item</li>
    </ul>
</div></code>```

Body:
I have a simple nested ul, the sublists are displayed right to their parent. However, if I hover other sublist elements than the first one (which is directly right to the parents list item), the hover of the parent ul is lost.  Here is a snippet where you can see the problem:

#btn {
    position: fixed;
    z-index: 5;
    top: 15px;
    left: 15px;
    cursor: pointer;
    transition: left 500ms cubic-bezier(0.6, 0.05, 0.28, 0.91);
}
#btn div {
    width: 35px;
    height: 2px;
    margin-bottom: 8px;
    background-color: #00dffc;
    transition: transform 500ms cubic-bezier(0.6, 0.05, 0.28, 0.91), opacity 500ms, background-color 250ms;
}
#btn.active {
    left: 230px;
}
#btn.active div {
    background-color: #343838;
}
#btn.active #top {
    transform: translateY(10px) rotate(-135deg);
}
#btn.active #middle {
    opacity: 0;
    transform: rotate(135deg);
}
#btn.active #bottom {
    transform: translateY(-10px) rotate(-45deg);
}
#box {
    position: fixed;
    z-index: 4;
    overflow: auto;
    top: 0px;
    left: 0px;
    width: 500px;
    opacity: 1;
    padding: 20px 0px;
    height: 100%;
    background-color: lightblue;
    color: white;
    transition: all 350ms cubic-bezier(0.6, 0.05, 0.28, 0.91);
}
#box.active {
    left: 0px;
    opacity: 1;
}
#items {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    list-style-type: none;
    padding-left: 0;
}
#items .item {
    position: relative;
    cursor: pointer;
    font-size: 2em;
    padding: 15px 30px;
    transition: all 250ms;
}
#items .item:hover {
    padding: 15px 45px;
    background-color: rgba(52, 56, 56, 0.2);
}
#items > li > ul{
    display: none;
    top: 0px;
}
#items > li:hover > ul {
    list-style-type: none;
    margin-left: 25px;
    position: absolute;
    display: inline;
}
#items > li > ul:hover {
    list-style-type: none;
    margin-left: 25px;
    position: absolute;
    display: inline;
}
#items > li > ul > li{
    border: 1px solid;
    transition: all 250ms;
    padding: 15px 30px;

}
#items > li:hover > ul > li:hover{
    padding: 15px 45px;
    background-color: rgba(52, 56, 56, 0.2);
}
#btn, #btn * {
    will-change: transform;
}
#box {
    will-change: transform, opacity;
}

Item 1

Item 2

Item 3

Subitem 1

Subitem 2

Subitem 3

Item 4

Subitem 1

Subitem 2

Subitem 3

Item 5

Subitem 1

Subitem 2

Item

Item

Item

I gave the sublists boxes so you can see their limits. As you see, you can only hover the first subitem. How can I fix this?

Body:
You only have to set the z-index to your nested <ul>. otherwise you will trigger the hover of the next <li>.

To learn more about z-index take a look at its
  documentation

#btn {
    position: fixed;
    z-index: 5;
    top: 15px;
    left: 15px;
    cursor: pointer;
    transition: left 500ms cubic-bezier(0.6, 0.05, 0.28, 0.91);
}
#btn div {
    width: 35px;
    height: 2px;
    margin-bottom: 8px;
    background-color: #00dffc;
    transition: transform 500ms cubic-bezier(0.6, 0.05, 0.28, 0.91), opacity 500ms, background-color 250ms;
}
#btn.active {
    left: 230px;
}
#btn.active div {
    background-color: #343838;
}
#btn.active #top {
    transform: translateY(10px) rotate(-135deg);
}
#btn.active #middle {
    opacity: 0;
    transform: rotate(135deg);
}
#btn.active #bottom {
    transform: translateY(-10px) rotate(-45deg);
}
#box {
    position: fixed;
    z-index: 4;
    overflow: auto;
    top: 0px;
    left: 0px;
    width: 500px;
    opacity: 1;
    padding: 20px 0px;
    height: 100%;
    background-color: lightblue;
    color: white;
    transition: all 350ms cubic-bezier(0.6, 0.05, 0.28, 0.91);
}
#box.active {
    left: 0px;
    opacity: 1;
}
#items {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    list-style-type: none;
    padding-left: 0;
}
#items .item {
    position: relative;
    cursor: pointer;
    font-size: 2em;
    padding: 15px 30px;
    transition: all 250ms;
}
#items .item:hover {
    padding: 15px 45px;
    background-color: rgba(52, 56, 56, 0.2);
}
#items > li > ul{
    display: none;
    top: 0px;
}
#items > li:hover > ul {
    list-style-type: none;
    margin-left: 25px;
    position: absolute;
    display: inline;
    z-index: 10;
}
#items > li > ul:hover {
    list-style-type: none;
    margin-left: 25px;
    position: absolute;
    display: inline;
    z-index: 10;
}
#items > li > ul > li{
    border: 1px solid;
    transition: all 250ms;
    padding: 15px 30px;

}
#items > li:hover > ul > li:hover{
    padding: 15px 45px;
    background-color: rgba(52, 56, 56, 0.2);
}
#btn, #btn * {
    will-change: transform;
}
#box {
    will-change: transform, opacity;
}

<div id="box">
    <ul id="items">
            <li class="item">Item 1</li>
            <li class="item">Item 2</li>
            <li class="item">Item 3
                <ul>
                <li>Subitem 1</li>
                <li>Subitem 2</li>
                <li>Subitem 3</li>
            </ul>
            </li>
            <li class="item">Item 4
                <ul>
                <li>Subitem 1</li>
                <li>Subitem 2</li>
                <li>Subitem 3</li>
                </ul>
            </li>
            <li class="item">Item 5
                <ul>
                <li>Subitem 1</li>
                <li>Subitem 2</li>
            </ul>
            </li>
            <li class="item">Item</li>
            <li class="item">Item</li>
            <li class="item">Item</li>
    </ul>
</div>