问:
Can I lookup an EJB from another EJB?
I have an EJB and it has a method that makes a lookup to another EJB.
I'm having a NameNotFoundException with this code.

ServiceEJBImpl :

```<code>@Stateless(name = "ServiceEJB", mappedName = "AppAcaAvaliacaoAtuarial-ModelAvaliacaoAtuarial-ServiceEJB")
public class ServiceEJBImpl implements ServiceEJB, ServiceEJBLocal{

public void persistConflicts(List<Conflict> conflicts)
{
    ConflictDAOLocal conflictDAO =  (ConflictDAOLocal) BeanLocator.lookup("java:comp/env/ejb/local/ConflictDAO");
    conflictDAO.persistAll(conflicts);
}
</code>```

ConflictDAOLocal:

```<code>@Local
public interface ConflitoDAOLocal{
   void persistAll(List<Conflict> conflicts);
}
</code>```

That's my lookupMethod:

```<code>public static Object lookup(String jndiName) {
    Context context = null;
    try {
        context = new InitialContext();
        return context.lookup(jndiName);
    } catch (NamingException ex) {
        throw new IllegalStateException("...",ex);
    } finally {
        try {
            context.close();
        } catch (NamingException ex) {
            throw new IllegalStateException("...",ex);
        }
    }
}
</code>```

web.xml:

```<code><ejb-local-ref>
    <ejb-ref-name>ejb/local/ConflictDAO</ejb-ref-name>
    <ejb-ref-type>Session</ejb-ref-type>
<local>br.gov.rj.rioprev.sigap.acompatuarial.avalatuarial.model.dao.ConflictDAOLocal</local>
    <ejb-link>ConflictDAO</ejb-link>
</ejb-local-ref>

 <ejb-local-ref>
    <ejb-ref-name>ejb/local/ServiceEJB</ejb-ref-name>
    <ejb-ref-type>Session</ejb-ref-type>
    <local>br.gov.rj.rioprev.sigap.acompatuarial.avalatuarial.model.dao.ServiceEJBLocal</local>
    <ejb-link>ServiceEJB</ejb-link>
</ejb-local-ref>
</code>```

Is there a problem instantiating a new context when making a lookup to an EJB inside another EJB that already has a context instantiated?

I'm not considering @EJB annotation.

答:
As far as you lookup with the correct jndi name you should be able to do it, im not an expert but if you are running this in a web server it would tell you the jndi at momment of the deploy, also you dont really need to create your own lookup, there is one already done that you can use it (actually you are using it but thats just a matter of style), the best aproach maybe is to give your initial context the web server's context, it depends I belive in every web server it should be done something like this </p>

```<code>try{

        Properties prop = new Properties();
        prop.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming"); //This is the one that you have to change depending on your webserver
        Context context = new InitialContext(prop);
         ejbean = (BitacoraBeanRemote)context.lookup("ejb:/EjbSite//BitacoraBean!some.package.bean.BitacoraBeanRemote"); // This is the lookup, it could be a local or a remote interface depending on needs
    }catch(Exception e){
        e.printStackTrace();
    }
</code>```

<p>I was writing when you edit your post just make sure your jndi name is fine "java:comp/env/ejb/local/ConflictDAO", you should probably change it you app is not finding this particular jndi </p>

Title: Can I lookup an EJB from another EJB?

Body:
I have an EJB and it has a method that makes a lookup to another EJB.
I'm having a NameNotFoundException with this code.

ServiceEJBImpl :

@Stateless(name = "ServiceEJB", mappedName = "AppAcaAvaliacaoAtuarial-ModelAvaliacaoAtuarial-ServiceEJB")
public class ServiceEJBImpl implements ServiceEJB, ServiceEJBLocal{

public void persistConflicts(List<Conflict> conflicts)
{
    ConflictDAOLocal conflictDAO =  (ConflictDAOLocal) BeanLocator.lookup("java:comp/env/ejb/local/ConflictDAO");
    conflictDAO.persistAll(conflicts);
}

ConflictDAOLocal:

@Local
public interface ConflitoDAOLocal{
   void persistAll(List<Conflict> conflicts);
}

That's my lookupMethod:

public static Object lookup(String jndiName) {
    Context context = null;
    try {
        context = new InitialContext();
        return context.lookup(jndiName);
    } catch (NamingException ex) {
        throw new IllegalStateException("...",ex);
    } finally {
        try {
            context.close();
        } catch (NamingException ex) {
            throw new IllegalStateException("...",ex);
        }
    }
}

web.xml:

<ejb-local-ref>
    <ejb-ref-name>ejb/local/ConflictDAO</ejb-ref-name>
    <ejb-ref-type>Session</ejb-ref-type>
<local>br.gov.rj.rioprev.sigap.acompatuarial.avalatuarial.model.dao.ConflictDAOLocal</local>
    <ejb-link>ConflictDAO</ejb-link>
</ejb-local-ref>

 <ejb-local-ref>
    <ejb-ref-name>ejb/local/ServiceEJB</ejb-ref-name>
    <ejb-ref-type>Session</ejb-ref-type>
    <local>br.gov.rj.rioprev.sigap.acompatuarial.avalatuarial.model.dao.ServiceEJBLocal</local>
    <ejb-link>ServiceEJB</ejb-link>
</ejb-local-ref>

Is there a problem instantiating a new context when making a lookup to an EJB inside another EJB that already has a context instantiated?

I'm not considering @EJB annotation.

Body:
As far as you lookup with the correct jndi name you should be able to do it, im not an expert but if you are running this in a web server it would tell you the jndi at momment of the deploy, also you dont really need to create your own lookup, there is one already done that you can use it (actually you are using it but thats just a matter of style), the best aproach maybe is to give your initial context the web server's context, it depends I belive in every web server it should be done something like this

try{

        Properties prop = new Properties();
        prop.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming"); //This is the one that you have to change depending on your webserver
        Context context = new InitialContext(prop);
         ejbean = (BitacoraBeanRemote)context.lookup("ejb:/EjbSite//BitacoraBean!some.package.bean.BitacoraBeanRemote"); // This is the lookup, it could be a local or a remote interface depending on needs
    }catch(Exception e){
        e.printStackTrace();
    }

I was writing when you edit your post just make sure your jndi name is fine "java:comp/env/ejb/local/ConflictDAO", you should probably change it you app is not finding this particular jndi


来源: stackexchange

问:
Tensorflow: Saving subset of variables from previously created model
I have created a model (Model A) with a bunch of variables. I plan to do transfer learning with Model A on a new model (Model B) using some of the layers from Model A. However, Model B has the same architecture as Model A so I can't just load all variables from model A before running Model B or else there will be errors with naming, etc. So, I am trying to create a new ckpt file that only stores the weights that I want from Model A. I will then use this new ckpt file to load into Model B. I have the following:

```<code>sess = tf.Session()
saver = tf.train.import_meta_graph('ModelA.ckpt.meta')
saver.restore(sess, 'ModelA.ckpt')

# I did not explicity name my variables in model A so I am just placing them in the list and taking the ones I want

store_list = []
for v in tf.trainable_variables():
    store_list.append(v)

var_list={"W_1": store_list[0], "b_1": store_list[1]}
v2_saver=tf.train.Saver(var_list)
sess.run(tf.global_variables_initializer())
v2_saver.save(sess, 'model_A_subset.ckpt')
</code>```

However when I restore model_A_subset.ckpt I still have all the variables from ModelA.ckpt. Am I doing something wrong? Is there a way I can easily delete the variables I don't want from ModelA.ckpt and use that?

答:
Are you sure the unnecessary variables are in the checkpoint? I ask because before restoring a checkpoint you need to create the graph, and if you're creating a graph with all variables of A in it you'll have this problem.

To inspect the checkpoint and see what's actually there try the inspect checkpoint tool.

ContentLicense: CC BY-SA 3.0

Body:
I have created a model (Model A) with a bunch of variables. I plan to do transfer learning with Model A on a new model (Model B) using some of the layers from Model A. However, Model B has the same architecture as Model A so I can't just load all variables from model A before running Model B or else there will be errors with naming, etc. So, I am trying to create a new ckpt file that only stores the weights that I want from Model A. I will then use this new ckpt file to load into Model B. I have the following:

sess = tf.Session()
saver = tf.train.import_meta_graph('ModelA.ckpt.meta')
saver.restore(sess, 'ModelA.ckpt')

# I did not explicity name my variables in model A so I am just placing them in the list and taking the ones I want

store_list = []
for v in tf.trainable_variables():
    store_list.append(v)

var_list={"W_1": store_list[0], "b_1": store_list[1]}
v2_saver=tf.train.Saver(var_list)
sess.run(tf.global_variables_initializer())
v2_saver.save(sess, 'model_A_subset.ckpt')

However when I restore model_A_subset.ckpt I still have all the variables from ModelA.ckpt. Am I doing something wrong? Is there a way I can easily delete the variables I don't want from ModelA.ckpt and use that?


问:
Ionic framework - 'ionic' is not recognized as an internal or external command
I was trying to install ionic and create a sample project on it since morning. But, was facing a series of issues since then. Tried solving them one by one. Atlast restarted my machine and opened command prompt to build the sample project and tried

```<code>path of the sample project> ionic build android
</code>```

But, i kept on facing the error that states 'ionic' is not recognized as an internal or external command.

I tried clearing the cache and reinstalling ionic in my machine. Still, I face the same issue of ionic is not recognized as an internal or external command.

Can somebody help me out on this issue?

Thanks
Manikandan J

答:
I ran this command to uninstall:

```<code>npm uninstall -g ionic cordova
</code>```

and then ran the install:

```<code>npm install -g ionic cordova
</code>```

and then everything started working again.

Body:
I was trying to install ionic and create a sample project on it since morning. But, was facing a series of issues since then. Tried solving them one by one. Atlast restarted my machine and opened command prompt to build the sample project and tried

path of the sample project> ionic build android

But, i kept on facing the error that states 'ionic' is not recognized as an internal or external command.

I tried clearing the cache and reinstalling ionic in my machine. Still, I face the same issue of ionic is not recognized as an internal or external command.

Can somebody help me out on this issue?

Thanks
Manikandan J

Body:
I ran this command to uninstall:

npm uninstall -g ionic cordova

and then ran the install:

npm install -g ionic cordova

and then everything started working again.


问:
tensorflow einsum vs. matmul vs. tensordot
In tensorflow, the functions tf.einsum, tf.matmul, and tf.tensordot can all be used for the same tasks. (I realize that tf.einsum and tf.tensordot have more general definitions; I also realize that tf.matmul has batch functionality.) In a situation where any of the three could be used, does one function tend to be fastest? Are there other recommendation rules?

For example, suppose that A is a rank-2 tensor, and b is rank-1 tensor, and you want to compute the product c_j = A_ij b_j. Of the three options:

c = tf.einsum('ij,j->i', A, b)

c = tf.matmul(A, tf.expand_dims(b,1))

c = tf.tensordot(A, b, 1)

Is any generally preferable to the others?

答:
Both tf.tensordot() and tf.einsum() are syntactic sugar that wrap one or more invocations of tf.matmul() (although in some special cases tf.einsum() can reduce to the simpler elementwise tf.multiply()).

In the limit, I'd expect all three functions to have equivalent performance for the same computation. However, for smaller matrices, it may be more efficient to use tf.matmul() directly, because it would yield a simpler TensorFlow graph with fewer operations, and hence the pre-operation invocation costs will be lower.

ContentLicense: CC BY-SA 4.0


问:
How to programmatically clear application data
I am developing automated tests for an android application (using Robotium). In order to ensure the consistency and reliability of tests, I would like to start each test with clean state (of the application under test). In order to do so, I need to clear the app data. This can be done manually in Settings/Applications/Manage Applications/[My App]/Clear data

What is the recommended way to get this done programmatically?

答:
What is the recommended way to get this done programmatically?

The only possible option is to run ADB command adb shell pm clear package before the test. The biggest problem is that it's kind of headache combining tests execution and shell commands.

However, we (at Mediafe) came with some solution that can work for you on regular unrooted device. All you need to do is to add an annotation. All the rest is done by running simple bash script.

Just add @ClearData annotation before ANY of your tests and tada , ADB clear command will be executed before the test execution.

This is an example of such test:

```<code>@Test
@ClearData
public void someTest() {
    // your test
}
</code>```

The idea is as follows

Read all tests by using adb shell am instrument -e log true

Build execution plan by parsing the output from (1)

Run the execution plan line by line

Using the same idea these are all options you can easily support:

Clear data

Clear notification bar

Parameterize

Filter and run by tags

Use only annotations. Like this:

```<code>@Test
@ClearData
@Tags(tags = {"sanity", "medium"})
@Parameterized.Repeat(count = 3)
public void myTest() throws Exception {
    String param = params[index];
    // ...
}
</code>```

Bonus!  For each failed test:

Collect Logcat + stacktrace

Record video (mp4)

Dump DB (sqlite)

Dump default shared preferences (xml)

Collect dumpsys files like: battery, netstats and other.

In general, it's easy to add more options, since the tests are executed one by one from bash script rather than from gradle task.

