问:
Haskell logbase error
I am trying to calculate the length of an Integer in Haskell, using the fact that the length is equal to truncate (log10(x)+1).

Using Integers I created:

```<code>len :: Integer -> Integer
len i = toInteger (truncate (logBase 10 (fromIntegral i)) + 1)
</code>```

Unfortunately, not all numbers get the correct length. I tried a few different cases and found that:

```<code>logBase 10 10         = 1.0
logBase 10 100        = 2.0
logBase 10 1000       = 2.9999..6
logBase 10 10000      = 4.0
logBase 10 100000     = 5.0
logBase 10 1000000    = 5.9999999
</code>```

Is there a reason why logBase 10 1000 doesn't return 3.0? How do I get the correct log-value for 1000 in base 10?

答:
If you don't need Double Floating precision then use Float type instead and it seems fine. Such as logBase 10 (1000 :: Float) would return 3.0 or functionally logBase 10 . (fromInteger :: Integer -> Float) $ 1000 would do the same.

As per your code toInteger seems redundant since truncate :: (Integral b, RealFrac a) => a -> b already does that job. So may simply do like

```<code>len :: Integer -> Integer
len = (+1) . truncate . logBase 10 . (fromIntegral :: Integer -> Float)
</code>```

This will work correctly up until 9999987.

Title: Haskell logbase error

Body:
I am trying to calculate the length of an Integer in Haskell, using the fact that the length is equal to truncate (log10(x)+1).

Using Integers I created:

len :: Integer -> Integer
len i = toInteger (truncate (logBase 10 (fromIntegral i)) + 1)

Unfortunately, not all numbers get the correct length. I tried a few different cases and found that:

logBase 10 10         = 1.0
logBase 10 100        = 2.0
logBase 10 1000       = 2.9999..6
logBase 10 10000      = 4.0
logBase 10 100000     = 5.0
logBase 10 1000000    = 5.9999999

Is there a reason why logBase 10 1000 doesn't return 3.0? How do I get the correct log-value for 1000 in base 10?

Body:
If you don't need Double Floating precision then use Float type instead and it seems fine. Such as logBase 10 (1000 :: Float) would return 3.0 or functionally logBase 10 . (fromInteger :: Integer -> Float) $ 1000 would do the same.

As per your code toInteger seems redundant since truncate :: (Integral b, RealFrac a) => a -> b already does that job. So may simply do like

len :: Integer -> Integer
len = (+1) . truncate . logBase 10 . (fromIntegral :: Integer -> Float)

This will work correctly up until 9999987.


来源: stackexchange

问:
user photo in tab navigation
In a react native project I am trying to set the user's profile photo as a tabBarIcon in tabNavigation. Below is how I am trying to retrieve the photo path and set it in the source for TabBarIcon.

First I have a token in AsyncStorage that gives me the username, email, or phonenumber of the user after login (works fine). This is in my constructor:

```<code>constructor(props) {
  super(props)

  this.state = {
    Access: []
  }

}
</code>```

I set the Access in my state to a value in my AsyncStorage with getItem('Access') which i know works fine.

Now i have a function getProfilePhoto where I use fetch to get the profile photo.

```<code>getProfilePhoto = () => {

  const { Access } = this.state.access;

  fetch('http://urltofiletogetprofilephoto', {
    method: 'POST',
    headers: {
      'Accept':'application/json',
      'Content-Type':'application/json',
    },
    body: JSON.stringify({
      Access:Access
    })
  }).then((response) => response.json())
    .then((responseJson) => {
      if(responseJson === 'NULL') {
        console.log('../Images/NoPhoto.png');
      } else {
        console.log('../' + responseJson);
      }
    })

}
</code>```

What I return from that file is:

```<code>$profilephoto = $row['ProfilePhoto'];
$profilephotoJson = json_encode($profilephoto);
echo $profilephotoJson;
</code>```

That should return something like "Images/userprofilephoto.png". Now in navigationOptions I have this:

```<code>static navigationOptions = {
    tabBarLabel: 'Profile',
    tabBarIcon: ({ tintColor }) => (
        <Image
            source = {this.getProfilePhoto}
            style={[styles.icon, {tintColor: tintColor}]}
        />
    )
}
</code>```

I thought calling the function would print the returned Image path, but when I run the app on my device I don't get an error but my tabBarIcon Image is just blank. I am new to react native and haven't worked with Json much I am hoping someone will be able to see something wrong that I am missing!

答:
try

```<code>source={require(this.getProfilePhoto())}
</code>```

However your function getProfilePhoto is not returning a path as you are using fetch.

Also navigationOptions is static, so this is not available.

You will need to access it via navigation params

```<code>static navigationOptions = ({ navigation }) => {
const { state } = navigation;
    return {
        tabBarLabel: 'Profile',
        tabBarIcon: ({ tintColor }) => (
            <Image
                source = {state.params.getImage()}
                style={[styles.icon, {tintColor: tintColor}]}
            />
        )
    }
}

componentWillMount() {
    this.props.navigation.setParams({
      getImage: () => {
        this.getProfilePhoto();
      },
    });
  }

getProfilePhoto () => {
    //here you can get the path from this.props which would be added
    //as before the component mounts
    return this.props.profileImagePath;  //set from redux connect
}
</code>```

One downside with this is that if you want to update the image on the fly, you will need to call setParams again to force it to re-render the tab.

```<code> componentWillReceiveProps(nextProps) {
   this.props.navigation.setParams({
      getImage: () => {
        this.getProfilePhoto();
      },
    });
 }
</code>```

I would have the action of getting the image separate to the component, and use Redux to connect to the latest image path. You can therefore set the Redux store triggered from another component.

ContentLicense: CC BY-SA 3.0

Title: user photo in tab navigation

Body:
In a react native project I am trying to set the user's profile photo as a tabBarIcon in tabNavigation. Below is how I am trying to retrieve the photo path and set it in the source for TabBarIcon.

First I have a token in AsyncStorage that gives me the username, email, or phonenumber of the user after login (works fine). This is in my constructor:

constructor(props) {
  super(props)

  this.state = {
    Access: []
  }

}

I set the Access in my state to a value in my AsyncStorage with getItem('Access') which i know works fine.

Now i have a function getProfilePhoto where I use fetch to get the profile photo.

getProfilePhoto = () => {

  const { Access } = this.state.access;

  fetch('http://urltofiletogetprofilephoto', {
    method: 'POST',
    headers: {
      'Accept':'application/json',
      'Content-Type':'application/json',
    },
    body: JSON.stringify({
      Access:Access
    })
  }).then((response) => response.json())
    .then((responseJson) => {
      if(responseJson === 'NULL') {
        console.log('../Images/NoPhoto.png');
      } else {
        console.log('../' + responseJson);
      }
    })

}

What I return from that file is:

$profilephoto = $row['ProfilePhoto'];
$profilephotoJson = json_encode($profilephoto);
echo $profilephotoJson;

That should return something like "Images/userprofilephoto.png". Now in navigationOptions I have this:

static navigationOptions = {
    tabBarLabel: 'Profile',
    tabBarIcon: ({ tintColor }) => (
        <Image
            source = {this.getProfilePhoto}
            style={[styles.icon, {tintColor: tintColor}]}
        />
    )
}

I thought calling the function would print the returned Image path, but when I run the app on my device I don't get an error but my tabBarIcon Image is just blank. I am new to react native and haven't worked with Json much I am hoping someone will be able to see something wrong that I am missing!

Body:
try

source={require(this.getProfilePhoto())}

However your function getProfilePhoto is not returning a path as you are using fetch.

Also navigationOptions is static, so this is not available.

You will need to access it via navigation params

static navigationOptions = ({ navigation }) => {
const { state } = navigation;
    return {
        tabBarLabel: 'Profile',
        tabBarIcon: ({ tintColor }) => (
            <Image
                source = {state.params.getImage()}
                style={[styles.icon, {tintColor: tintColor}]}
            />
        )
    }
}

componentWillMount() {
    this.props.navigation.setParams({
      getImage: () => {
        this.getProfilePhoto();
      },
    });
  }

getProfilePhoto () => {
    //here you can get the path from this.props which would be added
    //as before the component mounts
    return this.props.profileImagePath;  //set from redux connect
}

One downside with this is that if you want to update the image on the fly, you will need to call setParams again to force it to re-render the tab.

 componentWillReceiveProps(nextProps) {
   this.props.navigation.setParams({
      getImage: () => {
        this.getProfilePhoto();
      },
    });
 }

I would have the action of getting the image separate to the component, and use Redux to connect to the latest image path. You can therefore set the Redux store triggered from another component.


问:
How to manipulate information from a GET response
I'm new to java / rest / jersey, so please bear with me.

Problem: I want to use a GET method to retrieve some information I have previously POSTed. My only confusion is...where is the information after I call the GET?

Here is my post (you can ignore it as I know this part works):

```<code>@POST @Path("/tools")
public Response createTool(JsonNode tool) throws URISyntaxException {

    //use custom validator to de-couple implementation from validation
    ToolValidator validator = new ToolValidator(tool);

    if(validator.isNotNull() == false) {
        System.out.println("in not null");
        return Response.status(400).entity("Please add tool details").build();
    }

    if (validator.hasValidType() == false) {
        System.out.println("in valid timestamp");
        return Response.status(400).entity("Please provide a valid tool type").build();
    }

    if(validator.haveValidValues() == false ) {
        System.out.println("in valid values");
        return Response.status(400).entity("Please provide a tools list with valid numerical values").build();
    }

    String type= tool.get("type").asText();

    return Response.status(201).entity(tool).build().created(new URI("/tools/"+type)).build();

}
</code>```

