问:
How to check two checkbox unchecked in android
Hello i beginner in android. i am using four checkbox in my project. I want want to call one method after checkbox no 3 and 4 is unchecked state. how to write that code please help me.

Thanks in advance.

```<code>class myCheckBoxChnageClicker implements CompoundButton.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            // Is the view now checked?
            boolean checked = ((CheckBox) buttonView).isChecked();

            // Check which checkbox was clicked
            switch(buttonView.getId()) {

                case R.id.t3_check:

                    if (checked) {

                    } else {

                    }

                    break;

                case R.id.t4_check:

                    if (checked) {

                    } else {

                    }

                    break;

                case R.id.tsh_check:

                    if (checked) {

                    } else {

                    }

                    break;

                case R.id.weight_check:

                    if(checked) {

                    } else {

                    }

                    break;
                default:

            }

        }

        public void showTextNotification(String msgToDisplay) {

            if ((msgToDisplay.equals("Tsh_Check") && msgToDisplay.equals("Weight_Check"))) {

                Toast.makeText(getApplicationContext(), "match", Toast.LENGTH_SHORT).show();

            } else {

            }

        }
    }
</code>```

Hello this is my code i want to call showTextNotification() method when 3 and 4 checkbox is unchecked state.

答: You can call isChecked() on a checkbox to get its status.</p>

Body:
Hello i beginner in android. i am using four checkbox in my project. I want want to call one method after checkbox no 3 and 4 is unchecked state. how to write that code please help me.

Thanks in advance.

class myCheckBoxChnageClicker implements CompoundButton.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            // Is the view now checked?
            boolean checked = ((CheckBox) buttonView).isChecked();

            // Check which checkbox was clicked
            switch(buttonView.getId()) {

                case R.id.t3_check:

                    if (checked) {

                    } else {

                    }

                    break;

                case R.id.t4_check:

                    if (checked) {

                    } else {

                    }

                    break;

                case R.id.tsh_check:

                    if (checked) {

                    } else {

                    }

                    break;

                case R.id.weight_check:

                    if(checked) {

                    } else {

                    }

                    break;
                default:

            }

        }

        public void showTextNotification(String msgToDisplay) {

            if ((msgToDisplay.equals("Tsh_Check") && msgToDisplay.equals("Weight_Check"))) {

                Toast.makeText(getApplicationContext(), "match", Toast.LENGTH_SHORT).show();

            } else {

            }

        }
    }

Hello this is my code i want to call showTextNotification() method when 3 and 4 checkbox is unchecked state.


来源: stackexchange

问:
Java WebServices with Spring and OAS/OC4J
I'm having problems deploying a simple WebServices app (like "Hello World" simple) to OC4J. The same code works fine under Jetty, but breaks in OC4J, and I'm wondering if anyone else has faced the same issue. I'm using Enterprise Manager to deploy the app, but the deployment fails with this message:

```<code>    [Jan 23, 2009 8:46:20 AM] Binding TestWs web-module for application TestWs to site default-web-site under context root /TestWs
    [Jan 23, 2009 8:46:22 AM] Operation failed with error: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://cxf.apache.org/jaxws]
Offending resource: ServletContext resource [/WEB-INF/beans.xml]
</code>```

Looking at the beans.xml, the offending code seems to be the XML namespace declarations:

```<code><beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jaxws="http://cxf.apache.org/jaxws"
    xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">

    <import resource="classpath:META-INF/cxf/cxf.xml" />
    <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
    <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

    <jaxws:endpoint
        id="helloService"
        implementor="com.test.endpoint.HelloImpl"
        address="/HelloWorld" />
</beans>
</code>```

The stack trace is not terribly illuminating:

```<code>    09/01/23 08:57:28 oracle.oc4j.admin.internal.DeployerException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://cxf.apache.org/jaxws]
    Offending resource: ServletContext resource [/WEB-INF/beans.xml]

    09/01/23 08:57:28   at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)
    09/01/23 08:57:28   at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)
    09/01/23 08:57:28   at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:80)
    09/01/23 08:57:28   at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.error(BeanDefinitionParserDelegate.java:261)
    09/01/23 08:57:28   at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1120)
...
</code>```

Has anyone else run into similar problems? And if so, what's the best way to go about fixing it? My XML skills are middling, and I'm a complete noob with WebServices. But this may be an OC4J issue.

Thanks in advance for your help!

EDIT: This is not, as far as I can tell, a classpath issue, unless OC4J is odd about what jars it want to see where (as I know Tomcat can be). My WEB-INF/lib folder has the CXF jar, the Spring jars (beans, context, core, and web), xml-resolver-1.2.jar, and XmlSchema-1.4.2.jar. If I need to list everything in the WEB-INF/lib folder, I will. But again, the program works in Jetty.

Another Edit: Based on what I'm reading here, this appears to be an issue between Spring and the CXF jar -- there's a NamespaceHandler class in the CXF jar (in org.apache.cxf.frontend.spring to be precise), but there seems to be a configuration issue preventing Spring from seeing it.

Last Edit: Thank you everyone for your help. I never ended up getting CXF working in OC4J, because my client is on version 10.1.3.3.0. It's not J2EE 5 compliant, and I'm pretty sure they're not going to go for unpacking their oc4j.jar in order to change the boot.xml. But without the document Daniel pointed me to, I never would have known that.

So I switched to XFire version 1.2.6, and got my test app working after a few hiccups. Along the way I learned some interesting things about OC4J:

When deploying in Enterprise Manager, make sure you choose to load the local classpath first.

OC4J uses non-standard XML files, so make sure your app is not using any of OC4J's native XML files (in the Deployment Settings, uncheck all the currently selected imports -- that way, you can ensure that the app is using only files you provide in WEB-INF/lib)

If you can, use another app server. :P

Thank you all again!

答:
I would think its a CLASSPATH issue.

I'm not that familiar with OC4J, but how are you packaging/deploying your web-application?

You need to ensure that the CXF jar is in the WEB-INF/lib directory of your WAR?

Update: A little confused by your comments - if your spring config is in the META-INF directory of your EAR, then this is not the same classpath as that used by your web-app. So, in fact, sticking the CXF jar in WEB-INF/lib isn't going to work. You will either need to stick the JAR in the top-level of your EAR, or in some lib shared by all classloaders of OC4J. I suggest studying the enterprise-app/web-app classloader hierarchy documentation of OC4J to see if this can give more advice?

OwnerDisplayName: rtperson

ContentLicense: CC BY-SA 2.5

Body:
I'm having problems deploying a simple WebServices app (like "Hello World" simple) to OC4J. The same code works fine under Jetty, but breaks in OC4J, and I'm wondering if anyone else has faced the same issue. I'm using Enterprise Manager to deploy the app, but the deployment fails with this message:

    [Jan 23, 2009 8:46:20 AM] Binding TestWs web-module for application TestWs to site default-web-site under context root /TestWs
    [Jan 23, 2009 8:46:22 AM] Operation failed with error: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://cxf.apache.org/jaxws]
Offending resource: ServletContext resource [/WEB-INF/beans.xml]

Looking at the beans.xml, the offending code seems to be the XML namespace declarations:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jaxws="http://cxf.apache.org/jaxws"
    xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">

    <import resource="classpath:META-INF/cxf/cxf.xml" />
    <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
    <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

    <jaxws:endpoint
        id="helloService"
        implementor="com.test.endpoint.HelloImpl"
        address="/HelloWorld" />
</beans>

The stack trace is not terribly illuminating:

    09/01/23 08:57:28 oracle.oc4j.admin.internal.DeployerException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://cxf.apache.org/jaxws]
    Offending resource: ServletContext resource [/WEB-INF/beans.xml]

    09/01/23 08:57:28   at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)
    09/01/23 08:57:28   at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)
    09/01/23 08:57:28   at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:80)
    09/01/23 08:57:28   at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.error(BeanDefinitionParserDelegate.java:261)
    09/01/23 08:57:28   at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1120)
...

Has anyone else run into similar problems? And if so, what's the best way to go about fixing it? My XML skills are middling, and I'm a complete noob with WebServices. But this may be an OC4J issue.

Thanks in advance for your help!

EDIT: This is not, as far as I can tell, a classpath issue, unless OC4J is odd about what jars it want to see where (as I know Tomcat can be). My WEB-INF/lib folder has the CXF jar, the Spring jars (beans, context, core, and web), xml-resolver-1.2.jar, and XmlSchema-1.4.2.jar. If I need to list everything in the WEB-INF/lib folder, I will. But again, the program works in Jetty.

Another Edit: Based on what I'm reading here, this appears to be an issue between Spring and the CXF jar -- there's a NamespaceHandler class in the CXF jar (in org.apache.cxf.frontend.spring to be precise), but there seems to be a configuration issue preventing Spring from seeing it.

Last Edit: Thank you everyone for your help. I never ended up getting CXF working in OC4J, because my client is on version 10.1.3.3.0. It's not J2EE 5 compliant, and I'm pretty sure they're not going to go for unpacking their oc4j.jar in order to change the boot.xml. But without the document Daniel pointed me to, I never would have known that.

So I switched to XFire version 1.2.6, and got my test app working after a few hiccups. Along the way I learned some interesting things about OC4J:

When deploying in Enterprise Manager, make sure you choose to load the local classpath first.

OC4J uses non-standard XML files, so make sure your app is not using any of OC4J's native XML files (in the Deployment Settings, uncheck all the currently selected imports -- that way, you can ensure that the app is using only files you provide in WEB-INF/lib)

If you can, use another app server. :P

Thank you all again!

LastEditorDisplayName: rtperson

OwnerDisplayName: toolkit

LastEditorDisplayName: toolkit


问:
Smooth MultiPlayer movement
i am developing a multiplayer roleplaying game, (No, its not a mmorpg. ;)

My current setup is like this.

Client tells the server "I want to move forward"/"I want to move backwards", the server then updates your entity, and informs all clients in the area about the change. The server is also updating each entity every 20ms and sending updates every 100ms to the clients, these updates contains position, velocity, rotation etc.

So far so good, however i have nothing in store for smoothing the movement between the packets on the client side, and i must say, i can not get it working. I have been reading up on prediction, interpolation, deadreackoning but its all a big mess for me.