 The full blog post: https://medium.com/medisafe-tech-blog/running-android-ui-tests-53e85e5c8da8

 The source code with examples: https://github.com/medisafe/run-android-tests

Hope this answers 6 years question ;)

Body:
What is the recommended way to get this done programmatically?

The only possible option is to run ADB command adb shell pm clear package before the test. The biggest problem is that it's kind of headache combining tests execution and shell commands.

However, we (at Mediafe) came with some solution that can work for you on regular unrooted device. All you need to do is to add an annotation. All the rest is done by running simple bash script.

Just add @ClearData annotation before ANY of your tests and tada , ADB clear command will be executed before the test execution.

This is an example of such test:

@Test
@ClearData
public void someTest() {
    // your test
}

The idea is as follows

Read all tests by using adb shell am instrument -e log true

Build execution plan by parsing the output from (1)

Run the execution plan line by line

Using the same idea these are all options you can easily support:

Clear data

Clear notification bar

Parameterize

Filter and run by tags

Use only annotations. Like this:

@Test
@ClearData
@Tags(tags = {"sanity", "medium"})
@Parameterized.Repeat(count = 3)
public void myTest() throws Exception {
    String param = params[index];
    // ...
}

Bonus!  For each failed test:

Collect Logcat + stacktrace

Record video (mp4)

Dump DB (sqlite)

Dump default shared preferences (xml)

Collect dumpsys files like: battery, netstats and other.

In general, it's easy to add more options, since the tests are executed one by one from bash script rather than from gradle task.

 The full blog post: https://medium.com/medisafe-tech-blog/running-android-ui-tests-53e85e5c8da8

 The source code with examples: https://github.com/medisafe/run-android-tests

Hope this answers 6 years question ;)


问:
How do I validate if a username exists before sign up in Firebase and Swift 3?
I've incorporated a sign-up flow of five view controllers as opposed to one central VC for Firebase sign up.

Normally there would be the problem of data being lost before sign up, but I'm pushing all the entered values via segue programmatically to the final confirmation page and sending the data to Firebase for auth eventually.

My problem lies therein - I want to check if the username exists before signing up. This is imperative for the UX of my app and I can't just do this all one VC.

Here's the code I have for the UsernameViewController:

```<code>   let rootRef = FIRDatabase.database().reference()

   rootRef.queryOrdered(byChild: "users").queryEqual(toValue: self.chooseUsernameTextField.text!)
    .observe(FIRDataEventType.value, with: { (snapshot: FIRDataSnapshot!)  in

            if snapshot.hasChildren() == false {
                print("not found")

            } else {
                print("usr found")
            }
        });
</code>```

Here's the code I have for the Firebase Database Security Rules

```<code>   {
     "rules": {
        ".read": false,
        ".write": false,
      "users": {
        ".validate": "data.child('username').val() === true",
      ".read": true
      }
     }
    }
</code>```