It definitely posts a tool correctly (I've tested it and seen it, I believe this works but it might not).

Now what I want to do is get the json, see if adheres to some requirements, and return an answer.  Basically, irrelevant of the POST code above, for any url that returns some json when you navigate to it, I want to be able to grab that json and do something with it.

```<code>@GET @Path("/tools/{type}")
public Response getToolInfo(@PathParam("type") String type) {
    return Response.ok().build();
}
</code>```

My only question here is..."where" is the information to manipulate?? I feel like I'm asking an extremely fundamental, basic question for REST / Jersey, so I apologize if this is like the ABCs here.

Basically, I use my POST method to POST a tool with some specific json.  I can navigate to that page and see the json object.  Now I want to use a GET method to analyze the json but...I have no idea how / where this information is stored when I decide to use a GET method.

Does the @get annotation automatically store the information returned from the specified path somewhere? Does anything?

答:
From the code you pasted it doesn't look like anything is stored. In your @POST it looks like you pass JsonNode tool, from that you create an object of type ToolValidator which you use to do some sort of validation. From your JsonNode tool you retrieve a field called "type".

At last you create a response instance with the parameter you already passed and you change the Uri to "/tools/" and the String value of whatever is in the variable "type".

So it doesn't look like you are doing any database access to store the JsonNode passed as parameter.

It definitely posts a tool correctly (I've tested it and seen it).

It posts the tool because of this Response.status(201).entity(tool).build()
You are just simply telling it to set the response entity in the builder. Whereas build() a response instance.

For testing purposes only create a global variable, in your class, of type JsonNode and copy the passed parameter (JsonNode tool), in your POST method, to your global variable. Then you can retrieve it in your GET method. Don't forget to create getter and setter for your global variable.

In a real life scenario though you would be storing things in your database. If it's just for some prototype then a global variable should be enough

Here is a tiny example of what I mean:

```<code>public class SomeClass {
    private JsonNode copiedTool;

    @POST @Path("/tools")
    public Response createTool(JsonNode tool) throws URISyntaxException {

        setCopiedTool(tool);

        String type= tool.get("type").asText();

        return Response.status(201).entity(getCopiedTool()).build().created(new URI("/tools/"+type)).build();
    }

    @GET @Path("/tools/{type}")
    public Response getToolInfo(@PathParam("type") String type) {

        if(getCopiedTool().get("type").equals(type)) {
            return Response.ok(getCopiedTool()).build();
        }
        return Response.status(204).build();
    }

    public JsonNode getCopiedTool() {
        return copiedTool;
    }

    public void setCopiedTool(JsonNode copiedTool) {
        this.copiedTool = copiedTool;
    }
}
</code>```

Body:
I'm new to java / rest / jersey, so please bear with me.

Problem: I want to use a GET method to retrieve some information I have previously POSTed. My only confusion is...where is the information after I call the GET?

Here is my post (you can ignore it as I know this part works):

@POST @Path("/tools")
public Response createTool(JsonNode tool) throws URISyntaxException {

    //use custom validator to de-couple implementation from validation
    ToolValidator validator = new ToolValidator(tool);

    if(validator.isNotNull() == false) {
        System.out.println("in not null");
        return Response.status(400).entity("Please add tool details").build();
    }

    if (validator.hasValidType() == false) {
        System.out.println("in valid timestamp");
        return Response.status(400).entity("Please provide a valid tool type").build();
    }

    if(validator.haveValidValues() == false ) {
        System.out.println("in valid values");
        return Response.status(400).entity("Please provide a tools list with valid numerical values").build();
    }

    String type= tool.get("type").asText();

    return Response.status(201).entity(tool).build().created(new URI("/tools/"+type)).build();

}

It definitely posts a tool correctly (I've tested it and seen it, I believe this works but it might not).

Now what I want to do is get the json, see if adheres to some requirements, and return an answer.  Basically, irrelevant of the POST code above, for any url that returns some json when you navigate to it, I want to be able to grab that json and do something with it.

@GET @Path("/tools/{type}")
public Response getToolInfo(@PathParam("type") String type) {
    return Response.ok().build();
}

My only question here is..."where" is the information to manipulate?? I feel like I'm asking an extremely fundamental, basic question for REST / Jersey, so I apologize if this is like the ABCs here.

Basically, I use my POST method to POST a tool with some specific json.  I can navigate to that page and see the json object.  Now I want to use a GET method to analyze the json but...I have no idea how / where this information is stored when I decide to use a GET method.

Does the @get annotation automatically store the information returned from the specified path somewhere? Does anything?

Body:
From the code you pasted it doesn't look like anything is stored. In your @POST it looks like you pass JsonNode tool, from that you create an object of type ToolValidator which you use to do some sort of validation. From your JsonNode tool you retrieve a field called "type".

At last you create a response instance with the parameter you already passed and you change the Uri to "/tools/" and the String value of whatever is in the variable "type".

So it doesn't look like you are doing any database access to store the JsonNode passed as parameter.

It definitely posts a tool correctly (I've tested it and seen it).

It posts the tool because of this Response.status(201).entity(tool).build()
You are just simply telling it to set the response entity in the builder. Whereas build() a response instance.

For testing purposes only create a global variable, in your class, of type JsonNode and copy the passed parameter (JsonNode tool), in your POST method, to your global variable. Then you can retrieve it in your GET method. Don't forget to create getter and setter for your global variable.

In a real life scenario though you would be storing things in your database. If it's just for some prototype then a global variable should be enough

Here is a tiny example of what I mean:

public class SomeClass {
    private JsonNode copiedTool;

    @POST @Path("/tools")
    public Response createTool(JsonNode tool) throws URISyntaxException {

        setCopiedTool(tool);

        String type= tool.get("type").asText();

        return Response.status(201).entity(getCopiedTool()).build().created(new URI("/tools/"+type)).build();
    }

    @GET @Path("/tools/{type}")
    public Response getToolInfo(@PathParam("type") String type) {

        if(getCopiedTool().get("type").equals(type)) {
            return Response.ok(getCopiedTool()).build();
        }
        return Response.status(204).build();
    }

    public JsonNode getCopiedTool() {
        return copiedTool;
    }

    public void setCopiedTool(JsonNode copiedTool) {
        this.copiedTool = copiedTool;
    }
}


问:
Liquibase changelog parameters in liquibase.properties
As per documentation parameter values are looked up in the following order:

Passed as a parameter to your Liquibase runner (see Ant, command_line, etc. documentation for how to pass them)

As a JVM system property

In the parameters block ( Tag) of the DatabaseChangeLog file itself.

Can I set these parameters in the standard properties file?

答:
Yes, and is very usefull if you want to manage information under control...like passwords in differents enviroments:
liquibase.properties:

```<code>parameter.pass_admin=idonthavepassword
</code>```

and the changelog:

```<code><changeSet author="rbs" id="create_user_admin" labels="inicial">
    <preConditions onFail="CONTINUE">
    <sqlCheck expectedResult="0">SELECT COUNT(1) FROM pg_roles WHERE rolname='admin'</sqlCheck>
    </preConditions>
    <sql>CREATE USER admin PASSWORD '${pass_admin}' LOGIN SUPERUSER NOCREATEDB NOCREATEROLE INHERIT NOREPLICATION CONNECTION LIMIT -1
        <comment>Creating admin user</comment>
    </sql>
</changeSet>
</code>```

Body:
Yes, and is very usefull if you want to manage information under control...like passwords in differents enviroments:
liquibase.properties:

parameter.pass_admin=idonthavepassword

and the changelog:

<changeSet author="rbs" id="create_user_admin" labels="inicial">
    <preConditions onFail="CONTINUE">
    <sqlCheck expectedResult="0">SELECT COUNT(1) FROM pg_roles WHERE rolname='admin'</sqlCheck>
    </preConditions>
    <sql>CREATE USER admin PASSWORD '${pass_admin}' LOGIN SUPERUSER NOCREATEDB NOCREATEROLE INHERIT NOREPLICATION CONNECTION LIMIT -1
        <comment>Creating admin user</comment>
    </sql>
</changeSet>


问:
C++ permutations of specified parts in 2D array
I have a simple two 2D arrays (represented as map), filled with 1 and 0.

```<code>    | A | B | C | D | sum
--------------------------
  A | 0 | 1 | 1 | 1 |  3
  B | 1 | 0 | 0 | 0 |  1
  C | 1 | 0 | 0 | 1 |  2
  D | 1 | 0 | 1 | 0 |  1
</code>```

it is representation of a graph, so the table is symmetrical to the main diagonal (no members has relation to themselves /no recursion/).
I need to generate permutations of specified columns/rows.
I know there's a next_permutation() function, but i don't know how to use it (for 2D array representing graph), i guess i need to write own algorithm for just returning index of 2 columns/rows for switching. I cannot realize, that i would rewrite the whole table just because of switching 2 cols/rows.

And the most hard of all is, that switching all rows/cols is not neccessary, when there are rows, which has unique sum - this cols/rows (in my case A) can stay on their place, because it's clear to which member in second table they belong (= there's no more members with the same number of relations).

After i'll be able to generate permutations of A-D (its table), i can compare the generated table to the second and check, whether are same (that's what i have already done).

How can i do the permutations?

答: There are just 64 variants of bidirectional graphs like you describe with 4 vertices. In other words your graph contains 6 bits of information and is therefore easy to construct from numbers 0 to 63. </p>

ContentLicense: CC BY-SA 2.5

Body:
I have a simple two 2D arrays (represented as map), filled with 1 and 0.

    | A | B | C | D | sum
--------------------------
  A | 0 | 1 | 1 | 1 |  3
  B | 1 | 0 | 0 | 0 |  1
  C | 1 | 0 | 0 | 1 |  2
  D | 1 | 0 | 1 | 0 |  1

it is representation of a graph, so the table is symmetrical to the main diagonal (no members has relation to themselves /no recursion/).
I need to generate permutations of specified columns/rows.
I know there's a next_permutation() function, but i don't know how to use it (for 2D array representing graph), i guess i need to write own algorithm for just returning index of 2 columns/rows for switching. I cannot realize, that i would rewrite the whole table just because of switching 2 cols/rows.

And the most hard of all is, that switching all rows/cols is not neccessary, when there are rows, which has unique sum - this cols/rows (in my case A) can stay on their place, because it's clear to which member in second table they belong (= there's no more members with the same number of relations).

After i'll be able to generate permutations of A-D (its table), i can compare the generated table to the second and check, whether are same (that's what i have already done).

How can i do the permutations?


问:
Is there a way to use pipenv with Jupyter notebook?
Is there a way to use pipenv with Jupyter notebook?

Or more specifically, with an atom nteract/hydrogen python 3 kernel?

答:
Just tried the following with success.

In your project folder:

```<code>pipenv install ipykernel
pipenv shell
</code>```

This will bring up a terminal in your virtualenv like this:

```<code>(my-virtualenv-name) bash-4.4$
</code>```

In that shell do:

```<code>python -m ipykernel install --user --name=my-virtualenv-name
</code>```

Launch jupyter notebook:

```<code>jupyter notebook
</code>```

In your notebook, Kernel -> Change Kernel. Your kernel should now be an option.

Source: IPythonNotebookVirtualenvs

Body:
Just tried the following with success.

In your project folder:

pipenv install ipykernel
pipenv shell

This will bring up a terminal in your virtualenv like this:

(my-virtualenv-name) bash-4.4$

In that shell do:

python -m ipykernel install --user --name=my-virtualenv-name

Launch jupyter notebook:

jupyter notebook

In your notebook, Kernel -> Change Kernel. Your kernel should now be an option.

Source: IPythonNotebookVirtualenvs

ContentLicense: CC BY-SA 4.0


问:
How to use babel with npm package that will be used by react
Trying to do what I thought was a simple thing.

I have a node package that uses advanced js syntax. I want to depend on it in a react project.

So I installed babel packages via --save-dev, and added a .babelrc:

```<code>{
  "presets": ["env"],
  "plugins": ["transform-object-rest-spread"]
}
</code>```

That was not enough so I added an npm script under install to trigger the compilation. Then I had to include the compiled target lib/index.js as my entry point via main. So in the end my package.json looks something like this:

```<code>{
  "name": "bla",
  "version": "1.0.0",
  "scripts": {
    "postinstall": "babel src --out-dir lib"
  },
  "main": "lib/index.js",
  "dependencies": {},
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-plugin-transform-object-rest-spread": "^6.26.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react-native": "^4.0.0"
  }
}
</code>```

When I run npm install locally on this project, it builds properly. However when react scripts build this (the dep is from github), I get an error: sh: 1: babel: not found.

Why is this so difficult? What am I doing wrong?

答:
This hack worked instead of the postinstall:

```<code>...
"preinstall": "npm install --ignore-scripts && babel src --out-dir lib",
...
</code>```

Source: https://github.com/Financial-Times/structured-google-docs-client/commit/891180db742ed00cace0139b201850f79d337098

Also relevant: https://github.com/npm/npm/issues/10366

Body:
Trying to do what I thought was a simple thing.

I have a node package that uses advanced js syntax. I want to depend on it in a react project.

So I installed babel packages via --save-dev, and added a .babelrc:

{
  "presets": ["env"],
  "plugins": ["transform-object-rest-spread"]
}

That was not enough so I added an npm script under install to trigger the compilation. Then I had to include the compiled target lib/index.js as my entry point via main. So in the end my package.json looks something like this:

{
  "name": "bla",
  "version": "1.0.0",
  "scripts": {
    "postinstall": "babel src --out-dir lib"
  },
  "main": "lib/index.js",
  "dependencies": {},
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-plugin-transform-object-rest-spread": "^6.26.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react-native": "^4.0.0"
  }
}

When I run npm install locally on this project, it builds properly. However when react scripts build this (the dep is from github), I get an error: sh: 1: babel: not found.

Why is this so difficult? What am I doing wrong?

Body:
This hack worked instead of the postinstall:

...
"preinstall": "npm install --ignore-scripts && babel src --out-dir lib",
...

Source: https://github.com/Financial-Times/structured-google-docs-client/commit/891180db742ed00cace0139b201850f79d337098

Also relevant: https://github.com/npm/npm/issues/10366


问:
What is the total number of nodes generated by Iterative Deepening depth first search and Breadth First search
What is the total number of nodes generated by Iterative Deepening depth first search and Breadth First search in terms of branching factor "b" and depth of shallowest goal "d"</p>

答:
As seen on Wikipedia:

"In an iterative deepening search, the nodes at depth d are expanded once, those at depth d-1 are expanded twice, and so on up to the root of the search tree, which is expanded d+1 times.[5] So the total number of expansions in an iterative deepening search is
IDS number of expansions

Example:
For b=10 and d=5
example
"

Reference:
https://en.wikipedia.org/wiki/Iterative_deepening_depth-first_search#Proof


问:
geom_bar bars not displaying when specifying ylim
I'm having a problem with geom_bars wherein the bars are not rendered when I specify limits on the y-axis.  I believe the following should reproduce the problem:

```<code>data <- structure(list(RoleCond = structure(c(1L, 1L, 2L, 2L), .Label = c("Buyer", "Seller"), class = "factor"),
                   ArgCond = structure(c(1L, 2L, 1L, 2L), .Label = c("No Argument", "Argument"), class = "factor"),
                   mean = c(2210.71428571429, 2142.70833333333, 2282.40740740741, 2346.2962962963),
                   se = c(20.1231042081511, 16.7408757749718, 20.1471554637891, 15.708092540868)),
                   .Names = c("RoleCond", "ArgCond", "mean", "se"), row.names = c(NA, -4L), class = "data.frame")

library(ggplot2)
ggplot(data=data, aes(fill=RoleCond, y=mean, x=ArgCond)) +
      geom_bar(position="dodge", stat="identity") +
      geom_errorbar(limits, position=dodge, width=0.1, size=.75) +
      scale_y_continuous(limits=c(2000,2500))
</code>```

which gives me this

The same code without the limits specified works fine. The geom_errorbar() doesn't seem to be related to the problem, but it does illustrate where the bars should be showing up.

I've tried using coord_cartesian(ylim=c(2000,2500)) which works for limiting the yaxis and getting the bars to display, but the axis labels get messed up and I don't understand what I'm doing with it.