So right now i am just doing something like "Position = Packet.Position", which causes a very stuttering movement.

So, what i want help with is, how do i get a more smooth movement? Have been looking at the XNA Prediction Sample, but i could not get it right.

Thanks //F

答:
I'd suggest the idea from another question (see the accepted answer)

Here the client calculates its position itself as if its not a network game. Client regularly sends his current position to the server. And if client cheats or can't continue moving in the chosen direction, server just sends the client his correct position.

The same algorithm was used in Ultima Online (at least when I was playing it 10 years ago)

Title: Smooth MultiPlayer movement


问:
instanceof operator Vs obj.constructor
I want to know if is there any difference between these two methods of checking whether an object is an instance of a class/constructor. I searched about it and found these two ways.

```<code>obj instanceof SomeConstructor

obj.constructor === SomeConstructor
</code>```

So my questions are:
Is there any difference between the two?

Which one is a better practice?

Also, Is there any other way better than these two?

答:
As per the explanation of @Nisal Edu there, the instanceof is carrying prototype exists into the object chain else return false. obj.constructor === Object is necessary value for every object this return true.

It's mean

```<code>obj.constructor === Object // always return true
obj instanceof Object //return false if prototype is nowhere in object's prototype chain
</code>```

ContentLicense: CC BY-SA 3.0

Title: instanceof operator Vs obj.constructor

Body:
I want to know if is there any difference between these two methods of checking whether an object is an instance of a class/constructor. I searched about it and found these two ways.

obj instanceof SomeConstructor

obj.constructor === SomeConstructor

So my questions are:
Is there any difference between the two?

Which one is a better practice?

Also, Is there any other way better than these two?

Body:
As per the explanation of @Nisal Edu there, the instanceof is carrying prototype exists into the object chain else return false. obj.constructor === Object is necessary value for every object this return true.

It's mean

obj.constructor === Object // always return true
obj instanceof Object //return false if prototype is nowhere in object's prototype chain


问:
.net core with dotnet preview 2.0 cannot find files
My build definitions contains dotnet tasks. This is for a .Net Core 2.0 targeted build.

During build, the error I get is :

[error]No files matched the search pattern.

I've tried so many iterations of picking the path to projects but nothing seems to be picking it up.

I know 2.* is in preview but still I'm sure ppl are using it for .net core 2.0 projects. Any help to how I might fix up my path string?

答:
For TFVC repo, you should specify the project path as below for .NET core task:

```<code>[local/map/path/]relative/path/to/csproj
</code>```

Assume your TFVC repo folder structure as below:

```<code>TFVC Root (XPMoboleApp)
        |___API
             |___XP.API.DataObjects
                       |___XP.API.DataObjects
                                  |___XP.API.DataObjects.csproj
</code>```

In Get sources step, if you leave the local map path empty, you should specify the path to project(s) as:

```<code>API/XP.API.DataObjects/XP.API.DataObjects/XP.API.DataObjects.csproj
</code>```

In Get sources step, if you specified the local map path (such as map test folder), you should set path to project(s) option as:

```<code>test/API/XP.API.DataObjects/XP.API.DataObjects/XP.API.DataObjects.csproj
</code>```

Body:
For TFVC repo, you should specify the project path as below for .NET core task:

[local/map/path/]relative/path/to/csproj

Assume your TFVC repo folder structure as below:

TFVC Root (XPMoboleApp)
        |___API
             |___XP.API.DataObjects
                       |___XP.API.DataObjects
                                  |___XP.API.DataObjects.csproj

In Get sources step, if you leave the local map path empty, you should specify the path to project(s) as:

API/XP.API.DataObjects/XP.API.DataObjects/XP.API.DataObjects.csproj

In Get sources step, if you specified the local map path (such as map test folder), you should set path to project(s) option as:

test/API/XP.API.DataObjects/XP.API.DataObjects/XP.API.DataObjects.csproj


问:
How to Rock Paper Scissors game with images in PHP and HTML
first page-im using radio buttons..so the user will click
rock for example and the computer will play paper but i want it
to be using images.. i just started coding and so very lost

```<code><!DOCTYPE html>
<html lang="en">
<head>
     <title>Rock Paper Scissors Game</title>
</head>
<body>

<form action="rps3.php" method="post">
<h1> Rock Paper Scissors Game</h1>
    <p>Your Choice:</p>
    <p>Rock<input type="radio" value="rock" name="playerthrows"  />
       Paper<input type="radio" value="paper" name="playerthrows"  />
       Scissors<input type="radio" value="scissors" name="playerthrows" />
    </p>
    <p><input type="submit" value="Play"></p>

</form>

</body>
</html>
</code>```

second page- this is how i thought the php would look...
I dont know how to attatch images + this code is not working. The output would like this > You picked: scissors & The computer picked: rock, paper, scissors or> Notice: Undefined offset: 2 in /home/game/public_html/rps3.php on line 20
You picked: paper
&
The computer picked:

```<code><!DOCTYPE html>
<html lang="en">
<head>
     <title>Rock Paper Scissors Game</title>
</head>
<body>
<h1> Rock Paper Scissors Game</h1>

<?php
    if($_POST['playerthrows']){

}

    else if(!$_POST['playerthrows']){

}
        $playerthrows = $_POST['playerthrows'];
        $Choosefrom= array('rock, paper, scissors');
        $Choice= rand(0,2);
        $Computer=$Choosefrom[$Choice];

    echo 'You picked: '.$playerthrows.'';
    echo '<br />&<br />';
    echo 'The computer picked: '. $Computer .'';

    if($playerthrows == $Computer){
    }
    if ($playerthrows == $Computer){
    echo ' Draw  ';
    }
    else if($playerthrows == 'rock ' && $Computer == 'scissors'){
    echo 'You Win!';
}
    else if($playerthrows == 'rock' && $Computer == 'paper'){
    echo  'You Lose! ';
}
    else if($playerthrows == 'scissors' && $Computer == 'rock'){
    echo  ' You Lose! ';
}
    else if($playerthrows == 'scissors' && $Computer == 'paper'){
    echo ' You Win!' ;
}
    else if($playerthrows == 'paper' && $Computer == 'rock'){
    echo 'You Win!';
}
    else if($playerthrows == 'paper' && $Computer == 'scissors'){
    echo 'You Lose!' ;
}

?>

</body>
</code>```

I know these mistakes are probably really noob level but it'd be appreciated if any one can help

答:
Error is becauese you $Choosefrom variable have only one element, - string that contains comas. You should replace it with:

```<code>$Choosefrom= array('rock', 'paper', 'scissors');
</code>```

If you want to use images, than the best way for you is just to put  with pictures of rock paper or scissors, instead of captions.
There is a ways to make it all more plausable, but you will need to learn CSS

Body:
first page-im using radio buttons..so the user will click
rock for example and the computer will play paper but i want it
to be using images.. i just started coding and so very lost

<!DOCTYPE html>

     <title>Rock Paper Scissors Game</title>

<form action="rps3.php" method="post">

 Rock Paper Scissors Game

Your Choice:

Rock<input type="radio" value="rock" name="playerthrows"  />
       Paper<input type="radio" value="paper" name="playerthrows"  />
       Scissors<input type="radio" value="scissors" name="playerthrows" />

<input type="submit" value="Play">

</form>

second page- this is how i thought the php would look...
I dont know how to attatch images + this code is not working. The output would like this > You picked: scissors & The computer picked: rock, paper, scissors or> Notice: Undefined offset: 2 in /home/game/public_html/rps3.php on line 20
You picked: paper
&
The computer picked:

<!DOCTYPE html>

     <title>Rock Paper Scissors Game</title>

 Rock Paper Scissors Game

<?php
    if($_POST['playerthrows']){

}

    else if(!$_POST['playerthrows']){

}
        $playerthrows = $_POST['playerthrows'];
        $Choosefrom= array('rock, paper, scissors');
        $Choice= rand(0,2);
        $Computer=$Choosefrom[$Choice];

    echo 'You picked: '.$playerthrows.'';
    echo '
&
';
    echo 'The computer picked: '. $Computer .'';

    if($playerthrows == $Computer){
    }
    if ($playerthrows == $Computer){
    echo ' Draw  ';
    }
    else if($playerthrows == 'rock ' && $Computer == 'scissors'){
    echo 'You Win!';
}
    else if($playerthrows == 'rock' && $Computer == 'paper'){
    echo  'You Lose! ';
}
    else if($playerthrows == 'scissors' && $Computer == 'rock'){
    echo  ' You Lose! ';
}
    else if($playerthrows == 'scissors' && $Computer == 'paper'){
    echo ' You Win!' ;
}
    else if($playerthrows == 'paper' && $Computer == 'rock'){
    echo 'You Win!';
}
    else if($playerthrows == 'paper' && $Computer == 'scissors'){
    echo 'You Lose!' ;
}

?>

I know these mistakes are probably really noob level but it'd be appreciated if any one can help

Body:
Error is becauese you $Choosefrom variable have only one element, - string that contains comas. You should replace it with:

$Choosefrom= array('rock', 'paper', 'scissors');

If you want to use images, than the best way for you is just to put < img> with pictures of rock paper or scissors, instead of captions.
There is a ways to make it all more plausable, but you will need to learn CSS


问:
Java: static abstract (again) - best practice how to work around
I theoretically understand the point why there is no abstract static in Java, as explained for instance in Why can't static methods be abstract in Java .

But how do I solve such a problem then?

My application uses files of a few types, which I want to assign static properties like a description of that file type (like "data file", the other being "config file", etc.).
Obviously, I would put that into a static String so that the description is accessible without instancing a file (useful for the GUI f.i.).
On the other hand, obviously all file types should have some common methods like getStatus(), which obviously I want to inherit from a common superclass MyFileType.

getDescription() would of course be abstract in the superclass.

Tried using a combination of a superclass and an interface, but similar problem: A static implementation of an abstract method is not allowed.

How would a Java guru solve this?
Is it really such a bad implementation that I want to create?

Many thanks,
Philipp

答:
You could create a FileMetadata class that has all the info you need.  When your app starts up, you could create instances of FileMetadata, and keep static pointers to them so you can access them from anywhere in the JVM.

This way you put the abstract stuff in the actual instances; anything the stuff that does not call for abstract semantics can be static...