and finally, a screenshot of my Data tree (My Data tree won't let me nest any new users or create a user node without a value for some reason):

Picture of Firebase Data Tree: App Name/Users

I have a nagging suspicion that my data rules and tree are configured properly to match the code, but I'm stuck in a XY problem of not knowing what to do for Firebase security to get my code of username checking complete.

Please help me! :(

答:
If there's a user created within the Auth section of Firebase as well, then you can actually use the fetchProviders method, and if no providers are returned, you have no user in you Auth section.</p>

```<code>FIRAuth.auth()?.fetchProviders(forEmail: email, completion: { (providers, error) in
            if providers == nil {
                   // user doesn't exist
              } else {
                   // user does exist
              }
        })
</code>```

Body:
I've incorporated a sign-up flow of five view controllers as opposed to one central VC for Firebase sign up.

Normally there would be the problem of data being lost before sign up, but I'm pushing all the entered values via segue programmatically to the final confirmation page and sending the data to Firebase for auth eventually.

My problem lies therein - I want to check if the username exists before signing up. This is imperative for the UX of my app and I can't just do this all one VC.

Here's the code I have for the UsernameViewController:

   let rootRef = FIRDatabase.database().reference()

   rootRef.queryOrdered(byChild: "users").queryEqual(toValue: self.chooseUsernameTextField.text!)
    .observe(FIRDataEventType.value, with: { (snapshot: FIRDataSnapshot!)  in

            if snapshot.hasChildren() == false {
                print("not found")

            } else {
                print("usr found")
            }
        });

Here's the code I have for the Firebase Database Security Rules

   {
     "rules": {
        ".read": false,
        ".write": false,
      "users": {
        ".validate": "data.child('username').val() === true",
      ".read": true
      }
     }
    }

and finally, a screenshot of my Data tree (My Data tree won't let me nest any new users or create a user node without a value for some reason):

Picture of Firebase Data Tree: App Name/Users

I have a nagging suspicion that my data rules and tree are configured properly to match the code, but I'm stuck in a XY problem of not knowing what to do for Firebase security to get my code of username checking complete.

Please help me! :(

Body:
If there's a user created within the Auth section of Firebase as well, then you can actually use the fetchProviders method, and if no providers are returned, you have no user in you Auth section.

FIRAuth.auth()?.fetchProviders(forEmail: email, completion: { (providers, error) in
            if providers == nil {
                   // user doesn't exist
              } else {
                   // user does exist
              }
        })


问:
How would I make user be able to post and keep it on the site?
here is the code that I need help with

I want to be able to post text on this website and for it to stay

https://pastebin.com/JcnNkRKx

```<code><html>
  <head>
    <title>Negulos</title>
    <style>
      p {
        text-align: center;
        color: lime;
        font-size: 20px;
      }
      body {
        background-color: black;
        overflow-x: hidden;
      }
      input[type=text], select {
        boarder: none;
        background-color: black;
        color: lime;
        position: absolute;
        right: 550px;
      }
      div {
        border-radius: 5px;
        padding: 20px;
      }
    </style>
  </head>
  <body>
    <p>Welcome to Negulos the current time is</p><p id="t"></p>
    <p>Write anything you'd like to get off your chest</p>
    <div>
      <input type="text" id="user" value="Your text here">
    </div>
    <p onclick="post" onmouseover="colorOn(this)" onmouseout="colorOff(this)">post</p>
    <p id="post"></p>
    <script>
      function colorOn(x) {
        x.style.color = "red";
      }
      function colorOff(x) {
        x.style.color = "lime";
      }
    </script>
    <script>
      function post() {
        var x = document.getElementById("user").value;
        document.getElementById("post").innerHTML = x;
      }
    </script>
    <script>
      document.getElementById("t").innerHTML = Date();
    </script>
    <?php

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

答:
This part of your code doesn't do anything:

<p onclick="post"

You left out the brackets () which is supposed to trigger the post() function.

That needs to read as:

<p onclick="post()"

Body:
here is the code that I need help with

I want to be able to post text on this website and for it to stay

https://pastebin.com/JcnNkRKx

    <title>Negulos</title>

Welcome to Negulos the current time is

Write anything you'd like to get off your chest

      <input type="text" id="user" value="Your text here">

post

    <?php

?>


问:
Keep some lines of code private in a public GitHub repository
I am currently developing a kind of small web-application which I would like to put on GitHub in a public repository. I want to do this to make it open source but I would also like to use the advantages of git while developing it. Now since I am using PHP and MySQL to develop it I sometimes have a line in my code where I create a new object of the class $PDO in which I also have to write my username and password for my MySQL database. Now I would like to know if there is a way to still upload my scripts to GitHub and to also use Git while keeping those lines private.
Have a nice day.</p>

答:
There is no way to only version control part of a file, however, you can only version control specific files using the .gitignore

For example file structure:

```<code>-- .gitignore
-- password.txt
-- script.py
</code>```

And inside the .gitignore file:

```<code>password.txt
</code>```

This will make is so git does not add the password file to github & you can safely store you information in it!

Body:
There is no way to only version control part of a file, however, you can only version control specific files using the .gitignore

For example file structure:

-- .gitignore
-- password.txt
-- script.py

And inside the .gitignore file:

password.txt

This will make is so git does not add the password file to github & you can safely store you information in it!


问:
Change Squarespace CSS on scroll
I am trying to change the background color of the header element in my Squarespace site using custom CSS and code injection.

I found this previous, non-Squarespace solution.

I have attempted to adapt it, but given my lack of jQuery knowledge and how exactly Squarespace uses code injection, I am at a loss.

In the custom CSS area I have added

```<code>.transparent-header #header { background-color: rgba(0,0,0,0.7); }
</code>```

In the code injection area I have added

```<code><script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">

$(window).on('scroll',function(){

    if ($(window).scrollTop() >= 100) {
        $('.transparent-header #header').css({
            'background-color:' : 'rgba(0,0,0,0.7)'
        });
    } else {
        $('.transparent-header #header').css({
            'background-color:' : 'rgba(0,0,0,0.0)'
        });
    }
});
</script>
</code>```

The homepage of our website can be accessed here.

Edit:

Expected result: After scrolling some distance x (currently 100px) navigation header will add a semi-transparant fill

Current result: no change

答:
Change the background color of a specific page (rather than just the header) as the user scrolls, for example, change this:

```<code>.transparent-header #header {
    background-color: rgba(0,0,0,0.7);
}
</code>```

to

```<code>.transparent-background #collectionIDgoeshere {
    background-color: rgba(0,0,0,0.7);
}
</code>```

Title: Change Squarespace CSS on scroll

Body:
I am trying to change the background color of the header element in my Squarespace site using custom CSS and code injection.

I found this previous, non-Squarespace solution.

I have attempted to adapt it, but given my lack of jQuery knowledge and how exactly Squarespace uses code injection, I am at a loss.

In the custom CSS area I have added

.transparent-header #header { background-color: rgba(0,0,0,0.7); }

In the code injection area I have added

The homepage of our website can be accessed here.

Edit:

Expected result: After scrolling some distance x (currently 100px) navigation header will add a semi-transparant fill

Current result: no change

Body:
Change the background color of a specific page (rather than just the header) as the user scrolls, for example, change this:

.transparent-header #header {
    background-color: rgba(0,0,0,0.7);
}

to

.transparent-background #collectionIDgoeshere {
    background-color: rgba(0,0,0,0.7);
}


问:
Can I use an object property in the SET clause for neo4j cypher query
I want to create a node with properties that are object i.e

```<code>name: {
fname: String;
mname: String,
lname: String
}

Match (n: email:"123@mail.com"}) SET n.name=name Return n;
</code>```

I have been searching SO and the documentation without success. The closest I have seen is the {map} but I am not sure how to use it.

答:
You cannot store a dictionary/map/object as a property on a node in Neo4j, only primitives (int, float, string and arrays of primitives).

However, you can pass an object as a parameter and refer to elements of that object in a SET clause:

```<code>var name = {
    fname: "Bob",
    mname: "E",
    lname: "Loblaw",
}

WITH {name} AS name
MATCH (n:Person {email: "123@mail.com"})
SET n.fname = name.fname,
    n.mname = name.mname,
    n.lname = name.lname
</code>```

You can also set all elements of an object as properties on a node:

```<code>var name = {
    fname: "Bob",
    mname: "E",
    lname: "Loblaw",
}

WITH {name} AS name
MATCH (n:Person {email: "123@mail.com"})
SET n = n + name
</code>```

Body:
I want to create a node with properties that are object i.e

name: {
fname: String;
mname: String,
lname: String
}

Match (n: email:"123@mail.com"}) SET n.name=name Return n;

I have been searching SO and the documentation without success. The closest I have seen is the {map} but I am not sure how to use it.

Body:
You cannot store a dictionary/map/object as a property on a node in Neo4j, only primitives (int, float, string and arrays of primitives).

However, you can pass an object as a parameter and refer to elements of that object in a SET clause:

var name = {
    fname: "Bob",
    mname: "E",
    lname: "Loblaw",
}

WITH {name} AS name
MATCH (n:Person {email: "123@mail.com"})
SET n.fname = name.fname,
    n.mname = name.mname,
    n.lname = name.lname

You can also set all elements of an object as properties on a node:

var name = {
    fname: "Bob",
    mname: "E",
    lname: "Loblaw",
}

WITH {name} AS name
MATCH (n:Person {email: "123@mail.com"})
SET n = n + name


问:
JButton - No Click Anmation
i read some contributions about this but nothing helped.
I try to make a little application with a gui,
but the problem is, if i click the button, no animation appears and nothing happens. I hope you can help me.
That's the code:

```<code>public class StartFrame extends JFrame{

JTextField eingabe;
JLabel inhalt;
JButton button;
JCheckBox fett;
JCheckBox kursiv;
JCheckBox groß;
JPanel panel;

StartFrame(int sizeWidth, int sizeHeight, String title){

setSize(sizeWidth, sizeHeight);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle(title);
setLocationRelativeTo(null);
setLayout(null);

inhalt = new JLabel("TeXt");
inhalt.setBounds(0, 0, 500, 60);
Font font = inhalt.getFont().deriveFont(Font.ITALIC, 15);
inhalt.setFont(font);
inhalt.setToolTipText("Das ist ein Text");
add(inhalt);

button = new JButton("HIER");
button.setBounds(100, 10, 100, 50);
button.addActionListener(new ClickListener());
button.setEnabled(false);
add(button);

eingabe = new JTextField();
eingabe.setBounds(300, 50, 150, 25);
eingabe.addCaretListener(new SchreibkopfListener());
add(eingabe);

panel = new JPanel();
panel.setLayout(null);
panel.setBounds(10, 200, 150, 100);
add(panel);

fett = new JCheckBox("Fett");
fett.setBounds(0, 0, 150, 25);
fett.addItemListener(new FettListener());
panel.add(fett);

kursiv = new JCheckBox("Kursiv");
kursiv.setBounds(0, 25, 150, 25);
panel.add(kursiv);

groß = new JCheckBox("Groß");
groß.setBounds(0, 50, 150, 25);
panel.add(groß);

setVisible(true);

}

private class ClickListener implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent arg0) {

        inhalt.setText(eingabe.getText());

    }

}

private class SchreibkopfListener implements CaretListener{

    @Override
    public void caretUpdate(CaretEvent arg0) {

        String inTextField = eingabe.getText();
        inTextField = inTextField.trim();
        if(inTextField.isEmpty()){
            button.setEnabled(false);
        }else{

            button.setEnabled(true);

        }

    }

}

private class FettListener implements ItemListener{

    @Override
    public void itemStateChanged(ItemEvent arg0) {

        if(fett.isSelected()){

            Font font = inhalt.getFont().deriveFont(Font.BOLD, 15);
            inhalt.setFont(font);

        }else{

            Font font = inhalt.getFont().deriveFont(Font.ITALIC, 15);
            inhalt.setFont(font);

        }

    }

}
</code>```

}

答:
Here's a wonderful lesson into why null layouts suck (and you should stop using them)

Let's just take a little look at these lines...

```<code>nhalt = new JLabel("TeXt");
inhalt.setBounds(0, 0, 500, 60);
inhalt.setToolTipText("Das ist ein Text");
//...
button = new JButton("HIER");
button.setBounds(100, 10, 100, 50);
</code>```

So, the label starts at 0x0 and expands through 500x60, okay, the button starts at 100x10 and expands through 100x50, this means that the label and the button actually collide

Now, I know what you're thinking, but I add the button after the label, but this isn't how components actually get painted/respond to events.

Components are painted in reverse order of how they are added, this means that the label actually resides OVER the button (in terms of the Z-order), this also means that the label receives events BEFORE the button, this is important because...

```<code>inhalt.setToolTipText("Das ist ein Text");
</code>```

installs a MouseListener on the JLabel, which consumes ALL mouse events, preventing the button from been notified.

So, long answer short, don't use null layouts (and take the time to better understand how the API actually works :P)

Title: JButton - No Click Anmation

Body:
i read some contributions about this but nothing helped.
I try to make a little application with a gui,
but the problem is, if i click the button, no animation appears and nothing happens. I hope you can help me.
That's the code:

public class StartFrame extends JFrame{

JTextField eingabe;
JLabel inhalt;
JButton button;
JCheckBox fett;
JCheckBox kursiv;
JCheckBox groß;
JPanel panel;

StartFrame(int sizeWidth, int sizeHeight, String title){

setSize(sizeWidth, sizeHeight);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle(title);
setLocationRelativeTo(null);
setLayout(null);

inhalt = new JLabel("TeXt");
inhalt.setBounds(0, 0, 500, 60);
Font font = inhalt.getFont().deriveFont(Font.ITALIC, 15);
inhalt.setFont(font);
inhalt.setToolTipText("Das ist ein Text");
add(inhalt);

button = new JButton("HIER");
button.setBounds(100, 10, 100, 50);
button.addActionListener(new ClickListener());
button.setEnabled(false);
add(button);

eingabe = new JTextField();
eingabe.setBounds(300, 50, 150, 25);
eingabe.addCaretListener(new SchreibkopfListener());
add(eingabe);

panel = new JPanel();
panel.setLayout(null);
panel.setBounds(10, 200, 150, 100);
add(panel);

fett = new JCheckBox("Fett");
fett.setBounds(0, 0, 150, 25);
fett.addItemListener(new FettListener());
panel.add(fett);

kursiv = new JCheckBox("Kursiv");
kursiv.setBounds(0, 25, 150, 25);
panel.add(kursiv);

groß = new JCheckBox("Groß");
groß.setBounds(0, 50, 150, 25);
panel.add(groß);

setVisible(true);

}

private class ClickListener implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent arg0) {

        inhalt.setText(eingabe.getText());

    }

}

private class SchreibkopfListener implements CaretListener{

    @Override
    public void caretUpdate(CaretEvent arg0) {

        String inTextField = eingabe.getText();
        inTextField = inTextField.trim();
        if(inTextField.isEmpty()){
            button.setEnabled(false);
        }else{

            button.setEnabled(true);

        }

    }

}

private class FettListener implements ItemListener{

    @Override
    public void itemStateChanged(ItemEvent arg0) {

        if(fett.isSelected()){

            Font font = inhalt.getFont().deriveFont(Font.BOLD, 15);
            inhalt.setFont(font);

        }else{

            Font font = inhalt.getFont().deriveFont(Font.ITALIC, 15);
            inhalt.setFont(font);

        }

    }

}

}

Body:
Here's a wonderful lesson into why null layouts suck (and you should stop using them)

Let's just take a little look at these lines...

nhalt = new JLabel("TeXt");
inhalt.setBounds(0, 0, 500, 60);
inhalt.setToolTipText("Das ist ein Text");
//...
button = new JButton("HIER");
button.setBounds(100, 10, 100, 50);

So, the label starts at 0x0 and expands through 500x60, okay, the button starts at 100x10 and expands through 100x50, this means that the label and the button actually collide

Now, I know what you're thinking, but I add the button after the label, but this isn't how components actually get painted/respond to events.

Components are painted in reverse order of how they are added, this means that the label actually resides OVER the button (in terms of the Z-order), this also means that the label receives events BEFORE the button, this is important because...

inhalt.setToolTipText("Das ist ein Text");

installs a MouseListener on the JLabel, which consumes ALL mouse events, preventing the button from been notified.

So, long answer short, don't use null layouts (and take the time to better understand how the API actually works :P)


问:
Overriding methods in a class extension constrained to a protocol in swift
I am trying to add default implementations to UIViewController touches began to all controllers conforming to a protocol through a protocol extension. There the touch would be sent to a custom view all controllers implementing this protocol have.

Here's the initial state:

```<code>protocol WithView {
    var insideView: UIView! { get }
}