Thanks for any suggestions!  (I'm using R 2.15.0 and ggplot2 0.9.0)

答:
This worked for me based on the link shared previously.</p>

```<code>p + coord_cartesian(ylim=c(5,15))
</code>```

Body:
I'm having a problem with geom_bars wherein the bars are not rendered when I specify limits on the y-axis.  I believe the following should reproduce the problem:

data <- structure(list(RoleCond = structure(c(1L, 1L, 2L, 2L), .Label = c("Buyer", "Seller"), class = "factor"),
                   ArgCond = structure(c(1L, 2L, 1L, 2L), .Label = c("No Argument", "Argument"), class = "factor"),
                   mean = c(2210.71428571429, 2142.70833333333, 2282.40740740741, 2346.2962962963),
                   se = c(20.1231042081511, 16.7408757749718, 20.1471554637891, 15.708092540868)),
                   .Names = c("RoleCond", "ArgCond", "mean", "se"), row.names = c(NA, -4L), class = "data.frame")

library(ggplot2)
ggplot(data=data, aes(fill=RoleCond, y=mean, x=ArgCond)) +
      geom_bar(position="dodge", stat="identity") +
      geom_errorbar(limits, position=dodge, width=0.1, size=.75) +
      scale_y_continuous(limits=c(2000,2500))

which gives me this

The same code without the limits specified works fine. The geom_errorbar() doesn't seem to be related to the problem, but it does illustrate where the bars should be showing up.

I've tried using coord_cartesian(ylim=c(2000,2500)) which works for limiting the yaxis and getting the bars to display, but the axis labels get messed up and I don't understand what I'm doing with it.

Thanks for any suggestions!  (I'm using R 2.15.0 and ggplot2 0.9.0)

Body:
This worked for me based on the link shared previously.

p + coord_cartesian(ylim=c(5,15))


问:
Access Configuration from a View in ASP.NET Core
How can I access IConfiguration in an MVC View in ASP.NET Core 1.1?

Ex. _Layout.cshtml

```<code><link href="@Configuration["MyConfigEntry"]/css/site.min.css>
</code>```

答:
If the posted link is where you took your example, then Probably by doing

```<code><link href="@Startup.Configuration["MyConfigEntry"]/css/site.min.css>
</code>```

This is because you set the Configuration object as static while bootstrap the application.

From Configure an ASP.NET Core App

```<code>public static IConfigurationRoot Configuration { get; set; }
</code>```

Body:
How can I access IConfiguration in an MVC View in ASP.NET Core 1.1?

Ex. _Layout.cshtml

<link href="@Configuration["MyConfigEntry"]/css/site.min.css>

Body:
If the posted link is where you took your example, then Probably by doing

<link href="@Startup.Configuration["MyConfigEntry"]/css/site.min.css>

This is because you set the Configuration object as static while bootstrap the application.

From Configure an ASP.NET Core App

public static IConfigurationRoot Configuration { get; set; }


问:
I deleted a React component that was never used, but now the page won't render... huh?
I had a component in a ReactJS app I am working on that I sweeeearrr is not used anywhere. It even gave me the warning that "footer is defined but not used'. It isn't render anywhere and it never did anything, modify state... yet I'm getting an error message that says that the page cannot be rendered because the file is missing after I deleted it.

Is this simply a matter that I must be missing a connection somewhere?

答:
A few troubleshooting tips. It's helpful if you include these details in your question so we know what you've already tried. Try one at a time and see if the error resolves:

Restart your server (webpack-dev?).

Clear browser cache or open an incognito window and load the page again.

String-search your project for the file name.


问:
How to use HTTP server for getting input from the client and manipulate it
I'v been using python before but never web.

I want to write a python program for generating a server that get the client input and do some function with it.

for example: a word.

And than return it's ASCII value.

I guess it's a very basic question, but I am totaly new to this stuff.

答:
Easy way is to use BaseHTTPServer, check this example:

```<code>import BaseHTTPServer

class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
  def do_GET(self):
    requestPath = self.path
    self.send_response(200)
    self.send_header('Content-type', 'application/json')
    self.end_headers()
    self.wfile.write("requested path: " + requestPath)

httpServer = BaseHTTPServer.HTTPServer(('127.0.0.1', 80), RequestHandler)
httpServer.serve_forever()
</code>```

Note: To run on port 80 you need permissions, so either run this with sudo or use some bigger port number (like 8080).

Body:
Easy way is to use BaseHTTPServer, check this example:

import BaseHTTPServer

class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
  def do_GET(self):
    requestPath = self.path
    self.send_response(200)
    self.send_header('Content-type', 'application/json')
    self.end_headers()
    self.wfile.write("requested path: " + requestPath)

httpServer = BaseHTTPServer.HTTPServer(('127.0.0.1', 80), RequestHandler)
httpServer.serve_forever()

Note: To run on port 80 you need permissions, so either run this with sudo or use some bigger port number (like 8080).


问:
C++-CLI Button Arrays to C# Button Arrays in Winforms
I am designing an application in C# Winforms (for the first time). I've designed several applications in C++ in the past, and am having difficulty converting some of my C++-CLI functions to C#.

I have 5 buttons along a side bar that toggles the visibility of the button's corresponding panel per button click. In order to do this, I set the visibility of all other panels to false. In order to achieve this in C++-CLI, I've done the following:

```<code>private: System::Void panels_Click(System::Object^  sender, System::EventArgs^  e) {
    System::Windows::Forms::Button ^ currentbutton = (System::Windows::Forms::Button ^) sender;
    array < Panel ^ > ^ objects = { panel1, panel2, panel3, panel4, panel5, panel6};
    array < Button ^ > ^ buttons = { button1, button2, button3, button4, button5, button6 };

    for (int i = 0; i < 6; i++) {
        if (buttons[i]->Equals(currentbutton)) {
            objects[i]->Visible = true;
        }
        else objects[i]->Visible = false;
    }
}
</code>```

The issue I am having is with the " array Panel ^" portion, as I can not find an equivalent in C#. Any help is appreciated.

答:
Arrays are declared in C# using TypeName[].

```<code>Panel[] objects = { panel1, panel2, panel3, panel4, panel5, panel6 };
Button[] buttons = { button1, button2, button3, button4, button5, button6 };
</code>```

Body:
I am designing an application in C# Winforms (for the first time). I've designed several applications in C++ in the past, and am having difficulty converting some of my C++-CLI functions to C#.

I have 5 buttons along a side bar that toggles the visibility of the button's corresponding panel per button click. In order to do this, I set the visibility of all other panels to false. In order to achieve this in C++-CLI, I've done the following:

private: System::Void panels_Click(System::Object^  sender, System::EventArgs^  e) {
    System::Windows::Forms::Button ^ currentbutton = (System::Windows::Forms::Button ^) sender;
    array < Panel ^ > ^ objects = { panel1, panel2, panel3, panel4, panel5, panel6};
    array < Button ^ > ^ buttons = { button1, button2, button3, button4, button5, button6 };

    for (int i = 0; i < 6; i++) {
        if (buttons[i]->Equals(currentbutton)) {
            objects[i]->Visible = true;
        }
        else objects[i]->Visible = false;
    }
}

The issue I am having is with the " array Panel ^" portion, as I can not find an equivalent in C#. Any help is appreciated.

Body:
Arrays are declared in C# using TypeName[].

Panel[] objects = { panel1, panel2, panel3, panel4, panel5, panel6 };
Button[] buttons = { button1, button2, button3, button4, button5, button6 };


问:
Allow aa-exec temp user to gain access to a folder
I am currently working on a bash script which has a user that is created for the job it is running. The user does not exist outside of the script. I am trying to test my code coverage while leaving the user intact.

```<code>exec aa-exec -p test-user -- coverage run --source=/test/server ./main.py
</code>```

The problem is that the test-user does not have access to the code coverage folder. After running chmod -R 777 /usr/local/bin/coverage I still get /usr/bin/python: can't open file '/usr/local/bin/coverage': [Errno 13] Permission denied. I have also tried to temporarily elevate the user inside the bash script using sudo, but because the user only exists inside the file, the sudoers file throws an exception.

I am currently out of ideas since the permissions for this user have to remain restricted ideally. Any suggestions?

答:
Have you checked, that the user has access to each of the directories above?

I.e. the user needs to have 'x' and 'r' rights to each of these directories:

```<code>/usr
/usr/local
/usr/local/bin
</code>```

Body:
I am currently working on a bash script which has a user that is created for the job it is running. The user does not exist outside of the script. I am trying to test my code coverage while leaving the user intact.

exec aa-exec -p test-user -- coverage run --source=/test/server ./main.py

The problem is that the test-user does not have access to the code coverage folder. After running chmod -R 777 /usr/local/bin/coverage I still get /usr/bin/python: can't open file '/usr/local/bin/coverage': [Errno 13] Permission denied. I have also tried to temporarily elevate the user inside the bash script using sudo, but because the user only exists inside the file, the sudoers file throws an exception.

I am currently out of ideas since the permissions for this user have to remain restricted ideally. Any suggestions?

Body:
Have you checked, that the user has access to each of the directories above?

I.e. the user needs to have 'x' and 'r' rights to each of these directories:

/usr
/usr/local
/usr/local/bin


问:
stop synonyms.txt file Solr from being stemmed
In synonyms.txt file I have an entry
marine => saltwater,marine but both the words are getting stemmed to 'saltwat', 'marin' respectively inspite of being in protected words file. Is there a way to avoid it?

schema.xml

```<code> <fieldType name="text_en" class="solr.TextField" positionIncrementGap="100">
    <analyzer type="index">
      <tokenizer class="solr.StandardTokenizerFactory"/>
      <filter class="solr.ASCIIFoldingFilterFactory"/>
      <filter class="solr.LowerCaseFilterFactory"/>
      <filter class="solr.EnglishPossessiveFilterFactory"/>
      <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
      <filter class="solr.CommonGramsFilterFactory" words="lang/stopwords_en.txt" ignoreCase="true"/>
      <filter class="solr.PorterStemFilterFactory"/>
    </analyzer>
    <analyzer type="query">
      <tokenizer class="solr.StandardTokenizerFactory"/>
      <filter class="solr.StopFilterFactory" ignoreCase="true" words="lang/stopwords_en.txt" />
      <filter class="solr.ASCIIFoldingFilterFactory"/>
      <filter class="solr.LowerCaseFilterFactory"/>
      <filter class="solr.EnglishPossessiveFilterFactory"/>
      <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
      <filter class="solr.CommonGramsFilterFactory" words="lang/stopwords_en.txt" ignoreCase="true"/>
      <filter class="solr.PorterStemFilterFactory"/>
      <filter class="solr.SynonymGraphFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true" analyzer="org.apache.lucene.analysis.en.EnglishAnalyzer" />
    </analyzer>
  </fieldType>
</code>```

synonyms.txt

```<code>marine => saltwater,marine
</code>```

protwords.txt

```<code>saltwater
marine
</code>```

now when I do the analysis in admin panel and query for saltwat then saltwat | marin comes up. which means that saltwater did get stemmed to saltwat in synonyms.txt file

答:
Protwords (protected words) are words that would be stemmed by the
English porter stemmer that you do not want to be stemmed.

A customized protected word list may be specified with the "protected" attribute in the schema. Any words in the protected word list will not be modified by any stemmer in Solr.

```<code><fieldtype name="myfieldtype" class="solr.TextField">
  <analyzer>
    <tokenizer class="solr.WhitespaceTokenizerFactory"/>
    <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt" />
    <filter class="solr.PorterStemFilterFactory" />
  </analyzer>
</fieldtype>
</code>```

Body:
In synonyms.txt file I have an entry
marine => saltwater,marine but both the words are getting stemmed to 'saltwat', 'marin' respectively inspite of being in protected words file. Is there a way to avoid it?

schema.xml

 <fieldType name="text_en" class="solr.TextField" positionIncrementGap="100">
    <analyzer type="index">
      <tokenizer class="solr.StandardTokenizerFactory"/>
      <filter class="solr.ASCIIFoldingFilterFactory"/>
      <filter class="solr.LowerCaseFilterFactory"/>
      <filter class="solr.EnglishPossessiveFilterFactory"/>
      <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
      <filter class="solr.CommonGramsFilterFactory" words="lang/stopwords_en.txt" ignoreCase="true"/>
      <filter class="solr.PorterStemFilterFactory"/>
    </analyzer>
    <analyzer type="query">
      <tokenizer class="solr.StandardTokenizerFactory"/>
      <filter class="solr.StopFilterFactory" ignoreCase="true" words="lang/stopwords_en.txt" />
      <filter class="solr.ASCIIFoldingFilterFactory"/>
      <filter class="solr.LowerCaseFilterFactory"/>
      <filter class="solr.EnglishPossessiveFilterFactory"/>
      <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
      <filter class="solr.CommonGramsFilterFactory" words="lang/stopwords_en.txt" ignoreCase="true"/>
      <filter class="solr.PorterStemFilterFactory"/>
      <filter class="solr.SynonymGraphFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true" analyzer="org.apache.lucene.analysis.en.EnglishAnalyzer" />
    </analyzer>
  </fieldType>

synonyms.txt

marine => saltwater,marine

protwords.txt

saltwater
marine

now when I do the analysis in admin panel and query for saltwat then saltwat | marin comes up. which means that saltwater did get stemmed to saltwat in synonyms.txt file

Body:
Protwords (protected words) are words that would be stemmed by the
English porter stemmer that you do not want to be stemmed.

A customized protected word list may be specified with the "protected" attribute in the schema. Any words in the protected word list will not be modified by any stemmer in Solr.

<fieldtype name="myfieldtype" class="solr.TextField">
  <analyzer>
    <tokenizer class="solr.WhitespaceTokenizerFactory"/>
    <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt" />
    <filter class="solr.PorterStemFilterFactory" />
  </analyzer>
</fieldtype>


问:
MySQL change the file extension in the text column
A simple question for MySQL-pro. I've got a table that has a field with the filename in it (just the filename, no extra text). I need to change all file extension from ".png" to ".jpg", I know there's a way to do it with just query and no scripting in the programming language like PHP or Java.

Just in case, dropping "show create table" output:

```<code>CREATE TABLE `photos` (
  `id` bigint(20) NOT NULL,
  `owner_id` int(11) DEFAULT NULL,
  `photo_name` varchar(255) DEFAULT NULL,
  `comment` text,
  `normal_file_name` varchar(255) DEFAULT NULL,
  `thumb_file_name` varchar(255) DEFAULT NULL,
  `full_file_name` varchar(255) DEFAULT NULL,
  `photo_order` int(11) DEFAULT NULL,
  `gallery_file_name` varchar(255) DEFAULT NULL,
  `photo_type` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `FK_photos_OWNER_ID` (`owner_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 |
</code>```

The normal_file_name, thumb_file_name, gallery_file_name and full_file_name are fields with file paths.

Thanks for help in advance!

// Juriy

答:
Use the REPLACE function in an UPDATE statement:

```<code>UPDATE PHOTOS
   SET normal_file_name = REPLACE(normal_file_name, '.png', '.jpg'),
       thumb_file_name = REPLACE(thumb_file_name, '.png', '.jpg'),
       gallery_file_name = REPLACE(gallery_file_name, '.png', '.jpg'),
       full_file_name = REPLACE(full_file_name, '.png', '.jpg')
</code>```

If there's no match, the replacement won't happen.

Body:
A simple question for MySQL-pro. I've got a table that has a field with the filename in it (just the filename, no extra text). I need to change all file extension from ".png" to ".jpg", I know there's a way to do it with just query and no scripting in the programming language like PHP or Java.

Just in case, dropping "show create table" output:

CREATE TABLE `photos` (
  `id` bigint(20) NOT NULL,
  `owner_id` int(11) DEFAULT NULL,
  `photo_name` varchar(255) DEFAULT NULL,
  `comment` text,
  `normal_file_name` varchar(255) DEFAULT NULL,
  `thumb_file_name` varchar(255) DEFAULT NULL,
  `full_file_name` varchar(255) DEFAULT NULL,
  `photo_order` int(11) DEFAULT NULL,
  `gallery_file_name` varchar(255) DEFAULT NULL,
  `photo_type` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `FK_photos_OWNER_ID` (`owner_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 |

The normal_file_name, thumb_file_name, gallery_file_name and full_file_name are fields with file paths.

Thanks for help in advance!

// Juriy

Body:
Use the REPLACE function in an UPDATE statement:

UPDATE PHOTOS
   SET normal_file_name = REPLACE(normal_file_name, '.png', '.jpg'),
       thumb_file_name = REPLACE(thumb_file_name, '.png', '.jpg'),
       gallery_file_name = REPLACE(gallery_file_name, '.png', '.jpg'),
       full_file_name = REPLACE(full_file_name, '.png', '.jpg')

If there's no match, the replacement won't happen.


问:
From a low-level perspective, what is the difference between named pipes and remote procedure calls (RPC) in Windows?
I'm trying to understand a low-level architecture of Microsoft's implementation of named pipes vs RPC. I understand that both can be used for client/server communication between applications on a local network. But why would I choose one over another?

PS. Is RPC a higher level implementation built on top of named pipes, or vice versa? I'm also trying to see which one would have less overhead.

答:
Named pipes are a communications channel but they don't specify what data is to be sent (in a lot of ways they are a lot like either TCP or UDP on top of IP).

An RPC interface on the other hand specifies what data is needed for a successful communication and what data that communication will produce.

Note that RPC is capable of using a large number of communications channels and named pipes are just one of the possible options.


问:
Twitter Share encodeURIcomponent Struggle
I'm working on a project and I'm having some trouble with the encodeURIcomponent function. The site is a social media content bank that allows me to store copy in a CMS and display it on it's on page with links and buttons to share to social media sites. I'm struggling with the Twitter component and need some help. Here's my code:

function tweetClick() {
 var url = "http://urlfromcms.com";
 var text = "I'm getting this text dynamically from the CMS too.";
 window.open('http://twitter.com/share?url='+encodeURIComponent(url)+'&text='+encodeURIComponent(text), '');
   }                   ```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Tweet It!</code>```

This is working like a champ with one problem. If the copy has an ampersand, apostrophe, quotes, etc. then it get's encoded as well and and the tweet needs to be edited which defeats the purpose. How to I encode to get the %20 in the spaces that twitter needs but leave my ampersands and apostrophes alone?

Any help would be greatly appreciated!

答:
The issue is that the text you get from the CMS has encoded html entities

you can decode the HTML entities in text by using this answer

and then put the decoded string in the window.open call

Body:
I'm working on a project and I'm having some trouble with the encodeURIcomponent function. The site is a social media content bank that allows me to store copy in a CMS and display it on it's on page with links and buttons to share to social media sites. I'm struggling with the Twitter component and need some help. Here's my code:

function tweetClick() {
 var url = "http://urlfromcms.com";
 var text = "I'm getting this text dynamically from the CMS too.";
 window.open('http://twitter.com/share?url='+encodeURIComponent(url)+'&text='+encodeURIComponent(text), '');
   }

Tweet It!

This is working like a champ with one problem. If the copy has an ampersand, apostrophe, quotes, etc. then it get's encoded as well and and the tweet needs to be edited which defeats the purpose. How to I encode to get the %20 in the spaces that twitter needs but leave my ampersands and apostrophes alone?

Any help would be greatly appreciated!


答:
Use REPLACE. As an example:</p>

```<code>update photos
    set normal_file_name = replace(normal_file_name, '.png', '.jpg');
</code>```

Title: MySQL change the file extension in the text column

Body:
Use REPLACE. As an example:

update photos
    set normal_file_name = replace(normal_file_name, '.png', '.jpg');


问:
How to fix warning with %ms in scanf
I need to do something like this:

```<code>scanf("%ms", ...)
</code>```

and compile it with

```<code>g++ -Wall -pedantic -std=c++11
</code>```

also with

```<code>gcc -Wall -pedantic -std=c99
</code>```

And it prints warning: ISO C does not support the 'm' scanf flag.
How can i fix it?

答: The %ms notation is a POSIX extension in scanf() compared with the standard C version of scanf()</p>

Title: How to fix warning with %ms in scanf

Body:
I need to do something like this:

scanf("%ms", ...)

and compile it with

g++ -Wall -pedantic -std=c++11

also with

gcc -Wall -pedantic -std=c99

And it prints warning: ISO C does not support the 'm' scanf flag.
How can i fix it?


问:
SonarQube error during the analysis - missing property. but what property should i set?
I am trying to get sonarqube analysis don on my project. I keep getting this error . the error says there is a missing property. the code is c++ and i have also added the test path and also source directory path in the properties file. but i am not sure what property it is refering to. please guide !!!

```<code>14:10:11.010 INFO: 1072 files indexed
14:10:11.010 INFO: 1718 files ignored because of inclusion/exclusion patterns
   14:10:11.079 INFO: Quality profile for cpp: CleanSweep
   14:10:11.436 DEBUG: Code colorizer, supported languages:
   14:10:12.852 DEBUG: 'C' skipped because there is no related file in current project
   14:10:12.853 DEBUG: 'Objective-C' skipped because there is no related file in current project
   14:10:12.853 DEBUG: 'gcov' skipped because one of the required properties is missing
   14:10:12.853 DEBUG: 'llvm-cov' skipped because one of the required properties is missing
    14:10:12.853 DEBUG: 'cppunit' skipped because one of the required properties is missing
    14:10:12.854 DEBUG: 'VisualStudioCoverage' skipped because one of the required properties is missing
   14:10:12.854 DEBUG: 'bullseye' skipped because one of the required properties is missing
    14:10:12.854 DEBUG: 'FxCop (cs)' skipped because there is no related file in current project
    14:10:12.855 DEBUG: 'FxCop (vbnet)' skipped because there is no related file in current project
   14:10:12.856 DEBUG: 'JavaScript Squid Sensor' skipped because there is no related file in current project
   14:10:12.856 DEBUG: 'C#' skipped because there is no related file in current project
    14:10:12.857 DEBUG: 'C# Unit Tests Coverage Report Import' skipped because there is no related file in current project
    14:10:12.858 DEBUG: 'C# Integration Tests Coverage Report Import' skipped because there is no related file in current project
 14:10:12.858 DEBUG: 'C# Unit Test Results Import' skipped because there is no related file in current project
  14:10:12.859 DEBUG: 'SurefireSensor' skipped because there is no related file in current project
  14:10:12.860 DEBUG: 'JaCoCoSensor' skipped because there is no related file in current project
   14:10:12.860 DEBUG: 'JaCoCoItSensor' skipped because there is no related file in current project
   14:10:12.861 DEBUG: 'JaCoCoOverallSensor' skipped because there is no related file in current project
  14:10:12.861 DEBUG: 'JavaSquidSensor' skipped because there is no related file in current project
14:10:12.862 DEBUG: 'Linting sensor for TypeScript files' skipped because there is no related file in current project
 14:10:12.863 DEBUG: 'Combined LCOV and LOC sensor' skipped because there is no related file in current project
  14:10:12.869 DEBUG: Sensors : Lines Sensor (wrapped) -> com.stevpet.sonar.plugins.dotnet.mscover.failfast.FailFastSensor@370c9018 -> SCM Sensor (wrapped) -> C++ (wrapped) -> SonarJavaXmlFileSensor (wrapped) -> Zero Coverage Sensor (wrapped) -> Code Colorizer Sensor (wrapped) -> CPD Block Indexer (wrapped)
  14:10:12.894 INFO: devcockpit licensed to Software, PRODUCTION [Expiration: 2018-03-27, Server: 170e60000c88925]
  14:10:12.921 INFO: cpp licensed to Software, PRODUCTION [Expiration: 2018-09-27, Server: 170e60000c88925]
 14:10:12.926 INFO: Sensor Lines Sensor (wrapped)
 14:10:13.111 INFO: Sensor Lines Sensor (wrapped) (done) | time=185ms
  14:10:13.111 INFO: Sensor com.stevpet.sonar.plugins.dotnet.mscover.failfast.FailFastSensor
    14:10:13.117 INFO: ------------------------------------------------------------------------
  14:10:13.117 INFO: EXECUTION FAILURE
  14:10:13.117 INFO: ------------------------------------------------------------------------
   14:10:13.118 INFO: Total time: 13.853s
   14:10:13.258 INFO: Final Memory: 53M/313M
   14:10:13.258 INFO: ------------------------------------------------------------------------
   14:10:13.258 ERROR: Error during SonarQube Scanner execution
                                                                                com.stevpet.sonar.plugins.dotnet.mscover.property.InvalidPropertyValueException:      Missing property
sonar.mscover.integrationtests.dir
 property is required, and parent must exist
    at  com.stevpet.sonar.plugins.dotnet.mscover.property.CoverageRootProperty.onGetValue(CoverageRootProperty.java:51)
    at    com.stevpet.sonar.plugins.dotnet.mscover.property.CoverageRootProperty.onGetValue(CoverageRootProperty.java:29)
    at com.stevpet.sonar.plugins.dotnet.mscover.property.ConfigurationPropertyBase.getValue(ConfigurationPropertyBase.java:49)
    at  com.stevpet.sonar.plugins.dotnet.mscover.property.ConfigurationPropertyBase.validate(ConfigurationPropertyBase.java:55)
     at com.stevpet.sonar.plugins.dotnet.mscover.DefaultIntegrationTestsConfiguration.validate(DefaultIntegrationTestsConfiguration.java:121)
    at com.stevpet.sonar.plugins.dotnet.mscover.failfast.FailFastSensor.analyse(FailFastSensor.java:55)
   at org.sonar.batch.phases.SensorsExecutor.executeSensor(SensorsExecutor.java:58)
   at org.sonar.batch.phases.SensorsExecutor.execute(SensorsExecutor.java:50)
    at org.sonar.batch.phases.AbstractPhaseExecutor.execute(AbstractPhaseExecutor.java:83)
    at org.sonar.batch.scan.ModuleScanContainer.doAfterStart(ModuleScanContainer.java:192)
    at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:142)
    at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:127)
    at org.sonar.batch.scan.ProjectScanContainer.scan(ProjectScanContainer.java:241)
       at org.sonar.batch.scan.ProjectScanContainer.scanRecursively(ProjectScanContainer.java:236)
     at org.sonar.batch.scan.ProjectScanContainer.doAfterStart(ProjectScanContainer.java:226)
     at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:142)
      at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:127)
      at org.sonar.batch.task.ScanTask.execute(ScanTask.java:47)
     at org.sonar.batch.task.TaskContainer.doAfterStart(TaskContainer.java:86)
     at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:142)
    at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:127)
       at org.sonar.batch.bootstrap.GlobalContainer.executeTask(GlobalContainer.java:106)
      at org.sonar.batch.bootstrapper.Batch.executeTask(Batch.java:119)
         at org.sonarsource.scanner.api.internal.batch.BatchIsolatedLauncher.execute(BatchIsolatedLauncher.java:63)
       at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
       at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
     at sun.reflect.DelegatingMethodAccessorImpl.invoke  (DelegatingMethodAccessorImpl.java:43)
     at java.lang.reflect.Method.invoke(Method.java:498)
     at org.sonarsource.scanner.api.internal.IsolatedLauncherProxy.invoke(IsolatedLauncherProxy.java:60)
     at com.sun.proxy.$Proxy0.execute(Unknown Source)
     at org.sonarsource.scanner.api.EmbeddedScanner.doExecute(EmbeddedScanner.java:233)
    at org.sonarsource.scanner.api.EmbeddedScanner.runAnalysis  (EmbeddedScanner.java:151)
     at org.sonarsource.scanner.cli.Main.runAnalysis(Main.java:123)
    at org.sonarsource.scanner.cli.Main.execute(Main.java:77)
     at org.sonarsource.scanner.cli.Main.main(Main.java:61)
     14:10:13.262 DEBUG: Execution getVersion
    14:10:13.263 DEBUG: Execution stop
   [Pipeline] }
   [Pipeline] // withSonarQubeEnv
   [Pipeline] }
   [Pipeline] // stage
   [Pipeline] echo
   project build error: hudson.AbortException: script returned exit code 1
   [Pipeline] step
</code>```

My sonar properties file is

```<code>    # must be unique in a given SonarQube instance
    sonar.projectKey=server
    # this is the name and version displayed in the SonarQube UI. Was mandatory prior to SonarQube 6.1.
    sonar.projectName=server
    sonar.projectVersion=1.0

     # Path is relative to the sonar-project.properties file. Replace "\" by "/" on Windows.
     # This property is optional if sonar.modules is set.
    sonar.sources=.

    # language
    sonar.language=cpp

   # path to test source directories

    sonar.test.inclusions=**/UnitTest/**

    sonar.test.reportPath=**/test_result.xml

    # Encoding of the source code. Default is default system encoding
    sonar.sourceEncoding=UTF-8
</code>```

答:
The log says:

Missing property sonar.mscover.integrationtests.dir property is required, and parent must exist

This property is used by the sonar-mscover plugin.

It should points to the directory which stores integration tests.

You can probably disable this plugin by add a line sonar.mscover.integrationtests.mode= to the sonar.properties file.

Body:
I am trying to get sonarqube analysis don on my project. I keep getting this error . the error says there is a missing property. the code is c++ and i have also added the test path and also source directory path in the properties file. but i am not sure what property it is refering to. please guide !!!

14:10:11.010 INFO: 1072 files indexed
14:10:11.010 INFO: 1718 files ignored because of inclusion/exclusion patterns
   14:10:11.079 INFO: Quality profile for cpp: CleanSweep
   14:10:11.436 DEBUG: Code colorizer, supported languages:
   14:10:12.852 DEBUG: 'C' skipped because there is no related file in current project
   14:10:12.853 DEBUG: 'Objective-C' skipped because there is no related file in current project
   14:10:12.853 DEBUG: 'gcov' skipped because one of the required properties is missing
   14:10:12.853 DEBUG: 'llvm-cov' skipped because one of the required properties is missing
    14:10:12.853 DEBUG: 'cppunit' skipped because one of the required properties is missing
    14:10:12.854 DEBUG: 'VisualStudioCoverage' skipped because one of the required properties is missing
   14:10:12.854 DEBUG: 'bullseye' skipped because one of the required properties is missing
    14:10:12.854 DEBUG: 'FxCop (cs)' skipped because there is no related file in current project
    14:10:12.855 DEBUG: 'FxCop (vbnet)' skipped because there is no related file in current project
   14:10:12.856 DEBUG: 'JavaScript Squid Sensor' skipped because there is no related file in current project
   14:10:12.856 DEBUG: 'C#' skipped because there is no related file in current project
    14:10:12.857 DEBUG: 'C# Unit Tests Coverage Report Import' skipped because there is no related file in current project
    14:10:12.858 DEBUG: 'C# Integration Tests Coverage Report Import' skipped because there is no related file in current project
 14:10:12.858 DEBUG: 'C# Unit Test Results Import' skipped because there is no related file in current project
  14:10:12.859 DEBUG: 'SurefireSensor' skipped because there is no related file in current project
  14:10:12.860 DEBUG: 'JaCoCoSensor' skipped because there is no related file in current project
   14:10:12.860 DEBUG: 'JaCoCoItSensor' skipped because there is no related file in current project
   14:10:12.861 DEBUG: 'JaCoCoOverallSensor' skipped because there is no related file in current project
  14:10:12.861 DEBUG: 'JavaSquidSensor' skipped because there is no related file in current project
14:10:12.862 DEBUG: 'Linting sensor for TypeScript files' skipped because there is no related file in current project
 14:10:12.863 DEBUG: 'Combined LCOV and LOC sensor' skipped because there is no related file in current project
  14:10:12.869 DEBUG: Sensors : Lines Sensor (wrapped) -> com.stevpet.sonar.plugins.dotnet.mscover.failfast.FailFastSensor@370c9018 -> SCM Sensor (wrapped) -> C++ (wrapped) -> SonarJavaXmlFileSensor (wrapped) -> Zero Coverage Sensor (wrapped) -> Code Colorizer Sensor (wrapped) -> CPD Block Indexer (wrapped)
  14:10:12.894 INFO: devcockpit licensed to Software, PRODUCTION [Expiration: 2018-03-27, Server: 170e60000c88925]
  14:10:12.921 INFO: cpp licensed to Software, PRODUCTION [Expiration: 2018-09-27, Server: 170e60000c88925]
 14:10:12.926 INFO: Sensor Lines Sensor (wrapped)
 14:10:13.111 INFO: Sensor Lines Sensor (wrapped) (done) | time=185ms
  14:10:13.111 INFO: Sensor com.stevpet.sonar.plugins.dotnet.mscover.failfast.FailFastSensor
    14:10:13.117 INFO: ------------------------------------------------------------------------
  14:10:13.117 INFO: EXECUTION FAILURE
  14:10:13.117 INFO: ------------------------------------------------------------------------
   14:10:13.118 INFO: Total time: 13.853s
   14:10:13.258 INFO: Final Memory: 53M/313M
   14:10:13.258 INFO: ------------------------------------------------------------------------
   14:10:13.258 ERROR: Error during SonarQube Scanner execution
                                                                                com.stevpet.sonar.plugins.dotnet.mscover.property.InvalidPropertyValueException:      Missing property
sonar.mscover.integrationtests.dir
 property is required, and parent must exist
    at  com.stevpet.sonar.plugins.dotnet.mscover.property.CoverageRootProperty.onGetValue(CoverageRootProperty.java:51)
    at    com.stevpet.sonar.plugins.dotnet.mscover.property.CoverageRootProperty.onGetValue(CoverageRootProperty.java:29)
    at com.stevpet.sonar.plugins.dotnet.mscover.property.ConfigurationPropertyBase.getValue(ConfigurationPropertyBase.java:49)
    at  com.stevpet.sonar.plugins.dotnet.mscover.property.ConfigurationPropertyBase.validate(ConfigurationPropertyBase.java:55)
     at com.stevpet.sonar.plugins.dotnet.mscover.DefaultIntegrationTestsConfiguration.validate(DefaultIntegrationTestsConfiguration.java:121)
    at com.stevpet.sonar.plugins.dotnet.mscover.failfast.FailFastSensor.analyse(FailFastSensor.java:55)
   at org.sonar.batch.phases.SensorsExecutor.executeSensor(SensorsExecutor.java:58)
   at org.sonar.batch.phases.SensorsExecutor.execute(SensorsExecutor.java:50)
    at org.sonar.batch.phases.AbstractPhaseExecutor.execute(AbstractPhaseExecutor.java:83)
    at org.sonar.batch.scan.ModuleScanContainer.doAfterStart(ModuleScanContainer.java:192)
    at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:142)
    at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:127)
    at org.sonar.batch.scan.ProjectScanContainer.scan(ProjectScanContainer.java:241)
       at org.sonar.batch.scan.ProjectScanContainer.scanRecursively(ProjectScanContainer.java:236)
     at org.sonar.batch.scan.ProjectScanContainer.doAfterStart(ProjectScanContainer.java:226)
     at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:142)
      at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:127)
      at org.sonar.batch.task.ScanTask.execute(ScanTask.java:47)
     at org.sonar.batch.task.TaskContainer.doAfterStart(TaskContainer.java:86)
     at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:142)
    at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:127)
       at org.sonar.batch.bootstrap.GlobalContainer.executeTask(GlobalContainer.java:106)
      at org.sonar.batch.bootstrapper.Batch.executeTask(Batch.java:119)
         at org.sonarsource.scanner.api.internal.batch.BatchIsolatedLauncher.execute(BatchIsolatedLauncher.java:63)
       at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
       at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
     at sun.reflect.DelegatingMethodAccessorImpl.invoke  (DelegatingMethodAccessorImpl.java:43)
     at java.lang.reflect.Method.invoke(Method.java:498)
     at org.sonarsource.scanner.api.internal.IsolatedLauncherProxy.invoke(IsolatedLauncherProxy.java:60)
     at com.sun.proxy.$Proxy0.execute(Unknown Source)
     at org.sonarsource.scanner.api.EmbeddedScanner.doExecute(EmbeddedScanner.java:233)
    at org.sonarsource.scanner.api.EmbeddedScanner.runAnalysis  (EmbeddedScanner.java:151)
     at org.sonarsource.scanner.cli.Main.runAnalysis(Main.java:123)
    at org.sonarsource.scanner.cli.Main.execute(Main.java:77)
     at org.sonarsource.scanner.cli.Main.main(Main.java:61)
     14:10:13.262 DEBUG: Execution getVersion
    14:10:13.263 DEBUG: Execution stop
   [Pipeline] }
   [Pipeline] // withSonarQubeEnv
   [Pipeline] }
   [Pipeline] // stage
   [Pipeline] echo
   project build error: hudson.AbortException: script returned exit code 1
   [Pipeline] step