问:
Spring Boot JPA does not prepend schema name to tables in query
From what I understand (for example, from here), if I specify the schema for my entity, then it should use that schema name when creating the query.

So, if I have an entity of:

```<code>@Entity
@Table(name="proposalstatuses",schema="sales")
public class ProposalStatus implements Serializable {
    private static final long serialVersionUID = 1L;
    private int proposalStatusID;
    private String proposalStatusName;

    public ProposalStatus() {}

    public ProposalStatus(String proposalStatusName) {
        this.proposalStatusName = proposalStatusName;
    }

    @Id
    @Column(name="pk_proposalstatusid")
    @GeneratedValue(strategy = GenerationType.AUTO)
    public int getProposalStatusID() {
        return proposalStatusID;
    }

    public void setProposalStatusID(int proposalStatusID) {
        this.proposalStatusID = proposalStatusID;
    }

    @Column(name="proposalstatusname", unique=true, nullable=false)
    public String getProposalStatusName() {
        return proposalStatusName;
    }

    public void setProposalStatusName(String proposalStatusName) {
        this.proposalStatusName = proposalStatusName;
    }
}
</code>```

then I would expect Hibernate to generate its queries like select ... from sales.proposalstatuses.  However, instead I see:

```<code>select proposalst0_.pk_proposalstatusid as pk_propo1_8_, proposalst0_.proposalstatusname as proposal2_8_
from proposalstatuses proposalst0_
order by proposalst0_.proposalstatusname asc
</code>```

This is not a huge deal for this case, but now I want to be able to use joins with a table in a different schema, and that is failing because it thinks the tables don't exist (and they don't in the default schema).

So, I have one database (one connection) with multiple schema.  How do I get Hibernate to use the schema name when it references the tables?  It seems like it should be very straight-forward, but I must be missing something.

Thanks!

I am using Spring Boot 1.5.7 which uses Hibernate JPA 2.1 and Hibernate Core 5.0.12.  This does work if I use an H2 datasource.  I am only seeing a problem if MySQL is the datasource.

I have read about creating a view in the default schema for the table I want to reference. However, that is not a feasible option, as I would have to create a great many views; and it seems like Hibernate should be able to handle this without that much effort.

Here are the configuration settings from application.properties:

```<code>spring.datasource.url=jdbc:mysql://localhost/sales?verifyServerCertificate=false&useSSL=true
spring.datasource.username=user
spring.datasource.password=pass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.datasource.testWhileIdle=true
spring.datasource.validationQuery=SELECT 1
spring.jpa.show-sql=true
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
</code>```

Changing the name of the schema in the url allows me to access the data in that schema, but I can't get to any other schema than the one listed in the url.

答:
The way to handle this would be to specify your schemas for your entities that has a name conflict.

Use

```<code>@Table(name="TABLE_NAME", schema="SCHEMA_NAME")
</code>```

or

```<code>@Table(name="SCHEMA_NAME.TABLE_NAME")
</code>```

Body:
From what I understand (for example, from here), if I specify the schema for my entity, then it should use that schema name when creating the query.

So, if I have an entity of:

@Entity
@Table(name="proposalstatuses",schema="sales")
public class ProposalStatus implements Serializable {
    private static final long serialVersionUID = 1L;
    private int proposalStatusID;
    private String proposalStatusName;

    public ProposalStatus() {}

    public ProposalStatus(String proposalStatusName) {
        this.proposalStatusName = proposalStatusName;
    }

    @Id
    @Column(name="pk_proposalstatusid")
    @GeneratedValue(strategy = GenerationType.AUTO)
    public int getProposalStatusID() {
        return proposalStatusID;
    }

    public void setProposalStatusID(int proposalStatusID) {
        this.proposalStatusID = proposalStatusID;
    }

    @Column(name="proposalstatusname", unique=true, nullable=false)
    public String getProposalStatusName() {
        return proposalStatusName;
    }

    public void setProposalStatusName(String proposalStatusName) {
        this.proposalStatusName = proposalStatusName;
    }
}

then I would expect Hibernate to generate its queries like select ... from sales.proposalstatuses.  However, instead I see:

select proposalst0_.pk_proposalstatusid as pk_propo1_8_, proposalst0_.proposalstatusname as proposal2_8_
from proposalstatuses proposalst0_
order by proposalst0_.proposalstatusname asc

This is not a huge deal for this case, but now I want to be able to use joins with a table in a different schema, and that is failing because it thinks the tables don't exist (and they don't in the default schema).

So, I have one database (one connection) with multiple schema.  How do I get Hibernate to use the schema name when it references the tables?  It seems like it should be very straight-forward, but I must be missing something.

Thanks!

I am using Spring Boot 1.5.7 which uses Hibernate JPA 2.1 and Hibernate Core 5.0.12.  This does work if I use an H2 datasource.  I am only seeing a problem if MySQL is the datasource.

I have read about creating a view in the default schema for the table I want to reference. However, that is not a feasible option, as I would have to create a great many views; and it seems like Hibernate should be able to handle this without that much effort.

Here are the configuration settings from application.properties:

spring.datasource.url=jdbc:mysql://localhost/sales?verifyServerCertificate=false&useSSL=true
spring.datasource.username=user
spring.datasource.password=pass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.datasource.testWhileIdle=true
spring.datasource.validationQuery=SELECT 1
spring.jpa.show-sql=true
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy

Changing the name of the schema in the url allows me to access the data in that schema, but I can't get to any other schema than the one listed in the url.

Body:
The way to handle this would be to specify your schemas for your entities that has a name conflict.

Use

@Table(name="TABLE_NAME", schema="SCHEMA_NAME")

or

@Table(name="SCHEMA_NAME.TABLE_NAME")


问:
Unit Tests - Referencing 3.0.0.0 MVC, version actually 4.0.0.0
I am testing SendEmail using Unit Tests (Nunit):

```<code>// Arrange
var mockDbContext = new Mock<DbContext>();
IService service = new Service(mockDbContext.Object);

// Act
var result = service.SendEmail(string.Empty,1,1);

//Assert
Assert.That(result, Is.Not.Null);
Assert.That(result, Is.InstanceOf<bool>());
Assert.AreEqual(result, false);

public bool SendEmail(string emailAddress, int mId, int deadline)
{
    try
    {
        dynamic email = new Email("CirculationEmail");
        email.To = emailAddress;
        email.MId = mId;
        email.Deadline = deadline;
        email.Send();

        return true;
    }
    catch (Exception ex)
    {
        Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
        return false;
    }
}
</code>```

SendEmail uses Postal. I get the following error when I run the test. When I debug it throws the error before even hitting the first debug point within my SendEmail.

```<code>System.IO.FileLoadException : Could not load file or assembly 'System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
</code>```

I added the below to the app.config and searched through my code to see if it ever references 3.0.0.0, it doesn't.

```<code><runtime>
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <dependentAssembly>
      <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" culture="neutral" />
      <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
    </dependentAssembly>
  </assemblyBinding>
</runtime>
</code>```

I am wondering if maybe another error message is being masked (somehow) by the MVC wrong version one?

答:
I had the same error. I tried updating "System.Web.Mvc" package from NuGet package manager in the unit test project. But it didn't reflect any change in references to the unit test project. Heres my solution:

I opened the main project references and double clicked
"System.Web.Mvc" package which led to the view in the object browser.

Then I just copied that path of a file opened it in file explorer.
where I found dll file of "System.Web.Mvc" package.

I did the same procedure for the unit test project where I found dll
file of "System.Web.Mvc" package of an older version.

I replaced it with dll file of "System.Web.Mvc" package found from
main project.

It worked. Though it's not proper way for upgrading pages but its quick.

Body:
I am testing SendEmail using Unit Tests (Nunit):

// Arrange
var mockDbContext = new Mock<DbContext>();
IService service = new Service(mockDbContext.Object);

// Act
var result = service.SendEmail(string.Empty,1,1);

//Assert
Assert.That(result, Is.Not.Null);
Assert.That(result, Is.InstanceOf<bool>());
Assert.AreEqual(result, false);

public bool SendEmail(string emailAddress, int mId, int deadline)
{
    try
    {
        dynamic email = new Email("CirculationEmail");
        email.To = emailAddress;
        email.MId = mId;
        email.Deadline = deadline;
        email.Send();

        return true;
    }
    catch (Exception ex)
    {
        Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
        return false;
    }
}

SendEmail uses Postal. I get the following error when I run the test. When I debug it throws the error before even hitting the first debug point within my SendEmail.

System.IO.FileLoadException : Could not load file or assembly 'System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

I added the below to the app.config and searched through my code to see if it ever references 3.0.0.0, it doesn't.

<runtime>
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <dependentAssembly>
      <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" culture="neutral" />
      <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
    </dependentAssembly>
  </assemblyBinding>
</runtime>

I am wondering if maybe another error message is being masked (somehow) by the MVC wrong version one?


问:
Blender possible hidden animations?
Iron Man Model with mysterious green arrows

Another mysterious green arrowed Iron Man

Aloha all!

I am really new to blender, and am working on a rigging for this Iron Man model for a unity project (generously created and shared here https://www.blendswap.com/blends/view/67628
by user LucaScheller). I added my bones and heat maps but as I am starting to work on my animation, the green net arrows and lines keep getting my attention. Do these signify animations that are built in to the download? If so, how do I access and view them? If not, what are they for?

Thanks!

The Hidden Valkyrie

答:
The arrows and lines around the model represent bones in the armature. Instead of displaying bones as octahedral or sticks you can assign a mesh object as a custom shape that will be displayed in place of the bone.

The armature has a simple walk cycle animation and a pose library with a few different poses setup.

To play the walk cycle you will need to set it as the action for the rig, do that by selecting it in the action editor. You can also use the action in the NLA editor.

With the model containing over 420,000 vertices, I think you will find it too detailed to be used in a game. Also you will find more blender specific help at blender.stackexchange

Title: Blender possible hidden animations?


问:
Convert System::String^ to cv::String
I searched for a while trying to find if there was a similar question, but couldn't.

How can I convert System::String^ (from VC++) to cv::String (from OpenCV)?