class Controller1: UIViewController, WithView {

    var insideView: UIView!

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        insideView.touchesBegan(touches, with: event)
    }

    /* Functionality of Controller 1 */
}

class Controller2: UIViewController, WithView {

    var insideView: UIView!

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        insideView.touchesBegan(touches, with: event)
    }

    /* Functionality of Controller 2 */
}
</code>```

What I'd like to accomplish is a situation where all the UIViewControllers forwarded the touches to the insideView without specifying so for every controller the same way. Something like this:

```<code>protocol WithView {
    var insideView: UIView! { get }
}

extension UIViewController where Self: WithView {
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        insideView.touchesBegan(touches, with: event)
    }
}

class Controller1: UIViewController, WithView {

    var insideView: UIView!

    /* Functionality of Controller 1 */
}

class Controller2: UIViewController, WithView {

    var insideView: UIView!

    /* Functionality of Controller 2 */
}
</code>```

But this does not compile, saying 'Trailing where clause for extension of non-generic type UIViewController'

I tried to define it the other way around, like so:

```<code>extension WithView where Self: UIViewController {
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        insideView.touchesBegan(touches, with: event)
    }
}
</code>```

and while the extension is properly formatted, the compiler complains, as it cannot 'override' things in a protocol extension.

What I'd like is a class extension constrained to a protocol, such as I can override this methods and not being forced to copy-paste code inside all my controllers implementing this protocol.

Edit: as per proposed solutions

I also came up with this solution:

```<code>protocol WithView {
    var insideView: UIView! { get }
}

extension UIViewController {
    override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let viewSelf = (self as? WithView) else {
            super.touchesBegan(touches, with: event)
            return
        }
        viewSelf.insideView.touchesBegan(touches, with: event)
    }
}

class Controller1: UIViewController, WithView {

    var insideView: UIView!

    /* Functionality of Controller 1 */
}

class Controller2: UIViewController, WithView {

    var insideView: UIView!

    /* Functionality of Controller 2 */
}
</code>```

It does what I want, but it feels a bit messy though, because then all the UIViewControllers would intherit this behavior, and would override its code, checking if they implement the protocol.

答:
You could do this by creating a class and sub-classing from it:

```<code>class WithViewController: UIViewController, WithView {

    var insideView: UIView!

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        insideView.touchesBegan(touches, with: event)
    }
}

class ViewController: WithViewController {

}
</code>```

The only downside to this is you have to have a default insideView and it never get's changed.

Body:
I am trying to add default implementations to UIViewController touches began to all controllers conforming to a protocol through a protocol extension. There the touch would be sent to a custom view all controllers implementing this protocol have.

Here's the initial state:

protocol WithView {
    var insideView: UIView! { get }
}

class Controller1: UIViewController, WithView {

    var insideView: UIView!

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        insideView.touchesBegan(touches, with: event)
    }

    /* Functionality of Controller 1 */
}

class Controller2: UIViewController, WithView {

    var insideView: UIView!

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        insideView.touchesBegan(touches, with: event)
    }

    /* Functionality of Controller 2 */
}

What I'd like to accomplish is a situation where all the UIViewControllers forwarded the touches to the insideView without specifying so for every controller the same way. Something like this:

protocol WithView {
    var insideView: UIView! { get }
}

extension UIViewController where Self: WithView {
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        insideView.touchesBegan(touches, with: event)
    }
}

class Controller1: UIViewController, WithView {

    var insideView: UIView!

    /* Functionality of Controller 1 */
}

class Controller2: UIViewController, WithView {

    var insideView: UIView!

    /* Functionality of Controller 2 */
}

But this does not compile, saying 'Trailing where clause for extension of non-generic type UIViewController'

I tried to define it the other way around, like so:

extension WithView where Self: UIViewController {
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        insideView.touchesBegan(touches, with: event)
    }
}

and while the extension is properly formatted, the compiler complains, as it cannot 'override' things in a protocol extension.

What I'd like is a class extension constrained to a protocol, such as I can override this methods and not being forced to copy-paste code inside all my controllers implementing this protocol.

Edit: as per proposed solutions

I also came up with this solution:

protocol WithView {
    var insideView: UIView! { get }
}

extension UIViewController {
    override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let viewSelf = (self as? WithView) else {
            super.touchesBegan(touches, with: event)
            return
        }
        viewSelf.insideView.touchesBegan(touches, with: event)
    }
}

class Controller1: UIViewController, WithView {

    var insideView: UIView!

    /* Functionality of Controller 1 */
}

class Controller2: UIViewController, WithView {

    var insideView: UIView!

    /* Functionality of Controller 2 */
}

It does what I want, but it feels a bit messy though, because then all the UIViewControllers would intherit this behavior, and would override its code, checking if they implement the protocol.

Body:
You could do this by creating a class and sub-classing from it:

class WithViewController: UIViewController, WithView {

    var insideView: UIView!

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        insideView.touchesBegan(touches, with: event)
    }
}

class ViewController: WithViewController {

}

The only downside to this is you have to have a default insideView and it never get's changed.


问:
Connection string hell in .NET / LINQ-SQL / ASP.NET
I have a web application that comprises the following:

A web project (with a web.config file containing a connection string - but no data access code in the web project)

A data access project that uses LINQ-SQL classes to provide entities to the web project UI (this project has a settings file and an app.config - both of which have connection strings)

When I build and deploy, there is no settings file or app.config in the Bin directory with the data access .dll, but changing the connection string in the web.config file doesn't change the database accordingly - so the connection string must be compiled into the data access dll.

What I need is one config file for my entire deployment - website, data access dlls, everything - that has one connection string which gets used. At the moment there appear to be multiple connection strings getting used or hardcoded all over the place.

How do I best resolve this mess?

Thanks for any help.

答:
I know this is old but here's how I do it (I quite like @Seba's way but I haven't tried that)

This assumes your DBML file resides in its own class library, which I've found it most convenient when sharing entities and data access across multiple websites, and other class libraries. It also assumes you've named your connection string the same in each project. I use NAnt to set this when I deploy to different environments.

I based this on the top answer above from @tvanfosson - kudos to that guy.

Create your own base class, which derives from LinqDataContext

Here's the VB code:

```<code>    Imports System.Configuration

Public Class CustomDataContextBase
    Inherits System.Data.Linq.DataContext
    Implements IDisposable

    Private Shared overrideConnectionString As String

    Public Shared ReadOnly Property CustomConnectionString As String
        Get
            If String.IsNullOrEmpty(overrideConnectionString) Then
                overrideConnectionString = ConfigurationManager.ConnectionStrings("MyAppConnectionString").ConnectionString
            End If

            Return overrideConnectionString
        End Get
    End Property

    Public Sub New()
        MyBase.New(CustomConnectionString)
    End Sub

    Public Sub New(ByVal connectionString As String)
        MyBase.New(CustomConnectionString)
    End Sub

    Public Sub New(ByVal connectionString As String, ByVal mappingSource As System.Data.Linq.Mapping.MappingSource)
        MyBase.New(CustomConnectionString, mappingSource)
    End Sub

    Public Sub New(ByVal connection As IDbConnection, ByVal mappingSource As System.Data.Linq.Mapping.MappingSource)
        MyBase.New(CustomConnectionString, mappingSource)
    End Sub

End Class
</code>```

Open your DBML file, and in the Properties, add the above class name to the Base Class property.

Note, if you placed the custom data context class in the same assembly, simply include the class name, e.g. CustomDataContext.

If they are in different assemblies, use the fully qualified name, e.g. MyCo.MyApp.Data.CustomDataContext

To ensure the Designer stuff works properly, copy your connection string into the app.config file for the class library. This will not be used apart from in the IDE.

That's it.

You'll need to name your connection string the same

What you are essentially doing is forcing the data context to ignore the connection info set in the DBML file. Using the ConfigurationManager methods will mean that it will pick up the connection string from the calling assembly.

HTH

OwnerDisplayName: TerryRoquito

ContentLicense: CC BY-SA 2.5

Body:
I know this is old but here's how I do it (I quite like @Seba's way but I haven't tried that)

This assumes your DBML file resides in its own class library, which I've found it most convenient when sharing entities and data access across multiple websites, and other class libraries. It also assumes you've named your connection string the same in each project. I use NAnt to set this when I deploy to different environments.

I based this on the top answer above from @tvanfosson - kudos to that guy.

Create your own base class, which derives from LinqDataContext

Here's the VB code:

    Imports System.Configuration

Public Class CustomDataContextBase
    Inherits System.Data.Linq.DataContext
    Implements IDisposable

    Private Shared overrideConnectionString As String

    Public Shared ReadOnly Property CustomConnectionString As String
        Get
            If String.IsNullOrEmpty(overrideConnectionString) Then
                overrideConnectionString = ConfigurationManager.ConnectionStrings("MyAppConnectionString").ConnectionString
            End If

            Return overrideConnectionString
        End Get
    End Property

    Public Sub New()
        MyBase.New(CustomConnectionString)
    End Sub

    Public Sub New(ByVal connectionString As String)
        MyBase.New(CustomConnectionString)
    End Sub

    Public Sub New(ByVal connectionString As String, ByVal mappingSource As System.Data.Linq.Mapping.MappingSource)
        MyBase.New(CustomConnectionString, mappingSource)
    End Sub

    Public Sub New(ByVal connection As IDbConnection, ByVal mappingSource As System.Data.Linq.Mapping.MappingSource)
        MyBase.New(CustomConnectionString, mappingSource)
    End Sub

End Class

Open your DBML file, and in the Properties, add the above class name to the Base Class property.

Note, if you placed the custom data context class in the same assembly, simply include the class name, e.g. CustomDataContext.

If they are in different assemblies, use the fully qualified name, e.g. MyCo.MyApp.Data.CustomDataContext

To ensure the Designer stuff works properly, copy your connection string into the app.config file for the class library. This will not be used apart from in the IDE.

That's it.

You'll need to name your connection string the same

What you are essentially doing is forcing the data context to ignore the connection info set in the DBML file. Using the ConfigurationManager methods will mean that it will pick up the connection string from the calling assembly.

HTH


问:
cannot load png files with webpack, unexpected character
Im trying to reconfigure my webpack, and now i cannot load the css files. i keep my styles in src > styles > main.css

I am getting errors such as

```<code>ERROR in ./src/images/NavIcon03.png
Module build failed: SyntaxError: /Users/myname/work/site/src/images/NavIcon03.png: Unexpected character '�' (1:0)
</code>```

Here is my webpack configuration

```<code>var webpack = require('webpack')

