问:
Jackson Serializer not invoked Jersey Jax-RS
Developing JAX-RS app and struggle a problem.
Need to customize json-output from my resource so configured Jersey(2.22.2) to use Jackson(2.5) parser instead default Moxy (according to this answer).

Here is pom.xml fragment

```<code>        <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.glassfish.jersey</groupId>
                <artifactId>jersey-bom</artifactId>
                <version>${jersey.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet-core</artifactId>
            <!-- use the following artifactId if you don't need servlet 2.x compatibility -->
            <!-- artifactId>jersey-container-servlet</artifactId -->
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
            <version>2.25.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.5.3</version>
        </dependency>
    </dependencies>
    <properties>
        <jersey.version>2.22.2</jersey.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
</code>```

I also configured web.xml file to use Jackson by default

```<code>    <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>
                com.mycompany.myresourcepackage
                com.fasterxml.jackson.jaxrs
            </param-value>
        </init-param>
</code>```

But resource output is deffer from what I configure with annotations and serializer.
Here is model to represent as json

```<code>    @XmlRootElement(name = "geo")
public class Geometry {
    public Geometry() {
        coordinates = new ArrayList<List<Double>>();
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @JsonSerialize(using = CoordinatesSerializer.class)
    public List<List<Double>> getCoordinates() {
        return coordinates;
    }

    public void setCoordinates( List<List<Double>> coordinates) {
        this.coordinates = coordinates;
    }

    @JsonProperty("tp")
    private String  type;
    private List<List<Double>> coordinates;
}
</code>```

And serializer

```<code>protected CoordinatesSerializer(Class<List<List<Double>>> t) { }

private static final long serialVersionUID = 1L;

@Override
public void serialize(List<List<Double>> value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonGenerationException {
    try {
        jgen.writeArrayFieldStart("motherfucking-coordinates");

        int coordinates_size = value.size();
        for (int i = 0; i < coordinates_size; i++) {
            jgen.writeStartArray();
            jgen.writeNumber(value.get(i).get(0));
            jgen.writeNumber(value.get(i).get(1));
            jgen.writeEndArray();
        }

        jgen.writeEndArray();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

}

And here is resource fragment

```<code> @GET
    @Path("/route/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Geometry(@PathParam("id") int id) {
    // construct and return object
}
</code>```

Response json is not customized at all.

```<code>{"geometry":{"coordinates":["27.56 53.9","27.58 53.88","27.55 53.94"],"type":"LineString"},"id":"1","type":"Feature"}
</code>```

Desired output is

```<code>{"geometry":{"coordinates":[[27.56, 53.9],[27.58, 53.88],[27.55, 53.94]],"type":"LineString"},"id":"1","type":"Feature"}
</code>```

Thanks a lot.

答:
I finally managed to configure Jersey project to use Jackson JSON parser instead of Moxy(default). The application is running at Glassfish JEE Server.

Maven dependencies

```<code>    <dependencies>
    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet-core</artifactId>
        <!-- use the following artifactId if you don't need servlet 2.x compatibility -->
        <!-- artifactId>jersey-container-servlet</artifactId -->
        <version>${jersey.version}</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.jaxrs</groupId>
        <artifactId>jackson-jaxrs-json-provider</artifactId>
        <version>2.5.3</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.5.3</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
        <version>2.0</version>
        <scope>provided</scope>
    </dependency>
</dependencies>
</code>```

Than you need to create class with extends org.glassfish.jersey.server.ResourceConfig. The object of the class is created when app is first loaded.

```<code>public class MyApplication extends ResourceConfig {
public MyApplication() {
    // create custom ObjectMapper
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);

    // create JsonProvider to provide custom ObjectMapper
    JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider();
    provider.setMapper(mapper);

    register(provider);
    register(JacksonFeature.class);
    packages("your.resources.package");
}
}
</code>```

And created MyApplication class should be registered in web.xml file (to be actually created). Edit  section of web.xml.

```<code><servlet>
    <servlet-name>App</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value>your.app.package.MyApplication</param-value>

    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
</code>```

Listed steps are enough to register Jackson JSON Parser as default for Jersey Jax-RS app.

Body:
Developing JAX-RS app and struggle a problem.
Need to customize json-output from my resource so configured Jersey(2.22.2) to use Jackson(2.5) parser instead default Moxy (according to this answer).

Here is pom.xml fragment

        <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.glassfish.jersey</groupId>
                <artifactId>jersey-bom</artifactId>
                <version>${jersey.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet-core</artifactId>

        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
            <version>2.25.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.5.3</version>
        </dependency>
    </dependencies>
    <properties>
        <jersey.version>2.22.2</jersey.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

I also configured web.xml file to use Jackson by default

    <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>
                com.mycompany.myresourcepackage
                com.fasterxml.jackson.jaxrs
            </param-value>
        </init-param>

But resource output is deffer from what I configure with annotations and serializer.
Here is model to represent as json

    @XmlRootElement(name = "geo")
public class Geometry {
    public Geometry() {
        coordinates = new ArrayList<List<Double>>();
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @JsonSerialize(using = CoordinatesSerializer.class)
    public List<List<Double>> getCoordinates() {
        return coordinates;
    }

    public void setCoordinates( List<List<Double>> coordinates) {
        this.coordinates = coordinates;
    }

    @JsonProperty("tp")
    private String  type;
    private List<List<Double>> coordinates;
}

And serializer

protected CoordinatesSerializer(Class<List<List<Double>>> t) { }

private static final long serialVersionUID = 1L;

@Override
public void serialize(List<List<Double>> value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonGenerationException {
    try {
        jgen.writeArrayFieldStart("motherfucking-coordinates");

        int coordinates_size = value.size();
        for (int i = 0; i < coordinates_size; i++) {
            jgen.writeStartArray();
            jgen.writeNumber(value.get(i).get(0));
            jgen.writeNumber(value.get(i).get(1));
            jgen.writeEndArray();
        }

        jgen.writeEndArray();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

}

And here is resource fragment

 @GET
    @Path("/route/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Geometry(@PathParam("id") int id) {
    // construct and return object
}

Response json is not customized at all.

{"geometry":{"coordinates":["27.56 53.9","27.58 53.88","27.55 53.94"],"type":"LineString"},"id":"1","type":"Feature"}

Desired output is

{"geometry":{"coordinates":[[27.56, 53.9],[27.58, 53.88],[27.55, 53.94]],"type":"LineString"},"id":"1","type":"Feature"}

Thanks a lot.

Body:
I finally managed to configure Jersey project to use Jackson JSON parser instead of Moxy(default). The application is running at Glassfish JEE Server.

Maven dependencies

    <dependencies>
    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet-core</artifactId>
        <!-- use the following artifactId if you don't need servlet 2.x compatibility -->
        <!-- artifactId>jersey-container-servlet</artifactId -->
        <version>${jersey.version}</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.jaxrs</groupId>
        <artifactId>jackson-jaxrs-json-provider</artifactId>
        <version>2.5.3</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.5.3</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
        <version>2.0</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

Than you need to create class with extends org.glassfish.jersey.server.ResourceConfig. The object of the class is created when app is first loaded.

public class MyApplication extends ResourceConfig {
public MyApplication() {
    // create custom ObjectMapper
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);

    // create JsonProvider to provide custom ObjectMapper
    JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider();
    provider.setMapper(mapper);

    register(provider);
    register(JacksonFeature.class);
    packages("your.resources.package");
}
}

And created MyApplication class should be registered in web.xml file (to be actually created). Edit  section of web.xml.

<servlet>
    <servlet-name>App</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value>your.app.package.MyApplication</param-value>

    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

Listed steps are enough to register Jackson JSON Parser as default for Jersey Jax-RS app.


来源: stackexchange

问:
Visual Studio extension: Change the hint path of an assembly reference
I'm writing a Visual Studio extension and I would like to change the hint path of an assembly reference of a C#-project without to trigger the "File Modification Detected"-dialog.

```<code><Reference Include="SomeAssembly">
  <HintPath>C:\ChangeMe\SomeAssembly.dll</HintPath>
</Reference>
</code>```

But in the VSLangProj110.Reference5-interface I can't find any property that I can use. (Accessed through VSLangProj140.VSProject3.References)

答:
I create a demo and reproduce your issue on my side. I think it is a by design issue, if you modify the project outside the environment, it will popup the "File Modification Detected" dialog, we need to change it by manually.

you could post a feedback on the following link: https://connect.microsoft.com/VisualStudio/Feedback

Update:

```<code>DTE2 dte = (DTE2)this.ServiceProvider.GetService(typeof(DTE));
            EnvDTE.Project currentProject = dte.Solution.Projects.Item(1);

            // Create a new Project object.
            Microsoft.Build.BuildEngine.Project project = new Microsoft.Build.BuildEngine.Project();

            project.Load(currentProject.FullName);

            foreach (BuildItemGroup ig in project.ItemGroups)
            {
                //var items = ig.ToArray();

                foreach (BuildItem item in ig.ToArray())
                {
                    if (item.Include == "ClassLibrary1")
                    {
                        item.Include = "Utils";
                        item.SetMetadata("HintPath", @"C:\relativePath\Utils.dll");
                    }
                }
            }
            project.Save(currentProject.FullName);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm writing a Visual Studio extension and I would like to change the hint path of an assembly reference of a C#-project without to trigger the "File Modification Detected"-dialog.

<Reference Include="SomeAssembly">
  <HintPath>C:\ChangeMe\SomeAssembly.dll</HintPath>
</Reference>

But in the VSLangProj110.Reference5-interface I can't find any property that I can use. (Accessed through VSLangProj140.VSProject3.References)

Body:
I create a demo and reproduce your issue on my side. I think it is a by design issue, if you modify the project outside the environment, it will popup the "File Modification Detected" dialog, we need to change it by manually.

you could post a feedback on the following link: https://connect.microsoft.com/VisualStudio/Feedback