```<code>double x, y;
x = 10;
y = 10;
System::String ^ displayString = System::String::Concat("( ", x, " , ", y, " )");
char * test1 = displayString->ToCharArray;
cv::String test = cv::String(test1)
</code>```

gives the error

```<code>Severity    Code    Description Project File    Line    Suppression State
Error   C3867   'System::String::ToCharArray': non-standard syntax; use '&' to create a pointer to member   RobocopComputerVision   RobocopComputerVision   .cpp    156
</code>```

What is the best way to convert System::String^ to cv::String?

答:
Just try this,</p>

```<code>#include <msclr\marshal_cppstd.h>
using namespace msclr::interop;
/* ... ... */
System::String ^ displayString = System::String::Concat("( ", x, " , ", y,")");
cv::String test = marshal_as<std::string>(displayString);
</code>```

Title: Convert System::String^ to cv::String

Body:
I searched for a while trying to find if there was a similar question, but couldn't.

How can I convert System::String^ (from VC++) to cv::String (from OpenCV)?

double x, y;
x = 10;
y = 10;
System::String ^ displayString = System::String::Concat("( ", x, " , ", y, " )");
char * test1 = displayString->ToCharArray;
cv::String test = cv::String(test1)

gives the error

Severity    Code    Description Project File    Line    Suppression State
Error   C3867   'System::String::ToCharArray': non-standard syntax; use '&' to create a pointer to member   RobocopComputerVision   RobocopComputerVision   .cpp    156

What is the best way to convert System::String^ to cv::String?

Body:
Just try this,

#include <msclr\marshal_cppstd.h>
using namespace msclr::interop;
/* ... ... */
System::String ^ displayString = System::String::Concat("( ", x, " , ", y,")");
cv::String test = marshal_as<std::string>(displayString);


问:
Node.js how to pass variable reference so it's in callback functions scope
I'm trying to create a node.js app using the leaflet library, however the WMS I'm using uses Basic Authentication which isn't supported in leaflet so I've extended Tilelayer.WMS to grab the image with a seperate request and convert it to base64. This is all working correctly however I'm fairly new to node/javascript in general and have no idea how I'm supposed to pass a reference to my tile variable through so it's available in the later callback.

```<code>readerLoaded(reader) {
    console.log(reader.target.result);

    //want to be able to do something like this in here
    tile.src = reader.target.result;
},

createTile (coords, done) {
    var tile = document.createElement('img');

    //Removed non-relevant code setting up header options etc
    var reader = new FileReader();
    reader.onload = this.readerLoaded;

    http.get(url, options).subscribe(
        m => {reader.readAsDataURL(m.blob());},
        error => {console.log(error);}
    );

    return tile;
}
</code>```

How do I pass a reference to the specific tile created in each createTile call so it's available in the subsequent readerLoaded call?

Also is there an efficient way to delay createTile returning until the readerLoaded callback has finished? I know if I was designing this myself it'd be a callback which was executed when it was ready however since I'm editing an existing library rewriting large parts of it seems like more effort than it's worth.

Thanks.

答:
First off, you can't take an existing function definition like you show for readerLoaded() and "add" something to it's scope from within createTile().  That's just not how scope works in Javascript.

The usual way to make variables available within a function are to pass them as arguments or define them in the existing parent scope.  Here's an example of passing as an argument.

```<code>readerLoaded(reader, tile) {
    console.log(reader.target.result);

    //want to be able to do something like this in here
    tile.src = reader.target.result;
},

createTile (coords, done) {
    var tile = document.createElement('img');

    //Removed non-relevant code setting up header options etc

    var reader = new FileReader();
    reader.onload = (reader) => {
        return this.readerLoaded(reader, tile);
    }

    http.get(url, options).subscribe(m =>{reader.readAsDataURL(m.blob());},
                                     error=>{console.log(error);});

    return tile;
}
</code>```

If readerLoaded is going to be a method on an object, then you can't really define a temporaral variable such as tile in it's parent scope as there is no real Javascript syntax to do that.  So, it appears your best option here is to pass it as an argument.

Body:
I'm trying to create a node.js app using the leaflet library, however the WMS I'm using uses Basic Authentication which isn't supported in leaflet so I've extended Tilelayer.WMS to grab the image with a seperate request and convert it to base64. This is all working correctly however I'm fairly new to node/javascript in general and have no idea how I'm supposed to pass a reference to my tile variable through so it's available in the later callback.

readerLoaded(reader) {
    console.log(reader.target.result);

    //want to be able to do something like this in here
    tile.src = reader.target.result;
},

createTile (coords, done) {
    var tile = document.createElement('img');

    //Removed non-relevant code setting up header options etc
    var reader = new FileReader();
    reader.onload = this.readerLoaded;

    http.get(url, options).subscribe(
        m => {reader.readAsDataURL(m.blob());},
        error => {console.log(error);}
    );

    return tile;
}

How do I pass a reference to the specific tile created in each createTile call so it's available in the subsequent readerLoaded call?

Also is there an efficient way to delay createTile returning until the readerLoaded callback has finished? I know if I was designing this myself it'd be a callback which was executed when it was ready however since I'm editing an existing library rewriting large parts of it seems like more effort than it's worth.

Thanks.

Body:
First off, you can't take an existing function definition like you show for readerLoaded() and "add" something to it's scope from within createTile().  That's just not how scope works in Javascript.

The usual way to make variables available within a function are to pass them as arguments or define them in the existing parent scope.  Here's an example of passing as an argument.

readerLoaded(reader, tile) {
    console.log(reader.target.result);

    //want to be able to do something like this in here
    tile.src = reader.target.result;
},

createTile (coords, done) {
    var tile = document.createElement('img');

    //Removed non-relevant code setting up header options etc

    var reader = new FileReader();
    reader.onload = (reader) => {
        return this.readerLoaded(reader, tile);
    }

    http.get(url, options).subscribe(m =>{reader.readAsDataURL(m.blob());},
                                     error=>{console.log(error);});

    return tile;
}

If readerLoaded is going to be a method on an object, then you can't really define a temporaral variable such as tile in it's parent scope as there is no real Javascript syntax to do that.  So, it appears your best option here is to pass it as an argument.


问:
ASP.NET MVC2 - passing a parameter to a controller
This is for a project I'm doing in the university. We're using ASP.NET MVC2 to build a mini-prototype of a website just to show what we can do.

Now, I have a controller called ItemController.cs, a view Item/Index.aspx, a model Item.cs and a ViewModel ViewItems.cs. I use the ViewModel to pass information to the view from the controller. My question is - how do I call a controller method with parameters? Currently, I use

```<code>Html.ActionLink("View Event Items", "Index", "Item")
</code>```

which points to ItemController's Index() method. Say I want it to take an int parameter (Index(int eventId)) How would I write the ActionLink to pass the parameter to it?

Also, if I have any errors in how I think this stuff works, please feel free to point them out.

答:
I think that

```<code>Html.ActionLink("View Event Items", new { controller = "Item", action = "Index", id = 5 })
</code>```

should get you in the vicinity of where you're looking to go.

Body:
This is for a project I'm doing in the university. We're using ASP.NET MVC2 to build a mini-prototype of a website just to show what we can do.

Now, I have a controller called ItemController.cs, a view Item/Index.aspx, a model Item.cs and a ViewModel ViewItems.cs. I use the ViewModel to pass information to the view from the controller. My question is - how do I call a controller method with parameters? Currently, I use

Html.ActionLink("View Event Items", "Index", "Item")

which points to ItemController's Index() method. Say I want it to take an int parameter (Index(int eventId)) How would I write the ActionLink to pass the parameter to it?

Also, if I have any errors in how I think this stuff works, please feel free to point them out.

Body:
I think that

Html.ActionLink("View Event Items", new { controller = "Item", action = "Index", id = 5 })

should get you in the vicinity of where you're looking to go.


问:
adding next and previous buttons to ViewPager
I want to make an image slider with Android Studio.
I found a new slider code, built with ViewPager, I tried it and worked..
but I want to add 2 buttons for next and previous..

When clicked button, it must go to next picture or previous picture.

here the mainactivity,

```<code>package org.trial.slider;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
        ImageAdapter adapter = new ImageAdapter(this);
        viewPager.setAdapter(adapter);
     }
}
</code>```

ImageAdapter.java file,

```<code>    package org.trial.slider;

    import android.content.Context;
    import android.support.v4.view.PagerAdapter;
    import android.support.v4.view.ViewPager;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Button;
    import android.widget.ImageView;

    /**
     * Created by ismail on 30.03.16.
     */
    public class ImageAdapter extends PagerAdapter {
        Context context;

        private int[] GalImages = new int[] {
                R.drawable.one,
                R.drawable.two,
                R.drawable.three
        };
        ImageAdapter(Context context){
            this.context=context;
        }
        @Override
        public int getCount() {
            return GalImages.length;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == ((ImageView) object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ImageView imageView = new ImageView(context);
            int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_medium);
            imageView.setPadding(padding, padding, padding, padding);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageView.setImageResource(GalImages[position]);
            ((ViewPager) container).addView(imageView, 0);
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            ((ViewPager) container).removeView((ImageView) object);
        }
    }
</code>```

And I have 2 XML files; fragment_pager and swipe_fragment

答:
```<code>class MyClass extends Fragment implements ViewPager.OnPageChangeListener {

    private int selectedViewPager = 0;

    public void onViewClicked(View view) {

        switch (view.getId()) {
            case R.id.backward:
                if (selectedViewPager > 0) {
                    viewPager.setCurrentItem(selectedViewPager - 1, true);
                }
                break;

            case R.id.fwd:
                if (viewPager.getAdapter().getCount() > selectedViewPager) {
                    viewPager.setCurrentItem(selectedViewPager + 1, true);
                }
                break;
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        selectedViewPager = position;
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
</code>```

Body:
I want to make an image slider with Android Studio.
I found a new slider code, built with ViewPager, I tried it and worked..
but I want to add 2 buttons for next and previous..

When clicked button, it must go to next picture or previous picture.

here the mainactivity,

package org.trial.slider;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
        ImageAdapter adapter = new ImageAdapter(this);
        viewPager.setAdapter(adapter);
     }
}

