问:
Weird problem with Android/Java method. Control seems to jump across if/else block
In the following Android sample, I have a set of JSON objects(referred to as templates) and I'm doing a sort of inheritance processing on them. If a JSON object has a key "extends", the corresponding value will refer to another JSON object. I just copy the mappings in the referred JSON object to the current one. Each property (referred to as component in the code) will have sub properties, so each sub property is copied individually.
All the JSON objects are stored in a HashMap.
EDIT: Posting sample code which demonstrates the issue.

```<code>package com.trial;

import java.util.HashMap;
import java.util.Iterator;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;

public class Trial extends Activity {

    HashMap<String, JSONObject> templates = new HashMap<String, JSONObject>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        try {
            templates.put("entity", new JSONObject("{\"Health\":{\"health\":50,\"maxHealth\":100}}"));
            templates.put("unit", new JSONObject("{\"Health\":{\"health\":70},\"extends\":\"entity\"}"));
            Iterator<String> templatesIterator = templates.keySet().iterator();
            while (templatesIterator.hasNext()) {
                String templateName = templatesIterator.next();
                JSONObject template = templates.get(templateName);
                if (template.has("extends"))
                    templates.put(templateName, processInheritance(template));
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private JSONObject processInheritance(JSONObject template) throws JSONException {
        if (template.has("extends")) {
            //If current template extends from another template
            String parentTemplateName = template.getString("extends");
            template.remove("extends");
            JSONObject parentTemplate = processInheritance(templates.get(parentTemplateName));
            //Create a clone of the parent to which child properties/components can be added
            JSONObject processedTemplate = new JSONObject(parentTemplate.toString());
            Iterator<String> it = template.keys();
            while (it.hasNext()) {
                String componentName = it.next();
                if (processedTemplate.has(componentName)) {
                    //Component is already present. Loop through Component properties and make
                    //specific replacements
                    JSONObject componentData = template.getJSONObject(componentName);
                    Iterator<String> it2 = componentData.keys();
                    JSONObject processedComponentData = processedTemplate.getJSONObject(componentName);
                    while (it2.hasNext()) {
                        String propertyName = it2.next();
                        processedComponentData.put(propertyName, componentData.get(propertyName));
                    }
                    processedTemplate.put(componentName, processedComponentData);
                } else {
                    //Component is not already present. Simply copy
                    processedTemplate.put(componentName, template.get(componentName));
                }
            }
            return processedTemplate;
        } else {
            return template;
        }
    }
}
</code>```

On debugging I noticed that the code executes fine until after the while loop. Soon after the while loop, it jumps across the if/else and returns "template" instead of "processedTemplate". Even the resulting object indicates that "template" is being returned. I've tried clearing the binaries, recreating the emulator, and executing it on the actual device. The weird behavior persists. Could you someone tell me why this happens?

EDIT: The correct object IS being returned. My earlier comment that "template" was being returned was because of a bug where I was not saving the returned process object back into the HashMap.
I was simply doing

```<code>if (template.has("extends"))
    processInheritance(template));
</code>```

However the control still seems to jump across. An problem with Eclipse, I suppose.