module.exports = {
  entry: [
    './src/main.js'
  ],
  output: {
    path: __dirname,
    publicPath: '/',
    filename: 'bundle.js'
  },
  module: {
    loaders: [{
      exclude: /node_modules/,
      loader: 'babel'
    },
        {
          test: /\.css$/, // Only .css files
          loader: 'style!css' // Run both loaders
        }]
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  devServer: {
    contentBase: './'
  }
};
</code>```

Below is the package.json

```<code>{
  "name": "website",
  "version": "0.0.1",
  "dependencies": {
    "ampersand-app": "^1.0.4",
    "ampersand-model": "^5.0.3",
    "ampersand-react-mixin": "^0.1.3",
    "ampersand-rest-collection": "^4.0.0",
    "ampersand-router": "^3.0.2",
    "asynquence": "^0.8.2",
    "autoprefixer": "^5.2.0",
    "autoprefixer-core": "^5.2.0",
    "autoprefixer-stylus": "^0.7.0",
    "axios": "^0.9.1",
    "babel": "^5.5.8",
    "babel-core": "^5.5.8",
    "babel-loader": "^5.1.4",
    "bootstrap": "^3.3.6",
    "bootstrap-webpack": "0.0.5",
    "css-loader": "^0.15.1",
    "d3": "^3.5.12",
    "file-loader": "^0.8.4",
    "font-awesome": "^4.5.0",
    "google-map-react": "^0.9.3",
    "history": "^1.17.0",
    "hjs-webpack": "^2.6.0",
    "json-loader": "^0.5.2",
    "local-links": "^1.4.0",
    "lodash": "^4.3.0",
    "lodash.assign": "^3.2.0",
    "lodash.has": "^3.2.1",
    "lodash.merge": "^3.3.1",
    "lodash.pick": "^3.1.0",
    "lodash.result": "^3.1.2",
    "milliseconds": "^1.0.3",
    "moment": "^2.11.1",
    "node-libs-browser": "^0.5.2",
    "object-assign": "^4.0.1",
    "octicons": "^2.2.0",
    "postcss-loader": "^0.5.0",
    "qs": "^3.1.0",
    "react": "^0.14.6",
    "react-avatar-editor": "^3.2.0",
    "react-bootstrap": "*",
    "react-bootstrap-table": "^1.3.3",
    "react-bootstrap-validation": "^0.1.11",
    "react-cropper": "^0.6.0",
    "react-d3-components": "^0.6.0",
    "react-dom": "^0.14.6",
    "react-dropzone": "^3.3.0",
    "react-dropzone-component": "^0.8.1",
    "react-facebook-login": "^2.0.3",
    "react-fileupload": "^1.1.3",
    "react-google-maps": "^4.7.1",
    "react-hot-loader": "^1.3.0",
    "react-input-slider": "^1.5.0",
    "react-redux": "^4.4.0",
    "react-router": "^2.0.0",
    "react-select": "^1.0.0-beta8",
    "react-star-rating-component": "^0.1.0",
    "redux": "^3.3.1",
    "redux-promise": "^0.5.1",
    "slugger": "^1.0.0",
    "standard": "^4.3.1",
    "style-loader": "^0.12.3",
    "stylus-loader": "^1.2.1",
    "surge": "^0.14.2",
    "url-loader": "^0.5.6",
    "webpack": "^1.9.11",
    "webpack-dev-server": "^1.9.0",
    "xhr": "^2.0.2",
    "yeticss": "^6.0.7"
  },
  "license": "",
  "private": true,
  "scripts": {
    "build": "webpack",
    "deploy": "surge -p public -d labelr.surge.sh",
    "start": "webpack-dev-server",
    "yolo": "git add --all && git commit -am \"$(date)\" && npm version minor && git push origin master --tags && npm run build && npm run deploy"
  },
  "devDependencies": {
    "babel-preset-react": "^6.5.0",
    "css-loader": "^0.15.6",
    "redux-devtools": "^3.1.1",
    "style-loader": "^0.12.4"
  }
}
</code>```

答:
You can use image-webpack-loader with file-loader
https://www.davidmeents.com/blog/how-to-set-up-webpack-image-loader/

1) install them

$npm install image-webpack-loader file-loader --save-dev

2) add to webpack.config.js below babel-loader your new set: image-webpack-loaders and file-loader

```<code>module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel-loader',
        query: {
          presets: ['react', 'es2015', 'stage-0'],
          plugins: ['react-html-attrs', 'transform-class-properties', 'transform-decorators-legacy'],
        }
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        loaders: [
          'file-loader?hash=sha512&digest=hex&name=[hash].[ext]',
          'image-webpack-loader?bypassOnDebug&optimizationLevel=7&interlaced=false'
        ]
      }
    ]
  },
</code>```

3) Import your .jpg file into variable (for me it is 'imgabout' variable) and add this variable into src

```<code>import React from 'react';
import imgabout from './img-about.jpg';
export default class Article extends React.Component {
render() {

    const { title } = this.props;

    return (
      <div class="col-md-6">
         <img class="img-about" src={imgabout} alt="Logo" />
      </div>
    );}}
</code>```

Body:
Im trying to reconfigure my webpack, and now i cannot load the css files. i keep my styles in src > styles > main.css

I am getting errors such as

ERROR in ./src/images/NavIcon03.png
Module build failed: SyntaxError: /Users/myname/work/site/src/images/NavIcon03.png: Unexpected character '�' (1:0)

Here is my webpack configuration

var webpack = require('webpack')

module.exports = {
  entry: [
    './src/main.js'
  ],
  output: {
    path: __dirname,
    publicPath: '/',
    filename: 'bundle.js'
  },
  module: {
    loaders: [{
      exclude: /node_modules/,
      loader: 'babel'
    },
        {
          test: /\.css$/, // Only .css files
          loader: 'style!css' // Run both loaders
        }]
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  devServer: {
    contentBase: './'
  }
};

Below is the package.json

{
  "name": "website",
  "version": "0.0.1",
  "dependencies": {
    "ampersand-app": "^1.0.4",
    "ampersand-model": "^5.0.3",
    "ampersand-react-mixin": "^0.1.3",
    "ampersand-rest-collection": "^4.0.0",
    "ampersand-router": "^3.0.2",
    "asynquence": "^0.8.2",
    "autoprefixer": "^5.2.0",
    "autoprefixer-core": "^5.2.0",
    "autoprefixer-stylus": "^0.7.0",
    "axios": "^0.9.1",
    "babel": "^5.5.8",
    "babel-core": "^5.5.8",
    "babel-loader": "^5.1.4",
    "bootstrap": "^3.3.6",
    "bootstrap-webpack": "0.0.5",
    "css-loader": "^0.15.1",
    "d3": "^3.5.12",
    "file-loader": "^0.8.4",
    "font-awesome": "^4.5.0",
    "google-map-react": "^0.9.3",
    "history": "^1.17.0",
    "hjs-webpack": "^2.6.0",
    "json-loader": "^0.5.2",
    "local-links": "^1.4.0",
    "lodash": "^4.3.0",
    "lodash.assign": "^3.2.0",
    "lodash.has": "^3.2.1",
    "lodash.merge": "^3.3.1",
    "lodash.pick": "^3.1.0",
    "lodash.result": "^3.1.2",
    "milliseconds": "^1.0.3",
    "moment": "^2.11.1",
    "node-libs-browser": "^0.5.2",
    "object-assign": "^4.0.1",
    "octicons": "^2.2.0",
    "postcss-loader": "^0.5.0",
    "qs": "^3.1.0",
    "react": "^0.14.6",
    "react-avatar-editor": "^3.2.0",
    "react-bootstrap": "*",
    "react-bootstrap-table": "^1.3.3",
    "react-bootstrap-validation": "^0.1.11",
    "react-cropper": "^0.6.0",
    "react-d3-components": "^0.6.0",
    "react-dom": "^0.14.6",
    "react-dropzone": "^3.3.0",
    "react-dropzone-component": "^0.8.1",
    "react-facebook-login": "^2.0.3",
    "react-fileupload": "^1.1.3",
    "react-google-maps": "^4.7.1",
    "react-hot-loader": "^1.3.0",
    "react-input-slider": "^1.5.0",
    "react-redux": "^4.4.0",
    "react-router": "^2.0.0",
    "react-select": "^1.0.0-beta8",
    "react-star-rating-component": "^0.1.0",
    "redux": "^3.3.1",
    "redux-promise": "^0.5.1",
    "slugger": "^1.0.0",
    "standard": "^4.3.1",
    "style-loader": "^0.12.3",
    "stylus-loader": "^1.2.1",
    "surge": "^0.14.2",
    "url-loader": "^0.5.6",
    "webpack": "^1.9.11",
    "webpack-dev-server": "^1.9.0",
    "xhr": "^2.0.2",
    "yeticss": "^6.0.7"
  },
  "license": "",
  "private": true,
  "scripts": {
    "build": "webpack",
    "deploy": "surge -p public -d labelr.surge.sh",
    "start": "webpack-dev-server",
    "yolo": "git add --all && git commit -am \"$(date)\" && npm version minor && git push origin master --tags && npm run build && npm run deploy"
  },
  "devDependencies": {
    "babel-preset-react": "^6.5.0",
    "css-loader": "^0.15.6",
    "redux-devtools": "^3.1.1",
    "style-loader": "^0.12.4"
  }
}

Body:
You can use image-webpack-loader with file-loader
https://www.davidmeents.com/blog/how-to-set-up-webpack-image-loader/

1) install them

$npm install image-webpack-loader file-loader --save-dev

2) add to webpack.config.js below babel-loader your new set: image-webpack-loaders and file-loader

module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel-loader',
        query: {
          presets: ['react', 'es2015', 'stage-0'],
          plugins: ['react-html-attrs', 'transform-class-properties', 'transform-decorators-legacy'],
        }
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        loaders: [
          'file-loader?hash=sha512&digest=hex&name=[hash].[ext]',
          'image-webpack-loader?bypassOnDebug&optimizationLevel=7&interlaced=false'
        ]
      }
    ]
  },

3) Import your .jpg file into variable (for me it is 'imgabout' variable) and add this variable into src

import React from 'react';
import imgabout from './img-about.jpg';
export default class Article extends React.Component {
render() {

    const { title } = this.props;

    return (
      <div class="col-md-6">
         <img class="img-about" src={imgabout} alt="Logo" />
      </div>
    );}}


问:
RecyclerView onClick
Has anyone using RecyclerView found a way to set an onClickListener to items in the RecyclerView?
I thought of setting a listener to each of the layouts for each item but that seems a little too much hassle
I'm sure there is a way for the RecyclerView to listen for the onClick event but I can't quite figure it out.

答:
You can easily define setOnClickListener in your ViewHolder class as follow:

public class ViewHolder extends RecyclerView.ViewHolder {
    TextView product_name;

    ViewHolder(View itemView) {
        super(itemView);
        product_name = (TextView) itemView.findViewById(R.id.product_name);
        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int itemPosition = getLayoutPosition();
                Toast.makeText(getApplicationContext(), itemPosition + ":" + String.valueOf(product_name.getText()), Toast.LENGTH_SHORT).show();
            }
        });
    }
}
```