ImageAdapter.java file,

    package org.trial.slider;

    import android.content.Context;
    import android.support.v4.view.PagerAdapter;
    import android.support.v4.view.ViewPager;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Button;
    import android.widget.ImageView;

    /**
     * Created by ismail on 30.03.16.
     */
    public class ImageAdapter extends PagerAdapter {
        Context context;

        private int[] GalImages = new int[] {
                R.drawable.one,
                R.drawable.two,
                R.drawable.three
        };
        ImageAdapter(Context context){
            this.context=context;
        }
        @Override
        public int getCount() {
            return GalImages.length;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == ((ImageView) object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ImageView imageView = new ImageView(context);
            int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_medium);
            imageView.setPadding(padding, padding, padding, padding);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageView.setImageResource(GalImages[position]);
            ((ViewPager) container).addView(imageView, 0);
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            ((ViewPager) container).removeView((ImageView) object);
        }
    }

And I have 2 XML files; fragment_pager and swipe_fragment


问:
problems on index in matlab nd array
Here is a simplified example

```<code>x = reshape(1:2*4*3,2,4,3); % 3d array
i1 = [1 1 2]; % index in dim 1
i2 = [2 1 3]; % index in dim 2
</code>```

I want to extract x(i1(ii),i2(ii),:), namely x(1,2,:); x(1,1,:); x(2,3,:), which is of size [3,3].

But x(i1,i2,:) gives a 3d array of size [3,3,3].

So I used a stupid loop

```<code>y = nan(length(i1),3);
for ii = 1 : 3
    y(ii,:) = squeeze(x(i1(ii),i2(ii),:));
end
</code>```

which gives

```<code> 3    11    19
 1     9    17
 6    14    22
</code>```

I believe this must not be the fancy way.

答:
You can reshape x to a [8 * 3] matrix and convert subscripts to linear indexes:

```<code>x = reshape(x,[],3);
y = x(sub2ind([2 4],i1,i2),:)
</code>```

Title: problems on index in matlab nd array

Body:
Here is a simplified example

x = reshape(1:2*4*3,2,4,3); % 3d array
i1 = [1 1 2]; % index in dim 1
i2 = [2 1 3]; % index in dim 2

I want to extract x(i1(ii),i2(ii),:), namely x(1,2,:); x(1,1,:); x(2,3,:), which is of size [3,3].

But x(i1,i2,:) gives a 3d array of size [3,3,3].

So I used a stupid loop

y = nan(length(i1),3);
for ii = 1 : 3
    y(ii,:) = squeeze(x(i1(ii),i2(ii),:));
end

which gives

 3    11    19
 1     9    17
 6    14    22

I believe this must not be the fancy way.

Body:
You can reshape x to a [8 * 3] matrix and convert subscripts to linear indexes:

x = reshape(x,[],3);
y = x(sub2ind([2 4],i1,i2),:)


问:
Blocking queue and multi-threaded consumer, how to know when to stop
I have a single thread producer which creates some task objects which are then added into an ArrayBlockingQueue (which is of fixed size).

I also start a multi-threaded consumer. This is build as a fixed thread pool (Executors.newFixedThreadPool(threadCount);). I then submit some ConsumerWorker intances to this threadPool, each ConsumerWorker having a refference to the above mentioned ArrayBlockingQueue instance.

Each such Worker will do a take() on the queue and deal with the task.

My issue is, what's the best way to have a Worker know when there won't be any more work to be done. In other words, how do I tell the Workers that the producer has finished adding to the queue, and from this point on, each worker should stop when he sees that the Queue is empty.

What I've got now is a setup where my Producer is initialized with a callback which is triggered when he finishes it's job (of adding stuff to the queue). I also keep a list of all the ConsumerWorkers I've created and submitted to the ThreadPool. When the Producer Callback tells me that the producer is done, I can tell this to each of the workers. At this point they should simply keep checking if the queue is not empty, and when it becomes empty they should stop, thus allowing me to gracefully shutDown the ExecutorService thread pool. It's something like this

```<code>public class ConsumerWorker implements Runnable{

private BlockingQueue<Produced> inputQueue;
private volatile boolean isRunning = true;

public ConsumerWorker(BlockingQueue<Produced> inputQueue) {
    this.inputQueue = inputQueue;
}

@Override
public void run() {
    //worker loop keeps taking en element from the queue as long as the producer is still running or as
    //long as the queue is not empty:
    while(isRunning || !inputQueue.isEmpty()) {
        System.out.println("Consumer "+Thread.currentThread().getName()+" START");
        try {
            Object queueElement = inputQueue.take();
            //process queueElement
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

//this is used to signal from the main thread that he producer has finished adding stuff to the queue
public void setRunning(boolean isRunning) {
    this.isRunning = isRunning;
}
</code>```

}

The problem here is that I have an obvious race condition where sometimes the producer will finish, signal it, and the ConsumerWorkers will stop BEFORE consuming everything in the queue.

My question is what's the best way to synchronize this so that it all works ok? Should I synchronize the whole part where it checks if the producer is running plus if the queue is empty plus take something from the queue in one block (on the queue object)? Should I just synchronize the update of the isRunning boolean on the ConsumerWorker instance? Any other suggestion?

UPDATE, HERE'S THE WORKING IMPLEMENTATION THAT I'VE ENDED UP USING:

```<code>public class ConsumerWorker implements Runnable{

private BlockingQueue<Produced> inputQueue;

private final static Produced POISON = new Produced(-1);

public ConsumerWorker(BlockingQueue<Produced> inputQueue) {
    this.inputQueue = inputQueue;
}

@Override
public void run() {
    //worker loop keeps taking en element from the queue as long as the producer is still running or as
    //long as the queue is not empty:
    while(true) {
        System.out.println("Consumer "+Thread.currentThread().getName()+" START");
        try {
            Produced queueElement = inputQueue.take();
            Thread.sleep(new Random().nextInt(100));
            if(queueElement==POISON) {
                break;
            }
            //process queueElement
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Consumer "+Thread.currentThread().getName()+" END");
    }
}

//this is used to signal from the main thread that he producer has finished adding stuff to the queue
public void stopRunning() {
    try {
        inputQueue.put(POISON);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
</code>```

}

This was inspired heavily by JohnVint's answer below, with only some minor modifications.

=== Update due to @vendhan's comment.

Thank you for your obeservation. You are right, the first snippet of code in this question has (amongst other issues) the one where the while(isRunning || !inputQueue.isEmpty()) doesn't really make sense.

In my actual final implementation of this, I do something which is closer to your suggestion of replacing "||" (or) with "&&" (and), in the sense that each worker (consumer) now only checks if the element he's got from the list is a poison pill, and if so stops (so theoretically we can say that the worker has to be running AND the queue must not be empty).

答: Can not we do it using a CountDownLatch, where the size is the number of records in the producer. And every consumer will countDown after process a record. And its crosses the awaits() method when all tasks finished. Then stop all ur consumers. As all records are processed.

Body:
I have a single thread producer which creates some task objects which are then added into an ArrayBlockingQueue (which is of fixed size).

I also start a multi-threaded consumer. This is build as a fixed thread pool (Executors.newFixedThreadPool(threadCount);). I then submit some ConsumerWorker intances to this threadPool, each ConsumerWorker having a refference to the above mentioned ArrayBlockingQueue instance.

Each such Worker will do a take() on the queue and deal with the task.

My issue is, what's the best way to have a Worker know when there won't be any more work to be done. In other words, how do I tell the Workers that the producer has finished adding to the queue, and from this point on, each worker should stop when he sees that the Queue is empty.

What I've got now is a setup where my Producer is initialized with a callback which is triggered when he finishes it's job (of adding stuff to the queue). I also keep a list of all the ConsumerWorkers I've created and submitted to the ThreadPool. When the Producer Callback tells me that the producer is done, I can tell this to each of the workers. At this point they should simply keep checking if the queue is not empty, and when it becomes empty they should stop, thus allowing me to gracefully shutDown the ExecutorService thread pool. It's something like this