My sonar properties file is

    # must be unique in a given SonarQube instance
    sonar.projectKey=server
    # this is the name and version displayed in the SonarQube UI. Was mandatory prior to SonarQube 6.1.
    sonar.projectName=server
    sonar.projectVersion=1.0

     # Path is relative to the sonar-project.properties file. Replace "\" by "/" on Windows.
     # This property is optional if sonar.modules is set.
    sonar.sources=.

    # language
    sonar.language=cpp

   # path to test source directories

    sonar.test.inclusions=**/UnitTest/**

    sonar.test.reportPath=**/test_result.xml

    # Encoding of the source code. Default is default system encoding
    sonar.sourceEncoding=UTF-8


问:
Android - How to read txt file in JAVA
Please Will some one help me out i am trying to read an Arabic .txt file and it always give me the Arabic word like this "????? ???"</p>

```<code>private String ReadArabic() {

    String words="";
    try {
        InputStream stream = getAssets().open("arabwords.txt");

        int size = stream.available();
        byte[] buffer = new byte[size];
        stream.read(buffer);
        stream.close();
        words = new String(buffer, "UTF-8");
        words = words.replaceAll("(\\r|\\n)", "");
    } catch (IOException e) {
        // Handle exceptions here
    }
    return words;
}
</code>```