Title: RecyclerView onClick


问:
select related to max field
I have 3 tables: laptop, pc, printer with model and price fields.

I need to get max price among all products in these all tables.

I did union to get max price & model field for each table:

```<code>SELECT model,price
FROM  (SELECT model, price
       FROM pc
       WHERE price = (SELECT MAX(price) FROM pc)
       UNION
       SELECT model, price
       FROM laptop
       WHERE price = (SELECT MAX(price) FROM laptop)
       UNION
       SELECT model, price
       FROM printer WHERE price = (SELECT MAX(price) FROM printer)
      ) AS X
</code>```

As a result of this, I received

model   |   price

```<code> 1233  | 980.0000
 1276  | 400.0000
 1288  | 400.0000
 1750  | 1200.0000
</code>```

And now I'm stuck getting only model (in this case it will be '1750') with max price.

答:
using union all and top 1

```<code>select top 1 model, price
from (
    select top 1 model, price
    from pc
    order by price desc

    union all

    select top 1 model, price
    from laptop
    order by price desc

    union all

    select top 1 model, price
    from printer
    order by price desc
  ) as u
order by price desc
</code>```

<s>I do not know if this will create a different execution plan than Gordon's answer... I'm off to go find out.</s>

This answer produces the same query execution plan as Gordon's answer in SQL Server 2012, and as Gordon's is more concise I would go with that one.

Title: select related to max field

Body:
I have 3 tables: laptop, pc, printer with model and price fields.

I need to get max price among all products in these all tables.

I did union to get max price & model field for each table:

SELECT model,price
FROM  (SELECT model, price
       FROM pc
       WHERE price = (SELECT MAX(price) FROM pc)
       UNION
       SELECT model, price
       FROM laptop
       WHERE price = (SELECT MAX(price) FROM laptop)
       UNION
       SELECT model, price
       FROM printer WHERE price = (SELECT MAX(price) FROM printer)
      ) AS X

As a result of this, I received

model   |   price

 1233  | 980.0000
 1276  | 400.0000
 1288  | 400.0000
 1750  | 1200.0000

And now I'm stuck getting only model (in this case it will be '1750') with max price.

Body:
using union all and top 1

select top 1 model, price
from (
    select top 1 model, price
    from pc
    order by price desc

    union all

    select top 1 model, price
    from laptop
    order by price desc

    union all

    select top 1 model, price
    from printer
    order by price desc
  ) as u
order by price desc

<s>I do not know if this will create a different execution plan than Gordon's answer... I'm off to go find out.</s>

This answer produces the same query execution plan as Gordon's answer in SQL Server 2012, and as Gordon's is more concise I would go with that one.


问:
Not able to read raw XML into Spring Boot app
I am working on a Spring Boot project and i have a requirement where in I want to read a raw xml into the application and parse that xml using parser to convert into domain object. The xml that I have is a plain xml without any namespaces or schemas. below is my xml format

```<code><?xml version ="1.0" ?>
 <applications>
 <state>xyz</state>
 <app name="PROJECTx">
 <catids>
 <catid>1</catid>
 <catid>2</catid>
 </catids>
 <cys>
 <mxvalue>1000</mxvalue>
 <mnvalue>0.01</mnvalue>
 <activity>ACTIVE</activity>
 </cys>
 </app>
 </applications>
</code>```

I am planning a normal DOM Parser API in my boot app to read this xml and convert the values into domain objects.

```<code>@SpringBootApplication
@ComponentScan("com.test")
@ImportResource("applications.xml")
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
</code>```

I tried using the @ImportResource annotation to read this xml but I get the error below on spring boot start up.

```<code> Caused by: org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'applications'.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:203) ~[na:1.8.0_71]
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134) ~[na:1.8.0_71]
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:396) ~[na:1.8.0_71]
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:327) ~[na:1.8.0_71]
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:284) ~[na:1.8.0_71]
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(XMLSchemaValidator.java:1900) ~[na:1.8.0_71]
</code>```

Looks like the @ImportResource("applications.xml") is expecting some namespace and schemas.

Can someone help me with this and let me know is this is possible in SpringBoot application and how can I do it. Thanks in advance.

答: You should use JAXB annotations on your domain object.  Then in a spring boot @Configuration class you could create a JAXBContext and unmarshall the xml into your domain object.  A simple jaxb tutorial can be seen at http://www.mkyong.com/java/jaxb-hello-world-example/.  </p>

Body:
I am working on a Spring Boot project and i have a requirement where in I want to read a raw xml into the application and parse that xml using parser to convert into domain object. The xml that I have is a plain xml without any namespaces or schemas. below is my xml format

<?xml version ="1.0" ?>
 <applications>
 <state>xyz</state>
 <app name="PROJECTx">
 <catids>
 <catid>1</catid>
 <catid>2</catid>
 </catids>
 <cys>
 <mxvalue>1000</mxvalue>
 <mnvalue>0.01</mnvalue>
 <activity>ACTIVE</activity>
 </cys>
 </app>
 </applications>

I am planning a normal DOM Parser API in my boot app to read this xml and convert the values into domain objects.

@SpringBootApplication
@ComponentScan("com.test")
@ImportResource("applications.xml")
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

I tried using the @ImportResource annotation to read this xml but I get the error below on spring boot start up.

 Caused by: org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'applications'.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:203) ~[na:1.8.0_71]
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134) ~[na:1.8.0_71]
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:396) ~[na:1.8.0_71]
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:327) ~[na:1.8.0_71]
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:284) ~[na:1.8.0_71]
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(XMLSchemaValidator.java:1900) ~[na:1.8.0_71]

Looks like the @ImportResource("applications.xml") is expecting some namespace and schemas.

Can someone help me with this and let me know is this is possible in SpringBoot application and how can I do it. Thanks in advance.


问:
Is there any replacement for push notification in Ionic 2?
For some reasons I can not use push notification but I had to have such this ability in my application that send a notification from back-end (Oracle Apex) to special available user's application. One possible way I think is using SMS but I don't know is there any better way?

答:
I think the best alternative to push notifications is local notifications and it is much more simpler to add to any application.

As Josh Morony says:
There are two main types of notifications when it comes to mobile applications: local notifications and push notifications. It can be a little confusing to understand the difference, but essentially:
Local notifications can only be triggered by events on the user’s device
Push notifications can be triggered by events outside of the user’s device

this is docs:
https://ionicframework.com/docs/v2/native/local-notifications/

this is tutorial about how to use it with more explanation.
https://www.joshmorony.com/getting-familiar-with-local-notifications-in-ionic-2/


问:
How to calculate precision and recall in Keras
I am building a multi-class classifier with Keras 2.02 (with Tensorflow backend)，and I do not know how to calculate precision and recall in Keras. Please help me.</p>

答:
As of Keras 2.0, precision and recall were removed from the master branch. You will have to implement them yourself. Follow this guide to create custom metrics : Here.

Precision and recall equation can be found Here

Or reuse the code from keras before it was removed Here.

There metrics were remove because they were batch-wise so the value may or may not be correct.


问:
Regex for ranges of values in comma-separated list
I want to write a regex that match a list of numeric values, given in a comma-separated list, ranges allowed. Empty is not allowed.

Something like: 1-10,20-56,8,7

So far I have (([0-9]+)|([0-9]+-[0-9]+),)*[0-9]+. This does most of the job, except it misses the case of one range only (eg: 1-10 would not validate).

The checking for each range can be omitted (eg: 20-10 can be allowed as a valid range).

Any help would be appreciated.

答:
What you're after is one (number or range) optionally followed by zero or more:  comma plus (number or range):

```<code>(?:\d+(?:-\d+)?)(?:,(?:\d+(-\d+)?))*
</code>```

This uses the \d shortcut for [0-9] and the (?: ... ) non-capturing parentheses construct.

This regex doesn't allow any spaces to be included in the list.  To allow those, insert the "optional space" \s* between each term:

```<code>\s*(?:\d+(\s*-\s*\d+)?)\s*(?:,\s*(?:\d+(\s*-\s*\d+)?)\s*)*
</code>```

Body:
What you're after is one (number or range) optionally followed by zero or more:  comma plus (number or range):

(?:\d+(?:-\d+)?)(?:,(?:\d+(-\d+)?))*

This uses the \d shortcut for [0-9] and the (?: ... ) non-capturing parentheses construct.

This regex doesn't allow any spaces to be included in the list.  To allow those, insert the "optional space" \s* between each term:

\s*(?:\d+(\s*-\s*\d+)?)\s*(?:,\s*(?:\d+(\s*-\s*\d+)?)\s*)*


问:
FileProvider - Open File from Download Directory
I can't open any file from Download Folder.

I can download a file and save in Download Folder with this:

```<code>   DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
    request.setDescription(descricao);
    request.setTitle(titulo);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        request.allowScanningByMediaScanner();
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    }
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, nome);

    enq = downloadManager.enqueue(request);
</code>```

After this, my file is correct saved at Directory Folder: Android >> Internal Shared Storage >> Download.
***This path I see manually opening the device's hd in ubuntu. As the image shows the path.
Android HD by ubuntu folder - see the path

And I try open this file with this:

```<code>downloadManager = (DownloadManager)getContext().getSystemService(DOWNLOAD_SERVICE);
        BroadcastReceiver receiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if(DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                    long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                    DownloadManager.Query query = new DownloadManager.Query();
                    query.setFilterById(enq);
                    Cursor c = downloadManager.query(query);
                    if(c.moveToFirst()) {
                        int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
                        if(DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
                            String uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));

                            if (uriString.substring(0, 7).matches("file://")) {
                                uriString =  uriString.substring(7);
                            }

                            File file = new File(uriString);

                            Uri uriFile = FileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID + ".fileprovider", file);
                            String mimetype = "application/pdf";
                            Intent myIntent = new Intent(Intent.ACTION_VIEW);
                            myIntent.setDataAndType(uriFile, mimetype);

                            Intent intentChooser = Intent.createChooser(myIntent, "Choose Pdf Application");
                            startActivity(intentChooser);
                        }
                    }
                }
            }
        };

        getContext().registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
</code>```

I declare my file provider in manifest with this:

```<code>    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>
</code>```

and with this:

```<code><?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="Download" path="Download/"/>
</paths>
</code>```