public class ConsumerWorker implements Runnable{

private BlockingQueue<Produced> inputQueue;
private volatile boolean isRunning = true;

public ConsumerWorker(BlockingQueue<Produced> inputQueue) {
    this.inputQueue = inputQueue;
}

@Override
public void run() {
    //worker loop keeps taking en element from the queue as long as the producer is still running or as
    //long as the queue is not empty:
    while(isRunning || !inputQueue.isEmpty()) {
        System.out.println("Consumer "+Thread.currentThread().getName()+" START");
        try {
            Object queueElement = inputQueue.take();
            //process queueElement
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

//this is used to signal from the main thread that he producer has finished adding stuff to the queue
public void setRunning(boolean isRunning) {
    this.isRunning = isRunning;
}

}

The problem here is that I have an obvious race condition where sometimes the producer will finish, signal it, and the ConsumerWorkers will stop BEFORE consuming everything in the queue.

My question is what's the best way to synchronize this so that it all works ok? Should I synchronize the whole part where it checks if the producer is running plus if the queue is empty plus take something from the queue in one block (on the queue object)? Should I just synchronize the update of the isRunning boolean on the ConsumerWorker instance? Any other suggestion?

UPDATE, HERE'S THE WORKING IMPLEMENTATION THAT I'VE ENDED UP USING:

public class ConsumerWorker implements Runnable{

private BlockingQueue<Produced> inputQueue;

private final static Produced POISON = new Produced(-1);

public ConsumerWorker(BlockingQueue<Produced> inputQueue) {
    this.inputQueue = inputQueue;
}

@Override
public void run() {
    //worker loop keeps taking en element from the queue as long as the producer is still running or as
    //long as the queue is not empty:
    while(true) {
        System.out.println("Consumer "+Thread.currentThread().getName()+" START");
        try {
            Produced queueElement = inputQueue.take();
            Thread.sleep(new Random().nextInt(100));
            if(queueElement==POISON) {
                break;
            }
            //process queueElement
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Consumer "+Thread.currentThread().getName()+" END");
    }
}

//this is used to signal from the main thread that he producer has finished adding stuff to the queue
public void stopRunning() {
    try {
        inputQueue.put(POISON);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}

This was inspired heavily by JohnVint's answer below, with only some minor modifications.

=== Update due to @vendhan's comment.

Thank you for your obeservation. You are right, the first snippet of code in this question has (amongst other issues) the one where the while(isRunning || !inputQueue.isEmpty()) doesn't really make sense.

In my actual final implementation of this, I do something which is closer to your suggestion of replacing "||" (or) with "&&" (and), in the sense that each worker (consumer) now only checks if the element he's got from the list is a poison pill, and if so stops (so theoretically we can say that the worker has to be running AND the queue must not be empty).


答:
```<code>checkBox1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            if (checkBox2.isChecked() && isChecked) {
                // Perform task
            }
        }
    });

    checkBox2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            if (checkBox1.isChecked() && isChecked) {
                // Perform task
            }
        }
    });
</code>```

Title: How to check two checkbox unchecked in android

Body:
Hello i beginner in android. i am using four checkbox in my project. I want want to call one method after checkbox no 3 and 4 is unchecked state. how to write that code please help me.

Thanks in advance.

class myCheckBoxChnageClicker implements CompoundButton.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            // Is the view now checked?
            boolean checked = ((CheckBox) buttonView).isChecked();

            // Check which checkbox was clicked
            switch(buttonView.getId()) {

                case R.id.t3_check:

                    if (checked) {

                    } else {

                    }

                    break;

                case R.id.t4_check:

                    if (checked) {

                    } else {

                    }

                    break;

                case R.id.tsh_check:

                    if (checked) {

                    } else {

                    }

                    break;

                case R.id.weight_check:

                    if(checked) {

                    } else {

                    }

                    break;
                default:

            }

        }

        public void showTextNotification(String msgToDisplay) {

            if ((msgToDisplay.equals("Tsh_Check") && msgToDisplay.equals("Weight_Check"))) {

                Toast.makeText(getApplicationContext(), "match", Toast.LENGTH_SHORT).show();

            } else {

            }

        }
    }

Hello this is my code i want to call showTextNotification() method when 3 and 4 checkbox is unchecked state.


问:
Rails Validation: Limit input to specific values
I'm looking for "the Rails Way" to write a validation that limits acceptable input values to a predetermined list.

In my case, I want to only accept the values "-5", "-2", "+2", "+5", and nil. However, I think this is best as a general question: how do you predefine a list of acceptable entry values in a Rails model?

Thanks!

答:
You want to use validates_inclusion_of with the :in and :allow_nil options.

```<code>validates_inclusion_of :field, :in => %w(-5 -2 2 5), :allow_nil => true
</code>```

You'll probably also want to use in conjunction with validates_numericality_of

Body:
You want to use validates_inclusion_of with the :in and :allow_nil options.

validates_inclusion_of :field, :in => %w(-5 -2 2 5), :allow_nil => true

You'll probably also want to use in conjunction with validates_numericality_of


问:
Making modular VBA function (MS Access)
I am writing up a simple multi-condition search form.
The Access VBA function set for the first toggle button looks like this:

```<code>Private Sub ToggleQ1_Click()
Select Case ToggleQ1.Value
    Case True
        CondQ1 = "AND"
        ToggleQ1.Caption = CondQ1
    Case False
        CondQ1 = "OR"
        ToggleQ1.Caption = CondQ1
End Select
End Sub
</code>```

ToggleQ1 = button's name

CondQ1 = variable to be used with a string to create conditional search.

It would likely be absurd to create 50 more of the same button code, differ only in its name (ex. "ToggleQ50" and "CondQ50")

Is there any way to make it modular and reusable?
Thank you very much in advance.

答:
In the form's module create a function (not sub) like this:

```<code>Private Function SetCaption()
    Dim clickedButton As Control
    Dim CondQ1 As String

    Set clickedButton = Me.ActiveControl
    Select Case clickedButton.Value
        Case True
            CondQ1 = "AND"
            clickedButton.Caption = CondQ1
        Case False
            CondQ1 = "OR"
            clickedButton.Caption = CondQ1
    End Select
End Function
</code>```

In form designer select all 50 buttons and type in property On Click

```<code>=SetCaption()
</code>```

So, you won't need to create event handler for each button.

Title: Making modular VBA function (MS Access)

Body:
I am writing up a simple multi-condition search form.
The Access VBA function set for the first toggle button looks like this:

Private Sub ToggleQ1_Click()
Select Case ToggleQ1.Value
    Case True
        CondQ1 = "AND"
        ToggleQ1.Caption = CondQ1
    Case False
        CondQ1 = "OR"
        ToggleQ1.Caption = CondQ1
End Select
End Sub

ToggleQ1 = button's name

CondQ1 = variable to be used with a string to create conditional search.

It would likely be absurd to create 50 more of the same button code, differ only in its name (ex. "ToggleQ50" and "CondQ50")

Is there any way to make it modular and reusable?
Thank you very much in advance.

Body:
In the form's module create a function (not sub) like this:

Private Function SetCaption()
    Dim clickedButton As Control
    Dim CondQ1 As String

    Set clickedButton = Me.ActiveControl
    Select Case clickedButton.Value
        Case True
            CondQ1 = "AND"
            clickedButton.Caption = CondQ1
        Case False
            CondQ1 = "OR"
            clickedButton.Caption = CondQ1
    End Select
End Function

In form designer select all 50 buttons and type in property On Click

=SetCaption()

So, you won't need to create event handler for each button.


问:
Why isn't .reverse() working?
I am trying to take a sentence and split that sentence, reverse it, and print it to the screen.

I am having trouble understanding how .reverse() works?
When I do something like:

```<code>test = ['This','is','a','test']
new_test = test.reverse()
print(new_test)
</code>```

When I run this I am getting None, why is this? How can I make .reverse() work?

Here is my final code:

```<code>sentence = input("What is your sentence? ")
split_sentence = sentence.split().reverse()
for word in sentence:
    print(word,end='')
</code>```

答:
You can use slicing

```<code>test = ['This','is','a','test']
>>> print(test[::-1])
['test', 'a', 'is', 'This']
</code>```

Title: Why isn't .reverse() working?

Body:
I am trying to take a sentence and split that sentence, reverse it, and print it to the screen.

I am having trouble understanding how .reverse() works?
When I do something like:

test = ['This','is','a','test']
new_test = test.reverse()
print(new_test)

When I run this I am getting None, why is this? How can I make .reverse() work?

Here is my final code:

sentence = input("What is your sentence? ")
split_sentence = sentence.split().reverse()
for word in sentence:
    print(word,end='')

Body:
You can use slicing

test = ['This','is','a','test']
>>> print(test[::-1])
['test', 'a', 'is', 'This']


答:
reverse() reverses a list in-place, and returns None. Just print your original list:

```<code>test = ['This','is','a','test']
test.reverse() # In-place!
print(test)
</code>```

Title: Why isn't .reverse() working?

Body:
reverse() reverses a list in-place, and returns None. Just print your original list:

test = ['This','is','a','test']
test.reverse() # In-place!
print(test)


问:
iOS archive not working
I'm requesting your help to solve an archive issue for Apple iOS.

When I'm running the app with a local certificate everything is fine, but when I switch to archive (in order to publish it) I have an error.

Error is related with Alamofire and from what I consider with codesign

```<code>> Stripped
> /Users/..myuser../Library/Developer/Xcode/DerivedData/..myappname..-brxmobbquzmuhnbmcgzieifhgvjk/Build/Intermediates.noindex/ArchiveIntermediates/...myprojectname.../InstallationBuildProductsLocation/Applications//....app/Frameworks/Alamofire.framework/Alamofire
> of architectures: armv7 Code Signing
> /Users/...../Library/Developer/Xcode/DerivedData/......-brxmobbquzmuhnbmcgzieifhgvjk/Build/Intermediates.noindex/ArchiveIntermediates/..../InstallationBuildProductsLocation/Applications//.....app/Frameworks/Alamofire.framework
> with Identity iPhone Developer: name (code) /usr/bin/codesign --force
> --sign 7FEA49779804D0F60707E9954A90FE65C  --preserve-metadata=identifier,entitlements '/Users/...../Library/Developer/Xcode/DerivedData/.....-brxmobbquzmuhnbmcgzieifhgvjk/Build/Intermediates.noindex/ArchiveIntermediates/...../InstallationBuildProductsLocation/Applications//.....app/Frameworks/Alamofire.framework'
> /Users/...../Library/Developer/Xcode/DerivedData/....-brxmobbquzmuhnbmcgzieifhgvjk/Build/Intermediates.noindex/ArchiveIntermediates/....../InstallationBuildProductsLocation/Applications//......app/Frameworks/Alamofire.framework:
> unknown error -1=ffffffffffffffff Command /bin/sh failed with exit
> code 1
</code>```

Many thanks for your help

答:
Solved.

Somehow the keychain password "login" was my problem. Changing it solved the signed issue. It was not related with Alamofire package.

Title: iOS archive not working

Body:
I'm requesting your help to solve an archive issue for Apple iOS.

When I'm running the app with a local certificate everything is fine, but when I switch to archive (in order to publish it) I have an error.

Error is related with Alamofire and from what I consider with codesign

> Stripped
> /Users/..myuser../Library/Developer/Xcode/DerivedData/..myappname..-brxmobbquzmuhnbmcgzieifhgvjk/Build/Intermediates.noindex/ArchiveIntermediates/...myprojectname.../InstallationBuildProductsLocation/Applications//....app/Frameworks/Alamofire.framework/Alamofire
> of architectures: armv7 Code Signing
> /Users/...../Library/Developer/Xcode/DerivedData/......-brxmobbquzmuhnbmcgzieifhgvjk/Build/Intermediates.noindex/ArchiveIntermediates/..../InstallationBuildProductsLocation/Applications//.....app/Frameworks/Alamofire.framework
> with Identity iPhone Developer: name (code) /usr/bin/codesign --force
> --sign 7FEA49779804D0F60707E9954A90FE65C  --preserve-metadata=identifier,entitlements '/Users/...../Library/Developer/Xcode/DerivedData/.....-brxmobbquzmuhnbmcgzieifhgvjk/Build/Intermediates.noindex/ArchiveIntermediates/...../InstallationBuildProductsLocation/Applications//.....app/Frameworks/Alamofire.framework'
> /Users/...../Library/Developer/Xcode/DerivedData/....-brxmobbquzmuhnbmcgzieifhgvjk/Build/Intermediates.noindex/ArchiveIntermediates/....../InstallationBuildProductsLocation/Applications//......app/Frameworks/Alamofire.framework:
> unknown error -1=ffffffffffffffff Command /bin/sh failed with exit
> code 1

Many thanks for your help


问:
Show Dialog on React material-ui
I'm using material-ui's Dialog component for my React application. How do I set my component to a variable so that I can call the onShow() method?

答:
I recommend reading Dan Abramov's answer on how to implement a modal in React.

In order to use material-ui dialog you can replace the DeletePostModal in his example with the following:

```<code>import { deletePost, hideModal } from '../actions';
import React, {Component} from 'react';
import {connect} from "react-redux";
import {Button, Dialog, DialogActions, DialogTitle} from "material-ui";
import PropTypes from 'prop-types';

const DeletePostModal = ({ post, dispatch }) => (
  <Dialog open={true}>
       <DialogTitle>Delete post {post.name}?</DialogTitle>
            <DialogActions>
                 <button onClick={() => {
                      dispatch(deletePost(post.id)).then(() => {
                           dispatch(hideModal());
                      });
                  }}>
                        Yes
                  </button>
                  <button onClick={() => dispatch(hideModal())}>
                        Nope
                  </button>
        </DialogActions>
   </Dialog>
)

export default connect(
  (state, ownProps) => ({
    post: state.postsById[ownProps.postId]
  })
)(DeletePostModal)
</code>```

Title: Show Dialog on React material-ui

Body:
I recommend reading Dan Abramov's answer on how to implement a modal in React.

In order to use material-ui dialog you can replace the DeletePostModal in his example with the following:

import { deletePost, hideModal } from '../actions';
import React, {Component} from 'react';
import {connect} from "react-redux";
import {Button, Dialog, DialogActions, DialogTitle} from "material-ui";
import PropTypes from 'prop-types';

const DeletePostModal = ({ post, dispatch }) => (
  <Dialog open={true}>
       <DialogTitle>Delete post {post.name}?</DialogTitle>
            <DialogActions>
                 <button onClick={() => {
                      dispatch(deletePost(post.id)).then(() => {
                           dispatch(hideModal());
                      });
                  }}>
                        Yes
                  </button>
                  <button onClick={() => dispatch(hideModal())}>
                        Nope
                  </button>
        </DialogActions>
   </Dialog>
)

export default connect(
  (state, ownProps) => ({
    post: state.postsById[ownProps.postId]
  })
)(DeletePostModal)


问:
How do I sort by a custom field without manually creating a new page?
Having a bit of an issue with Wordpress here.  In all honesty I've always designed my sites from scratch and "coded" from the ground up.  Lately I've been trying to work with WP as I've heard good things about it.

It would appear that WP gives you many things for free (e.g. dynamic "pages" based on CATEGORIES).  However, I would like to know how to manipulate these freebies without reinventing the wheel.  For example, I would like to have my SUB-MENU display a list of post categories.  But I would like to sort those categories by a CUSTOM FIELD.

Now, I could reinvent the wheel and manually create (and link to) a new page for each sort, so on and so forth, (which I don't fundamentally mind doing) however, I'm hoping there is a way around this via plugins or otherwise.  I've seen several tutorials on custom queries, but they stop short of implementation -- they simply give the query without telling exactly whether to create a new page or plug it into a function somewhere.

Any input would be most appreciated.

Best.

答:
At the top of category.php template in your theme's root directory, add the following to add your custom sort field to the query:

```<code><?php
function is_valid_custom_sort_field($field)
{
    // implementation left as an exercise for the questioner
    return true;
}
if ($_REQUEST['sort_custom_field'] && is_valid_custom_sort_field($_REQUEST['sort_custom_field'])) {
    query_posts($query_string . '&orderby='.$_REQUEST['sort_custom_field']);
}
</code>```

See:
http://codex.wordpress.org/Function_Reference/query_posts

If your theme doesn't have a category.php, here is a simple default template to base it on (copied from the included twentyten theme):

```<code><?php
/**
 * The template for displaying Category Archive pages.
 */

get_header(); ?>

        <div id="container">
            <div id="content" role="main">

                <h1 class="page-title"><?php
                    printf( __( 'Category Archives: %s', 'twentyten' ), '<span>' . single_cat_title( '', false ) . '</span>' );
                ?></h1>
                <?php
                    $category_description = category_description();
                    if ( ! empty( $category_description ) )
                        echo '<div class="archive-meta">' . $category_description . '</div>';

                /* Run the loop for the category page to output the posts.
                 * If you want to overload this in a child theme then include a file
                 * called loop-category.php and that will be used instead.
                 */
                get_template_part( 'loop', 'category' );
                ?>

            </div><!-- #content -->
        </div><!-- #container -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>
</code>```

Body:
At the top of category.php template in your theme's root directory, add the following to add your custom sort field to the query:

<?php
function is_valid_custom_sort_field($field)
{
    // implementation left as an exercise for the questioner
    return true;
}
if ($_REQUEST['sort_custom_field'] && is_valid_custom_sort_field($_REQUEST['sort_custom_field'])) {
    query_posts($query_string . '&orderby='.$_REQUEST['sort_custom_field']);
}

See:
http://codex.wordpress.org/Function_Reference/query_posts

If your theme doesn't have a category.php, here is a simple default template to base it on (copied from the included twentyten theme):

<?php
/**
 * The template for displaying Category Archive pages.
 */

get_header(); ?>

        <div id="container">
            <div id="content" role="main">

                <h1 class="page-title"><?php
                    printf( __( 'Category Archives: %s', 'twentyten' ), '<span>' . single_cat_title( '', false ) . '</span>' );
                ?></h1>
                <?php
                    $category_description = category_description();
                    if ( ! empty( $category_description ) )
                        echo '<div class="archive-meta">' . $category_description . '</div>';

                /* Run the loop for the category page to output the posts.
                 * If you want to overload this in a child theme then include a file
                 * called loop-category.php and that will be used instead.
                 */
                get_template_part( 'loop', 'category' );
                ?>

            </div><!-- #content -->
        </div><!-- #container -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>


问:
How can i design y=log(x) in verilog?
i need to write a code in verilog but i'm new to it. I've actually tried $log10() function but when synthesize the code i get an error "Unsupported System Function Call" for $log10(). </p>

答:
Maybe consider using a power series approximation? You could break it up into a piece-wise function for greater accuracy

See the Wolfram Mathematica screenshot below (click on it for a better view).

Maybe something to work with.

Title: How can i design y=log(x) in verilog?


问:
Is there a shorter way for if-else chains?
```<code>if (80 <= m <= 100):
    g = "A"
elif (70 <= m < 80):
    g = "B"
elif (60 <= m < 70):
    g = "C"
elif (50 <= m < 60):
    g = "D"
elif (m < 50):
    g = "U"
</code>```

This is basically a grade measuring piece of code that takes in value m, meaning mark, and obtains grade g. Is there a shorter not necessarily more pythonic way for the same purpose?

Thanks in advance.

答:
I'll exploit the single answer and touching ranges to reduce the number of comparisons, but also express the lookup table's structure using a tuple unpacking. </p>

```<code>if m <= 100:
    g = next(grade for grade, belowscore in
           (('U',50), ('D',60), ('C',70), ('B',80), ('A',100+1))
           if m < belowscore)
</code>```

<p>This uses a generator expression to process a list of similar tests, shortcutting by reading only one result. This is inspired by LISP's conditional operation. Haskell has a similar thing in pattern guards. </p>

Body:
if (80 <= m <= 100):
    g = "A"
elif (70 <= m < 80):
    g = "B"
elif (60 <= m < 70):
    g = "C"
elif (50 <= m < 60):
    g = "D"
elif (m < 50):
    g = "U"

This is basically a grade measuring piece of code that takes in value m, meaning mark, and obtains grade g. Is there a shorter not necessarily more pythonic way for the same purpose?

Thanks in advance.

Body:
I'll exploit the single answer and touching ranges to reduce the number of comparisons, but also express the lookup table's structure using a tuple unpacking.

if m <= 100:
    g = next(grade for grade, belowscore in
           (('U',50), ('D',60), ('C',70), ('B',80), ('A',100+1))
           if m < belowscore)

This uses a generator expression to process a list of similar tests, shortcutting by reading only one result. This is inspired by LISP's conditional operation. Haskell has a similar thing in pattern guards.


问:
Visual Studio Live Testing - Start failed because TestPlatform V2 can not be located
No matter what I do, I can't seem to get live testing to start in Visual studio 2017 (15.3.5)

I get this error:
Start failed because TestPlatform V2 can not be located. Please try to modify your Visual Studio installation through Microsoft Visual Studio Installer, and make sure Testing tools core features is selected under Individual components -> Debugging and testing
[13:23:22.396 Info] For more information, see https://go.microsoft.com/fwlink/?linkid=852911.

I have installed the required component and it still won't run. Although the tests will run if I manually run them.

Any help is appreciated.

答: Hi i also had the similar problem. After checking Extentions and Updates in Vs 2017, the extention Dotnet Extention for test explorer disabled. After enabling this its worked


问:
i wonder!! why there is no Object interface in java?
if there is one, then any one could implement its own object depending on what is their requirement.(ie how they want to implement their own locking mechanism, their own memory realization etc.).
but there is no object interface provided by java creator. Any specific reason?</p>

答:
An interface in Java only has the method type, name and some parameters and the actual implementation is done in a class that implements it. So you never create object for an interface. You can have a local variable for that interface type and the value assigned to that variable would refer to an instance of some concrete implementation of the interface.

All in all, the actual object will always be an instance of some concrete implementation.


问:
websocket.ERROR: Connection error occurred Warning: SessionHandler::read(): Session is not active
using GeniusesOfSymfony/WebSocketBundle with

```<code>    Symfony configuration
        framework:
            session:
                handler_id:  session.handler.native_file
                save_path:   "%kernel.root_dir%/../var/sessions/%kernel.environment%"

    Bundle configuration
            gos_web_socket:
                server:
                    port: 8443
                    host: 127.0.0.1
                    router:
                        resources:
                            - "%kernel.root_dir%/../src/AppBundle/Resources/config/pubsub/routing.yml"
                client:
                    firewall: main
                    session_handler: "@session.handler.native_file"
                topics:
                    - "@o4sh_socket.topic_chat"
                pushers:
                    wamp:
                        host: 127.0.0.1
                        port: 8443

Firewall configuration
             main:
                pattern: ^/
                form_login:
                    provider: fos_userbundle
                    csrf_token_generator: security.csrf.token_manager
                    default_target_path: app_homepage
                    always_use_default_target_path: false
                logout:       true
                anonymous:    true
                switch_user: {role: user.switch_user} #use role rights
</code>```

generates me error when connecting to websocket server

2017-11-14 07:52:25] websocket.ERROR: Connection error occurred Warning: SessionHandler::read(): Session is not active in /srv/www/karli/vendor/symfony/symfony/src/Symfony/Component/HttpFoundation/Session/Storage/Proxy/SessionHandlerProxy.php line 61 {"connection_id":635,"session_id":"14425940785a0aa0b983236618314789"}

[2017-11-14 07:52:25] websocket.ERROR: Connection error occurred Warning: SessionHandler::read(): Session is not active in /srv/www/karli/vendor/symfony/symfony/src/Symfony/Component/HttpFoundation/Session/Storage/Proxy/SessionHandlerProxy.php line 61 {"connection_id":635,"session_id":"14425940785a0aa0b983236618314789"}

[2017-11-14 07:52:25] websocket.ERROR: Connection error occurred Notice: Undefined property: stdClass::$clientStorageId in /srv/www/karli/vendor/gos/web-socket-bundle/Server/App/WampApplication.php line 136 {"connection_id":635,"session_id":"14425940785a0aa0b983236618314789"}

[2017-11-14 07:52:25] websocket.ERROR: Connection error occurred Notice: Undefined property: stdClass::$clientStorageId in /srv/www/karli/vendor/gos/web-socket-bundle/Server/App/WampApplication.php line 136 {"connection_id":635,"session_id":"14425940785a0aa0b983236618314789"}

more detailed error:

答:
Okey, finally figured it out, as in documentation (took time to find it), you cannot use native session handlers with ratchet, all i had to do, was:

session_handler: "@session.handler.pdo"

and everything works as expected.

Body:
using GeniusesOfSymfony/WebSocketBundle with

    Symfony configuration
        framework:
            session:
                handler_id:  session.handler.native_file
                save_path:   "%kernel.root_dir%/../var/sessions/%kernel.environment%"

    Bundle configuration
            gos_web_socket:
                server:
                    port: 8443
                    host: 127.0.0.1
                    router:
                        resources:
                            - "%kernel.root_dir%/../src/AppBundle/Resources/config/pubsub/routing.yml"
                client:
                    firewall: main
                    session_handler: "@session.handler.native_file"
                topics:
                    - "@o4sh_socket.topic_chat"
                pushers:
                    wamp:
                        host: 127.0.0.1
                        port: 8443

Firewall configuration
             main:
                pattern: ^/
                form_login:
                    provider: fos_userbundle
                    csrf_token_generator: security.csrf.token_manager
                    default_target_path: app_homepage
                    always_use_default_target_path: false
                logout:       true
                anonymous:    true
                switch_user: {role: user.switch_user} #use role rights

generates me error when connecting to websocket server

2017-11-14 07:52:25] websocket.ERROR: Connection error occurred Warning: SessionHandler::read(): Session is not active in /srv/www/karli/vendor/symfony/symfony/src/Symfony/Component/HttpFoundation/Session/Storage/Proxy/SessionHandlerProxy.php line 61 {"connection_id":635,"session_id":"14425940785a0aa0b983236618314789"}

[2017-11-14 07:52:25] websocket.ERROR: Connection error occurred Warning: SessionHandler::read(): Session is not active in /srv/www/karli/vendor/symfony/symfony/src/Symfony/Component/HttpFoundation/Session/Storage/Proxy/SessionHandlerProxy.php line 61 {"connection_id":635,"session_id":"14425940785a0aa0b983236618314789"}

[2017-11-14 07:52:25] websocket.ERROR: Connection error occurred Notice: Undefined property: stdClass::$clientStorageId in /srv/www/karli/vendor/gos/web-socket-bundle/Server/App/WampApplication.php line 136 {"connection_id":635,"session_id":"14425940785a0aa0b983236618314789"}

[2017-11-14 07:52:25] websocket.ERROR: Connection error occurred Notice: Undefined property: stdClass::$clientStorageId in /srv/www/karli/vendor/gos/web-socket-bundle/Server/App/WampApplication.php line 136 {"connection_id":635,"session_id":"14425940785a0aa0b983236618314789"}

more detailed error:


问:
Adding a space to a resx language value
I want to add a space between two words in a language resx file where I am translating from English to Afrikaans/Dutch, specifically for an input placeholder field. The problem I'm having is when I run the cshtml page, the words after the space don't show. The only way they do show is if I remove the spaces from the resx value field. Is there a way to have a space and show the whole sentence (with spaces) in the value field

Is there a way for the space to be included in the value field and show up in the input placeholder field?

答:
Update to this question I asked: In the placeholder field where the the field is referenced, add the name field in inverted commas.
E.g. placeholder="resources.languages.sales_order_item_details";
This removed spaces after the first space

Title: Adding a space to a resx language value


问:
Recycler View Horizontal Scroll with 2 columns
Here is I have I have tried so far

```<code>LinearLayoutManager layoutManager =
        new GridLayoutManager(getActivity(), 2, GridLayoutManager.HORIZONTAL, false);
</code>```

but It showed 2 rows instead of two columns.

How can I show two items with horizontal scroll with recycler view?

答:
try below code</p>

```<code>RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 2);
    recyclerView.setLayoutManager(mLayoutManager);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here is I have I have tried so far

LinearLayoutManager layoutManager =
        new GridLayoutManager(getActivity(), 2, GridLayoutManager.HORIZONTAL, false);

but It showed 2 rows instead of two columns.

How can I show two items with horizontal scroll with recycler view?

Body:
try below code

RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 2);
    recyclerView.setLayoutManager(mLayoutManager);


问:
Using a local ARM Template with New-AzureRMResource (Microsoft.DevTestLab/labs/users/environments)
I am attempting to deploy a Microsoft.DevTestLab/labs/users/environments resource which will contain a Microsoft.Network/virtualNetworks resource and a Microsoft.Compute/virtualMachineScaleSets resource. I have those resources defined in an ARM template on my local machine (I do not have access to a private github or vsts to add as a repo to my DevTestLab).

I am wondering if it is possible to specify the path to my local ARM template as the armTemplateId for the Microsoft.DevTestLab/labs/users/environments deploymentProperties?

I can't seem to find any other way to specify my ARM template for use in creating the Microsoft.DevTestLab/labs/users/environments resource.

Any help is greatly appreciated

答:
AFAIK, Azure DevTest Labs only support environments from a repository. It must be in a repo, not on the local machine.

You may create a feedback item here for this feature.


问:
How do I write a loop that prints the year and balance?
```<code>Scanner console = new Scanner(System.in);
System.out.println("Enter Starting Balance: ");
Double balance = Double.parseDouble(console.nextLine());
System.out.println("Enter Yearly Contribution: ");
Double cont = Double.parseDouble(console.nextLine());
System.out.println("Enter Average Return On Investment as %: ");
Double avg = Double.parseDouble(console.nextLine());
System.out.println("Enter Number of years: ");
int year = Integer.parseInt(console.nextLine());

double result1 = (balance + cont) * (1 + avg / 100);
double result2 = (result1 + cont) * (1 + avg / 100);

  year = 0;
    while (year <= year) {
        System.out.println("Year " + year + ": " + balance + "");
        year = year + 1;
        for (result2 = result2; result2 >= result2; result2 = result2 + result2) {
        }
</code>```

<p>//I am aware that the loop is wrong, just not sure the best way to write it.</p>

答:
So provided there isn't a whole lot of detail, I wrote this code which results in output very close to the example you provided. Modify it as needed to match your desired output.</p>

```<code>package various;

import java.util.Scanner;

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

        System.out.println("Enter Starting Balance: ");
        double balance = sc.nextDouble();

        System.out.println("Enter Yearly Contribution: ");
        double cont = sc.nextDouble();

        System.out.println("Enter Average Return On Investment as %: ");
        double avg = sc.nextDouble();

        System.out.println("Enter Number of years: ");
        int years = sc.nextInt();

        double temp = 0;

        for(int i = 0; i <= years; i++) {
            double result = balance + (i*cont)+ (i*temp*(avg/100));
            temp = result;
            System.out.println("Year "+i+": "+result);
        }

        sc.close();
    }
}
</code>```

Body:
Scanner console = new Scanner(System.in);
System.out.println("Enter Starting Balance: ");
Double balance = Double.parseDouble(console.nextLine());
System.out.println("Enter Yearly Contribution: ");
Double cont = Double.parseDouble(console.nextLine());
System.out.println("Enter Average Return On Investment as %: ");
Double avg = Double.parseDouble(console.nextLine());
System.out.println("Enter Number of years: ");
int year = Integer.parseInt(console.nextLine());

double result1 = (balance + cont) * (1 + avg / 100);
double result2 = (result1 + cont) * (1 + avg / 100);

  year = 0;
    while (year <= year) {
        System.out.println("Year " + year + ": " + balance + "");
        year = year + 1;
        for (result2 = result2; result2 >= result2; result2 = result2 + result2) {
        }

//I am aware that the loop is wrong, just not sure the best way to write it.

Body:
So provided there isn't a whole lot of detail, I wrote this code which results in output very close to the example you provided. Modify it as needed to match your desired output.

package various;

import java.util.Scanner;

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

        System.out.println("Enter Starting Balance: ");
        double balance = sc.nextDouble();

        System.out.println("Enter Yearly Contribution: ");
        double cont = sc.nextDouble();

        System.out.println("Enter Average Return On Investment as %: ");
        double avg = sc.nextDouble();

        System.out.println("Enter Number of years: ");
        int years = sc.nextInt();

        double temp = 0;

        for(int i = 0; i <= years; i++) {
            double result = balance + (i*cont)+ (i*temp*(avg/100));
            temp = result;
            System.out.println("Year "+i+": "+result);
        }

        sc.close();
    }
}