答:
Its possible that your console is not set to
  properly display UTF-8 characters.

The configuration of that depends
on the IDE. You might need to configure the same there.

Title: Android - How to read txt file in JAVA

Body:
Please Will some one help me out i am trying to read an Arabic .txt file and it always give me the Arabic word like this "????? ???"

private String ReadArabic() {

    String words="";
    try {
        InputStream stream = getAssets().open("arabwords.txt");

        int size = stream.available();
        byte[] buffer = new byte[size];
        stream.read(buffer);
        stream.close();
        words = new String(buffer, "UTF-8");
        words = words.replaceAll("(\\r|\\n)", "");
    } catch (IOException e) {
        // Handle exceptions here
    }
    return words;
}


问:
ASP.NET fails to send email through Gmail SMTP, but Outlook 2007 succeeds
Hi all
a couple weeks ago, my ASP.NET website stopped sending user comments which I implemented by emailing those comments to my email account through Gmail SMTP server (smtp.gmail.com). I opened the project on my development machine and again it fails to send the email after a couple minutes with the following exception message:

Failure sending mail

Unable to read data from the transport connection: net_io_connectionclosed.

I'm using Gmail's SMTP with port 465, and MailClient.EnableSSL = True.
The weird thing is my Office Outlook 2007 is using the same settings and it doesn't have any problems sending mail using the same Gmail account.