Update:

DTE2 dte = (DTE2)this.ServiceProvider.GetService(typeof(DTE));
            EnvDTE.Project currentProject = dte.Solution.Projects.Item(1);

            // Create a new Project object.
            Microsoft.Build.BuildEngine.Project project = new Microsoft.Build.BuildEngine.Project();

            project.Load(currentProject.FullName);

            foreach (BuildItemGroup ig in project.ItemGroups)
            {
                //var items = ig.ToArray();

                foreach (BuildItem item in ig.ToArray())
                {
                    if (item.Include == "ClassLibrary1")
                    {
                        item.Include = "Utils";
                        item.SetMetadata("HintPath", @"C:\relativePath\Utils.dll");
                    }
                }
            }
            project.Save(currentProject.FullName);


问:
Convert datatable to JSON in C#

I want to get records from database into a DataTable.

Then convert the DataTable into a JSON object.

Return the JSON object to my JavaScript function.

I use this code by calling:

```<code>string result = JsonConvert.SerializeObject(DatatableToDictionary(queryResult, "Title"), Newtonsoft.Json.Formatting.Indented);
</code>```

To convert a DataTable to JSON, it works correctly and return the following:

```<code>{
    "1": {
    "viewCount": 703,
    "clickCount": 98
    },
    "2": {
    "viewCount": 509,
    "clickCount": 85
    },
    "3": {
    "viewCount": 578,
    "clickCount": 86
    },
    "4": {
    "viewCount": 737,
    "clickCount": 108
    },
    "5": {
    "viewCount": 769,
    "clickCount": 130
    }
}
</code>```

But I would like it to return the following:

```<code>{"records":[
{
"Title": 1,
"viewCount": 703,
"clickCount": 98
},
{
"Title": 2,
"viewCount": 509,
"clickCount": 85
},
{
"Title": 3,
"viewCount": 578,
"clickCount": 86
},
{
"Title": 4,
"viewCount": 737,
"clickCount": 108
},
{
"Title": 5,
"viewCount": 769,
"clickCount": 130
}
]}
</code>```

How can I do this?

答:
```<code>//Common DLL client, server
public class transferDataTable
{
    public class myError
    {
        public string Message { get; set; }
        public int Code { get; set; }
    }

    public myError Error { get; set; }
    public List<string> ColumnNames { get; set; }
    public List<string> DataTypes { get; set; }
    public List<Object> Data { get; set; }
    public int Count { get; set; }
}

public static class ExtensionMethod
{
    public static transferDataTable LoadData(this transferDataTable transfer, DataTable dt)
    {
        if (dt != null)
        {
            transfer.DataTypes = new List<string>();
            transfer.ColumnNames = new List<string>();
            foreach (DataColumn c in dt.Columns)
            {
                transfer.ColumnNames.Add(c.ColumnName);
                transfer.DataTypes.Add(c.DataType.ToString());
            }

            transfer.Data = new List<object>();
            foreach (DataRow dr in dt.Rows)
            {
                foreach (DataColumn col in dt.Columns)
                {
                    transfer.Data.Add(dr[col] == DBNull.Value ? null : dr[col]);
                }
            }
            transfer.Count = dt.Rows.Count;
        }
        return transfer;
    }

    public static DataTable GetDataTable(this transferDataTable transfer, bool ConvertToLocalTime = true)
    {
        if (transfer.Error != null || transfer.ColumnNames == null || transfer.DataTypes == null || transfer.Data == null)
            return null;

        int columnsCount = transfer.ColumnNames.Count;
        DataTable dt = new DataTable();
        for (int i = 0; i < columnsCount; i++ )
        {
            Type colType = Type.GetType(transfer.DataTypes[i]);
            dt.Columns.Add(new DataColumn(transfer.ColumnNames[i], colType));
        }

        int index = 0;
        DataRow row = dt.NewRow();
        foreach (object o in transfer.Data)
        {
            if (ConvertToLocalTime && o != null && o.GetType() == typeof(DateTime))
            {
                DateTime dat = Convert.ToDateTime(o);
                row[index] = dat.ToLocalTime();
            }
            else
                row[index] = o == null ? DBNull.Value : o;

            index++;

            if (columnsCount == index)
            {
                index = 0;
                dt.Rows.Add(row);
                row = dt.NewRow();
            }
        }
        return dt;
    }
}

//Server
    [OperationContract]
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest, UriTemplate = "json/data")]
    transferDataTable _Data();

    public transferDataTable _Data()
    {
        try
        {
            using (SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["myConnString"]))
            {
                con.Open();
                DataSet ds = new DataSet();
                SqlDataAdapter myAdapter = new SqlDataAdapter("SELECT * FROM tbGalleries", con);
                myAdapter.Fill(ds, "table");
                DataTable dt = ds.Tables["table"];
                return new transferDataTable().LoadData(dt);
            }
        }
        catch(Exception ex)
        {
            return new transferDataTable() { Error = new transferDataTable.myError() { Message = ex.Message, Code = ex.HResult } };
        }
    }

//Client
        Response = Vossa.getAPI(serviceUrl + "json/data");
        transferDataTable transfer = new JavaScriptSerializer().Deserialize<transferDataTable>(Response);
        if (transfer.Error == null)
        {
            DataTable dt = transfer.GetDataTable();
            dbGrid.ItemsSource = dt.DefaultView;
        }
        else
            MessageBox.Show(transfer.Error.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
</code>```

Title: Convert datatable to JSON in C#

Body:
I want to get records from database into a DataTable.

Then convert the DataTable into a JSON object.

Return the JSON object to my JavaScript function.

I use this code by calling:

string result = JsonConvert.SerializeObject(DatatableToDictionary(queryResult, "Title"), Newtonsoft.Json.Formatting.Indented);

To convert a DataTable to JSON, it works correctly and return the following:

{
    "1": {
    "viewCount": 703,
    "clickCount": 98
    },
    "2": {
    "viewCount": 509,
    "clickCount": 85
    },
    "3": {
    "viewCount": 578,
    "clickCount": 86
    },
    "4": {
    "viewCount": 737,
    "clickCount": 108
    },
    "5": {
    "viewCount": 769,
    "clickCount": 130
    }
}

But I would like it to return the following:

{"records":[
{
"Title": 1,
"viewCount": 703,
"clickCount": 98
},
{
"Title": 2,
"viewCount": 509,
"clickCount": 85
},
{
"Title": 3,
"viewCount": 578,
"clickCount": 86
},
{
"Title": 4,
"viewCount": 737,
"clickCount": 108
},
{
"Title": 5,
"viewCount": 769,
"clickCount": 130
}
]}

How can I do this?


问:
Sort Multidimensional Array in VB.NET
I have a 2X50 array like this-

```<code>R-125212,11
C-254645,25
R-456598,96
M-456878,35
O-980857,89
And so on...
</code>```

Now I want to sort this array with the values of the 2nd Column. So the output should look like-

```<code>R-125212,11
C-254645,25
M-456878,35
O-980857,89
R-456598,96
And so on...
</code>```

How to do this with VB.NET easily? If there is other better way to have the similar result without using array, that also will help me.

答:
There are many possible solutions to your question, but in my experience the best is to use a System.Data.DataTable:

```<code>Dim dtb As New System.Data.DataTable
dtb.Columns.Add("Column1")
dtb.Columns.Add("Column2", GetType(Integer))
dtb.Rows.Add("Z-123456", 2)
dtb.Rows.Add("R-125212", 11)
dtb.Rows.Add("C-254645", 25)
dtb.Rows.Add("R-456598", 96)
dtb.Rows.Add("M-456878", 35)
dtb.Rows.Add("O-980857", 89)
Dim dvw As DataView = dtb.DefaultView
dvw.Sort = "Column2 ASC"
Dim dtbSorted As DataTable = dvw.ToTable()
DataGridView1.DataSource = dtbSorted
</code>```

Title: Sort Multidimensional Array in VB.NET

Body:
I have a 2X50 array like this-

R-125212,11
C-254645,25
R-456598,96
M-456878,35
O-980857,89
And so on...

Now I want to sort this array with the values of the 2nd Column. So the output should look like-

R-125212,11
C-254645,25
M-456878,35
O-980857,89
R-456598,96
And so on...

How to do this with VB.NET easily? If there is other better way to have the similar result without using array, that also will help me.

Body:
There are many possible solutions to your question, but in my experience the best is to use a System.Data.DataTable:

Dim dtb As New System.Data.DataTable
dtb.Columns.Add("Column1")
dtb.Columns.Add("Column2", GetType(Integer))
dtb.Rows.Add("Z-123456", 2)
dtb.Rows.Add("R-125212", 11)
dtb.Rows.Add("C-254645", 25)
dtb.Rows.Add("R-456598", 96)
dtb.Rows.Add("M-456878", 35)
dtb.Rows.Add("O-980857", 89)
Dim dvw As DataView = dtb.DefaultView
dvw.Sort = "Column2 ASC"
Dim dtbSorted As DataTable = dvw.ToTable()
DataGridView1.DataSource = dtbSorted


问:
Composer update without versioning
I'm developing a composer package used in another application. The package resides in a separate repository. Every now and then when I fix something in the package during the development, I have to increment its version by assigning a git tag so that the application where the package is used can download the latest version of it. I end up having lots of tags.

Is there a more appropriate way allowing to update (the composer update cmd) the package under development in the app where it's used without using thousands of tags?

Say I change the package, commit and push the changes to the repo. When I do composer update in the app's scope, it updates the package, although it's version is not incremented with the last change, there are only new commits in the package's repo.

答:
Usually there are two ways to update packages by composer update: tags and branches. Since you don’t want to use tags, let’s only talk branches here.

Such as, if you are working on master branch, and want the changes from master branch can be installed in your app, you need to change the dependencies of the package in composer.json as

```<code>{
    "require": {
        "vendor/package": "dev-master"
    }
}
</code>```

More detail, you can refer versions.