But when I click the button to download I receive this message: "This file coud be not accessed. Check the location or the network and try again."

Resuming:

1 - The file is downloaded and saved at the directory folder.

2 - The intent is started, but the file is not openned.

3 - Debug mode give me this at "new File(urlString)": "urlString=/storage/emulated/0/Download/name.pdf"

4 - At "FileProvider.getUriFromFile..." debug mode have this:

"uriFile = content://com.example.android.parlamentaresapp.fileprovider/Download/name.pdf"

Thank you.

答: Call addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) on the Intent that you use with startActivity() and the FileProvider Uri. Without that, the activity has no rights to access your content.

Body:
I can't open any file from Download Folder.

I can download a file and save in Download Folder with this:

   DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
    request.setDescription(descricao);
    request.setTitle(titulo);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        request.allowScanningByMediaScanner();
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    }
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, nome);

    enq = downloadManager.enqueue(request);

After this, my file is correct saved at Directory Folder: Android >> Internal Shared Storage >> Download.
***This path I see manually opening the device's hd in ubuntu. As the image shows the path.
Android HD by ubuntu folder - see the path

And I try open this file with this:

downloadManager = (DownloadManager)getContext().getSystemService(DOWNLOAD_SERVICE);
        BroadcastReceiver receiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if(DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                    long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                    DownloadManager.Query query = new DownloadManager.Query();
                    query.setFilterById(enq);
                    Cursor c = downloadManager.query(query);
                    if(c.moveToFirst()) {
                        int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
                        if(DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
                            String uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));

                            if (uriString.substring(0, 7).matches("file://")) {
                                uriString =  uriString.substring(7);
                            }

                            File file = new File(uriString);

                            Uri uriFile = FileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID + ".fileprovider", file);
                            String mimetype = "application/pdf";
                            Intent myIntent = new Intent(Intent.ACTION_VIEW);
                            myIntent.setDataAndType(uriFile, mimetype);

                            Intent intentChooser = Intent.createChooser(myIntent, "Choose Pdf Application");
                            startActivity(intentChooser);
                        }
                    }
                }
            }
        };

        getContext().registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

I declare my file provider in manifest with this:

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>

and with this:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="Download" path="Download/"/>
</paths>

But when I click the button to download I receive this message: "This file coud be not accessed. Check the location or the network and try again."

Resuming:

1 - The file is downloaded and saved at the directory folder.

2 - The intent is started, but the file is not openned.

3 - Debug mode give me this at "new File(urlString)": "urlString=/storage/emulated/0/Download/name.pdf"

4 - At "FileProvider.getUriFromFile..." debug mode have this:

"uriFile = content://com.example.android.parlamentaresapp.fileprovider/Download/name.pdf"

Thank you.


问:
How to make rows on bootstrap with unknown number of columns?
I have dynamic generated columns that have variable width according to the user screen size:

How can I split these divs in rows?

答:
Bootstrap row has a length of twelve, this means everything above twelve will be placed under the row. Unfortunately this is not looking nice. I do not know how you make the those divs. Assuming you pass an array to your front-end you can use javascript based on how many divs.

there is probaly a better way. I am new to programming, but would think of something like this:

Note that you need to change yourArray to the variable name of your array.

```<code><div id="allRows">
<script>
    var mqxs = window.matchMedia( "(max-width: 767px)" );
    var mqsm = window.matchMedia( "(min-width: 768px)" );
    var mqmd = window.matchMedia( "(min-width: 992px)" );
    var mqlg = window.matchMedia( "(min-width: 1200px)" );
    var html = '<div class="row">';
    if (mqxs.matches){
        var max = 2;
        var count = 1;
        for(var i=0; i < yourArray.length; i++){
             if (var > max){
                 html += "</div>";
                 html+= "<div class='row'>";
                 count = 1;
             }
             html+= "<div class= 'col-xs-6>yourArray[i]'</div>";
             count += 1;
        }
    }else if (mqsm.matches){
        var max = 3;
        var count = 1;
        for(var i=0; i < yourArray.length; i++){
             if (var > max){
                 html += "</div>";
                 html+= "<div class='row'>";
                 count = 1;
             }
             html+= "<div class= 'col-sm-4'>yourArray[i]'</div>";
             count += 1;
        }
    }}else if (mqmd.matches){
        var max = 4;
        var count = 1;
        for(var i=0; i < yourArray.length; i++){
             if (var > max){
                 html += "</div>";
                 html+= "<div class='row'>";
                 count = 1;
             }
             html+= "<div class='col-md-3'>yourArray[i]'</div>";
             count += 1;
        }
    }else (mqlg.matches){
        var max = 6;
        var count = 1;
        for(var i=0; i < yourArray.length; i++){
             if (var > max){
                 html += "</div>";
                 html+= "<div class='row'>";
                 count = 1;
             }
             html+= "<div class= 'col-lg-2>yourArray[i]'</div>";
             count += 1;
        }
    }

    html += </div>
    document.getElementById("allRows").innerHTML = html;
</script>
</div>
</code>```

Body:
Bootstrap row has a length of twelve, this means everything above twelve will be placed under the row. Unfortunately this is not looking nice. I do not know how you make the those divs. Assuming you pass an array to your front-end you can use javascript based on how many divs.

there is probaly a better way. I am new to programming, but would think of something like this:

Note that you need to change yourArray to the variable name of your array.

<div id="allRows">
<script>
    var mqxs = window.matchMedia( "(max-width: 767px)" );
    var mqsm = window.matchMedia( "(min-width: 768px)" );
    var mqmd = window.matchMedia( "(min-width: 992px)" );
    var mqlg = window.matchMedia( "(min-width: 1200px)" );
    var html = '<div class="row">';
    if (mqxs.matches){
        var max = 2;
        var count = 1;
        for(var i=0; i < yourArray.length; i++){
             if (var > max){
                 html += "</div>";
                 html+= "<div class='row'>";
                 count = 1;
             }
             html+= "<div class= 'col-xs-6>yourArray[i]'</div>";
             count += 1;
        }
    }else if (mqsm.matches){
        var max = 3;
        var count = 1;
        for(var i=0; i < yourArray.length; i++){
             if (var > max){
                 html += "</div>";
                 html+= "<div class='row'>";
                 count = 1;
             }
             html+= "<div class= 'col-sm-4'>yourArray[i]'</div>";
             count += 1;
        }
    }}else if (mqmd.matches){
        var max = 4;
        var count = 1;
        for(var i=0; i < yourArray.length; i++){
             if (var > max){
                 html += "</div>";
                 html+= "<div class='row'>";
                 count = 1;
             }
             html+= "<div class='col-md-3'>yourArray[i]'</div>";
             count += 1;
        }
    }else (mqlg.matches){
        var max = 6;
        var count = 1;
        for(var i=0; i < yourArray.length; i++){
             if (var > max){
                 html += "</div>";
                 html+= "<div class='row'>";
                 count = 1;
             }
             html+= "<div class= 'col-lg-2>yourArray[i]'</div>";
             count += 1;
        }
    }

    html += </div>
    document.getElementById("allRows").innerHTML = html;
</script>
</div>


问:
Why when i'm setting big size when cloning new objects some of them are out of the terrain area?
```<code>using System;
using UnityEngine;
using Random = UnityEngine.Random;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

public class CloneObjects : MonoBehaviour {

    public GameObject objectToClone;
    public int objectsStartingHeight = 20;
    [HideInInspector]
    public GameObject[] objects;

    // for tracking properties change
    private Vector3 _extents;
    private int _objectCount;
    private float _objectSize;

    /// <summary>
    ///     How far to place spheres randomly.
    /// </summary>
    public Vector3 Extents;

    /// <summary>
    ///     How many spheres wanted.
    /// </summary>
    public int ObjectCount;
    public float ObjectSize;

    // Use this for initialization
    void Start () {

        Clone();
        objects = GameObject.FindGameObjectsWithTag("objectToClone");
    }

    private void OnValidate()
    {
        // prevent wrong values to be entered
        Extents = new Vector3(Mathf.Max(0.0f, Extents.x), Mathf.Max(0.0f, Extents.y), Mathf.Max(0.0f, Extents.z));
        ObjectCount = Mathf.Max(0, ObjectCount);
        ObjectSize = Mathf.Max(0.0f, ObjectSize);
    }

    private void Reset()
    {
        Extents = new Vector3(250.0f, 20.0f, 250.0f);
        ObjectCount = 100;
        ObjectSize = 20.0f;
    }

    // Update is called once per frame
    void Update () {

    }

    private void Clone()
    {
        if (Extents == _extents && ObjectCount == _objectCount && Mathf.Approximately(ObjectSize, _objectSize))
            return;

        // cleanup
        var ObjectToDestroy = GameObject.FindGameObjectsWithTag("ClonedObject");
        foreach (var t in ObjectToDestroy)
        {
            if (Application.isEditor)
            {
                DestroyImmediate(t);
            }
            else
            {
                Destroy(t);
            }
        }

        var withTag = GameObject.FindWithTag("Terrain");
        if (withTag == null)
            throw new InvalidOperationException("Terrain not found");

        for (var i = 0; i < ObjectCount; i++)
        {
            var o = Instantiate(objectToClone);
            o.tag = "ClonedObject";
            o.transform.SetParent(base.gameObject.transform);
            o.transform.localScale = new Vector3(ObjectSize, ObjectSize, ObjectSize);

            // get random position
            var x = Random.Range(-Extents.x, Extents.x);
            var y = Extents.y; // sphere altitude relative to terrain below
            var z = Random.Range(-Extents.z, Extents.z);

            // now send a ray down terrain to adjust Y according terrain below
            var height = 10000.0f; // should be higher than highest terrain altitude
            var origin = new Vector3(x, height, z);
            var ray = new Ray(origin, Vector3.down);
            RaycastHit hit;
            var maxDistance = 20000.0f;
            var nameToLayer = LayerMask.NameToLayer("Terrain");
            var layerMask = 1 << nameToLayer;
            if (Physics.Raycast(ray, out hit, maxDistance, layerMask))
            {
                var distance = hit.distance;
                y = height - distance + y; // adjust
            }
            else
            {
                Debug.LogWarning("Terrain not hit, using default height !");
            }

            //o.transform.Rotate(0.0f,randomNumbers[i],0.0f);
            // place !
            o.transform.position = new Vector3(x, y+objectsStartingHeight, z);
        }

        _extents = Extents;
        _objectCount = ObjectCount;
        _objectSize = ObjectSize;
    }
}
</code>```

If i set to clone 10 objects and the size is 20 it's fine.
But if i change the size to 50 and there is a new object spawn near the terrain edge the object will be half on the terrain half out of the terrain area.

The terrain position is X = -250 Y = 0 Z = -250
The terrain size is Width = 500 Length = 500 Height = 600

How can i fix it ?