Any thoughts?

答: One oddity I found with formmail going through gmail (on Windows server) was that the port number was the problem. My code was similar to yours, but it only worked when I changed the port to 25 rather than the 587 or 465. That might be what you need here.</p>


问:
C# Put Static Class Inside Dictionary
I was unclear in an earlier question I ask so I will try to be more explicit.

Is there a way to put a static class inside of a dictionary so that its functions can be called? If this is not possible, what is the best alternative that doesn't involve using instances that you can suggest?

Here is how I would like to use it:

```<code>static class MyStatic : IInterface
{
    static void Do(){}
}

static class MyStatic2 : IInterface
{
    static void Do(){}
}

class StaticMap
{
    static Dictionary<Type,IInterface.class> dictionary = new Dictionary<Type,IInterface.class>
    {
        {Type.1, MyStatic}
        {Type.2, MyStatic2}
    };
}

// Client Code

class ClientCode
{
    void Start()
    {
        StaticMap.dictionary[Type.1].Do();
    }
}
</code>```

答:
There are some fundamental reasons why you can't do that directly:

Static method calls are bound at compile-time

Static calls are not inherited - they are tied to the class that defines them

There is no implicit base type (and therefore no polymorphism) between static methods, even if the name, inputs, and outputs are all the same

Since your signature is the same for every static method, you could store a Action in the dictionary instead:

```<code>static Dictionary<Type,Action> dictionary = new Dictionary<Type,Action>
{
    {Type.1, MyStatic.Do}
    {Type.2, MyStatic2.Do}
};
</code>```

then you can call the Action directly:

```<code>void Start()
{
    StaticMap.dictionary[Type.1]();
}
</code>```

It's slightly repetetive because you have to specify the method name in the dictionary as well, but it's type safe.

Title: C# Put Static Class Inside Dictionary

Body:
I was unclear in an earlier question I ask so I will try to be more explicit.

Is there a way to put a static class inside of a dictionary so that its functions can be called? If this is not possible, what is the best alternative that doesn't involve using instances that you can suggest?

Here is how I would like to use it:

static class MyStatic : IInterface
{
    static void Do(){}
}

static class MyStatic2 : IInterface
{
    static void Do(){}
}

class StaticMap
{
    static Dictionary<Type,IInterface.class> dictionary = new Dictionary<Type,IInterface.class>
    {
        {Type.1, MyStatic}
        {Type.2, MyStatic2}
    };
}

// Client Code

class ClientCode
{
    void Start()
    {
        StaticMap.dictionary[Type.1].Do();
    }
}

Body:
There are some fundamental reasons why you can't do that directly:

Static method calls are bound at compile-time

Static calls are not inherited - they are tied to the class that defines them

There is no implicit base type (and therefore no polymorphism) between static methods, even if the name, inputs, and outputs are all the same

Since your signature is the same for every static method, you could store a Action in the dictionary instead:

static Dictionary<Type,Action> dictionary = new Dictionary<Type,Action>
{
    {Type.1, MyStatic.Do}
    {Type.2, MyStatic2.Do}
};

then you can call the Action directly:

void Start()
{
    StaticMap.dictionary[Type.1]();
}

It's slightly repetetive because you have to specify the method name in the dictionary as well, but it's type safe.


问:
Mobx injector store not available in React Native app
I am getting an error "MobX injector: Store 'systemStore' is not available! make sure it is provided by some provider. What I really need to do is pass the store to all of my components so that I hace access to them in the this.props.systemStore in like, componentWillMount

```<code>import React from 'react';
import { Platform, StatusBar, StyleSheet, View } from 'react-native';
import { AppLoading, Asset, Font } from 'expo';
import { Ionicons } from '@expo/vector-icons';
import {NavigationActions} from 'react-navigation'
import RootNavigation from './navigation/RootNavigation';

import { inject,  observer, Provider } from 'mobx-react';
import { observable, action } from "mobx";
import SystemStore from "./stores/SystemStore";

class Main extends React.Component {

render() {
  return (
      <Provider systemStore={SystemStore} >
          <App />
      </Provider>
    );
   }
 }

@inject("systemStore")
export default class App extends React.Component {

state = {
  isLoadingComplete: false,
};

render() {
 if (!this.state.isLoadingComplete && !this.props.skipLoadingScreen) {
  return (

    <AppLoading
      startAsync={this._loadResourcesAsync}
      onError={this._handleLoadingError}
      onFinish={this._handleFinishLoading}
    />
  );
} else {
  return (
        <View style={styles.container}>
          {Platform.OS === 'ios' && <StatusBar barStyle="default" />}
          {Platform.OS === 'android' &&
            <View style={styles.statusBarUnderlay} />}
          <RootNavigation />
        </View>
  );
}
}

_loadResourcesAsync = async () => {
  return Promise.all([

  Font.loadAsync([
    // This is the font that we are using for our tab bar
    Ionicons.font,
    // We include SpaceMono because we use it in HomeScreen.js. Feel free
    // to remove this if you are not using it in your app
    { 'space-mono': require('./assets/fonts/SpaceMono-Regular.ttf') },
  ]),

  Asset.loadAsync([
    require('./assets/images/robot-dev.png'),
    require('./assets/images/robot-prod.png'),
  ]),
 ]);
};

 _handleLoadingError = error => {
   console.warn(error);
};

  _handleFinishLoading = () => {
   this.setState({ isLoadingComplete: true });
};
}

 const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
 },
 statusBarUnderlay: {
  height: 24,
    backgroundColor: 'rgba(0,0,0,0.2)',
    },
});

Expo.registerRootComponent(Main);
</code>```

and the store looks like this

```<code>import {observable, action, computed} from 'mobx'

class SystemStore {

@observable loggedIn    = false;
@observable controlAuth = false;
@observable testingKey = "Testing-Yo"

}

export default new SystemStore()
</code>```

i have been all over looking for a solution, just cannot seem to get my head around this one. thanks

答:
So how I deal with this issue is, I create a file called stores.js which looks like this:

import SystemStore from './stores/systemStore';

const systemStore = new SystemStore();

export {
  SystemStore
}

export default {
  systemStore
}```
</div>
</div>
</p>

<p>In this file I import and export all my stores, so that I can always call stores.systemStore (and all other stores you have) with just importing my stores.js like this</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React from 'react';
import {observer} from 'mobx-react';
import stores from './../../stores';

@observer
class TestComponent extends React.Component {
  constructor(props){
    super(props);
  }

  render() {
    return (
      <div>
        {stores.systemStore.testingKey}
      </div>
    );

  }
}

export default TestComponent;</code>```

And my stores look like this then:

import store from 'store';
import {observable, action, computed} from 'mobx';

class systemStore {

  @observable loggedIn = false;
  @observable controlAuth = false;
  @observable testingKey = "Testing-Yo";

}

export default systemStore;```

I hope this will help you. It works for me :)

Body:
I am getting an error "MobX injector: Store 'systemStore' is not available! make sure it is provided by some provider. What I really need to do is pass the store to all of my components so that I hace access to them in the this.props.systemStore in like, componentWillMount

import React from 'react';
import { Platform, StatusBar, StyleSheet, View } from 'react-native';
import { AppLoading, Asset, Font } from 'expo';
import { Ionicons } from '@expo/vector-icons';
import {NavigationActions} from 'react-navigation'
import RootNavigation from './navigation/RootNavigation';

import { inject,  observer, Provider } from 'mobx-react';
import { observable, action } from "mobx";
import SystemStore from "./stores/SystemStore";

class Main extends React.Component {

render() {
  return (
      <Provider systemStore={SystemStore} >
          <App />
      </Provider>
    );
   }
 }

@inject("systemStore")
export default class App extends React.Component {

state = {
  isLoadingComplete: false,
};

render() {
 if (!this.state.isLoadingComplete && !this.props.skipLoadingScreen) {
  return (

    <AppLoading
      startAsync={this._loadResourcesAsync}
      onError={this._handleLoadingError}
      onFinish={this._handleFinishLoading}
    />
  );
} else {
  return (
        <View style={styles.container}>
          {Platform.OS === 'ios' && <StatusBar barStyle="default" />}
          {Platform.OS === 'android' &&
            <View style={styles.statusBarUnderlay} />}
          <RootNavigation />
        </View>
  );
}
}

_loadResourcesAsync = async () => {
  return Promise.all([

  Font.loadAsync([
    // This is the font that we are using for our tab bar
    Ionicons.font,
    // We include SpaceMono because we use it in HomeScreen.js. Feel free
    // to remove this if you are not using it in your app
    { 'space-mono': require('./assets/fonts/SpaceMono-Regular.ttf') },
  ]),

  Asset.loadAsync([
    require('./assets/images/robot-dev.png'),
    require('./assets/images/robot-prod.png'),
  ]),
 ]);
};

 _handleLoadingError = error => {
   console.warn(error);
};

  _handleFinishLoading = () => {
   this.setState({ isLoadingComplete: true });
};
}

 const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
 },
 statusBarUnderlay: {
  height: 24,
    backgroundColor: 'rgba(0,0,0,0.2)',
    },
});

Expo.registerRootComponent(Main);

and the store looks like this

import {observable, action, computed} from 'mobx'

class SystemStore {

@observable loggedIn    = false;
@observable controlAuth = false;
@observable testingKey = "Testing-Yo"

}

export default new SystemStore()

i have been all over looking for a solution, just cannot seem to get my head around this one. thanks

Body:
So how I deal with this issue is, I create a file called stores.js which looks like this:

import SystemStore from './stores/systemStore';

const systemStore = new SystemStore();

export {
  SystemStore
}

export default {
  systemStore
}

In this file I import and export all my stores, so that I can always call stores.systemStore (and all other stores you have) with just importing my stores.js like this

import React from 'react';
import {observer} from 'mobx-react';
import stores from './../../stores';

@observer
class TestComponent extends React.Component {
  constructor(props){
    super(props);
  }

  render() {
    return (
      <div>
        {stores.systemStore.testingKey}
      </div>
    );

  }
}

export default TestComponent;

And my stores look like this then:

import store from 'store';
import {observable, action, computed} from 'mobx';

class systemStore {

  @observable loggedIn = false;
  @observable controlAuth = false;
  @observable testingKey = "Testing-Yo";

}

export default systemStore;

I hope this will help you. It works for me :)


问:
WooCommerce - New Order Email - Add Shipping Address
I am looking to add the shipping address from the order to the New Order email. Can anyone please provide detailed information on how to do so? I am pretty new to editing functions.php, hooks, etc.

Thanks

答:
Use this
you can comment out the conditional part if you want to have it on customer email as well.</p>

```<code>add_action( 'woocommerce_email_after_order_table', 'woocommerce_add_shipping_address_to_admin_emails', 15, 2 );
function woocommerce_add_shipping_address_to_admin_emails( $order, $is_admin_email ) {
    if ( $is_admin_email ) {
        echo '<p><strong>Shipping Address:</strong> ' . $order->get_formatted_shipping_address() . '</p>';
    }
}
</code>```

Body:
Use this
you can comment out the conditional part if you want to have it on customer email as well.

add_action( 'woocommerce_email_after_order_table', 'woocommerce_add_shipping_address_to_admin_emails', 15, 2 );
function woocommerce_add_shipping_address_to_admin_emails( $order, $is_admin_email ) {
    if ( $is_admin_email ) {
        echo '<p><strong>Shipping Address:</strong> ' . $order->get_formatted_shipping_address() . '</p>';
    }
}


问:
Removing decimal dot
I'm currently developing a iOS (SWIFT) app where I need to remove the dot in decimal values.

For example:

20.50 -> 2050

20.00 -> 2000

Then add 2 zero at the end of the string.

In android i can do this:

```<code>java.text.DecimalFormat("#.00").format(amount))
</code>```

but there is no such thing like DecimalFormat in Swift or am I wrong?

答:
let num = 123.45
let str = String(format: "%.00f", num * 100)
print(str)

prints 12345

Title: Removing decimal dot

Body:
I'm currently developing a iOS (SWIFT) app where I need to remove the dot in decimal values.

For example:

20.50 -> 2050

20.00 -> 2000

Then add 2 zero at the end of the string.

In android i can do this:

java.text.DecimalFormat("#.00").format(amount))

but there is no such thing like DecimalFormat in Swift or am I wrong?


问:
accepts_nested_attributes_for keeps form fields from showing
When I use accepts_nested_attributes_for the corresponding fields no longer show in my view.

```<code>class Survey < ActiveRecord::Base
  has_many :questions
  accepts_nested_attributes_for :questions