Title: Composer update without versioning

Body:
Usually there are two ways to update packages by composer update: tags and branches. Since you don’t want to use tags, let’s only talk branches here.

Such as, if you are working on master branch, and want the changes from master branch can be installed in your app, you need to change the dependencies of the package in composer.json as

{
    "require": {
        "vendor/package": "dev-master"
    }
}

More detail, you can refer versions.


问:
Check Symbol(✓) doesn't display in PDF using jasper report
I developed a report in jasper wherein it displays a check symbol(✓) for existing records (i.e. list of requirements).
It seems like I would never had a problem displaying it since the check symbol is visible during preview in the iReport. But once I viewed the report in PDF format, the check symbol is no longer visible. I even tried unicode characters instead of the check image, even unicode for square root.

What configuration am I missing here?

答:
This is the way to add image of (check-mark) and build

To create parameter paramImage and set  the image expression property as $P{paramImage}.

To passing value to this variable as

```<code>String imagePath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/images/IMAGE.jpg");
</code>```

Then put parameters as given below

```<code>paramaters.put("paramImage",imagePath);
</code>```

Body:
This is the way to add image of (check-mark) and build

To create parameter paramImage and set  the image expression property as $P{paramImage}.

To passing value to this variable as

String imagePath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/images/IMAGE.jpg");

Then put parameters as given below

paramaters.put("paramImage",imagePath);


OwnerDisplayName: Jawny Thompson

Title: Decode Ascii string values from reverse-engineered lua file

Body:
I decompiled a lua file with unluac and it turns out all the string variables are not readable and are instead ascii encoded