In the screenshot the marked/clicked object is half in the terrain half out.

This is a screenshot of the object the script is attached to and the settings on the inspector:

Update

What i tried is to change this 3 lines:

```<code>var x = Random.Range(-Extents.x, Extents.x);
var y = Extents.y;
var z = Random.Range(-Extents.z, Extents.z);
</code>```

To

```<code>var x = Random.Range(-Extents.x + (float)(0.5 * o.transform.localScale.x), Extents.x - (float)(0.5 * o.transform.localScale.x));
var y = (float)0.5 * Extents.y;
var z = Random.Range(-Extents.z + (float)(0.5 * o.transform.localScale.z), Extents.z - (float)(0.5 * o.transform.localScale.z));
</code>```

But then i'm getting in some places two cubes each inside the other one.
Also there is no space between the cubes and i need to have spaces and maybe even to add some variable to be able to control the space between the cubes the position is random but to decide some minimum space limit.

答:
Raycasts are very thin and are cast from the middle of each cube. If you want your cubes to fit inside the terrain, you need to reduce your extents by the half the width of the cube. Let me know if it works.

You don't divide by 2. Maybe I misinterpreted your code. The part where you get random position. You need to change this:
var x = Random.Range(-Extents.x, Extents.x);
to something that looks like this:
var x = Random.Range(-Extents.x + (0.5*currentCubeWidth) , Extents.x - (0.5*currentCubeWidth);

The above is pseudocode, I am not sure where you are defining the cube size in your game. They all appear to be different sizes. This should also be done for x, y and z.

Body:
using System;
using UnityEngine;
using Random = UnityEngine.Random;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

public class CloneObjects : MonoBehaviour {

    public GameObject objectToClone;
    public int objectsStartingHeight = 20;
    [HideInInspector]
    public GameObject[] objects;

    // for tracking properties change
    private Vector3 _extents;
    private int _objectCount;
    private float _objectSize;

    ///
    ///     How far to place spheres randomly.
    ///
    public Vector3 Extents;

    ///
    ///     How many spheres wanted.
    ///
    public int ObjectCount;
    public float ObjectSize;

    // Use this for initialization
    void Start () {

        Clone();
        objects = GameObject.FindGameObjectsWithTag("objectToClone");
    }

    private void OnValidate()
    {
        // prevent wrong values to be entered
        Extents = new Vector3(Mathf.Max(0.0f, Extents.x), Mathf.Max(0.0f, Extents.y), Mathf.Max(0.0f, Extents.z));
        ObjectCount = Mathf.Max(0, ObjectCount);
        ObjectSize = Mathf.Max(0.0f, ObjectSize);
    }

    private void Reset()
    {
        Extents = new Vector3(250.0f, 20.0f, 250.0f);
        ObjectCount = 100;
        ObjectSize = 20.0f;
    }

    // Update is called once per frame
    void Update () {

    }

    private void Clone()
    {
        if (Extents == _extents && ObjectCount == _objectCount && Mathf.Approximately(ObjectSize, _objectSize))
            return;

        // cleanup
        var ObjectToDestroy = GameObject.FindGameObjectsWithTag("ClonedObject");
        foreach (var t in ObjectToDestroy)
        {
            if (Application.isEditor)
            {
                DestroyImmediate(t);
            }
            else
            {
                Destroy(t);
            }
        }

        var withTag = GameObject.FindWithTag("Terrain");
        if (withTag == null)
            throw new InvalidOperationException("Terrain not found");

        for (var i = 0; i < ObjectCount; i++)
        {
            var o = Instantiate(objectToClone);
            o.tag = "ClonedObject";
            o.transform.SetParent(base.gameObject.transform);
            o.transform.localScale = new Vector3(ObjectSize, ObjectSize, ObjectSize);

            // get random position
            var x = Random.Range(-Extents.x, Extents.x);
            var y = Extents.y; // sphere altitude relative to terrain below
            var z = Random.Range(-Extents.z, Extents.z);

            // now send a ray down terrain to adjust Y according terrain below
            var height = 10000.0f; // should be higher than highest terrain altitude
            var origin = new Vector3(x, height, z);
            var ray = new Ray(origin, Vector3.down);
            RaycastHit hit;
            var maxDistance = 20000.0f;
            var nameToLayer = LayerMask.NameToLayer("Terrain");
            var layerMask = 1 << nameToLayer;
            if (Physics.Raycast(ray, out hit, maxDistance, layerMask))
            {
                var distance = hit.distance;
                y = height - distance + y; // adjust
            }
            else
            {
                Debug.LogWarning("Terrain not hit, using default height !");
            }

            //o.transform.Rotate(0.0f,randomNumbers[i],0.0f);
            // place !
            o.transform.position = new Vector3(x, y+objectsStartingHeight, z);
        }

        _extents = Extents;
        _objectCount = ObjectCount;
        _objectSize = ObjectSize;
    }
}

If i set to clone 10 objects and the size is 20 it's fine.
But if i change the size to 50 and there is a new object spawn near the terrain edge the object will be half on the terrain half out of the terrain area.

The terrain position is X = -250 Y = 0 Z = -250
The terrain size is Width = 500 Length = 500 Height = 600

How can i fix it ?

In the screenshot the marked/clicked object is half in the terrain half out.

This is a screenshot of the object the script is attached to and the settings on the inspector:

Update

What i tried is to change this 3 lines:

var x = Random.Range(-Extents.x, Extents.x);
var y = Extents.y;
var z = Random.Range(-Extents.z, Extents.z);

To

var x = Random.Range(-Extents.x + (float)(0.5 * o.transform.localScale.x), Extents.x - (float)(0.5 * o.transform.localScale.x));
var y = (float)0.5 * Extents.y;
var z = Random.Range(-Extents.z + (float)(0.5 * o.transform.localScale.z), Extents.z - (float)(0.5 * o.transform.localScale.z));

But then i'm getting in some places two cubes each inside the other one.
Also there is no space between the cubes and i need to have spaces and maybe even to add some variable to be able to control the space between the cubes the position is random but to decide some minimum space limit.


问:
How to debug stored procedures in Sybase ASE?
Is there a good tool from either Sybase or elsewhere that will enable me to debug stored procedures in Sybase ASE? I need to be able to set breakpoints & watchpoints.

Previously, in Sybase ASA (not ASE), I used Sybase Central to do this. There is a plugin for ASE, but I doubt it will let me debug procedures.

答:
Aqua Data Studio from Aqua Fold has SQL debuggers for Sybase ASE and others (Oracle, DB2 LUW, and SQL Server).

Also, Sybase ASE ships with a command line sp debugger called sqldbgr.

OwnerDisplayName: Mike Thompson


问:
matching the regular expression with the whole string
im kinda strumped in a situation where i need to match a whole string with a regular expression rather than finding if the pattern exists in the string.

suppose if i have a regular expression

```<code>/\\^^\\w+\\$^/
</code>```

what i want is that the code will run through various strings , compare the strings with the regular expression and perform some task if the strings start and end with a ^.

Examples

^hello world^ is a match

my ^hello world^ should not be a match

the php function preg_match matches both of the results

any clues ???

答:
Actually, ^\^\w+\^$ will not match "^hello world^" because you have two words there; the regex is only looking for a single word enclosed by "^"s.

What you are looking for is: ^\^.*\^$
This will match "^^", "^hello world^", "^a very long string of characters^", etc. while not matching "hello ^world^".

Body:
im kinda strumped in a situation where i need to match a whole string with a regular expression rather than finding if the pattern exists in the string.

suppose if i have a regular expression

/\\^^\\w+\\$^/

what i want is that the code will run through various strings , compare the strings with the regular expression and perform some task if the strings start and end with a ^.

Examples

^hello world^ is a match

my ^hello world^ should not be a match

the php function preg_match matches both of the results

any clues ???


问:
How to check if variable is defined?
I building E-shop and there will be diferent products categories, so each category product can have diferent columns. For example one product have color, other product from other category don't have color.
I want to do when I adding new product for which don't need use color column I want that in show page, this line below will be not displaying (Color:).

```<code><p>
  <strong>Color:</strong>
  <%= @product.color %>
</p>
</code>```

Product show.html.erb

```<code>  <p>
    <strong>Name:</strong>
    <%= @product.name %>
  </p>
  <br>
  <p>
    <strong>Description:</strong>
    <%= @product.description %>
  </p>
  <br>
  <p>
    <strong>Year of manufacture:</strong>
    <%= @product.year_of_manufacture %>
  </p>
  <br>
  <p>
   <strong>Color:</strong>
   <%= @product.color %>
 </p>
</code>```

Product form.html.erb

```<code>  <div class="form-group">
    <%= f.label :name %><br>
    <%= f.text_field :name, class: "form-control" %>
  </div>
  <br>
  <div class="form-group">
    <%= f.label :description %>
    <%= f.text_area :description, class: "form-control" %>
  </div>
  <br>
  <div class="form-group">
  <%= f.label :year_of_manufacture %>
  <%= f.text_field :year_of_manufacture, class: "form-control" %>
  </div>
  <br>
  <div class="form-group">
  <%= f.label :color %>
  <%= f.text_field :color, class: "form-control" %>
  </div>
</code>```

Thank you for help.

答:
To display that section only if the color attribute of your Product record is defined as a non-blank, non-nil value:

```<code><% if @product.color? %>
  <p>
    <strong>Color:</strong>
    <%= @product.color %>
  </p>
<% end %>
</code>```

This is equivalent to @product.color.present?. ActiveRecord maps database fields to properties automatically, so if you have a color column for that model the method will exist.

Title: How to check if variable is defined?

Body:
I building E-shop and there will be diferent products categories, so each category product can have diferent columns. For example one product have color, other product from other category don't have color.
I want to do when I adding new product for which don't need use color column I want that in show page, this line below will be not displaying (Color:).

  Color:
  <%= @product.color %>

Product show.html.erb

    Name:
    <%= @product.name %>

    Description:
    <%= @product.description %>

    Year of manufacture:
    <%= @product.year_of_manufacture %>

   Color:
   <%= @product.color %>

Product form.html.erb

    <%= f.label :name %>

    <%= f.text_field :name, class: "form-control" %>

    <%= f.label :description %>
    <%= f.text_area :description, class: "form-control" %>

  <%= f.label :year_of_manufacture %>
  <%= f.text_field :year_of_manufacture, class: "form-control" %>

  <%= f.label :color %>
  <%= f.text_field :color, class: "form-control" %>

Thank you for help.

Body:
To display that section only if the color attribute of your Product record is defined as a non-blank, non-nil value:

<% if @product.color? %>
  <p>
    <strong>Color:</strong>
    <%= @product.color %>
  </p>
<% end %>

This is equivalent to @product.color.present?. ActiveRecord maps database fields to properties automatically, so if you have a color column for that model the method will exist.