end

class Question < ActiveRecord::Base
  belongs_to :survey
end
</code>```

Then in my view:

```<code><%= form_for @survey do |f| %>
  <%= f.fields_for :questions do |question_fields| %>
    <%= question_fields.text_area :text %>
  <% end %>
<% end %>
</code>```

If I remove accepts_nested_attributes_for then the text_area shows, but if I keep it...nothing gets renders.

I'm running Rails 3.0.3

答:
Do you want to create new questions or are you editing them?  You might want to try something like this if you are creating a new question for this survey:</p>

```
<= f.fields_for @survey.questions.build do |question_fields| %>
```

Body:
When I use accepts_nested_attributes_for the corresponding fields no longer show in my view.

class Survey < ActiveRecord::Base
  has_many :questions
  accepts_nested_attributes_for :questions
end

class Question < ActiveRecord::Base
  belongs_to :survey
end

Then in my view:

<%= form_for @survey do |f| %>
  <%= f.fields_for :questions do |question_fields| %>
    <%= question_fields.text_area :text %>
  <% end %>
<% end %>

If I remove accepts_nested_attributes_for then the text_area shows, but if I keep it...nothing gets renders.

I'm running Rails 3.0.3

Body:
Do you want to create new questions or are you editing them?  You might want to try something like this if you are creating a new question for this survey:

<= f.fields_for @survey.questions.build do |question_fields| %>


问:
How to do paging in Survey Monkey
I need to page the results I get back from Survey Monkey. I tried from the docs the following:

```<code>curl -i -X GET -H "Authorization:bearer my.access.token.which.i.have" -H "Content-Type": "application/json" https://api.surveymonkey.net/v3/surveys?page=2&per_page=5
</code>```

the response seems to ignore the values I am sending in the url (page=2&per_page=8)

The response still has as per_page:50 as the header of the response, and the links have, for example for prev the value: https://api.surveymonkey.net/v3/surveys?page=1&per_page=50

What am I missing in the URL structure to get paging correctly?

I will point that I do get a result with my surveys back, which (probably) means I am setup properly to work with the API as far as credentials, correct url and scopes.

答:
Add quotes around your url otherwise, your shell will interpret the first & and will make the command on the left of & run in background (thus ignoring all the parameters you have added on the right of it eg per_page=5) :

curl -i -H "Authorization:bearer my.access.token.which.i.have" \
        -H "Content-Type: application/json" \
        "https://api.surveymonkey.net/v3/surveys?page=2&per_page=5"
```

Also -H "Content-Type": "application/json" header is not correctly formatted

Title: How to do paging in Survey Monkey

Body:
I need to page the results I get back from Survey Monkey. I tried from the docs the following:

curl -i -X GET -H "Authorization:bearer my.access.token.which.i.have" -H "Content-Type": "application/json" https://api.surveymonkey.net/v3/surveys?page=2&per_page=5

the response seems to ignore the values I am sending in the url (page=2&per_page=8)

The response still has as per_page:50 as the header of the response, and the links have, for example for prev the value: https://api.surveymonkey.net/v3/surveys?page=1&per_page=50

What am I missing in the URL structure to get paging correctly?

I will point that I do get a result with my surveys back, which (probably) means I am setup properly to work with the API as far as credentials, correct url and scopes.

Body:
Add quotes around your url otherwise, your shell will interpret the first & and will make the command on the left of & run in background (thus ignoring all the parameters you have added on the right of it eg per_page=5) :

curl -i -H "Authorization:bearer my.access.token.which.i.have" \
        -H "Content-Type: application/json" \
        "https://api.surveymonkey.net/v3/surveys?page=2&per_page=5"

Also -H "Content-Type": "application/json" header is not correctly formatted


问:
Dynamically change references from import in Python
Short:

How can I import a module if a different module with the same name has already been imported? I don't need the old module anymore, but I can't import the new one under a different name.
importlib.reload() doesn't have the desired effect and apparently you really shouldn't mess with sys.modules

Context:

I'm automating a testing workflow by writing a script (A). The test script is provided and can not be altered.

The target of the Testing is a class in a script (B) of which there are different versions in subfolders. Unfortunately Script B and the class always have the same name, nothing I can do about that.

```<code>main_folder
├──script_a.py
├──test_script.py
│
├──version_1
│    ├──script_b.py
│
├──version_2
│    ├──script_b.py
│
├──version_3
│    ├──script_b.py
</code>```

The test script imports the object and runs tests on it.

```<code># test_script
from script_b import my_class

# creat instance of my_class
# and test it
</code>```

script_a iterates over the version folders and runs the test script on script_b.
In each iteration one subfolder is added to the import path so the test script will find the corresponding script_b. The path is removed after the iteration.

If sys.modules already contains a version of test_script,

```<code># script_a
import sys
import os
import importlib

folders = ['version_1', 'version_2', 'version_3']
folders = [os.getcwd() + '/' + folder for folder in folders]

for folder in folders:
    sys.path.append(folder)

    if 'test_script' in sys.modules:
        importlib.reload(sys.modules['test_script'])
    else:
        importlib.import_module('test_script')

    sys.path.remove(folder)
</code>```

Issue:

It seems reload has no effect on script_b, which is imported by test_script. So although I change the import path to different subfolders test_script always runs on version 1.
How can I make test_script use the different versions of script_b without altering test_script itself?

Follow up:
Although the original question is answered, I was wondering, how is this solution from a design perspective? Is there a better / more elegant way to automate this testing process?

From what I found, it isn't considered good practice to reload modules.

答:
Figured it out while writing the question. Hope it will help someone some day

Even if you can't alter test_script (or script_b) there's a work around.

Because an import statement does nothing if the relevant module is already imported we can reload script_b from the path we want directly in script_a. Since it then is replaced with the new version in sys.modules the import statement in test_script will cause no problem.

Updated code:

```<code># script_a
import sys
import os
import importlib

folders = ['version_1', 'version_2', 'version_3']
folders = [os.getcwd() + '/' + folder for folder in folders]

for folder in folders:
    sys.path.append(folder)

    if 'test_script' in sys.modules:
        importlib.reload(sys.modules['script_b'])      # this line added
        importlib.reload(sys.modules['test_script'])
    else:
        importlib.import_module('test_script')

    sys.path.remove(folder)
</code>```

Body:
Short:

How can I import a module if a different module with the same name has already been imported? I don't need the old module anymore, but I can't import the new one under a different name.
importlib.reload() doesn't have the desired effect and apparently you really shouldn't mess with sys.modules

Context:

I'm automating a testing workflow by writing a script (A). The test script is provided and can not be altered.

The target of the Testing is a class in a script (B) of which there are different versions in subfolders. Unfortunately Script B and the class always have the same name, nothing I can do about that.

main_folder
├──script_a.py
├──test_script.py
│
├──version_1
│    ├──script_b.py
│
├──version_2
│    ├──script_b.py
│
├──version_3
│    ├──script_b.py

The test script imports the object and runs tests on it.

# test_script
from script_b import my_class

# creat instance of my_class
# and test it

script_a iterates over the version folders and runs the test script on script_b.
In each iteration one subfolder is added to the import path so the test script will find the corresponding script_b. The path is removed after the iteration.

If sys.modules already contains a version of test_script,

# script_a
import sys
import os
import importlib

folders = ['version_1', 'version_2', 'version_3']
folders = [os.getcwd() + '/' + folder for folder in folders]

for folder in folders:
    sys.path.append(folder)

    if 'test_script' in sys.modules:
        importlib.reload(sys.modules['test_script'])
    else:
        importlib.import_module('test_script')

    sys.path.remove(folder)

Issue:

It seems reload has no effect on script_b, which is imported by test_script. So although I change the import path to different subfolders test_script always runs on version 1.
How can I make test_script use the different versions of script_b without altering test_script itself?

Follow up:
Although the original question is answered, I was wondering, how is this solution from a design perspective? Is there a better / more elegant way to automate this testing process?

From what I found, it isn't considered good practice to reload modules.

Body:
Figured it out while writing the question. Hope it will help someone some day

Even if you can't alter test_script (or script_b) there's a work around.

Because an import statement does nothing if the relevant module is already imported we can reload script_b from the path we want directly in script_a. Since it then is replaced with the new version in sys.modules the import statement in test_script will cause no problem.

Updated code:

# script_a
import sys
import os
import importlib

folders = ['version_1', 'version_2', 'version_3']
folders = [os.getcwd() + '/' + folder for folder in folders]

for folder in folders:
    sys.path.append(folder)

    if 'test_script' in sys.modules:
        importlib.reload(sys.modules['script_b'])      # this line added
        importlib.reload(sys.modules['test_script'])
    else:
        importlib.import_module('test_script')

    sys.path.remove(folder)