clues = {
  {
    answer = {
      "\216\173",
      "\216\177",
      "\216\168",
      "\216\167",
      "\216\161"
    },
    text = "\216\173\217\138\217\136\216\167\217\134\032\216\178\216\167\216\173\217\129\032\217\138\216\186\217\138\216\177\032\217\132\217\136\217\134\032\216\172\217\132\216\175\217\135",
    syllables = {
      {"\216\173", "\216\177"},
      {"\216\168", "\216\167"},
      {"\216\161"}
    }

How do i go about decoding the whole file ignoring any non ascii characters in python or java?

Body:
Try this:

import re

data = '\\216\\173\\217\\138\\217\\136\\216\\167\\217\\134\\032\\216\\178\\216\\167\\216\\173\\217\\129\\032\\217\\138\\216\\186\\217\\138\\216\\177\\032\\217\\132\\217\\136\\217\\134\\032\\216\\172\\217\\132\\216\\175\\217\\135'
decoded_data = re.sub('\\\\(\d{1,3})', lambda x: chr(int(x.group(1))), data).decode('utf-8')

print(repr(decoded_data))


问:
url in multi languages
Right now I'm working on a project, which has a multi lingual project i.e. English, Chinese, Danish, Korean etc. The page URL must be changed based on a selected language. Like :

```<code>English : example.com/pages/fullpage
Chinese : example.com/ch/頁面/整頁
Danish : example.com/dk/sider/fuldside
</code>```

I have read the CakePhp 3.x document, but I can't get a proper answer for it. I do it through routing.
Like :

```<code>Router::scope('/', function (RouteBuilder $routes) {
    $routes->connect('/pages/fullpage',   ['controller' => 'pages', 'action' => 'fullpage'] );
    $routes->connect('/頁面/整頁',   ['controller' => 'pages', 'action' => 'fullpage'] );
    $routes->connect('/sider/fuldside',   ['controller' => 'pages', 'action' => 'fullpage'] );
});
</code>```

It works perfectly, but I want reliable concept because in this scenario, I need to define the routing for all actions.

So if you have any thoughts about this please help.

Thanks in advance.

答:
Instead of writing thousands of routes just use the translation methods and toggle the language on whatever parameter you use to set it:

```<code>// Detect and set language before, we use a middleware
$routes->connect('/' . __d('routes', 'pages') . '/' . __d('routes', 'fullpage'), [ /*...*/]);
</code>```

That's the way we use for ~20 languages on our site.

Title: url in multi languages

Body:
Right now I'm working on a project, which has a multi lingual project i.e. English, Chinese, Danish, Korean etc. The page URL must be changed based on a selected language. Like :

English : example.com/pages/fullpage
Chinese : example.com/ch/頁面/整頁
Danish : example.com/dk/sider/fuldside

I have read the CakePhp 3.x document, but I can't get a proper answer for it. I do it through routing.
Like :

Router::scope('/', function (RouteBuilder $routes) {
    $routes->connect('/pages/fullpage',   ['controller' => 'pages', 'action' => 'fullpage'] );
    $routes->connect('/頁面/整頁',   ['controller' => 'pages', 'action' => 'fullpage'] );
    $routes->connect('/sider/fuldside',   ['controller' => 'pages', 'action' => 'fullpage'] );
});

It works perfectly, but I want reliable concept because in this scenario, I need to define the routing for all actions.

So if you have any thoughts about this please help.

Thanks in advance.

Body:
Instead of writing thousands of routes just use the translation methods and toggle the language on whatever parameter you use to set it:

// Detect and set language before, we use a middleware
$routes->connect('/' . __d('routes', 'pages') . '/' . __d('routes', 'fullpage'), [ /*...*/]);

That's the way we use for ~20 languages on our site.


问:
How to resolve angular lang json file(angular-localization module) from jasmine test case
I have angular service method which uses  angular-localization locale service .
I want to write jasmine test cases for  method , which are failing as jasmine is not able to
resolve it. May be it is not waiting till it resolve completely

```<code>//service method
$scope.getExcelName = function() {
  var name = locale.getString('export.fileName')
  return name;
}

//lang file
'fileName': 'Status Report'

//Jasmine test case
describe('Service:MyService', function() {
  var myService
  beforeEach(module('app'))

  beforeEach(inject(function($injector) {
    myService = $injector.get('MyService');
  }))

  it('check export name', function() {
    //myService.getExcel giving '' instead of  Status Report
    expect(myService.getExcelName()).toBe('Status Report')
  })
})
</code>```

How  to resolve above issue ?

答:
It seems like you are experiencing a race condition (excerpt from the documentation):

Race conditions

Always use locale.ready() passing in the filename(s)
  in which the token(s) exists in that context, and enclose any other
  relevant calls to locale.getString() within this promise's callback
  function block. Failure to do so may cause unexpected (empty) results
  due to the asynchronous nature of your entire JavaScript application.

You may use locale.getPath() to find the filename for any given token.

So the solution should be to inject the locale service and wrap the expect line inside a locale.ready() call, e.g.:

```<code>it('check export name', function(done) {
  locale.ready('export')
    .then(function() {
      expect(myService.getExcelName()).toBe('Status Report');
      done();
    })
    .catch(done.fail);
});
</code>```

Probably you should also do the same in the service itself to be safe.

Body:
I have angular service method which uses  angular-localization locale service .
I want to write jasmine test cases for  method , which are failing as jasmine is not able to
resolve it. May be it is not waiting till it resolve completely

//service method
$scope.getExcelName = function() {
  var name = locale.getString('export.fileName')
  return name;
}

//lang file
'fileName': 'Status Report'

//Jasmine test case
describe('Service:MyService', function() {
  var myService
  beforeEach(module('app'))

  beforeEach(inject(function($injector) {
    myService = $injector.get('MyService');
  }))

  it('check export name', function() {
    //myService.getExcel giving '' instead of  Status Report
    expect(myService.getExcelName()).toBe('Status Report')
  })
})

How  to resolve above issue ?

Body:
It seems like you are experiencing a race condition (excerpt from the documentation):

Race conditions

Always use locale.ready() passing in the filename(s)
  in which the token(s) exists in that context, and enclose any other
  relevant calls to locale.getString() within this promise's callback
  function block. Failure to do so may cause unexpected (empty) results
  due to the asynchronous nature of your entire JavaScript application.

You may use locale.getPath() to find the filename for any given token.

So the solution should be to inject the locale service and wrap the expect line inside a locale.ready() call, e.g.:

it('check export name', function(done) {
  locale.ready('export')
    .then(function() {
      expect(myService.getExcelName()).toBe('Status Report');
      done();
    })
    .catch(done.fail);
});

Probably you should also do the same in the service itself to be safe.


问:
XPath Find any element with text() within node selection
I have a fairly deeply nested xml structure and I would like to find an element with a particular value after I have already selected a node. In the sample below I have an array of 'B' and after selecting each of the 'B' nodes I would like to get the text of one of the children (which are not consistent) that starts with the word 'history'

```<code><A>
    <Items>
        <B>
            <C>
                <D>history: pressed K,E</D>  // could be nested anywhere
            </C>
        </B>
        <B>
            <C>
                <E>history: pressed W</E>
            </C>
        </B>
    </Items>
</A>

    // Select the nodes from the array (B)
var nodes = select(xmldoc, "//A/Items/B");

    // Iterate through the nodes.
nodes.forEach(node){

    // is it possible to select any element that starts with the text 'history' from the already selected node.
var history = select(node, "???[starts-with(.,'history')]");
</code>```

all the samples I have seen start with : //*[text()] which searches from the root of the structure.

答:
```<code>//B//*[starts-with(normalize-space(), 'history')]
</code>```

looks like it would do what you intend.

It selects "any descendant element of  whose text content starts with 'history'".

Manual iteration to find further nodes is not typically necessary. XPath does that for you. If you must iterate for some other reason, use the context node . to select.

```<code>nodes.forEach(function (node) {
    var history = select(node, "./*[starts-with(.,'history')]");
});
</code>```

If you are actually looking for "any text node..."

```<code>//B//text()[starts-with(normalize-space(), 'history')]
</code>```

Or "any element node that has no further child elements..."

```<code>//B//*[not(*) and starts-with(normalize-space(), 'history')]
</code>```

Body:
I have a fairly deeply nested xml structure and I would like to find an element with a particular value after I have already selected a node. In the sample below I have an array of 'B' and after selecting each of the 'B' nodes I would like to get the text of one of the children (which are not consistent) that starts with the word 'history'

    <Items>

            <C>
                <D>history: pressed K,E</D>  // could be nested anywhere
            </C>

            <C>
                <E>history: pressed W</E>
            </C>

    </Items>

    // Select the nodes from the array (B)
var nodes = select(xmldoc, "//A/Items/B");

    // Iterate through the nodes.
nodes.forEach(node){

    // is it possible to select any element that starts with the text 'history' from the already selected node.
var history = select(node, "???[starts-with(.,'history')]");

all the samples I have seen start with : //*[text()] which searches from the root of the structure.

Body:
//B//*[starts-with(normalize-space(), 'history')]

looks like it would do what you intend.

It selects "any descendant element of <B> whose text content starts with 'history'".

Manual iteration to find further nodes is not typically necessary. XPath does that for you. If you must iterate for some other reason, use the context node . to select.

nodes.forEach(function (node) {
    var history = select(node, "./*[starts-with(.,'history')]");
});

If you are actually looking for "any text node..."

//B//text()[starts-with(normalize-space(), 'history')]

Or "any element node that has no further child elements..."

//B//*[not(*) and starts-with(normalize-space(), 'history')]


问:
Gradle not compiling dependency jars in lib folder
I am new to gradle and learning now. I am trying to build a runnable jar using gradle(My builded jar should be run from command prompt). I just started with a simple HelloWorld project with a dependency and try to build it using gradle. I am not using maven. So I added the dependency jar to the lib folder inside project folder. Below are the details.

Gradle Version: 3.1
Eclipse Version: Neon

HelloWorld.java

```<code>package com.padhu.test;
import org.joda.time.LocalTime;

public class HelloWorld {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        LocalTime currentTime = new LocalTime();
        System.out.println("The current local time is: " + currentTime);

        System.out.println("Hello World");

    }

}
</code>```

Project structure:

project_structure

build_path_snap

build_path_details

build.gradle file:

```<code>apply plugin: 'java'
apply plugin: 'application'
mainClassName = 'com.padhu.test.HelloWorld'

repositories {

   flatDir {
      dirs 'lib'
   }
}

dependencies {

    compile files(fileTree(dir: 'lib', includes: ['*.jar']))

    }

jar {
  manifest {
    attributes(

      'Main-Class': 'com.padhu.test.HelloWorld'
    )
  }
}
</code>```

I can successfully execute gradle build in my cmd and jar file is getting generated.  But inside jar file, I can see only HelloWorld folder structure, but couldnt see the dependency files. So I am not able to run the jar from command prompt since I am getting NoClassDefFoundError: org/joda/time/LocalTime..

I tried fixing the issue myself by searching and reading blogs..but I am not able to run the jar successfully.

Kindly help me.

答:
It seems, you misunderstand, how does application plugin behave. It doesn't make a so-called fat-jar, which includes all it's dependencies, rather creates a jar and able to run it, adding all the dependencies to the classpath.

You can run your application as follows:

```<code>gradle run
</code>```

Or you can use the automatically applied distribution plugin and create a distribution of your project with scripts to start it and all the dependent libraries in separate folder. Just run it as:

```<code>gradle distZip
</code>```

You can read more about it in the official user guide.

Body:
I am new to gradle and learning now. I am trying to build a runnable jar using gradle(My builded jar should be run from command prompt). I just started with a simple HelloWorld project with a dependency and try to build it using gradle. I am not using maven. So I added the dependency jar to the lib folder inside project folder. Below are the details.

Gradle Version: 3.1
Eclipse Version: Neon

HelloWorld.java

package com.padhu.test;
import org.joda.time.LocalTime;

public class HelloWorld {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        LocalTime currentTime = new LocalTime();
        System.out.println("The current local time is: " + currentTime);

        System.out.println("Hello World");

    }

}

Project structure:

project_structure

build_path_snap

build_path_details

build.gradle file:

apply plugin: 'java'
apply plugin: 'application'
mainClassName = 'com.padhu.test.HelloWorld'

repositories {

   flatDir {
      dirs 'lib'
   }
}

dependencies {

    compile files(fileTree(dir: 'lib', includes: ['*.jar']))

    }

jar {
  manifest {
    attributes(

      'Main-Class': 'com.padhu.test.HelloWorld'
    )
  }
}

I can successfully execute gradle build in my cmd and jar file is getting generated.  But inside jar file, I can see only HelloWorld folder structure, but couldnt see the dependency files. So I am not able to run the jar from command prompt since I am getting NoClassDefFoundError: org/joda/time/LocalTime..

I tried fixing the issue myself by searching and reading blogs..but I am not able to run the jar successfully.

Kindly help me.

Body:
It seems, you misunderstand, how does application plugin behave. It doesn't make a so-called fat-jar, which includes all it's dependencies, rather creates a jar and able to run it, adding all the dependencies to the classpath.

You can run your application as follows:

gradle run

Or you can use the automatically applied distribution plugin and create a distribution of your project with scripts to start it and all the dependent libraries in separate folder. Just run it as:

gradle distZip

You can read more about it in the official user guide.


问:
Cron job schedule
I want to schedule cron job for my app to do a particular task. How can i schedule in this requirement?

Requirement:
cron-data.js should be run every Mondays to Fridays hourly from 9:30am - 3:30pm.

答:
```<code>30 09-15 * * 1-5 [Commad to Execute]
</code>```

30 : 30th Min

09-15 : 9AM to 3 PM

* :  Every day

* : Every Month

1-5 : Mon to Fri

Title: Cron job schedule

Body:
30 09-15 * * 1-5 [Commad to Execute]

30 : 30th Min

09-15 : 9AM to 3 PM

* :  Every day

* : Every Month

1-5 : Mon to Fri


问:
ERROR org.apache.zookeeper.ClientCnxn - Error while calling watcher
I am new to zookeeper. I have written simple program to create Persistent Node. Its working but giving exception once execution is completed.I tried to search on google but there is no satisfactory answer. Can any one advice me anything.</p>

```<code>public class ZkProg {
    public static void main(String[] args) throws IOException, KeeperException, InterruptedException
    {
        ZooKeeper zk=new ZooKeeper("localhost",1281, null);
        zk.create("/zookeeper/Names",new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        //zk.delete("/zookeeper/Names",-1);
        zk.close();
    }
}
</code>```

答:
If you don't want to watch events, you can write your own "StubWatcher".

Create a class that inherits from Watcher and implement the process method with empty body.

That should do it.

Body:
I am new to zookeeper. I have written simple program to create Persistent Node. Its working but giving exception once execution is completed.I tried to search on google but there is no satisfactory answer. Can any one advice me anything.

public class ZkProg {
    public static void main(String[] args) throws IOException, KeeperException, InterruptedException
    {
        ZooKeeper zk=new ZooKeeper("localhost",1281, null);
        zk.create("/zookeeper/Names",new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        //zk.delete("/zookeeper/Names",-1);
        zk.close();
    }
}


问:
Json with dynamic properties - deserialize into C# object
I have the following JSON when user clicks save

```<code>tasks      : {
        updated : [
            { Id : 123, SomeField1 : 'new value', SomeField2 : 'new value', SomeField3 : 'new value' },
            { Id : 125, SomeField2 : 'new value' },
            { Id : 127, SomeField1 : 'new value', SomeField4 : 'new value' },
            { Id : 129, SomeField2 : 'new value', SomeField3 : 'new value' },
            { ................ }
        ],
        removed : [
            { Id : 345 },
            { Id : 847 }
        ]
    }
</code>```

on the MVC server side (C#), I have a ViewModel and .NET deserializes this back to my viewmodel object.
in this example, This object has Id, SomeField1, SomeField2, SomeField3, SomeField4.

The problem I am having is that the client only sends the fields which were actually updated, so If the user never updated SomeField3 it wont be in the json and .NET for that array object will have a null as SomeeField3 ...

so i cant get record, update all the fields to what the viewmodel is and then call an update as it will set SomeField3 to null , which is not correct - there could be data in that field which the user just didn't touch in this case .. (in another case they may have deleted their text, which then the update would be valid..

I am not sure what is the best way to tackle this problem.
Looking forward to your suggestions.

答:
I suggest you to post updated string in API action, then you can get your solution as :
Create dynamic property mapping function :

```<code>    public static class DynamicToStatic
    {
     public static T ToStatic<T>(object source, T destination)
     {
        var entity = destination;

        //source implements dictionary
        var properties = source as IDictionary<string, object>;

        if (properties == null)
            return entity;

        foreach (var entry in properties)
        {
            var propertyInfo = entity.GetType().GetProperty(entry.Key);
            if (propertyInfo != null && entry.Value != null)//Check property and its values exist or not ,change only when source contains value
                propertyInfo.SetValue(entity, entry.Value, null);
        }
        return entity;
    }
 }
</code>```

Convert your request json to dynamic object and then map dynamic object to Your static class type model, Class type model initialized from your db record or any source as per your requirement.

```<code>//updatedJsonObjectString bound from request post data(JSONSTRINGIFY of post data)
dynamic source = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(updatedJsonObjectString);
Class1 model = new Class1();//mapped/filled by data call
var retUser = DynamicToStatic.ToStatic<Class1>(source, model);
</code>```

Body:
I have the following JSON when user clicks save

tasks      : {
        updated : [
            { Id : 123, SomeField1 : 'new value', SomeField2 : 'new value', SomeField3 : 'new value' },
            { Id : 125, SomeField2 : 'new value' },
            { Id : 127, SomeField1 : 'new value', SomeField4 : 'new value' },
            { Id : 129, SomeField2 : 'new value', SomeField3 : 'new value' },
            { ................ }
        ],
        removed : [
            { Id : 345 },
            { Id : 847 }
        ]
    }

on the MVC server side (C#), I have a ViewModel and .NET deserializes this back to my viewmodel object.
in this example, This object has Id, SomeField1, SomeField2, SomeField3, SomeField4.

The problem I am having is that the client only sends the fields which were actually updated, so If the user never updated SomeField3 it wont be in the json and .NET for that array object will have a null as SomeeField3 ...

so i cant get record, update all the fields to what the viewmodel is and then call an update as it will set SomeField3 to null , which is not correct - there could be data in that field which the user just didn't touch in this case .. (in another case they may have deleted their text, which then the update would be valid..

I am not sure what is the best way to tackle this problem.
Looking forward to your suggestions.

Body:
I suggest you to post updated string in API action, then you can get your solution as :
Create dynamic property mapping function :

    public static class DynamicToStatic
    {
     public static T ToStatic<T>(object source, T destination)
     {
        var entity = destination;

        //source implements dictionary
        var properties = source as IDictionary<string, object>;

        if (properties == null)
            return entity;

        foreach (var entry in properties)
        {
            var propertyInfo = entity.GetType().GetProperty(entry.Key);
            if (propertyInfo != null && entry.Value != null)//Check property and its values exist or not ,change only when source contains value
                propertyInfo.SetValue(entity, entry.Value, null);
        }
        return entity;
    }
 }

Convert your request json to dynamic object and then map dynamic object to Your static class type model, Class type model initialized from your db record or any source as per your requirement.

//updatedJsonObjectString bound from request post data(JSONSTRINGIFY of post data)
dynamic source = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(updatedJsonObjectString);
Class1 model = new Class1();//mapped/filled by data call
var retUser = DynamicToStatic.ToStatic<Class1>(source, model);


问:
How to resolve 404 Error for an AJAX call in Django
I am getting a 404 Error for an AJAX call in Django

Here's my code:
jQuery Script:

```<code>$('#cluster-id').change( function(){
        $.ajax({
            url: '/ajax_demo/',
            type: 'get',
            dataType: 'json',
            complete: function( jqXHR, textStatus ){
                console.log("complete " + textStatus);
            },
            success: function( data, jqXHR, textStatus ){
                console.log("success " + data);
            },
            error: function(jqXHR, textStatus, errorThrown ){

                console.log("error: " + errorThrown );
            }
        });
</code>```

I am trying to get the data( in json ) form this function:

```<code>from django.http import JsonResponse
def ajax_demo( request ):
    cluster = request.GET.get('cluster', None)
    data = {
        'name' : 'abc'
    }
return JsonResponse(data)
</code>```

I have set the url correctly too:

```<code>urlpatterns = [
    url( r'^$', views.main_page_demo, name = 'main_page_demo' ),
    url( r'^demo/', views.ajax_demo, name = 'ajax_demo'),

    ]
</code>```

I am new to AJAX and jQuery and i don't know what's the issue.

root url
```<code>urlpatterns =[

    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', include( 'app.urls', namespace = "mainPage")),
</code>```

答:
You have several obvious errors here.

Firstly, you are posting to /ajax_demo/, but you don't have that as a URL; only /demo/. You did either change the URL pattern or the URL you are posting to.

Secondly, you have included the app patterns wrongly; to must not use a terminal $ with include. It should be:

```<code>url(r'^$', include( 'app.urls', namespace = "mainPage")),
</code>```

Thirdly, you are not including any data with your request. You need a data key:

```<code>   $.ajax({
            url: '/demo/',
            type: 'get',
            data: {"cluster": "value"}
            ...
</code>```

Body:
I am getting a 404 Error for an AJAX call in Django

Here's my code:
jQuery Script:

$('#cluster-id').change( function(){
        $.ajax({
            url: '/ajax_demo/',
            type: 'get',
            dataType: 'json',
            complete: function( jqXHR, textStatus ){
                console.log("complete " + textStatus);
            },
            success: function( data, jqXHR, textStatus ){
                console.log("success " + data);
            },
            error: function(jqXHR, textStatus, errorThrown ){

                console.log("error: " + errorThrown );
            }
        });

I am trying to get the data( in json ) form this function:

from django.http import JsonResponse
def ajax_demo( request ):
    cluster = request.GET.get('cluster', None)
    data = {
        'name' : 'abc'
    }
return JsonResponse(data)

I have set the url correctly too:

urlpatterns = [
    url( r'^$', views.main_page_demo, name = 'main_page_demo' ),
    url( r'^demo/', views.ajax_demo, name = 'ajax_demo'),

    ]

I am new to AJAX and jQuery and i don't know what's the issue.

root url

urlpatterns =[

    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', include( 'app.urls', namespace = "mainPage")),

Body:
You have several obvious errors here.

Firstly, you are posting to /ajax_demo/, but you don't have that as a URL; only /demo/. You did either change the URL pattern or the URL you are posting to.

Secondly, you have included the app patterns wrongly; to must not use a terminal $ with include. It should be:

url(r'^$', include( 'app.urls', namespace = "mainPage")),

Thirdly, you are not including any data with your request. You need a data key:

   $.ajax({
            url: '/demo/',
            type: 'get',
            data: {"cluster": "value"}
            ...

ContentLicense: CC BY-SA 4.0


问:
check if an item in weblist is indented or not
I have list of items in a weblist and which has both parent and child.  Child is indented to the right,  I need to retrieve values of child and parent in two different columns in a datatable.

My code goes like this:

```<code>list = qtp_getroproperty(page.weblist(), "items count", itemsCount
For n = 1 To itemsCount
  items = page.weblist(), getitem(n)
</code>```

答:
In VBScript it's Left():</p>

```<code>>> For Each s In Array("x", " x", "  x")
>>     WScript.Echo s, CStr(" " = Left(s, 1))
>> Next
>>
x Falsch
 x Wahr
  x Wahr
>>
</code>```

Body:
I have list of items in a weblist and which has both parent and child.  Child is indented to the right,  I need to retrieve values of child and parent in two different columns in a datatable.

My code goes like this:

list = qtp_getroproperty(page.weblist(), "items count", itemsCount
For n = 1 To itemsCount
  items = page.weblist(), getitem(n)

Body:
In VBScript it's Left():

>> For Each s In Array("x", " x", "  x")
>>     WScript.Echo s, CStr(" " = Left(s, 1))
>> Next
>>
x Falsch
 x Wahr
  x Wahr
>>


问:
"Clickable" textblock?
I have a WP7 app where I would like to have a "clickable" TextBlock area, that when a user clicks on the TextBlock, it puts it into edit mode (a different control).
This would add another explicit step for a user before editing text.

There is no click event for the TextBlock (which doesn't surprise me).

Is there any way to do this?  Wrapped in another control, or something similar?

答:
It sounds like you just need a button. Change the control template to remove the border styling etc. and make your own (or clear the existing) visual states. Or even edit it so the 'depressed' state gives a little 3D projection.

Also, with a button, you can also use the Command on the button if you're using MVVM.

Luke

Title: "Clickable" textblock?

ContentLicense: CC BY-SA 2.5


问:
Git clone with preexisting public key
I have a requirement in which a script must be able to clone some git repositories using a preexisting public key (simply copying it to /home/user/.ssh).

What I am asking is if this is possible without the private key. HTTPS is not an option.

Any help is greatly appreciated.

答: No. You need a private key to authenticate to SSH (GIT). Other possibility is to use password.</p>

Title: Git clone with preexisting public key


问:
Between query in cakephp 3.3
THE QUERY IS WORKING

Want to write the query below by using cakephp 3.3

```<code>SELECT
</code>```

Books.id AS Books__id,
  Books.title AS Books__title,
  Books.for_min_age AS Books__for_min_age,
  Books.for_max_age AS Books__for_max_age,
  Books.for_min_grade AS Books__for_min_grade,
  Books.for_max_grade AS Books__for_max_grade
FROM
  books Books
WHERE
    4 BETWEEN Books.for_min_age AND Books.for_max_age
    OR
    2 BETWEEN Books.for_min_grade AND Books.for_max_grade

答:
I achieve this by -</p>

```<code> $this->find()->where([$age . ' BETWEEN Books.for_min_age AND Books.for_max_age OR ' . $grade . ' BETWEEN Books.for_min_grade AND Books.for_max_grade']);
</code>```

Title: Between query in cakephp 3.3

Body:
THE QUERY IS WORKING

Want to write the query below by using cakephp 3.3

SELECT

Books.id AS Books__id,
  Books.title AS Books__title,
  Books.for_min_age AS Books__for_min_age,
  Books.for_max_age AS Books__for_max_age,
  Books.for_min_grade AS Books__for_min_grade,
  Books.for_max_grade AS Books__for_max_grade
FROM
  books Books
WHERE
    4 BETWEEN Books.for_min_age AND Books.for_max_age
    OR
    2 BETWEEN Books.for_min_grade AND Books.for_max_grade

Body:
I achieve this by -

 $this->find()->where([$age . ' BETWEEN Books.for_min_age AND Books.for_max_age OR ' . $grade . ' BETWEEN Books.for_min_grade AND Books.for_max_grade']);


问:
Insert image path into database not working
I want to insert image path into database table so I can later display it on a different place but only thing that is getting inserted into the table is the folder name where pictures are uploaded into and the image name is missing.

Here is my code:

```<code><?php
require "connect.php";

if(isset($_GET['id']))
{
    $id = $_GET['id'];
}

$uploaddir = 'uploaded';
if(isset($_POST['submit']))
{
    $filename = $_FILES['image']['name'];
    $tmp = $_FILES['image']['tmp_name'];
    $filepath = $uploaddir . $filename;
    move_uploaded_file($tmp,$filepath);
    $filepath=addslashes($filepath);
    mysqli_query($conn,"UPDATE vijesti SET imeslike='$filepath' WHERE id='$id'");
    mysqli_close($conn);
}
?>
<div id="main">
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit" value="upload"/>
</form>
</div>
</code>```

Table column named imeslike is supposed to be updated with image path but it only shows uploaded/. It's like it does not accept variables when I put some random string in my query it gets updated and the string value shows up in the imeslike column.

The uploaded folder is in same directory so the relative path is OK and I also tried absolute path like:

```<code>$uploaddir="C:/wamp/www/admirovsajt/uploaded"
</code>```

But same problem.

答:
Try:</p>

```<code><?php
require "connect.php";

if(isset($_GET['id'])) {
  echo $id = $_GET['id'];
}

$uploaddir = 'uploaded/';

if(isset($_POST['submit'])) {
  $pid = $_POST['pid'];
  $filename = $_FILES['image']['name'];
  $tmp = $_FILES['image']['tmp_name'];
  $filepath = $uploaddir . $filename;
  move_uploaded_file($tmp,$filepath);
  $filepath=addslashes($filepath);
  mysqli_query($conn,"UPDATE vijesti SET imeslike='$filepath' WHERE id='$pid'");
  mysqli_close($conn);
}
?>
<div id="main">
  <form action="" method="post" enctype="multipart/form-data">
    <input type="text" name="pid" value="<?php echo $id;?>">
    <input type="file" name="image"/>
    <input name="submit" type="submit" value="upload"/>
  </form>
</div>
</code>```

Body:
I want to insert image path into database table so I can later display it on a different place but only thing that is getting inserted into the table is the folder name where pictures are uploaded into and the image name is missing.

Here is my code:

<?php
require "connect.php";

if(isset($_GET['id']))
{
    $id = $_GET['id'];
}

$uploaddir = 'uploaded';
if(isset($_POST['submit']))
{
    $filename = $_FILES['image']['name'];
    $tmp = $_FILES['image']['tmp_name'];
    $filepath = $uploaddir . $filename;
    move_uploaded_file($tmp,$filepath);
    $filepath=addslashes($filepath);
    mysqli_query($conn,"UPDATE vijesti SET imeslike='$filepath' WHERE id='$id'");
    mysqli_close($conn);
}
?>

<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit" value="upload"/>
</form>

Table column named imeslike is supposed to be updated with image path but it only shows uploaded/. It's like it does not accept variables when I put some random string in my query it gets updated and the string value shows up in the imeslike column.

The uploaded folder is in same directory so the relative path is OK and I also tried absolute path like:

$uploaddir="C:/wamp/www/admirovsajt/uploaded"

But same problem.

Body:
Try:

<?php
require "connect.php";

if(isset($_GET['id'])) {
  echo $id = $_GET['id'];
}

$uploaddir = 'uploaded/';

if(isset($_POST['submit'])) {
  $pid = $_POST['pid'];
  $filename = $_FILES['image']['name'];
  $tmp = $_FILES['image']['tmp_name'];
  $filepath = $uploaddir . $filename;
  move_uploaded_file($tmp,$filepath);
  $filepath=addslashes($filepath);
  mysqli_query($conn,"UPDATE vijesti SET imeslike='$filepath' WHERE id='$pid'");
  mysqli_close($conn);
}
?>
<div id="main">
  <form action="" method="post" enctype="multipart/form-data">
    <input type="text" name="pid" value="<?php echo $id;?>">
    <input type="file" name="image"/>
    <input name="submit" type="submit" value="upload"/>
  </form>
</div>


问:
Dynamic Height Issue for UITableView Cells (Swift)
Text data of variable length are being injected into tableview cell labels. In order for each cell height to be properly sized, I have implemented in viewDidLoad():

```<code>self.tableView.estimatedRowHeight = 88.0
self.tableView.rowHeight = UITableViewAutomaticDimension
</code>```

This estimates the height to be 88.0 pixels and should resize the height automatically if larger. It works perfectly for cells that have yet to be scrolled to (as UITableViewAutomaticDimention is called upon scrolling to the cell), but not for the cells that are initially rendered onscreen upon loading the table with data.

I have tried reloading the data (as suggested in many other resources):

```<code>self.tableView.reloadData()
</code>```

in both viewDidAppear() and viewWillAppear() and it did not help. I am lost.. does anyone know how to render the dynamic height for the cells loaded initially on screen?

答:
Dynamic sizing cell of UITableView required 2 things

Setting the the right constraint of your view inside the table view cell (mostly it includes giving your view proper top , bottom and traling constraints)

Calling these properties of TableView in viewDidLoad()

```<code> tableView.rowHeight = UITableViewAutomaticDimension

 tableView.estimatedRowHeight = 140
</code>```

This is a wonderfull tutorial on self-sizing (dynamic table view cells) written in swift 3 .

Body:
Text data of variable length are being injected into tableview cell labels. In order for each cell height to be properly sized, I have implemented in viewDidLoad():

self.tableView.estimatedRowHeight = 88.0
self.tableView.rowHeight = UITableViewAutomaticDimension

This estimates the height to be 88.0 pixels and should resize the height automatically if larger. It works perfectly for cells that have yet to be scrolled to (as UITableViewAutomaticDimention is called upon scrolling to the cell), but not for the cells that are initially rendered onscreen upon loading the table with data.

I have tried reloading the data (as suggested in many other resources):

self.tableView.reloadData()

in both viewDidAppear() and viewWillAppear() and it did not help. I am lost.. does anyone know how to render the dynamic height for the cells loaded initially on screen?

Body:
Dynamic sizing cell of UITableView required 2 things

Setting the the right constraint of your view inside the table view cell (mostly it includes giving your view proper top , bottom and traling constraints)

Calling these properties of TableView in viewDidLoad()

 tableView.rowHeight = UITableViewAutomaticDimension

 tableView.estimatedRowHeight = 140

This is a wonderfull tutorial on self-sizing (dynamic table view cells) written in swift 3 .


问:
selected and deselected checkbox in Swift
How to know my button selected or not in swift 3 .selected property  not found.

when i type checkBtn.selected not found in Swift 3 (Xcode 8.0)

```<code> if let button = sender as? UIButton {
        if button.selected {
            // set selected
            button.selected = true
        } else {
            // set deselected
            button.selected = false
        }
    }
</code>```

答: In swift 3 you will have isSelected instead of selected. Your code looks fine just make a change.

Body:
How to know my button selected or not in swift 3 .selected property  not found.

when i type checkBtn.selected not found in Swift 3 (Xcode 8.0)

 if let button = sender as? UIButton {
        if button.selected {
            // set selected
            button.selected = true
        } else {
            // set deselected
            button.selected = false
        }
    }


问:
Retrieve/process/show wikipedia page in IOS application
I am going to show a mobile version of wikipedia page in my app.

The easiest way is to use UIWebView to show mobile view page, e.g. https://en.m.wikipedia.org/w/index.php?title=White_House

However I want to make certain changes to the page:

Remove the search bar.

remove all external links in the page.

while keep all format/image/layout unchanged.

I did some search. Seems I have to retrieve all contents in json with wikipedia API and reformat everything by myself.

Any easier way?

答:
You can load the HTML, make "Find and replace" and remove whatever you want. (Modify the HTML itself.
After that you can load the HTML into the UIWebView.

Note: This might break when wikipedia will change it's webpage structure...


问:
Best way to multi-thread?
What is the best way to multi-thread in the C language? I want something that is very efficient and not a CPU hog. Thanks.</p>

答:
The correct (standard) way to do this on C and Windows is with __beginthreadex.

This is usually preferred to calling CreateThread directly as CreateThread doesn't init C runtime support for the thread. So if you create a thread using CreateThread, and call a CRT function, bad stuff can/will happen.

Note that __beginthreadex calls CreateThread internally, but performs some other work behind the scenes.

OwnerDisplayName: Sasayins

Title: Best way to multi-thread?

LastEditorDisplayName: John


答:
try this below code

```<code>if let button = sender as? UIButton {
        if button.isSelected {
            // set selected
            button.isSelected = true
        } else {
            // set deselected
            button.isSelected = false
        }
    }
</code>```

For shorthand, try this

```<code>if let button = sender as? UIButton {
     button.isSelected = !button.isSelected
}
</code>```

Title: selected and deselected checkbox in Swift

Body:
try this below code

if let button = sender as? UIButton {
        if button.isSelected {
            // set selected
            button.isSelected = true
        } else {
            // set deselected
            button.isSelected = false
        }
    }

For shorthand, try this

if let button = sender as? UIButton {
     button.isSelected = !button.isSelected
}


问:
PHP search filter function doesn't work
I created search filter function in php form. Fetched data from mysql in table. All query and others written well. But search function doesn't work.

```<code><?php
    require_once 'init.php';
    include 'header.php';
    include 'navigation.php';

    if(isset($_POST['search'])){
      $valSearch = $_POST['searchButton'];
      $query = "SELECT * FROM mainTable WHERE CONCAT ('id','commandName','commandDesc','status') LIKE '%".$valSearch."%'";
      $featured = filterTable($query);
    }else{
      $query = "SELECT * FROM mainTable";
      $featured = filterTable($query);
    }

    function filterTable($query){
      $connect = mysqli_connect("localhost","root","","linuxcommanddictionary");
      $filter_result = mysqli_query($connect,$query);
      return $filter_result;
    }

 ?>
 <form action = "index.php" method="post">
    <div class="container">
      <h3>Linux Fedora OS</h3><hr>
        <button type="submit" name ="searchButton" class="btn btn-default"><span class="glyphicon glyphicon-search"></span></button>
        <input type="text" name = "search" class="form-control" placeholder="Хайх үгээ бичнэ үү">
        <div class="col-md-12">
            <div class="row">
                <table class="table table-bordered">
                    <thead>
                        <th>ID</th>
                        <th>Command Name</th>
                        <th>Command Description</th>
                        <th>Status</th>
                    </thead>
                    <tbody>
                      <?php while($result = mysqli_fetch_assoc($featured)): ?>
                      <tr>
                          <td><?=$result['id']; ?></td>
                          <td><?=$result['commandName']; ?></td>
                          <td><?=$result['commandDesc']; ?></td>
                          <td><?=$result['status']; ?></td>
                      </tr>
                      <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</form>
<?php
    include 'footer.php';
 ?>
 </body>
 </html>
</code>```

Here is Database structure.

```<code>create table if not exists mainTable(
   id int auto_increment,
   commandName varchar(255),
   commandDesc varchar(255),
   status int(2),
   primary key(id)
)
</code>```

答:
As mentioned in the comments, you are calling the mysqli connection inside a function and then ask for mysqli_fetch_assoc() outside of the 'Scope' of the function.

learn scope http://php.net/manual/en/language.variables.scope.php

You can
-Move your while loop inside your function and return an 'copy' of the array ( memory suck up).
-or-
Create you connector in the global scope and call 'global' in your function to fetch the data (cpu suck up) -or- move everything all tohether in the global scope.

Title: PHP search filter function doesn't work

Body:
I created search filter function in php form. Fetched data from mysql in table. All query and others written well. But search function doesn't work.

<?php
    require_once 'init.php';
    include 'header.php';
    include 'navigation.php';

    if(isset($_POST['search'])){
      $valSearch = $_POST['searchButton'];
      $query = "SELECT * FROM mainTable WHERE CONCAT ('id','commandName','commandDesc','status') LIKE '%".$valSearch."%'";
      $featured = filterTable($query);
    }else{
      $query = "SELECT * FROM mainTable";
      $featured = filterTable($query);
    }

    function filterTable($query){
      $connect = mysqli_connect("localhost","root","","linuxcommanddictionary");
      $filter_result = mysqli_query($connect,$query);
      return $filter_result;
    }

 ?>
 <form action = "index.php" method="post">

Linux Fedora OS

        <button type="submit" name ="searchButton" class="btn btn-default"></button>
        <input type="text" name = "search" class="form-control" placeholder="Хайх үгээ бичнэ үү">

                        ID
                        Command Name
                        Command Description
                        Status

                      <?php while($result = mysqli_fetch_assoc($featured)): ?>

                          <?=$result['id']; ?>
                          <?=$result['commandName']; ?>
                          <?=$result['commandDesc']; ?>
                          <?=$result['status']; ?>

                      <?php endwhile; ?>

</form>
<?php
    include 'footer.php';
 ?>

Here is Database structure.

create table if not exists mainTable(
   id int auto_increment,
   commandName varchar(255),
   commandDesc varchar(255),
   status int(2),
   primary key(id)
)


问:
Download most recent file from Firebase Storage
I want to know if there is a way to download the most recent file from Firebase Storage (to my Android app)? There is a way to download the file if you know the name:

```<code>storageRef.child("users/me/profile.png").getBytes(Long.MAX_VALUE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
    @Override
    public void onSuccess(byte[] bytes) {
        // Use the bytes to display the image
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception exception) {
        // Handle any errors
    }
});
</code>```

The idea is to upload a local image using a python script, issue a push notification through Firebase Notifications (already done), and download the newest image after receiving the notification.

答: Cloud Storage for Firebase does not have a concept of "most recently uploaded file".  You will need some other source of metadata that records and describes what you're trying to do.  For Firebase apps, this would typically be some data in Firebase Realtime Database that you can query.  The client that uploads the file needs to also update the database to indicate what it has done.</p>

Body:
I want to know if there is a way to download the most recent file from Firebase Storage (to my Android app)? There is a way to download the file if you know the name:

storageRef.child("users/me/profile.png").getBytes(Long.MAX_VALUE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
    @Override
    public void onSuccess(byte[] bytes) {
        // Use the bytes to display the image
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception exception) {
        // Handle any errors
    }
});

The idea is to upload a local image using a python script, issue a push notification through Firebase Notifications (already done), and download the newest image after receiving the notification.


问:
Laravel: How to insert multi select2 dropdown selected data to mysql database?
I am trying to insert data into database. But i don't know how to insert multi select data into the mysql database.</p>

答:
You have to to iterate through the multi select array then save one by one.</p>

```<code>foreach ($_POST['your_key'] as $selectedOption) {
   // save $selectedOption to database
}
</code>```

Body:
You have to to iterate through the multi select array then save one by one.

foreach ($_POST['your_key'] as $selectedOption) {
   // save $selectedOption to database
}


问:
JSON error org.json.JSONException: No value for item
After tweaking JSON response a bit the error has changed to W/System.err: org.json.JSONException: No value for retCode.

The complete error:

```<code>04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err: org.json.JSONException: No value for retCode
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at org.json.JSONObject.get(JSONObject.java:389)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at org.json.JSONObject.getString(JSONObject.java:550)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at com.allianz.azemployee.ActivityRegister$2.serviceResult(ActivityRegister.java:194)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at com.allianz.azemployee.Net$1$1.run(Net.java:420)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at android.os.Looper.loop(Looper.java:148)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
04-03 12:53:26.703 14366-14454/com.allianz.azemployee V/RenderScript: 0x9d789000 Launching thread(s), CPUs 4
</code>```

This my ActivityRegister.java class:

```<code>public class ActivityRegister extends AppCompatActivity implements View.OnClickListener {

    Button btnRequestPin, btnConfirm, btnRequestNewPin;
    EditText editTextEmail;
    EditText editTextPin;

    private static final String FIRST_START_KEY = "first_start";
    private static final boolean ALWAYS_SEND_FIRST_START_BROADCAST = false;

    private String emailTemp, tokenTemp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        btnRequestPin = (Button)findViewById(R.id.btn_request_pin);
        btnConfirm = (Button)findViewById(R.id.btn_confirm);
        btnRequestNewPin = (Button)findViewById(R.id.btn_request_newpin);
        editTextEmail = (EditText) findViewById(R.id.editText_mail);
        editTextPin = (EditText) findViewById(R.id.editText_pin);

        btnRequestPin.setOnClickListener(this);
        btnConfirm.setOnClickListener(this);
        btnRequestNewPin.setOnClickListener(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
        Intent intent = new Intent(this,ActivityLogin.class);
        this.startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        if(v == btnConfirm){

            final String email = editTextEmail.getText().toString();
            final String token = editTextPin.getText().toString();

            if (email == null || email.length() == 0){
                Toast.makeText(this,"Email required",Toast.LENGTH_SHORT).show();
                return;
            }

            if (token == null || token.length() == 0){
                Toast.makeText(this,"OTP required",Toast.LENGTH_SHORT).show();
                return;
            }

            //Check if email is valid
            if(!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()){
                Toast.makeText(this,"Valid email required.",Toast.LENGTH_SHORT).show();
                return;
            }

            String postBody = Net.getInstance().getJSONForRegister(email,token);
            Net.getInstance().callServiceWithURLPart(this, Net.kURLPartEmpAuthentication, postBody, new Net.ICallServiceResult() {
                @Override
                public void serviceResult(String urlPart, boolean expected, String errorMsg) {

                    if(!expected){

                        if(errorMsg!=null){
                            Net.fastToast(ActivityRegister.this,"Unable to register. Try again.\n\n"+errorMsg);
                        }
                        else {
                            Net.fastToast(ActivityRegister.this,"Unable to register. Try again.");
                        }
                    }
                    else {
                        try {
                            JSONObject jsonObject = new JSONObject(errorMsg);

                            String retCode = jsonObject.getString("retCode");
                            String status = jsonObject.getString("status");

                            int retCodeInt = Integer.parseInt(retCode);
                            Net.fastToast(ActivityRegister.this,status);

                            if (retCodeInt==0) { //Registration success

                                //Store user-email and token
                                Net.getInstance().saveUserWithValues(ActivityRegister.this, email, token, "");
                                //Take user to login screen.
                                ActivityRegister.this.finish();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Net.fastToast(ActivityRegister.this,"Unable to get valid response for registration. Try again.");
                        }
                    }
                }
            });
        }
        if(v == btnRequestPin || v == btnRequestNewPin){

            final String email = editTextEmail.getText().toString();

            if (email == null || email.length() == 0){
                Toast.makeText(this,"Email required",Toast.LENGTH_SHORT).show();
                return;
            }

            //Check if email is valid
            if(!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()){
                Toast.makeText(this,"Valid email required.",Toast.LENGTH_SHORT).show();
                return;
            }

            final Button button = (Button) v;
            String postBody = Net.getInstance().getJSONForPinGeneration(email);
            Net.getInstance().callServiceWithURLPart(this, Net.kURLPartEmpAuthentication, postBody, new Net.ICallServiceResult() {
                @Override
                public void serviceResult(String urlPart, boolean expected, String errorMsg) {

                    if(!expected){
                        Log.i("Aditi","errorMsg== " +errorMsg);
                        if(errorMsg!=null){
                            Net.fastToast(ActivityRegister.this,"Unable to generate pin. Try again.\n\n"+errorMsg);
                        }
                        else {
                            Net.fastToast(ActivityRegister.this,"Unable to generate pin. Try again.");
                        }
                    }
                    else {
                        try {
                            JSONObject jsonObject = new JSONObject(errorMsg);

                            String retCode = jsonObject.getString("retCode");
                            String status = jsonObject.getString("status");

                            Log.i("Aditi","retCode===" + retCode + " ,status== "+status);
                            Log.i("Aditi","errorMsg== " +errorMsg);

                            int retCodeInt = Integer.parseInt(retCode);
                            Net.fastToast(ActivityRegister.this,status);

                            if(retCodeInt == 0 && button == btnRequestNewPin){

                                ActivityRegister.this.finish(); //take user to login on success.
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                            Net.fastToast(ActivityRegister.this,"Unable to get valid response for pin generation. Try again.");
                        }
                    }

                }
            });
        }
    }
}
</code>```

This is the stringResponse I'm giving:

```<code>public void callServiceWithURLPart(final Activity activity, final String urlPart, final String postBody, final ICallServiceResult callServiceResult){

        final ProgressDialog progress = new ProgressDialog(activity);
        progress.setTitle("Processing..");
        progress.setProgressStyle(android.R.attr.progressBarStyleSmall);
        //progress.setMessage("Connecting...");
        progress.show();

        ConnectivityManager connMgr = (ConnectivityManager)
                activity.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {

            Runnable r = new Runnable() {
                @Override
                public void run() {

                    OkHttpClient client = new OkHttpClient.Builder().connectTimeout(60, TimeUnit.SECONDS).build();

                    try{

                        String servicePath = kURLBase + urlPart;

                        Log.d("OkHttpClient","servicePath = "+servicePath);
                        Log.d("postBody",postBody);

                        Request request = new Request.Builder()
                                .url(servicePath)
                                .put(RequestBody.create(MEDIA_TYPE_JSON, postBody))
                                .build();

                        final Response response = client.newCall(request).execute();
                        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

                        //final String stringResponse = response.body().string();

                        final String stringResponse = "{'serviceName': 'registerToken', 'emailID': '', 'token': ''}";

                        if(stringResponse!=null){
                            Log.d("ServiceResponseString",stringResponse);
                        }else {
                            Log.d("ServiceResponseString","null");
                        }

                        if(callServiceResult!=null){
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    progress.dismiss();
                                    if(stringResponse!=null){
                                        callServiceResult.serviceResult(urlPart,true,stringResponse);
                                    }
                                    else {
                                        callServiceResult.serviceResult(urlPart,false,stringResponse);
                                    }
                                }
                            });
                        }
                    } catch (Exception e){

                        Log.d("OkHttpClient exception",e.toString());
                        final Exception _e = e;
                        if(callServiceResult!=null){
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    progress.dismiss();
           callServiceResult.serviceResult(urlPart,false,_e.toString());
                                }
                            });
                        }
                    }
                }
            };
            Thread t = new Thread(r);
            t.start();
        } else {
            progress.dismiss();
            fastToast(activity,"Connect to internet and try again.");
        }
    }
</code>```

My base URL is: public static final String kURLBase = "https://api-test.allianz.com/digithonempwebservice/rest"; which is being provided when stringResponse is asked.
Any help would be appreciated.

答: There is no retCode in your JSON

Body:
After tweaking JSON response a bit the error has changed to W/System.err: org.json.JSONException: No value for retCode.

The complete error:

04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err: org.json.JSONException: No value for retCode
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at org.json.JSONObject.get(JSONObject.java:389)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at org.json.JSONObject.getString(JSONObject.java:550)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at com.allianz.azemployee.ActivityRegister$2.serviceResult(ActivityRegister.java:194)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at com.allianz.azemployee.Net$1$1.run(Net.java:420)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at android.os.Looper.loop(Looper.java:148)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
04-03 12:53:26.703 14366-14454/com.allianz.azemployee V/RenderScript: 0x9d789000 Launching thread(s), CPUs 4

This my ActivityRegister.java class:

public class ActivityRegister extends AppCompatActivity implements View.OnClickListener {

    Button btnRequestPin, btnConfirm, btnRequestNewPin;
    EditText editTextEmail;
    EditText editTextPin;

    private static final String FIRST_START_KEY = "first_start";
    private static final boolean ALWAYS_SEND_FIRST_START_BROADCAST = false;

    private String emailTemp, tokenTemp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        btnRequestPin = (Button)findViewById(R.id.btn_request_pin);
        btnConfirm = (Button)findViewById(R.id.btn_confirm);
        btnRequestNewPin = (Button)findViewById(R.id.btn_request_newpin);
        editTextEmail = (EditText) findViewById(R.id.editText_mail);
        editTextPin = (EditText) findViewById(R.id.editText_pin);

        btnRequestPin.setOnClickListener(this);
        btnConfirm.setOnClickListener(this);
        btnRequestNewPin.setOnClickListener(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
        Intent intent = new Intent(this,ActivityLogin.class);
        this.startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        if(v == btnConfirm){

            final String email = editTextEmail.getText().toString();
            final String token = editTextPin.getText().toString();

            if (email == null || email.length() == 0){
                Toast.makeText(this,"Email required",Toast.LENGTH_SHORT).show();
                return;
            }

            if (token == null || token.length() == 0){
                Toast.makeText(this,"OTP required",Toast.LENGTH_SHORT).show();
                return;
            }

            //Check if email is valid
            if(!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()){
                Toast.makeText(this,"Valid email required.",Toast.LENGTH_SHORT).show();
                return;
            }

            String postBody = Net.getInstance().getJSONForRegister(email,token);
            Net.getInstance().callServiceWithURLPart(this, Net.kURLPartEmpAuthentication, postBody, new Net.ICallServiceResult() {
                @Override
                public void serviceResult(String urlPart, boolean expected, String errorMsg) {

                    if(!expected){

                        if(errorMsg!=null){
                            Net.fastToast(ActivityRegister.this,"Unable to register. Try again.\n\n"+errorMsg);
                        }
                        else {
                            Net.fastToast(ActivityRegister.this,"Unable to register. Try again.");
                        }
                    }
                    else {
                        try {
                            JSONObject jsonObject = new JSONObject(errorMsg);

                            String retCode = jsonObject.getString("retCode");
                            String status = jsonObject.getString("status");

                            int retCodeInt = Integer.parseInt(retCode);
                            Net.fastToast(ActivityRegister.this,status);

                            if (retCodeInt==0) { //Registration success

                                //Store user-email and token
                                Net.getInstance().saveUserWithValues(ActivityRegister.this, email, token, "");
                                //Take user to login screen.
                                ActivityRegister.this.finish();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Net.fastToast(ActivityRegister.this,"Unable to get valid response for registration. Try again.");
                        }
                    }
                }
            });
        }
        if(v == btnRequestPin || v == btnRequestNewPin){

            final String email = editTextEmail.getText().toString();

            if (email == null || email.length() == 0){
                Toast.makeText(this,"Email required",Toast.LENGTH_SHORT).show();
                return;
            }

            //Check if email is valid
            if(!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()){
                Toast.makeText(this,"Valid email required.",Toast.LENGTH_SHORT).show();
                return;
            }

            final Button button = (Button) v;
            String postBody = Net.getInstance().getJSONForPinGeneration(email);
            Net.getInstance().callServiceWithURLPart(this, Net.kURLPartEmpAuthentication, postBody, new Net.ICallServiceResult() {
                @Override
                public void serviceResult(String urlPart, boolean expected, String errorMsg) {

                    if(!expected){
                        Log.i("Aditi","errorMsg== " +errorMsg);
                        if(errorMsg!=null){
                            Net.fastToast(ActivityRegister.this,"Unable to generate pin. Try again.\n\n"+errorMsg);
                        }
                        else {
                            Net.fastToast(ActivityRegister.this,"Unable to generate pin. Try again.");
                        }
                    }
                    else {
                        try {
                            JSONObject jsonObject = new JSONObject(errorMsg);

                            String retCode = jsonObject.getString("retCode");
                            String status = jsonObject.getString("status");

                            Log.i("Aditi","retCode===" + retCode + " ,status== "+status);
                            Log.i("Aditi","errorMsg== " +errorMsg);

                            int retCodeInt = Integer.parseInt(retCode);
                            Net.fastToast(ActivityRegister.this,status);

                            if(retCodeInt == 0 && button == btnRequestNewPin){

                                ActivityRegister.this.finish(); //take user to login on success.
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                            Net.fastToast(ActivityRegister.this,"Unable to get valid response for pin generation. Try again.");
                        }
                    }

                }
            });
        }
    }
}

This is the stringResponse I'm giving:

public void callServiceWithURLPart(final Activity activity, final String urlPart, final String postBody, final ICallServiceResult callServiceResult){

        final ProgressDialog progress = new ProgressDialog(activity);
        progress.setTitle("Processing..");
        progress.setProgressStyle(android.R.attr.progressBarStyleSmall);
        //progress.setMessage("Connecting...");
        progress.show();

        ConnectivityManager connMgr = (ConnectivityManager)
                activity.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {

            Runnable r = new Runnable() {
                @Override
                public void run() {

                    OkHttpClient client = new OkHttpClient.Builder().connectTimeout(60, TimeUnit.SECONDS).build();

                    try{

                        String servicePath = kURLBase + urlPart;

                        Log.d("OkHttpClient","servicePath = "+servicePath);
                        Log.d("postBody",postBody);

                        Request request = new Request.Builder()
                                .url(servicePath)
                                .put(RequestBody.create(MEDIA_TYPE_JSON, postBody))
                                .build();

                        final Response response = client.newCall(request).execute();
                        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

                        //final String stringResponse = response.body().string();

                        final String stringResponse = "{'serviceName': 'registerToken', 'emailID': '', 'token': ''}";

                        if(stringResponse!=null){
                            Log.d("ServiceResponseString",stringResponse);
                        }else {
                            Log.d("ServiceResponseString","null");
                        }

                        if(callServiceResult!=null){
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    progress.dismiss();
                                    if(stringResponse!=null){
                                        callServiceResult.serviceResult(urlPart,true,stringResponse);
                                    }
                                    else {
                                        callServiceResult.serviceResult(urlPart,false,stringResponse);
                                    }
                                }
                            });
                        }
                    } catch (Exception e){

                        Log.d("OkHttpClient exception",e.toString());
                        final Exception _e = e;
                        if(callServiceResult!=null){
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    progress.dismiss();
           callServiceResult.serviceResult(urlPart,false,_e.toString());
                                }
                            });
                        }
                    }
                }
            };
            Thread t = new Thread(r);
            t.start();
        } else {
            progress.dismiss();
            fastToast(activity,"Connect to internet and try again.");
        }
    }

My base URL is: public static final String kURLBase = "https://api-test.allianz.com/digithonempwebservice/rest"; which is being provided when stringResponse is asked.
Any help would be appreciated.

Body: There is no retCode in your JSON