答:
This happens because you will processInheritance of all objects, until you get the root one. (The one that doesn't have an "extends" value.)

Hence, the first return that you find is the one in the else branch.

Repeating my explanation:

Here is your striped-down code:

```<code>private JSONObject processInheritance(JSONObject template) throws AssetLoadingException {
        try {
            if (template.has("extends")) {

                JSONObject parentTemplate = processInheritance(templates.get(parentTemplateName));

                }
                return processedTemplate;
            } else {
                return template;
            }
        } catch (JSONException ex) {
            throw new AssetLoadingException(ex);
        }
    }
</code>```

If you've got the sequence ROOT <- C <- B <- A (where B extends A and so-on) and start evaluating A, this is what will happen:

process A

A is extending B (has "extends"), so process B

B is extending C, so process C

C is extending ROOT, so process ROOT

ROOT extends nothing so enter the else and return template.

(then there will be a sequence of returns after finishing processing C, B and A)

Body:
In the following Android sample, I have a set of JSON objects(referred to as templates) and I'm doing a sort of inheritance processing on them. If a JSON object has a key "extends", the corresponding value will refer to another JSON object. I just copy the mappings in the referred JSON object to the current one. Each property (referred to as component in the code) will have sub properties, so each sub property is copied individually.
All the JSON objects are stored in a HashMap.
EDIT: Posting sample code which demonstrates the issue.

package com.trial;

import java.util.HashMap;
import java.util.Iterator;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;

public class Trial extends Activity {

    HashMap<String, JSONObject> templates = new HashMap<String, JSONObject>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        try {
            templates.put("entity", new JSONObject("{\"Health\":{\"health\":50,\"maxHealth\":100}}"));
            templates.put("unit", new JSONObject("{\"Health\":{\"health\":70},\"extends\":\"entity\"}"));
            Iterator<String> templatesIterator = templates.keySet().iterator();
            while (templatesIterator.hasNext()) {
                String templateName = templatesIterator.next();
                JSONObject template = templates.get(templateName);
                if (template.has("extends"))
                    templates.put(templateName, processInheritance(template));
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private JSONObject processInheritance(JSONObject template) throws JSONException {
        if (template.has("extends")) {
            //If current template extends from another template
            String parentTemplateName = template.getString("extends");
            template.remove("extends");
            JSONObject parentTemplate = processInheritance(templates.get(parentTemplateName));
            //Create a clone of the parent to which child properties/components can be added
            JSONObject processedTemplate = new JSONObject(parentTemplate.toString());
            Iterator<String> it = template.keys();
            while (it.hasNext()) {
                String componentName = it.next();
                if (processedTemplate.has(componentName)) {
                    //Component is already present. Loop through Component properties and make
                    //specific replacements
                    JSONObject componentData = template.getJSONObject(componentName);
                    Iterator<String> it2 = componentData.keys();
                    JSONObject processedComponentData = processedTemplate.getJSONObject(componentName);
                    while (it2.hasNext()) {
                        String propertyName = it2.next();
                        processedComponentData.put(propertyName, componentData.get(propertyName));
                    }
                    processedTemplate.put(componentName, processedComponentData);
                } else {
                    //Component is not already present. Simply copy
                    processedTemplate.put(componentName, template.get(componentName));
                }
            }
            return processedTemplate;
        } else {
            return template;
        }
    }
}

On debugging I noticed that the code executes fine until after the while loop. Soon after the while loop, it jumps across the if/else and returns "template" instead of "processedTemplate". Even the resulting object indicates that "template" is being returned. I've tried clearing the binaries, recreating the emulator, and executing it on the actual device. The weird behavior persists. Could you someone tell me why this happens?

EDIT: The correct object IS being returned. My earlier comment that "template" was being returned was because of a bug where I was not saving the returned process object back into the HashMap.
I was simply doing

if (template.has("extends"))
    processInheritance(template));

However the control still seems to jump across. An problem with Eclipse, I suppose.

Body:
This happens because you will processInheritance of all objects, until you get the root one. (The one that doesn't have an "extends" value.)

Hence, the first return that you find is the one in the else branch.

Repeating my explanation:

Here is your striped-down code:

private JSONObject processInheritance(JSONObject template) throws AssetLoadingException {
        try {
            if (template.has("extends")) {

                JSONObject parentTemplate = processInheritance(templates.get(parentTemplateName));

                }
                return processedTemplate;
            } else {
                return template;
            }
        } catch (JSONException ex) {
            throw new AssetLoadingException(ex);
        }
    }

If you've got the sequence ROOT <- C <- B <- A (where B extends A and so-on) and start evaluating A, this is what will happen:

process A

A is extending B (has "extends"), so process B

B is extending C, so process C

C is extending ROOT, so process ROOT

ROOT extends nothing so enter the else and return template.

(then there will be a sequence of returns after finishing processing C, B and A)


来源: stackexchange

问:
How to Get Historical Data from Instagram API
I'm making an Instagram analytics web app.  I've carefully read all of the Instagram API endpoints and I can't find any way to get historical data (ie, followers over time).  All I would need would be something like a date followed, attached to each follower object.

However, there are Instagram analytics sites that offer this, for example, minter.io.

https://minter.io/faq#faq-posting-1

From link above:   "Minter.io provides full historical data on Instagram accounts and hashtags except for:
Accounts – List of Lost Followers
Hashtags – Reach and Exposure
In these reports the data will only be available from the date the report is first generated."

An example of this historical data, from minter.io report on my account:

At this point, I think that either:

Minter has some special arrangement with Instagram to get additional data that otherwise isn't provided through API.

I'm missing something..

I understand how this could be done by comparing user data to previous reports (like this SO question asked) but clearly Minter is doing it some other way, because that report was generated from the very first time I created a trial account with them.

Any help would be much appreciated.

答:
Now Facebook graph API has released the Instagram Insights API which returns detailed insights of Instagram Business accounts.

https://developers.facebook.com/docs/instagram-api/reference/user#insights

Above is for user insights, which has follower count. there are many media insights as well now available under graph API.

Details on how to consume this API is captured in the answer at: How to access Instagram feed of any user with new Graph API?

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
Difference between Flask abort() or returning a status
What is the difference between abort(400) and returning a response with a 400 status? Is using return bad form for errors?

```<code>abort(400, "some error message")
# or
return {'message': "some error message"}, 400
</code>```

答: abort raises an error, which an error handler will convert to a response. return returns a response, error handlers don't trigger. It's up to how you want your application to flow.

Body:
What is the difference between abort(400) and returning a response with a 400 status? Is using return bad form for errors?

abort(400, "some error message")
# or
return {'message': "some error message"}, 400


问:
Error Creating a Maven Project
I'm trying to create a maven project by following this tutorial https://docs.mulesoft.com/mule-user-guide/v/3.7/building-a-mule-application-with-maven-in-studio that time that time when Studio builds the Maven Project automatically, I get this error : updating maven project has encountered a problem There was an error running the studio:studio goal on project test and in the console:

```<code>[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR]   The project com.mycompany:test:1.0.0-SNAPSHOT (C:\Users\Rajeun\AnypointStudio\workspace\test\pom.xml) has 2 errors
[ERROR]     Unresolveable build extension: Plugin org.mule.tools.maven:mule-app-maven-plugin:1.1 or one of its dependencies could not be resolved: Could not find artifact com.sun:tools:jar:1.5.0 at specified path C:\Program Files (x86)\Java\jre1.8.0_40/../lib/tools.jar -> [Help 2]
[ERROR]     Unknown packaging: mule @ line 8, column 16
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException
[ERROR] [Help 2] http://cwiki.apache.org/confluence/display/MAVEN/PluginManagerException
</code>```

答:
I have faced same issue and got resolved by changing the JRE to JDK in preferences and restarted the any point studio.
This resolved the issue to me.</p>

Title: Error Creating a Maven Project

Body:
I'm trying to create a maven project by following this tutorial https://docs.mulesoft.com/mule-user-guide/v/3.7/building-a-mule-application-with-maven-in-studio that time that time when Studio builds the Maven Project automatically, I get this error : updating maven project has encountered a problem There was an error running the studio:studio goal on project test and in the console:

[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR]   The project com.mycompany:test:1.0.0-SNAPSHOT (C:\Users\Rajeun\AnypointStudio\workspace\test\pom.xml) has 2 errors
[ERROR]     Unresolveable build extension: Plugin org.mule.tools.maven:mule-app-maven-plugin:1.1 or one of its dependencies could not be resolved: Could not find artifact com.sun:tools:jar:1.5.0 at specified path C:\Program Files (x86)\Java\jre1.8.0_40/../lib/tools.jar -> [Help 2]
[ERROR]     Unknown packaging: mule @ line 8, column 16
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException
[ERROR] [Help 2] http://cwiki.apache.org/confluence/display/MAVEN/PluginManagerException


答: abort is a wrapper that raises HTTPException classes. Calling abort is the same as raising an exception and Flask will handle both the same way. Returning is not the same as raising an exception and will be handled differently.

Title: Difference between Flask abort() or returning a status


问:
Can you store Visual Studio 2013 project template in source control?
We've created a custom project template in visual studio 2013 for the whole team to use, as the vast majority of our projects have the same styling/branding/main pages etc.

We've managed to export this template and distributed it around the team so everyone has it available in their list of installed templates when they begin a new project.

What we're now wondering is whether there is any method for storing the template itself in source control (we use TFS generally but open to alternatives) so that the template can evolve over time and then a team member can just get the most up to date version of the template down prior to beginning a new project?

Any suggestions appreciated.

答:
There's nothing stopping you from exporting the process template XML and putting it in source control. However, you still have to manually upload the process template and/or apply template changes.

You can certainly use the build system to automate the process of uploading process templates, but the XAML build system in TFS 2013 makes that prospect unappealing.


问:
how do i format my JSON responce in PHP to look like this
My PHP code:

```<code>require ("connect.php");

$input = $_GET["query"];
$data = array();

$query = mysql_query("SELECT `abbr` FROM `states_list` WHERE `abbr` LIKE '{$input}%'") or die(mysql_error());
while ($obj = mysql_fetch_object($query)) {
    //$json = array();
    //$json['query'] = $input;
    //$json['suggestion'] = $row['abbr'];
    $json[] = $obj;
    $data = array("query"=>"$input", "suggestion"=>array($obj));
}
header("Content-type: application/json");
//echo json_encode($data);
echo '{"query":'.$input.' "suggestion":'.json_encode($json).'}';
</code>```

This is my actual response:

```<code>{"query":c "suggestion":[{"abbr":"CA"},{"abbr":"CO"},{"abbr":"CT"}]}
</code>```

This is how I would like it to look like:

```<code>{"query":c "suggestion":["CA","CO","CT"]}
</code>```

I can't seem to figure out the right way to arrange the output to get what I want ;(

答:
Try formatting it like this:

```<code>$query = "c";
$suggestion = array('CA', 'CO', 'CT');
$return = array('query' => $query, 'suggestion' => $suggestion);
echo json_encode($return);
</code>```

Build $query and $suggestion in the loops.

ContentLicense: CC BY-SA 2.5

Body:
My PHP code:

require ("connect.php");

$input = $_GET["query"];
$data = array();

$query = mysql_query("SELECT `abbr` FROM `states_list` WHERE `abbr` LIKE '{$input}%'") or die(mysql_error());
while ($obj = mysql_fetch_object($query)) {
    //$json = array();
    //$json['query'] = $input;
    //$json['suggestion'] = $row['abbr'];
    $json[] = $obj;
    $data = array("query"=>"$input", "suggestion"=>array($obj));
}
header("Content-type: application/json");
//echo json_encode($data);
echo '{"query":'.$input.' "suggestion":'.json_encode($json).'}';

This is my actual response:

{"query":c "suggestion":[{"abbr":"CA"},{"abbr":"CO"},{"abbr":"CT"}]}

This is how I would like it to look like:

{"query":c "suggestion":["CA","CO","CT"]}

I can't seem to figure out the right way to arrange the output to get what I want ;(

Body:
Try formatting it like this:

$query = "c";
$suggestion = array('CA', 'CO', 'CT');
$return = array('query' => $query, 'suggestion' => $suggestion);
echo json_encode($return);

Build $query and $suggestion in the loops.


问:
Can not bind socket in linux
There is my function. I pass argument port as 80 and I always can not bind socket.</p>

```<code>int create_socket(int port)
{
    int sock;
    struct sockaddr_in name;

    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0) {
        fprintf(stderr, "Can not create socket\n");
        return -1;
    }
    //Assigning a name to the socket
    name.sin_family = AF_INET;
    name.sin_port = htons((unsigned short)port);
    name.sin_addr.s_addr = htonl(INADDR_ANY);
    if (bind(sock, (const struct sockaddr *) &name, sizeof(name)) == -1) {
        fprintf(stderr, "Can not bind socket\n");
        return -1;
    }
    return sock;
}
</code>```

答:
Typically port number less than 1024 are used by well known network servers and in linux, root privilege is required to open these ports.

80 is HTTP port and so your program requires root privilege.

Title: Can not bind socket in linux

Body:
There is my function. I pass argument port as 80 and I always can not bind socket.

int create_socket(int port)
{
    int sock;
    struct sockaddr_in name;

    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0) {
        fprintf(stderr, "Can not create socket\n");
        return -1;
    }
    //Assigning a name to the socket
    name.sin_family = AF_INET;
    name.sin_port = htons((unsigned short)port);
    name.sin_addr.s_addr = htonl(INADDR_ANY);
    if (bind(sock, (const struct sockaddr *) &name, sizeof(name)) == -1) {
        fprintf(stderr, "Can not bind socket\n");
        return -1;
    }
    return sock;
}


问:
Auto add place to a form field by GEO location AMP-HTML conform
Is there a way to add place to a form field by GEO location? It should be an AMP-HTML solution or a solution without JavaScript.</p>

答: This is possible by rendering the form via amp-list. You can determine the GEO location based on the amp-list's src request (which is not cached) and then include the location in the returned JSON response. Inside the amp-list's mustache template you then can simply render the form with the correct location using the JSON response.  </p>


问:
Logrotate not rotating old files even after rotate is set to 0
In my log rotate setup, for a specific log file the rotate has been set to 0. But once the size of the file is reached, the old file is rotated to application.log.1 instead of being deleted.

As per the documentation, the file should be deleted when rotate is set to 0. Why is this happening? I must also say that log rotate is configured to run every hour, but our log file reaches the size within 1 hour. So when logrotate runs every hour, it deletes the old application.log.1, rolls over the current application.log to application.log.1 and creates a new application.log file.
The config for the file looks like below:

```<code>/var/log/application.log
{
    rotate 0
    weekly
    size 256M
    missingok
    notifempty
    copytruncate
    compress
    delaycompress
    sharedscripts
    postrotate
            reload rsyslog >/dev/null 2>&1 || true
            /usr/sbin/scalyr-agent-2 stop
            /usr/sbin/scalyr-agent-2 start
    endscript
}
</code>```

答:
It looks like both copytruncate and delaycompress cause new files to be created, despite the rotate 0 setting. Since you want to delete old files immediately (why not just log to /dev/null directly in the first place?), you don't need any compress settings anyway.

I see two options:

If you really need copytruncate, add a postrotate command to delete the created file:

```<code>/var/log/application.log {
    rotate 0
    size 256M
    missingok
    notifempty
    copytruncate
    postrotate
        reload rsyslog >/dev/null 2>&1 || true
        /usr/sbin/scalyr-agent-2 stop
        /usr/sbin/scalyr-agent-2 start
        rm -f /var/log/application.log.1
    endscript
}
</code>```

If you don't need copytruncate, replaced it with create (if at all, maybe your service creates a new log file on its own):

```<code>/var/log/application.log {
    rotate 0
    size 256M
    missingok
    notifempty
    create
    postrotate
        reload rsyslog >/dev/null 2>&1 || true
        /usr/sbin/scalyr-agent-2 stop
        /usr/sbin/scalyr-agent-2 start
    endscript
}
</code>```

Add owner and permission as needed to the create command.

I also did the following:

Remove weekly: frequencies and size are mutually exclusive

Remove the compress and delaycompress commands: you want to delete your old files, so why bother with compressing in the first place?

But, as pointed out above, it looks like you don't want the logs in the first place, so try preventing the application from writing them, or redirect to /dev/null, if you really don't need them.

Side note: your description of what's happening is not quite accurate because of the copytruncate setting: the logfile is never deleted, only copied, then truncated in place. This is used for programs that can't change the file handle they're writing to.

Body:
In my log rotate setup, for a specific log file the rotate has been set to 0. But once the size of the file is reached, the old file is rotated to application.log.1 instead of being deleted.

As per the documentation, the file should be deleted when rotate is set to 0. Why is this happening? I must also say that log rotate is configured to run every hour, but our log file reaches the size within 1 hour. So when logrotate runs every hour, it deletes the old application.log.1, rolls over the current application.log to application.log.1 and creates a new application.log file.
The config for the file looks like below:

/var/log/application.log
{
    rotate 0
    weekly
    size 256M
    missingok
    notifempty
    copytruncate
    compress
    delaycompress
    sharedscripts
    postrotate
            reload rsyslog >/dev/null 2>&1 || true
            /usr/sbin/scalyr-agent-2 stop
            /usr/sbin/scalyr-agent-2 start
    endscript
}

Body:
It looks like both copytruncate and delaycompress cause new files to be created, despite the rotate 0 setting. Since you want to delete old files immediately (why not just log to /dev/null directly in the first place?), you don't need any compress settings anyway.

I see two options:

If you really need copytruncate, add a postrotate command to delete the created file:

/var/log/application.log {
    rotate 0
    size 256M
    missingok
    notifempty
    copytruncate
    postrotate
        reload rsyslog >/dev/null 2>&1 || true
        /usr/sbin/scalyr-agent-2 stop
        /usr/sbin/scalyr-agent-2 start
        rm -f /var/log/application.log.1
    endscript
}

If you don't need copytruncate, replaced it with create (if at all, maybe your service creates a new log file on its own):

/var/log/application.log {
    rotate 0
    size 256M
    missingok
    notifempty
    create
    postrotate
        reload rsyslog >/dev/null 2>&1 || true
        /usr/sbin/scalyr-agent-2 stop
        /usr/sbin/scalyr-agent-2 start
    endscript
}

Add owner and permission as needed to the create command.

I also did the following:

Remove weekly: frequencies and size are mutually exclusive

Remove the compress and delaycompress commands: you want to delete your old files, so why bother with compressing in the first place?

But, as pointed out above, it looks like you don't want the logs in the first place, so try preventing the application from writing them, or redirect to /dev/null, if you really don't need them.

Side note: your description of what's happening is not quite accurate because of the copytruncate setting: the logfile is never deleted, only copied, then truncated in place. This is used for programs that can't change the file handle they're writing to.


问:
Select rows with any member of list of substrings in string
In a Micrososft SQL Server table I have a column with a string.

Example:

```<code>'Servernamexyz.server.operationunit.otherstuff.icouldnt.predict.domain.domain2.domain3'
</code>```

I also have a dynamic list of substrings

Example:

```<code>('icouldnt', 'stuff', 'banana')
</code>```

I don't care for string manipulation. The substrings could also be called:

```<code>('%icouldnt%', '%stuff%', '%banana%')
</code>```

What's the best way to find all rows where the string contains one of the substrings?

Solutions that are not possible:

multiple OR Statements in the WHERE clause, the list is dynamic

external Code to do a "for each", its a multi value parameter from the reportbuilder, so nothing useful here

changing the database, its the database of a tool a costumer is using and we can't change it, even if we would like... so much

I really cant believe how hard such a simple problem can turn out. It would need a "LIKE IN" command to do it in a way that looks ok. Right now I cant think of anything but a messy temp table.

答:
One option is to use CHARINDEX

```<code>DECLARE @tab TABLE (Col1 NVARCHAR(200))
INSERT INTO @tab (Col1)
VALUES (N'Servernamexyz.server.operationunit.otherstuff.icouldnt.predict.domain.domain2.domain3' )

;WITH cteX
AS(
    SELECT 'icouldnt' Strings
    UNION ALL
    SELECT 'stuff'
    UNION ALL
    SELECT 'banana'
)
SELECT
    T.*, X.Strings
FROM @tab   T
CROSS APPLY (SELECT X.Strings FROM cteX X) X
WHERE CHARINDEX(X.Strings, T.Col1) > 1
</code>```

Output

EDIT - using an unknown dynamic string variable - @substrings

```<code>DECLARE @tab TABLE (Col1 NVARCHAR(200))
INSERT INTO @tab (Col1)
VALUES (N'Servernamexyz.server.operationunit.otherstuff.icouldnt.predict.domain.domain2.domain3' )

DECLARE @substrings NVARCHAR(200) = 'icouldnt,stuff,banana'

SELECT
    T.*, X.Strings
FROM @tab   T
CROSS APPLY
(   --dynamically split the string
    SELECT Strings = y.i.value('(./text())[1]', 'nvarchar(4000)')
    FROM
    (
    SELECT x = CONVERT(XML, '<i>'
        + REPLACE(@substrings, ',', '</i><i>')
        + '</i>').query('.')
    ) AS a CROSS APPLY x.nodes('i') AS y(i)
) X
WHERE CHARINDEX(X.Strings, T.Col1) > 1
</code>```

Body:
In a Micrososft SQL Server table I have a column with a string.

Example:

'Servernamexyz.server.operationunit.otherstuff.icouldnt.predict.domain.domain2.domain3'

I also have a dynamic list of substrings

Example:

('icouldnt', 'stuff', 'banana')

I don't care for string manipulation. The substrings could also be called:

('%icouldnt%', '%stuff%', '%banana%')

What's the best way to find all rows where the string contains one of the substrings?

Solutions that are not possible:

multiple OR Statements in the WHERE clause, the list is dynamic

external Code to do a "for each", its a multi value parameter from the reportbuilder, so nothing useful here

changing the database, its the database of a tool a costumer is using and we can't change it, even if we would like... so much

I really cant believe how hard such a simple problem can turn out. It would need a "LIKE IN" command to do it in a way that looks ok. Right now I cant think of anything but a messy temp table.

Body:
One option is to use CHARINDEX

DECLARE @tab TABLE (Col1 NVARCHAR(200))
INSERT INTO @tab (Col1)
VALUES (N'Servernamexyz.server.operationunit.otherstuff.icouldnt.predict.domain.domain2.domain3' )

;WITH cteX
AS(
    SELECT 'icouldnt' Strings
    UNION ALL
    SELECT 'stuff'
    UNION ALL
    SELECT 'banana'
)
SELECT
    T.*, X.Strings
FROM @tab   T
CROSS APPLY (SELECT X.Strings FROM cteX X) X
WHERE CHARINDEX(X.Strings, T.Col1) > 1

Output

EDIT - using an unknown dynamic string variable - @substrings

DECLARE @tab TABLE (Col1 NVARCHAR(200))
INSERT INTO @tab (Col1)
VALUES (N'Servernamexyz.server.operationunit.otherstuff.icouldnt.predict.domain.domain2.domain3' )

DECLARE @substrings NVARCHAR(200) = 'icouldnt,stuff,banana'

SELECT
    T.*, X.Strings
FROM @tab   T
CROSS APPLY
(   --dynamically split the string
    SELECT Strings = y.i.value('(./text())[1]', 'nvarchar(4000)')
    FROM
    (
    SELECT x = CONVERT(XML, '<i>'
        + REPLACE(@substrings, ',', '</i><i>')
        + '</i>').query('.')
    ) AS a CROSS APPLY x.nodes('i') AS y(i)
) X
WHERE CHARINDEX(X.Strings, T.Col1) > 1


问:
How I can change render to return json in view Django
I have function in view

```<code>from django.shortcuts import render
from .models import myModel

def articleTheme(request):
    if request.method == 'POST':
        article_id = request.POST['id']
        article = myModel.objects.get(id=article_id)
        theme = article.theme
        return render(request, 'theme.html', {'newTheme': theme })
</code>```

now it works normal. But I have excess html. I want return json object.
What I can import and return?

答:
Use JsonResponse

```<code>from django.http import JsonResponse
..
def articleTheme(request):
    ..
    return JsonResponse({'newTheme': theme })
</code>```

Body:
I have function in view

from django.shortcuts import render
from .models import myModel

def articleTheme(request):
    if request.method == 'POST':
        article_id = request.POST['id']
        article = myModel.objects.get(id=article_id)
        theme = article.theme
        return render(request, 'theme.html', {'newTheme': theme })

now it works normal. But I have excess html. I want return json object.
What I can import and return?

Body:
Use JsonResponse

from django.http import JsonResponse
..
def articleTheme(request):
    ..
    return JsonResponse({'newTheme': theme })


问:
SQL or PL/SQL to return the value of nodes with same name to one row
From the below XML I would like to return the following.

```<code>ID            Departments
-----------   ------------------------------
EMP10Level1   98,850,876,896,901,908,936,987
</code>```

I have tried a few things, such as parsing the XML and using Listagg, but am getting the same values for every ID.

Hopefully a more enlightenment mind can solve this problem for me.

Is also a column called ID that contains EMP10Level1 which is the value from the PromotionID tag below.

```<code> <Promotion>
    <MajorVersion>1</MajorVersion>
    <MinorVersion>7</MinorVersion>
    <PromotionID>EMP10Level1</PromotionID>
    <MultibuyGroup>
        <UseLowestNetValue>0</UseLowestNetValue>
        <MMGroupID>850</MMGroupID>
        <MMGroupID>901</MMGroupID>
        <MMGroupID>908</MMGroupID>
        <MMGroupID>936</MMGroupID>
        <MMGroupID>896</MMGroupID>
        <MMGroupID>987</MMGroupID>
        <MMGroupID>876</MMGroupID>
        <MMGroupID>98</MMGroupID>
        <TriggerOnLostSales>0</TriggerOnLostSales>
    </MultibuyGroup>
</Promotion>
</code>```

答:
Here is one way using sort-of-nested XMLTABLEs:</p>

```<code>WITH sample_data AS (SELECT XMLTYPE('<Promotion>
    <MajorVersion>1</MajorVersion>
    <MinorVersion>7</MinorVersion>
    <PromotionID>EMP10Level1</PromotionID>
    <MultibuyGroup>
        <UseLowestNetValue>0</UseLowestNetValue>
        <MMGroupID>850</MMGroupID>
        <MMGroupID>901</MMGroupID>
        <MMGroupID>908</MMGroupID>
        <MMGroupID>936</MMGroupID>
        <MMGroupID>896</MMGroupID>
        <MMGroupID>987</MMGroupID>
        <MMGroupID>876</MMGroupID>
        <MMGroupID>98</MMGroupID>
        <TriggerOnLostSales>0</TriggerOnLostSales>
    </MultibuyGroup>
</Promotion>') xmldata FROM dual)
SELECT ids.id,
       listagg(depts.department, ',') WITHIN GROUP (ORDER BY depts.department) departments
FROM   sample_data sd
       CROSS JOIN XMLTABLE('/Promotion' PASSING sd.xmldata
                           COLUMNS ID VARCHAR2(20) PATH 'PromotionID',
                                   dept_xml XMLTYPE PATH 'MultibuyGroup') ids
       CROSS JOIN XMLTABLE('//MMGroupID' PASSING ids.dept_xml
                           COLUMNS department INTEGER PATH '.') depts
GROUP BY ids.id;

ID                   DEPARTMENTS
-------------------- --------------------------------------------------------------------------------
EMP10Level1          98,850,876,896,901,908,936,987
</code>```

Body:
From the below XML I would like to return the following.

ID            Departments
-----------   ------------------------------
EMP10Level1   98,850,876,896,901,908,936,987

I have tried a few things, such as parsing the XML and using Listagg, but am getting the same values for every ID.

Hopefully a more enlightenment mind can solve this problem for me.

Is also a column called ID that contains EMP10Level1 which is the value from the PromotionID tag below.

 <Promotion>
    <MajorVersion>1</MajorVersion>
    <MinorVersion>7</MinorVersion>
    <PromotionID>EMP10Level1</PromotionID>
    <MultibuyGroup>
        <UseLowestNetValue>0</UseLowestNetValue>
        <MMGroupID>850</MMGroupID>
        <MMGroupID>901</MMGroupID>
        <MMGroupID>908</MMGroupID>
        <MMGroupID>936</MMGroupID>
        <MMGroupID>896</MMGroupID>
        <MMGroupID>987</MMGroupID>
        <MMGroupID>876</MMGroupID>
        <MMGroupID>98</MMGroupID>
        <TriggerOnLostSales>0</TriggerOnLostSales>
    </MultibuyGroup>
</Promotion>

Body:
Here is one way using sort-of-nested XMLTABLEs:

WITH sample_data AS (SELECT XMLTYPE('<Promotion>
    <MajorVersion>1</MajorVersion>
    <MinorVersion>7</MinorVersion>
    <PromotionID>EMP10Level1</PromotionID>
    <MultibuyGroup>
        <UseLowestNetValue>0</UseLowestNetValue>
        <MMGroupID>850</MMGroupID>
        <MMGroupID>901</MMGroupID>
        <MMGroupID>908</MMGroupID>
        <MMGroupID>936</MMGroupID>
        <MMGroupID>896</MMGroupID>
        <MMGroupID>987</MMGroupID>
        <MMGroupID>876</MMGroupID>
        <MMGroupID>98</MMGroupID>
        <TriggerOnLostSales>0</TriggerOnLostSales>
    </MultibuyGroup>
</Promotion>') xmldata FROM dual)
SELECT ids.id,
       listagg(depts.department, ',') WITHIN GROUP (ORDER BY depts.department) departments
FROM   sample_data sd
       CROSS JOIN XMLTABLE('/Promotion' PASSING sd.xmldata
                           COLUMNS ID VARCHAR2(20) PATH 'PromotionID',
                                   dept_xml XMLTYPE PATH 'MultibuyGroup') ids
       CROSS JOIN XMLTABLE('//MMGroupID' PASSING ids.dept_xml
                           COLUMNS department INTEGER PATH '.') depts
GROUP BY ids.id;

ID                   DEPARTMENTS
-------------------- --------------------------------------------------------------------------------
EMP10Level1          98,850,876,896,901,908,936,987


问:
Continuous hatch line needed in canvas with repeated pattern
I am trying to build a hatch pattern using a combination of canvas and kinetic and I am having issues trying to get a continuous line.

This jsfiddle shows what I have so far, but because my repeat pattern is a sqaure the corners are affecting the line, I have tried using the lineJoin and lineCap properties, but cannot seem to get the desired result.

The main code in question is this:

```<code>var hatchPattern = document.getElementById("canvas")
var context = hatchPattern.getContext('2d');
context.strokeStyle = "#FF0000";
context.beginPath();
context.moveTo(0, 20);
context.lineTo(20, 0);
context.lineWidth = 5;
context.stroke();
context.closePath();
</code>```

Can anyone help?

UPDATE:

I have created another jsfiddle which although not perfect, will probably do for me, still not sure why there is a slight gap though!

答:
markE's code doesn't produce a 45º-angle pinstripe pattern (in fact, it doesn't match that of his example png image), so I ended up rewriting it to generalise it.

Code snippet:

/** Creates a canvas filled with a 45-degree pinstripe.
  * @returns the filled HTMLCanvasElement. */
function createPinstripeCanvas() {
    const patternCanvas = document.createElement("canvas");
    const pctx = patternCanvas.getContext('2d', { antialias: true });
    const colour = "#B4645D";

    const CANVAS_SIDE_LENGTH = 90;
    const WIDTH = CANVAS_SIDE_LENGTH;
    const HEIGHT = CANVAS_SIDE_LENGTH;
    const DIVISIONS = 4;

    patternCanvas.width = WIDTH;
    patternCanvas.height = HEIGHT;
    pctx.fillStyle = colour;

    // Top line
    pctx.beginPath();
    pctx.moveTo(0, HEIGHT * (1 / DIVISIONS));
    pctx.lineTo(WIDTH * (1 / DIVISIONS), 0);
    pctx.lineTo(0, 0);
    pctx.lineTo(0, HEIGHT * (1 / DIVISIONS));
    pctx.fill();

    // Middle line
    pctx.beginPath();
    pctx.moveTo(WIDTH, HEIGHT * (1 / DIVISIONS));
    pctx.lineTo(WIDTH * (1 / DIVISIONS), HEIGHT);
    pctx.lineTo(0, HEIGHT);
    pctx.lineTo(0, HEIGHT * ((DIVISIONS - 1) / DIVISIONS));
    pctx.lineTo(WIDTH * ((DIVISIONS - 1) / DIVISIONS), 0);
    pctx.lineTo(WIDTH, 0);
    pctx.lineTo(WIDTH, HEIGHT * (1 / DIVISIONS));
    pctx.fill();

    // Bottom line
    pctx.beginPath();
    pctx.moveTo(WIDTH, HEIGHT * ((DIVISIONS - 1) / DIVISIONS));
    pctx.lineTo(WIDTH * ((DIVISIONS - 1) / DIVISIONS), HEIGHT);
    pctx.lineTo(WIDTH, HEIGHT);
    pctx.lineTo(WIDTH, HEIGHT * ((DIVISIONS - 1) / DIVISIONS));
    pctx.fill();

    return patternCanvas;
}

/** Fills the whole area of a given htmlCanvasElement with a patternCanvas.
  * @param targetCanvas – the HTMLCanvasElement to fill into.
  * @param patternCanvas – a HTMLCanvasElement containing a pattern to fill with.
  */
function fillWithPattern(targetCanvas, patternCanvas){
    const ctx = targetCanvas.getContext('2d', { antialias: false, depth: false });
    const width = targetCanvas.width;
    const height = targetCanvas.height;
    if (!width || !height) throw new Error("progressCanvas's width/height falsy.");

    ctx.fillStyle = ctx.createPattern(patternCanvas, 'repeat');
    ctx.fillRect(0, 0, width, height);

    return targetCanvas;
}

fillWithPattern(document.getElementById("targetCanvas"), createPinstripeCanvas());```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#targetCanvas{border:1px dotted black;}</code>```

<canvas id="targetCanvas" width=300 height=300></canvas>```

Body:
I am trying to build a hatch pattern using a combination of canvas and kinetic and I am having issues trying to get a continuous line.

This jsfiddle shows what I have so far, but because my repeat pattern is a sqaure the corners are affecting the line, I have tried using the lineJoin and lineCap properties, but cannot seem to get the desired result.

The main code in question is this:

var hatchPattern = document.getElementById("canvas")
var context = hatchPattern.getContext('2d');
context.strokeStyle = "#FF0000";
context.beginPath();
context.moveTo(0, 20);
context.lineTo(20, 0);
context.lineWidth = 5;
context.stroke();
context.closePath();

Can anyone help?

UPDATE:

I have created another jsfiddle which although not perfect, will probably do for me, still not sure why there is a slight gap though!

Body:
markE's code doesn't produce a 45º-angle pinstripe pattern (in fact, it doesn't match that of his example png image), so I ended up rewriting it to generalise it.

Code snippet:

/** Creates a canvas filled with a 45-degree pinstripe.
  * @returns the filled HTMLCanvasElement. */
function createPinstripeCanvas() {
    const patternCanvas = document.createElement("canvas");
    const pctx = patternCanvas.getContext('2d', { antialias: true });
    const colour = "#B4645D";

    const CANVAS_SIDE_LENGTH = 90;
    const WIDTH = CANVAS_SIDE_LENGTH;
    const HEIGHT = CANVAS_SIDE_LENGTH;
    const DIVISIONS = 4;

    patternCanvas.width = WIDTH;
    patternCanvas.height = HEIGHT;
    pctx.fillStyle = colour;

    // Top line
    pctx.beginPath();
    pctx.moveTo(0, HEIGHT * (1 / DIVISIONS));
    pctx.lineTo(WIDTH * (1 / DIVISIONS), 0);
    pctx.lineTo(0, 0);
    pctx.lineTo(0, HEIGHT * (1 / DIVISIONS));
    pctx.fill();

    // Middle line
    pctx.beginPath();
    pctx.moveTo(WIDTH, HEIGHT * (1 / DIVISIONS));
    pctx.lineTo(WIDTH * (1 / DIVISIONS), HEIGHT);
    pctx.lineTo(0, HEIGHT);
    pctx.lineTo(0, HEIGHT * ((DIVISIONS - 1) / DIVISIONS));
    pctx.lineTo(WIDTH * ((DIVISIONS - 1) / DIVISIONS), 0);
    pctx.lineTo(WIDTH, 0);
    pctx.lineTo(WIDTH, HEIGHT * (1 / DIVISIONS));
    pctx.fill();

    // Bottom line
    pctx.beginPath();
    pctx.moveTo(WIDTH, HEIGHT * ((DIVISIONS - 1) / DIVISIONS));
    pctx.lineTo(WIDTH * ((DIVISIONS - 1) / DIVISIONS), HEIGHT);
    pctx.lineTo(WIDTH, HEIGHT);
    pctx.lineTo(WIDTH, HEIGHT * ((DIVISIONS - 1) / DIVISIONS));
    pctx.fill();

    return patternCanvas;
}

/** Fills the whole area of a given htmlCanvasElement with a patternCanvas.
  * @param targetCanvas – the HTMLCanvasElement to fill into.
  * @param patternCanvas – a HTMLCanvasElement containing a pattern to fill with.
  */
function fillWithPattern(targetCanvas, patternCanvas){
    const ctx = targetCanvas.getContext('2d', { antialias: false, depth: false });
    const width = targetCanvas.width;
    const height = targetCanvas.height;
    if (!width || !height) throw new Error("progressCanvas's width/height falsy.");

    ctx.fillStyle = ctx.createPattern(patternCanvas, 'repeat');
    ctx.fillRect(0, 0, width, height);

    return targetCanvas;
}

fillWithPattern(document.getElementById("targetCanvas"), createPinstripeCanvas());

#targetCanvas{border:1px dotted black;}

<canvas id="targetCanvas" width=300 height=300></canvas>


问:
SQL improvement - UNION?
I have 2 tables: "packages" and "items".

"packages" has the following columns: pack_id | item_id

"items" has the following columns.......:    item_id | type

One package can have multiple items.

UPDATE:

Sample Data and Expected Results:

```<code>pack_id | item_id
1           1
1           2
1           3
2           2
2           1
3           4
3           5
3           6

item_id | type
1           C
2           F
3           Z
4           Z
5           Z
6           Z
</code>```

Expected result:

```<code>pack_id | pack_type
1           Mixed
2           Cool
3           Not Cool
</code>```

My question is:

Is there a better way to query these 2 tables, in order to get a 3rd one, having as columns: "pack_id" and the new column "pack_type"? Those UNIONs seem to add a huge amount of time to the run time.

```<code>    SELECT pack_id, pack_type
    FROM (
      -- CASE 1 - pack_type is 'Cool' - type 'C' or 'F', but not 'Z'
      SELECT  Distinct q1.pack_id, 'Cool' AS pack_type
        FROM (
            SELECT  Distinct p.pack_id, i.type
            FROM packages p
            INNER JOIN items i
                ON p.item_id = i.item_id
            WHERE i.type <> 'Z') q1
        WHERE q1.type IN ('C','F')

      UNION

      -- CASE 2 - pack_type is 'Not-Cool' - type 'Z', but not 'C' or 'F'
      SELECT  Distinct q2.pack_id, 'Not-Cool' AS pack_type
        FROM (
            SELECT  Distinct p.pack_id, i.type
            FROM packages p
            INNER JOIN items i
                ON p.item_id = i.item_id
            WHERE i.type = 'Z') q2
        WHERE q2.type NOT IN ('C','F')

      UNION

     -- CASE 3 - pack_type is 'Mixed' - type 'Z' and ('C' or 'F')
     SELECT  Distinct q3.pack_id, 'Mixed' AS pack_type
        FROM (
            SELECT  Distinct p.pack_id, i.type
            FROM packages p
            INNER JOIN items i
                ON p.item_id = i.item_id
            WHERE i.type = 'Z') q3
        WHERE q3.type IN ('C','F')
    ) m
</code>```

NOTE: some explication for the multiple comments that point to "A type cannot be Z and also C or F".

I also thought that, but the way I understand the behavior of the query is that if u say "type IN ('C','F')", it will look at each item of type 'C' or 'F' and get the package id that has that item. BUT, a package that has items of type 'C' or 'F' can also have items of type 'Z', hence the inner select, dealing with items of type 'Z' first.

答:
I think you can put it in single query like this

```<code>SELECT  Distinct *
FROM (
SELECT  p.pack_id,
        CASE WHEN i.type <> 'Z' AND i.type IN ('C','F') THEN 'Cool'
             WHEN i.type = 'Z' AND i.type NOT IN ('C','F') THEN 'Not-Cool'
             WHEN i.type = 'Z' AND i.type IN ('C','F') THEN 'Mixed'
        END AS pack_type
FROM packages p
INNER JOIN items i ON p.item_id = i.item_id
WHERE (i.type <> 'Z' AND i.type IN ('C','F'))
    OR (i.type = 'Z' AND i.type NOT IN ('C','F'))
    OR (i.type = 'Z' AND i.type IN ('C','F'))
) as temp
</code>```

Updated: After reviewed carefully your logic, I think @Tim answer is the right one

Title: SQL improvement - UNION?

Body:
I have 2 tables: "packages" and "items".

"packages" has the following columns: pack_id | item_id

"items" has the following columns.......:    item_id | type

One package can have multiple items.

UPDATE:

Sample Data and Expected Results:

pack_id | item_id
1           1
1           2
1           3
2           2
2           1
3           4
3           5
3           6

item_id | type
1           C
2           F
3           Z
4           Z
5           Z
6           Z

Expected result:

pack_id | pack_type
1           Mixed
2           Cool
3           Not Cool

My question is:

Is there a better way to query these 2 tables, in order to get a 3rd one, having as columns: "pack_id" and the new column "pack_type"? Those UNIONs seem to add a huge amount of time to the run time.

    SELECT pack_id, pack_type
    FROM (
      -- CASE 1 - pack_type is 'Cool' - type 'C' or 'F', but not 'Z'
      SELECT  Distinct q1.pack_id, 'Cool' AS pack_type
        FROM (
            SELECT  Distinct p.pack_id, i.type
            FROM packages p
            INNER JOIN items i
                ON p.item_id = i.item_id
            WHERE i.type <> 'Z') q1
        WHERE q1.type IN ('C','F')

      UNION

      -- CASE 2 - pack_type is 'Not-Cool' - type 'Z', but not 'C' or 'F'
      SELECT  Distinct q2.pack_id, 'Not-Cool' AS pack_type
        FROM (
            SELECT  Distinct p.pack_id, i.type
            FROM packages p
            INNER JOIN items i
                ON p.item_id = i.item_id
            WHERE i.type = 'Z') q2
        WHERE q2.type NOT IN ('C','F')

      UNION

     -- CASE 3 - pack_type is 'Mixed' - type 'Z' and ('C' or 'F')
     SELECT  Distinct q3.pack_id, 'Mixed' AS pack_type
        FROM (
            SELECT  Distinct p.pack_id, i.type
            FROM packages p
            INNER JOIN items i
                ON p.item_id = i.item_id
            WHERE i.type = 'Z') q3
        WHERE q3.type IN ('C','F')
    ) m

NOTE: some explication for the multiple comments that point to "A type cannot be Z and also C or F".

I also thought that, but the way I understand the behavior of the query is that if u say "type IN ('C','F')", it will look at each item of type 'C' or 'F' and get the package id that has that item. BUT, a package that has items of type 'C' or 'F' can also have items of type 'Z', hence the inner select, dealing with items of type 'Z' first.

Body:
I think you can put it in single query like this

SELECT  Distinct *
FROM (
SELECT  p.pack_id,
        CASE WHEN i.type <> 'Z' AND i.type IN ('C','F') THEN 'Cool'
             WHEN i.type = 'Z' AND i.type NOT IN ('C','F') THEN 'Not-Cool'
             WHEN i.type = 'Z' AND i.type IN ('C','F') THEN 'Mixed'
        END AS pack_type
FROM packages p
INNER JOIN items i ON p.item_id = i.item_id
WHERE (i.type <> 'Z' AND i.type IN ('C','F'))
    OR (i.type = 'Z' AND i.type NOT IN ('C','F'))
    OR (i.type = 'Z' AND i.type IN ('C','F'))
) as temp

Updated: After reviewed carefully your logic, I think @Tim answer is the right one


问:
Android unit testing Realm
I can't find a solution to do some unit testing on Android. I am trying to test Realm interaction with a service.
I tried using PowerMockito and in memory solution, but in each case it's not working for me.

I am looking for a solution to check the data stored in realm. Could someone can give me a resource or a hint?

Edit: My sample code for inMemory

build.gradle

```<code>testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
...
dependencies {
  androidTestImplementation 'com.android.support:support-annotations:26.1.0'
  androidTestImplementation 'com.android.support.test:runner:1.0.1'
  androidTestImplementation 'com.android.support.test:rules:1.0.1'
}
</code>```

Sync Service

```<code>@RunWith(AndroidJUnit4::class)
class StateSyncServiceTest {

    lateinit var mockRealm: Realm

    @Before
    fun setup() {
        val testConfig = RealmConfiguration.Builder().inMemory().name("test-realm").build()
        mockRealm = Realm.getInstance(testConfig)
    }

    @Test
    fun shouldBeAbleToGetDefaultInstance() {
        Assert.assertThat(Realm.getDefaultInstance(), `is`(mockRealm)) //NOT WORKING WRONG OBJECT
    }

    @Test
    fun correctSynchronizationPerformed() {
        //given
        val organizationsDTO = listOf<OrganizationDTO>(OrganizationDTO(3, "Organization Mauritius", true))
        val statesDTO = listOf<StateDTO>(StateDTO(2, 3, false, "State 2"), StateDTO(3, 3, false, "State 3"))
        val stateDAO = StateDAO()
        val stateSynchroService = StateSyncService()

        //when
        stateSynchroService.synchronize(statesDTO, organizationsDTO)

        //then
        val resultRealm = stateDAO.findAll()
        Assert.assertEquals(statesDTO.size, resultRealm?.size) //WRONG DATA, MIX PRODUCTION AND TEST
    }
}
</code>```

Plus the data aren't erased from the emulator. I still can get the realm db file with the mix data after execution..

答:
Ok found it, with the help of @Sarthak Mittal.
The init part wasn't working properly.</p>

```<code>@Before
fun setup() {
    val testConfig = RealmConfiguration.Builder().inMemory().name("test-realm").build()
    Realm.setDefaultConfiguration(testConfig)
    mockRealm = Realm.getDefaultInstance()
}

@After
@Throws(Exception::class)
public override fun tearDown() {
    mockRealm.close()
}
</code>```

Title: Android unit testing Realm

Body:
I can't find a solution to do some unit testing on Android. I am trying to test Realm interaction with a service.
I tried using PowerMockito and in memory solution, but in each case it's not working for me.

I am looking for a solution to check the data stored in realm. Could someone can give me a resource or a hint?

Edit: My sample code for inMemory

build.gradle

testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
...
dependencies {
  androidTestImplementation 'com.android.support:support-annotations:26.1.0'
  androidTestImplementation 'com.android.support.test:runner:1.0.1'
  androidTestImplementation 'com.android.support.test:rules:1.0.1'
}

Sync Service

@RunWith(AndroidJUnit4::class)
class StateSyncServiceTest {

    lateinit var mockRealm: Realm

    @Before
    fun setup() {
        val testConfig = RealmConfiguration.Builder().inMemory().name("test-realm").build()
        mockRealm = Realm.getInstance(testConfig)
    }

    @Test
    fun shouldBeAbleToGetDefaultInstance() {
        Assert.assertThat(Realm.getDefaultInstance(), `is`(mockRealm)) //NOT WORKING WRONG OBJECT
    }

    @Test
    fun correctSynchronizationPerformed() {
        //given
        val organizationsDTO = listOf<OrganizationDTO>(OrganizationDTO(3, "Organization Mauritius", true))
        val statesDTO = listOf<StateDTO>(StateDTO(2, 3, false, "State 2"), StateDTO(3, 3, false, "State 3"))
        val stateDAO = StateDAO()
        val stateSynchroService = StateSyncService()

        //when
        stateSynchroService.synchronize(statesDTO, organizationsDTO)

        //then
        val resultRealm = stateDAO.findAll()
        Assert.assertEquals(statesDTO.size, resultRealm?.size) //WRONG DATA, MIX PRODUCTION AND TEST
    }
}

Plus the data aren't erased from the emulator. I still can get the realm db file with the mix data after execution..

Body:
Ok found it, with the help of @Sarthak Mittal.
The init part wasn't working properly.

@Before
fun setup() {
    val testConfig = RealmConfiguration.Builder().inMemory().name("test-realm").build()
    Realm.setDefaultConfiguration(testConfig)
    mockRealm = Realm.getDefaultInstance()
}

@After
@Throws(Exception::class)
public override fun tearDown() {
    mockRealm.close()
}


问:
firebase functions push Notifications to specific user
i want to send Push notification via firebase functions to the user who posted the post when some other user likes his/her post.

i want to get the highlighted user-id in the image to get fcm token of this user id stored in other tree.

here is my firebase function code below.

```<code>    const functions = require('firebase-functions');

    const admin = require('firebase-admin');
    admin.initializeApp(functions.config().firebase);

exports.sendNotification = functions.database.ref('/user-posts/{userID}/{pushId}/stars/')
        .onWrite(event=> {
            var request = event.data.val();

            console.log("request",request);
            console.log("key",Object.keys(request)[0]);
            var key = Object.keys(request)[0];
            var token;

            const payload = {
          notification: {
            title: 'You have a new follower!',
            body: 'is now following you.'
          }
        };

             const getDeviceTokensPromise = admin.database()
             .ref(`/users-notifications/${key}`)
             .once('value').then(function(snapshot) {
                    console.log("val",snapshot.val());
                        token= snapshot.val();

                        admin.messaging().sendToDevice(token,payload)
            .then(response=>{
                console.log("Successfully sent message:", response);

            })
            .catch(function(error){
                console.log("error sending message",error);
            })
        })

                    }, function(error) {
                        // The Promise was rejected.
                    console.error(error);
                    });
</code>```

答: Try extracting it from the uri with event.params.userID

Body:
i want to send Push notification via firebase functions to the user who posted the post when some other user likes his/her post.

i want to get the highlighted user-id in the image to get fcm token of this user id stored in other tree.

here is my firebase function code below.

    const functions = require('firebase-functions');

    const admin = require('firebase-admin');
    admin.initializeApp(functions.config().firebase);

exports.sendNotification = functions.database.ref('/user-posts/{userID}/{pushId}/stars/')
        .onWrite(event=> {
            var request = event.data.val();

            console.log("request",request);
            console.log("key",Object.keys(request)[0]);
            var key = Object.keys(request)[0];
            var token;

            const payload = {
          notification: {
            title: 'You have a new follower!',
            body: 'is now following you.'
          }
        };

             const getDeviceTokensPromise = admin.database()
             .ref(`/users-notifications/${key}`)
             .once('value').then(function(snapshot) {
                    console.log("val",snapshot.val());
                        token= snapshot.val();

                        admin.messaging().sendToDevice(token,payload)
            .then(response=>{
                console.log("Successfully sent message:", response);

            })
            .catch(function(error){
                console.log("error sending message",error);
            })
        })

                    }, function(error) {
                        // The Promise was rejected.
                    console.error(error);
                    });


问:
Association type mismatch in Rails app
```<code>Rails 5.1
</code>```

My migration file:

```<code>class CreateFwExports < ActiveRecord::Migration[5.1]
  def change
    create_table :fw_exports, id: :string do |t|
      t.string :screen_name, index: true, limit: 16
      t.string :full_name, limit: 21
      t.string :location

      t.timestamps
    end

  end
end
</code>```

In my helper file, I have the following method:

```<code>def process_spreadsheet(number_of_rows, spreadsheet)
  for i in 1..number_of_rows do
    fw_export_record = FwExport.new(
        :screen_name => spreadsheet[i][0].to_s,
        :full_name => spreadsheet[i][1].to_s,
        :location => spreadsheet[i][2].to_s,
    )
    fw_export_record.save
  end
end
</code>```

What this method does, is receive a spreadsheet CSV object, and iterates through the data, trying to save each row to the fw_exports table.

The first data row is:

```<code>xxxxxxxx,xxxxxxxxxx,"Nottingham, England"
</code>```

I am getting the following error message:

```<code>ActiveRecord::AssociationTypeMismatch (Location(#38400060) expected, got "Nottingham, England" which is an instance of String(#10657520)):
app/helpers/fw_exports_helper.rb:21:in `block in process_spreadsheet'
app/helpers/fw_exports_helper.rb:20:in `process_spreadsheet'
app/controllers/fw_exports_controller.rb:82:in `process_parsed_spreadsheet'
</code>```

When I looked at the actual MySQL table, here's what I got:

```<code>id Primary  varchar(255)    utf8mb4_unicode_ci      No  None
screen_name  varchar(16)    utf8mb4_unicode_ci      Yes NULL
full_name   varchar(21) utf8mb4_unicode_ci      Yes NULL
location    varchar(255)    utf8mb4_unicode_ci      Yes NULL
</code>```

From the controller:

```<code>def fw_export_params
  params.require(:fw_export).permit(:screen_name, :full_name, :location)
end
</code>```

id is generated through a method defined in the concerns section

Any idea why I'm getting the error message?

Edit:

In my fw_exports.rb model, I had the following:

```<code>has_one :location
</code>```

I have a locations table (and model), with the following fields:

```<code>  t.string :fw_exports_id, index: true
  t.string :city
  t.string :state
  t.string :country
</code>```

When I commented out, the line in the fw_exports.rb model:

```<code># has_one :location
</code>```

I stopped getting the above mentioned error, and instead, I am now getting the following error:

```<code>NoMethodError (undefined method `each' for "0":String):
app/helpers/fw_exports_helper.rb:21:in `block in process_spreadsheet'
app/helpers/fw_exports_helper.rb:20:in `process_spreadsheet'
app/controllers/fw_exports_controller.rb:82:in `process_parsed_spreadsheet'
</code>```

Same spot in code, different message.

答:
As you have:

```<code>class FwExport < ApplicationRecord
  has_one :location
</code>```

and assuming that:

```<code>class Location < ApplicationRecord
  belongs_to :fw_export
</code>```

so you cannot define :location as a string column in CreateFwExports migration.

First you need to write another migration to remove the column from :fw_exports table:

```<code>class RemoveColumnFromFwExports < ActiveRecord::Migration[5.1]
  def change
    remove_column :fw_exports, :location, :string
  end
end
</code>```

Now rewrite the helper method that would parse the location string from csv into a Location instance and assign it into the FwExport instance:

```<code>def process_spreadsheet(number_of_rows, spreadsheet)
  1.upto(number_of_rows) do |i|
    fw_export_record = FwExport.new(
        screen_name: spreadsheet[i][0].to_s,
        full_name: spreadsheet[i][1].to_s,
    )
    fw_export_record.save

    # now create the location and associate it to fw_export_record
    location = find_or_create_location(spreadsheet[i][2].to_s)
    location.fw_exports_id = fw_export_record.id
    location.save
  end
end

private

def find_or_create_location(s)
  city, country = s.split(',').map(&:strip)
  Location.find_or_create_by!(city: city, country: country)
end
</code>```

Title: Association type mismatch in Rails app

Body:
Rails 5.1

My migration file:

class CreateFwExports < ActiveRecord::Migration[5.1]
  def change
    create_table :fw_exports, id: :string do |t|
      t.string :screen_name, index: true, limit: 16
      t.string :full_name, limit: 21
      t.string :location

      t.timestamps
    end

  end
end

In my helper file, I have the following method:

def process_spreadsheet(number_of_rows, spreadsheet)
  for i in 1..number_of_rows do
    fw_export_record = FwExport.new(
        :screen_name => spreadsheet[i][0].to_s,
        :full_name => spreadsheet[i][1].to_s,
        :location => spreadsheet[i][2].to_s,
    )
    fw_export_record.save
  end
end

What this method does, is receive a spreadsheet CSV object, and iterates through the data, trying to save each row to the fw_exports table.

The first data row is:

xxxxxxxx,xxxxxxxxxx,"Nottingham, England"

I am getting the following error message:

ActiveRecord::AssociationTypeMismatch (Location(#38400060) expected, got "Nottingham, England" which is an instance of String(#10657520)):
app/helpers/fw_exports_helper.rb:21:in `block in process_spreadsheet'
app/helpers/fw_exports_helper.rb:20:in `process_spreadsheet'
app/controllers/fw_exports_controller.rb:82:in `process_parsed_spreadsheet'

When I looked at the actual MySQL table, here's what I got:

id Primary  varchar(255)    utf8mb4_unicode_ci      No  None
screen_name  varchar(16)    utf8mb4_unicode_ci      Yes NULL
full_name   varchar(21) utf8mb4_unicode_ci      Yes NULL
location    varchar(255)    utf8mb4_unicode_ci      Yes NULL

From the controller:

def fw_export_params
  params.require(:fw_export).permit(:screen_name, :full_name, :location)
end

id is generated through a method defined in the concerns section

Any idea why I'm getting the error message?

Edit:

In my fw_exports.rb model, I had the following:

has_one :location

I have a locations table (and model), with the following fields:

  t.string :fw_exports_id, index: true
  t.string :city
  t.string :state
  t.string :country

When I commented out, the line in the fw_exports.rb model:

# has_one :location

I stopped getting the above mentioned error, and instead, I am now getting the following error:

NoMethodError (undefined method `each' for "0":String):
app/helpers/fw_exports_helper.rb:21:in `block in process_spreadsheet'
app/helpers/fw_exports_helper.rb:20:in `process_spreadsheet'
app/controllers/fw_exports_controller.rb:82:in `process_parsed_spreadsheet'

Same spot in code, different message.

Body:
As you have:

class FwExport < ApplicationRecord
  has_one :location

and assuming that:

class Location < ApplicationRecord
  belongs_to :fw_export

so you cannot define :location as a string column in CreateFwExports migration.

First you need to write another migration to remove the column from :fw_exports table:

class RemoveColumnFromFwExports < ActiveRecord::Migration[5.1]
  def change
    remove_column :fw_exports, :location, :string
  end
end

Now rewrite the helper method that would parse the location string from csv into a Location instance and assign it into the FwExport instance:

def process_spreadsheet(number_of_rows, spreadsheet)
  1.upto(number_of_rows) do |i|
    fw_export_record = FwExport.new(
        screen_name: spreadsheet[i][0].to_s,
        full_name: spreadsheet[i][1].to_s,
    )
    fw_export_record.save

    # now create the location and associate it to fw_export_record
    location = find_or_create_location(spreadsheet[i][2].to_s)
    location.fw_exports_id = fw_export_record.id
    location.save
  end
end

private

def find_or_create_location(s)
  city, country = s.split(',').map(&:strip)
  Location.find_or_create_by!(city: city, country: country)
end


问:
fopen fails invisibly when creating files in system drive (C:\)
Whenever I try to create a file using fopen, fopen acts as if the file has been opened properly and that it has full access to it, but it doesn't actually create the file.  My program doesn't have write access to the system root folder because it needs admin access to write there, but why isn't fopen() giving any errors?

Any idea how to tell if there's an error or not?  The file handle that gets returned when I'm trying to open the file in a protected directory is exactly the same as when I open a file in a directory where I have write access.

I've tried this with the various different versions of fopen (fopen, _wfopen, _wfopen_s) but they all have the same output.

Interestingly enough, GetLastError() returns ERROR_ALREADY_EXISTS.

Here's the code that I'm using:

```<code>FILE *FileHandle;
DWORD error = _wfopen_s(&FileHandle, L"\\filename.txt", L"a");
Win32Error = GetLastError();

if (error != 0 || FileHandle == NULL)
{
    //Throw error
}
else
{
    //write to file
    //close file
}
</code>```

EDIT: As rerun pointed out, the file is getting created in %APPDATA% because of virtualization.  Does anyone know how to disable this feature?

答: If you are literally running the code you posted, then you aren't asking for a file in the root directory at all. You need to go "c:\\filename.txt" (two '\' characters) instead. Maybe if you look in the current directory you'll find you've successfully created a weirdly named file (basically <formfeed>ilename.txt, I think).

Body:
Whenever I try to create a file using fopen, fopen acts as if the file has been opened properly and that it has full access to it, but it doesn't actually create the file.  My program doesn't have write access to the system root folder because it needs admin access to write there, but why isn't fopen() giving any errors?

Any idea how to tell if there's an error or not?  The file handle that gets returned when I'm trying to open the file in a protected directory is exactly the same as when I open a file in a directory where I have write access.

I've tried this with the various different versions of fopen (fopen, _wfopen, _wfopen_s) but they all have the same output.

Interestingly enough, GetLastError() returns ERROR_ALREADY_EXISTS.

Here's the code that I'm using:

FILE *FileHandle;
DWORD error = _wfopen_s(&FileHandle, L"\\filename.txt", L"a");
Win32Error = GetLastError();

if (error != 0 || FileHandle == NULL)
{
    //Throw error
}
else
{
    //write to file
    //close file
}

EDIT: As rerun pointed out, the file is getting created in %APPDATA% because of virtualization.  Does anyone know how to disable this feature?


问:
Trouble stopping a timer program in Python and Tkinter
I have this timer program in python with a Tkinter GUI. I am able to run the timer user inputs, but I am having trouble pausing or stopping the timer from a tkinter button. I tried creating a variable that changes when the stop button press to initiate time.sleep() in my if statement, but no luck. Any ideas?

```<code>from tkinter import Tk, Label, StringVar
from tkinter.ttk import Button, Entry

class Timer:
    def __init__(self, master):
        self.seconds = 0
        self.f = False
        self.time = StringVar()
        self.time_label = Label(master, relief='flat', font=("Cambria", 20),
                            textvariable=self.time)

        self.hr = StringVar()
        self.hr_label = Label(master, text='Hours:').grid(row=1, column=1, padx=5, pady=1)
        self.entry_hr = Entry(master, textvariable=self.hr, width=4)
        self.entry_hr.grid(row=1, column=2)

        self.mins = StringVar()
        self.min_label = Label(master, text='Minutes:').grid(row=2, column=1, padx=5, pady=1)
        self.entry_min = Entry(master, textvariable=self.mins, width=4)
        self.entry_min.grid(row=2, column=2)

        self.secs = StringVar()
        self.secs_label = Label(master, text='Seconds:').grid(row=3, column=1, padx=5, pady=1)
        self.entry_sec = Entry(master, textvariable=self.secs, width=4)
        self.entry_sec.grid(row=3, column=2)

        self.time.set('00:00:00')
        self.start_button = Button(master, text='Start')
        self.start_button.bind('<Button-1>', self.start_countdown)
        self.stop_button = Button(master, text='Stop')

        self.time_label.grid(row=0, columnspan=4, padx=30, pady=10)
        self.start_button.grid(row=4, columnspan=4, pady=(10,20))
        self.stop_button.grid(row=5, columnspan=4, pady=(10,20))

    def set_time(self, hours, minutes, seconds):
        self.seconds = hours * 3600 + minutes * 60 + seconds
        self.time.set(self.format_time(self.seconds))

    def start_countdown(self, event):
        f = False
        h = self.entry_hr.get()
        m = self.entry_min.get()
        s = self.entry_sec.get()
        h,m,s = map(lambda x: int(x) if x else 0, (h,m,s))
        self.set_time(h,m,s)
        self.countdown()

    def stop(self):
        global f
        f= True

    def countdown(self):
        if self.seconds <= 0:
        return
        else:
            self.end_label = Label( text ="Time's up")
        if self.f == True:
            time.sleep()
        self.time.set(self.format_time(self.seconds))
        self.seconds -= 1
        self.time_label.after(1000, self.countdown)

    def format_time(self, seconds):
        h = seconds // 3600
        m = (seconds - h*3600) // 60
        s = seconds - h*3600 - m*60
        return '{:0>2}:{:0>2}:{:0>2}'.format(h,m,s)

if __name__ == '__main__':
    root = Tk()
    timer = Timer(root)
    root.mainloop()
</code>```

答:
First of all your Button widget self.stop_button doesn't have a command or binding associated with it, so it doesn't actually do anything.

Secondly, even if it did call the function you're changing the value of the global variable f but in your if statement you're referencing the local variable self.f (Timer.f).

Thirdly, you're not calling time.sleep() correctly, it requires a value in seconds to sleep for.

And fourthly, time.sleep() would only delay the function from running for the period of time you specify and would eventually cause the timer to start ticking down again.

Instead, you should do something like the below (after associating the Button widget to the function self.stop()):

```<code>def stop(self):
    self.f = True

def countdown(self):
    if self.f == False:
        print(self.f)
        if self.seconds <= 0:
            return
        else:
            self.end_label = Label( text ="Time's up")
        self.time.set(self.format_time(self.seconds))
        self.seconds -= 1
        self.time_label.after(1000, self.countdown)
</code>```

This will mean that every time we cycle through the function the first thing we do is check whether self.f is False, if it isn't then the timer stops where it is.

Body:
I have this timer program in python with a Tkinter GUI. I am able to run the timer user inputs, but I am having trouble pausing or stopping the timer from a tkinter button. I tried creating a variable that changes when the stop button press to initiate time.sleep() in my if statement, but no luck. Any ideas?

from tkinter import Tk, Label, StringVar
from tkinter.ttk import Button, Entry

class Timer:
    def __init__(self, master):
        self.seconds = 0
        self.f = False
        self.time = StringVar()
        self.time_label = Label(master, relief='flat', font=("Cambria", 20),
                            textvariable=self.time)

        self.hr = StringVar()
        self.hr_label = Label(master, text='Hours:').grid(row=1, column=1, padx=5, pady=1)
        self.entry_hr = Entry(master, textvariable=self.hr, width=4)
        self.entry_hr.grid(row=1, column=2)

        self.mins = StringVar()
        self.min_label = Label(master, text='Minutes:').grid(row=2, column=1, padx=5, pady=1)
        self.entry_min = Entry(master, textvariable=self.mins, width=4)
        self.entry_min.grid(row=2, column=2)

        self.secs = StringVar()
        self.secs_label = Label(master, text='Seconds:').grid(row=3, column=1, padx=5, pady=1)
        self.entry_sec = Entry(master, textvariable=self.secs, width=4)
        self.entry_sec.grid(row=3, column=2)

        self.time.set('00:00:00')
        self.start_button = Button(master, text='Start')
        self.start_button.bind('<Button-1>', self.start_countdown)
        self.stop_button = Button(master, text='Stop')

        self.time_label.grid(row=0, columnspan=4, padx=30, pady=10)
        self.start_button.grid(row=4, columnspan=4, pady=(10,20))
        self.stop_button.grid(row=5, columnspan=4, pady=(10,20))

    def set_time(self, hours, minutes, seconds):
        self.seconds = hours * 3600 + minutes * 60 + seconds
        self.time.set(self.format_time(self.seconds))

    def start_countdown(self, event):
        f = False
        h = self.entry_hr.get()
        m = self.entry_min.get()
        s = self.entry_sec.get()
        h,m,s = map(lambda x: int(x) if x else 0, (h,m,s))
        self.set_time(h,m,s)
        self.countdown()

    def stop(self):
        global f
        f= True

    def countdown(self):
        if self.seconds <= 0:
        return
        else:
            self.end_label = Label( text ="Time's up")
        if self.f == True:
            time.sleep()
        self.time.set(self.format_time(self.seconds))
        self.seconds -= 1
        self.time_label.after(1000, self.countdown)

    def format_time(self, seconds):
        h = seconds // 3600
        m = (seconds - h*3600) // 60
        s = seconds - h*3600 - m*60
        return '{:0>2}:{:0>2}:{:0>2}'.format(h,m,s)

if __name__ == '__main__':
    root = Tk()
    timer = Timer(root)
    root.mainloop()

Body:
First of all your Button widget self.stop_button doesn't have a command or binding associated with it, so it doesn't actually do anything.

Secondly, even if it did call the function you're changing the value of the global variable f but in your if statement you're referencing the local variable self.f (Timer.f).

Thirdly, you're not calling time.sleep() correctly, it requires a value in seconds to sleep for.

And fourthly, time.sleep() would only delay the function from running for the period of time you specify and would eventually cause the timer to start ticking down again.

Instead, you should do something like the below (after associating the Button widget to the function self.stop()):

def stop(self):
    self.f = True

def countdown(self):
    if self.f == False:
        print(self.f)
        if self.seconds <= 0:
            return
        else:
            self.end_label = Label( text ="Time's up")
        self.time.set(self.format_time(self.seconds))
        self.seconds -= 1
        self.time_label.after(1000, self.countdown)

This will mean that every time we cycle through the function the first thing we do is check whether self.f is False, if it isn't then the timer stops where it is.


问:
Spray json trait formatter with nested subclasses
My use-case is the following:

```<code>import spray.json._
import DefaultJsonProtocol._

sealed trait TestT
case class A(a: String) extends TestT
case class B(b: String) extends TestT
case class C(c: TestT) extends TestT

case class Parent(list: Seq[TestT])

implicit val aFormat = jsonFormat1(A)
implicit val bFormat = jsonFormat1(B)

implicit lazy val cFormat = lazyFormat(jsonFormat1(C))

implicit object TestTJsonFormat extends RootJsonFormat[TestT] {
  override def read(json: JsValue) = {
    if(json.asJsObject.fields.get("a").isDefined) {
      json.convertTo[A]
    } else if(json.asJsObject.fields.get("b").isDefined) {
      json.convertTo[B]
    } else if(json.asJsObject.fields.get("c").isDefined) {
      json.convertTo[C]
    } else {
      ???
    }
  }

  override def write(obj: TestT) = {
    obj match {
      case a:A => a.toJson
      case b:B => b.toJson
      case c:C => c.toJson
      case _ => ???
    }
  }
}

implicit val pFormat = jsonFormat1(Parent)

val json = Parent(Seq(A("test"), B("test2"), A("test3"))).toJson
println(json)
val p = json.convertTo[Parent]
println(p)
</code>```

The main problem is that I can't make a formatter for C if I don't have a formatter for TestT. But I can't make a formatter for TestT because I don't have a json.convertTo for C yet...

Any idea how can I resolve this form of dependency?

答:
https://github.com/milessabin/spray-json-shapeless

Serialize whole classtrees.

```<code>object MyFormats extends DefaultJsonProtocol with FamilyFormats {
  // gives a slight performance boost, but isn't necessary
  implicit val MyAdtFormats = shapeless.cachedImplicit[JsonFormat[TestT]]
}
import MyFormats._
</code>```

Body:
My use-case is the following:

import spray.json._
import DefaultJsonProtocol._

sealed trait TestT
case class A(a: String) extends TestT
case class B(b: String) extends TestT
case class C(c: TestT) extends TestT

case class Parent(list: Seq[TestT])

implicit val aFormat = jsonFormat1(A)
implicit val bFormat = jsonFormat1(B)

implicit lazy val cFormat = lazyFormat(jsonFormat1(C))

implicit object TestTJsonFormat extends RootJsonFormat[TestT] {
  override def read(json: JsValue) = {
    if(json.asJsObject.fields.get("a").isDefined) {
      json.convertTo[A]
    } else if(json.asJsObject.fields.get("b").isDefined) {
      json.convertTo[B]
    } else if(json.asJsObject.fields.get("c").isDefined) {
      json.convertTo[C]
    } else {
      ???
    }
  }

  override def write(obj: TestT) = {
    obj match {
      case a:A => a.toJson
      case b:B => b.toJson
      case c:C => c.toJson
      case _ => ???
    }
  }
}

implicit val pFormat = jsonFormat1(Parent)

val json = Parent(Seq(A("test"), B("test2"), A("test3"))).toJson
println(json)
val p = json.convertTo[Parent]
println(p)

The main problem is that I can't make a formatter for C if I don't have a formatter for TestT. But I can't make a formatter for TestT because I don't have a json.convertTo for C yet...

Any idea how can I resolve this form of dependency?

Body:
https://github.com/milessabin/spray-json-shapeless

Serialize whole classtrees.

object MyFormats extends DefaultJsonProtocol with FamilyFormats {
  // gives a slight performance boost, but isn't necessary
  implicit val MyAdtFormats = shapeless.cachedImplicit[JsonFormat[TestT]]
}
import MyFormats._


问:
passing props with Link in React-Router
Hello i'm trying to pass Props to a Details Component with the Link Component from React Router. I don't want to display the Detail Component  on the page, it should render when a button is clicked but also the url should look like this '/details/KvhNJecsqr6JFMSRTS' when the new Component renders.

```<code> class  Card extends Component {
                    render(props){
                    return(
                   <Col xs={12} md={4}>
                    <Thumbnail src="./someiamge">
                      <h3>{this.props.cardHeading}</h3>
                      <p>{this.props.cardDesc}</p>
                        <Button bsStyle="primary">Mieten</Button>
                        <Button bsStyle="default"><Link to='/details' params={{cardId: this.props.cardId}} 'here i wanna pass some props how i do this ?' >Details</Link></Button>
                    </Thumbnail>
                  </Col>

                    )
                  }
                }

export default Card
</code>```

Here is my Router stuff

```<code><BrowserRouter>
          <div>
              <Route name='details' path='/details/:cardId' component={Details}/>
            </div>
          </div>
</BrowserRouter>
</code>```

hier is my Details Component:

```<code>    class Details extends Component {
      render() {
        return (
          <div >
            <div style={{textAlign: "left"}}>
              <h3>{this.props.cardHeading}</h3>
              <p>{this.props.cardDesc}</p>
              .......
            </div>
          </div>
        );
      }
    }

    export default Details;
</code>```

答:
In your link code it should be this, I believe:

```<code><Link to={{ pathname: '/details', query: { cardId: this.props.cardId } }}/>
</code>```

The Route would be the same as you currently have it.

Title: passing props with Link in React-Router

Body:
Hello i'm trying to pass Props to a Details Component with the Link Component from React Router. I don't want to display the Detail Component  on the page, it should render when a button is clicked but also the url should look like this '/details/KvhNJecsqr6JFMSRTS' when the new Component renders.

 class  Card extends Component {
                    render(props){
                    return(
                   <Col xs={12} md={4}>
                    <Thumbnail src="./someiamge">

{this.props.cardHeading}

{this.props.cardDesc}

                        <Button bsStyle="primary">Mieten</Button>
                        <Button bsStyle="default"><Link to='/details' params={{cardId: this.props.cardId}} 'here i wanna pass some props how i do this ?' >Details</Link></Button>
                    </Thumbnail>
                  </Col>

                    )
                  }
                }

export default Card

Here is my Router stuff

<BrowserRouter>

              <Route name='details' path='/details/:cardId' component={Details}/>

</BrowserRouter>

hier is my Details Component:

    class Details extends Component {
      render() {
        return (

{this.props.cardHeading}

{this.props.cardDesc}

              .......

        );
      }
    }

    export default Details;

Body:
In your link code it should be this, I believe:

<Link to={{ pathname: '/details', query: { cardId: this.props.cardId } }}/>

The Route would be the same as you currently have it.


问:
Why isn't Date(2015, 11, 1) the first of December?
When I convert that date to ISO string I get the 30th of november 2015. Why wouldn't it be first of december? I have googled and I know that month is 0-indexed and that overflows lead to the next day/month/year. But I cannot explain myself that behaviour and when I google it I find unrelated topics.</p>

答:
```<code>var date = new Date(Date.UTC(2015, 11, 1));
console.log(date.toISOString());
</code>```

Output:

```<code>2015-12-01T02:00:00.000Z
</code>```

Body:
var date = new Date(Date.UTC(2015, 11, 1));
console.log(date.toISOString());

Output:

2015-12-01T02:00:00.000Z


问:
React JSX vs function call to present component
```<code>const Component = ({ text }) => (
  <div>{text}</div>
)

const Example = () => (
  <div>
    <Component text="123" />
    {Component({ text: "123" })}
  </div>
)
</code>```

Is there any difference between the two methods of rendering? Which is preferred and why?

答:
I recommend that you don't call function components but render them instead. This approach may lead to unexpected behaviors (mainly if you are using hooks). For more details see Don't call a React function component by Kent C. Dodds.

However the second is faster because it's not mounted with React.createElement. See this great article by Philippe Lehoux that talks about the differences (mainly in performance) between both approaches.

Body:
const Component = ({ text }) => (

{text}

)

const Example = () => (

    <Component text="123" />
    {Component({ text: "123" })}

)

Is there any difference between the two methods of rendering? Which is preferred and why?