问:
Getting weird errors on stack manipulation
As part of some simulations that I am running using a tool called JIST/SWANS I am getting some weird errors. This simulator has been written for Java 1.4 and I am attempting to port it to 1.5.

What I am trying to do is to compile the original code with the 1.5 SDK. The problem is that the simulator uses bcel to rewrite the bytecode so that JVM could be used for simulations. When I compile the code under the new SDK, I get the error given below. Can someone point me in the right direction to fix this? I know the byte code produced by 1.4 and 1.5 are somewhat different but I have no clue where to start looking from.

```<code>java.lang.ArrayIndexOutOfBoundsException: -1
    at java.util.ArrayList.remove(ArrayList.java:390)
    at org.apache.bcel.verifier.structurals.OperandStack.pop(OperandStack.java:135)
    at org.apache.bcel.verifier.structurals.ExecutionVisitor.visitPUTFIELD(ExecutionVisitor.java:1048)
    at org.apache.bcel.generic.PUTFIELD.accept(PUTFIELD.java:78)
    at jist.runtime.RewriterFlow.execute(RewriterFlow.java:235)
    at jist.runtime.RewriterFlow.doFlow(RewriterFlow.java:187)
    at jist.runtime.RewriterTraversalContinuableMethods.doMethod(Rewriter.java:3059)
    at jist.runtime.ClassTraversal.processMethodGen(ClassTraversal.java:136)
    at jist.runtime.ClassTraversal.processClassGen(ClassTraversal.java:96)
    at jist.runtime.ClassTraversal.processClass(ClassTraversal.java:63)
    at jist.runtime.Rewriter.rewriteClass(Rewriter.java:621)
    at jist.runtime.Rewriter.findClass(Rewriter.java:410)
    at jist.runtime.Rewriter.loadClass(Rewriter.java:367)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2427)
    at java.lang.Class.getDeclaredMethod(Class.java:1935)
    at jist.swans.app.AppJava.findMain(AppJava.java:86)
    at jist.swans.app.AppJava.<init>(AppJava.java:61)
    at driver.aodvtest.createNode(aodvtest.java:192)
    at driver.aodvtest.createSim(aodvtest.java:235)
    at driver.aodvtest.main(aodvtest.java:277)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at jist.runtime.Bootstrap$JavaMain.startSimulation(Bootstrap.java:163)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at jist.runtime.Controller.processEvent(Controller.java:650)
    at jist.runtime.Controller.eventLoop(Controller.java:428)
    at jist.runtime.Controller.run(Controller.java:457)
    at java.lang.Thread.run(Thread.java:619)

java.lang.NullPointerException
    at driver.aodvtest.createNode(aodvtest.java:198)
    at driver.aodvtest.createSim(aodvtest.java:235)
    at driver.aodvtest.main(aodvtest.java:277)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at jist.runtime.Bootstrap$JavaMain.startSimulation(Bootstrap.java:163)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at jist.runtime.Controller.processEvent(Controller.java:650)
    at jist.runtime.Controller.eventLoop(Controller.java:428)
    at jist.runtime.Controller.run(Controller.java:457)
    at java.lang.Thread.run(Thread.java:619)
</code>```

UPDATE:
I narrowed down to this line from where the exception is being thrown:

```<code>private Method findMain(Class<?> c) throws NoSuchMethodException {
  return c.getDeclaredMethod("main", new Class<?>[] { String[].class });
}
</code>```

There is a main method in the class which is being passed to this function so I have no clue why it is returning a null.

UPDATE 2:

There is one function:

```<code>createNode(..., ..., ..., ..., MyClient.class, ..., ...)
</code>```

which passes the MyClient.class to a function that makes use of this in the findMain method posted above. Using the debugger, I can see that declaredMethods is null so obviously the getDeclaredMethods call is dying. The MyClient class is defined as an inner static class in the following way:

```<code>public static class MyClient {
   public static void main(String[] args[]) {

      ...

   }
}
</code>```

I am not sure if this has anything to do with declaredMethods being null so I tried extracting the class into a separate class but with no luck.

UPDATE 3:

Ok narrowed it down. The following throws an exception even in the main class:

```<code>System.out.println(MyClient.class.getDeclaredMethods());
</code>```

答:
Perhaps downloading BCEL's source code and putting a breakpoint at line 135 of this method

```<code>org.apache.bcel.verifier.structurals.OperandStack.pop(OperandStack.java:135)
</code>```

will tell you more. Obviously, there's a problem somewhere with array index manipulation.

From what I see, BCEL is no more in development, so if a bug exists, it might be difficult to have it fixed if you report it.

ASM is a more modern bytecode generation library that's under development. You probably already know this; but if you have that simulator's source code and it isn't using BCEL too much, you might be able to rewrite it using ASM. Of course, stuff like this is usually overkill.

Body:
As part of some simulations that I am running using a tool called JIST/SWANS I am getting some weird errors. This simulator has been written for Java 1.4 and I am attempting to port it to 1.5.

What I am trying to do is to compile the original code with the 1.5 SDK. The problem is that the simulator uses bcel to rewrite the bytecode so that JVM could be used for simulations. When I compile the code under the new SDK, I get the error given below. Can someone point me in the right direction to fix this? I know the byte code produced by 1.4 and 1.5 are somewhat different but I have no clue where to start looking from.

java.lang.ArrayIndexOutOfBoundsException: -1
    at java.util.ArrayList.remove(ArrayList.java:390)
    at org.apache.bcel.verifier.structurals.OperandStack.pop(OperandStack.java:135)
    at org.apache.bcel.verifier.structurals.ExecutionVisitor.visitPUTFIELD(ExecutionVisitor.java:1048)
    at org.apache.bcel.generic.PUTFIELD.accept(PUTFIELD.java:78)
    at jist.runtime.RewriterFlow.execute(RewriterFlow.java:235)
    at jist.runtime.RewriterFlow.doFlow(RewriterFlow.java:187)
    at jist.runtime.RewriterTraversalContinuableMethods.doMethod(Rewriter.java:3059)
    at jist.runtime.ClassTraversal.processMethodGen(ClassTraversal.java:136)
    at jist.runtime.ClassTraversal.processClassGen(ClassTraversal.java:96)
    at jist.runtime.ClassTraversal.processClass(ClassTraversal.java:63)
    at jist.runtime.Rewriter.rewriteClass(Rewriter.java:621)
    at jist.runtime.Rewriter.findClass(Rewriter.java:410)
    at jist.runtime.Rewriter.loadClass(Rewriter.java:367)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2427)
    at java.lang.Class.getDeclaredMethod(Class.java:1935)
    at jist.swans.app.AppJava.findMain(AppJava.java:86)
    at jist.swans.app.AppJava.<init>(AppJava.java:61)
    at driver.aodvtest.createNode(aodvtest.java:192)
    at driver.aodvtest.createSim(aodvtest.java:235)
    at driver.aodvtest.main(aodvtest.java:277)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at jist.runtime.Bootstrap$JavaMain.startSimulation(Bootstrap.java:163)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at jist.runtime.Controller.processEvent(Controller.java:650)
    at jist.runtime.Controller.eventLoop(Controller.java:428)
    at jist.runtime.Controller.run(Controller.java:457)
    at java.lang.Thread.run(Thread.java:619)

java.lang.NullPointerException
    at driver.aodvtest.createNode(aodvtest.java:198)
    at driver.aodvtest.createSim(aodvtest.java:235)
    at driver.aodvtest.main(aodvtest.java:277)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at jist.runtime.Bootstrap$JavaMain.startSimulation(Bootstrap.java:163)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at jist.runtime.Controller.processEvent(Controller.java:650)
    at jist.runtime.Controller.eventLoop(Controller.java:428)
    at jist.runtime.Controller.run(Controller.java:457)
    at java.lang.Thread.run(Thread.java:619)

UPDATE:
I narrowed down to this line from where the exception is being thrown:

private Method findMain(Class<?> c) throws NoSuchMethodException {
  return c.getDeclaredMethod("main", new Class<?>[] { String[].class });
}

There is a main method in the class which is being passed to this function so I have no clue why it is returning a null.

UPDATE 2:

There is one function:

createNode(..., ..., ..., ..., MyClient.class, ..., ...)

which passes the MyClient.class to a function that makes use of this in the findMain method posted above. Using the debugger, I can see that declaredMethods is null so obviously the getDeclaredMethods call is dying. The MyClient class is defined as an inner static class in the following way:

public static class MyClient {
   public static void main(String[] args[]) {

      ...

   }
}

I am not sure if this has anything to do with declaredMethods being null so I tried extracting the class into a separate class but with no luck.

UPDATE 3:

Ok narrowed it down. The following throws an exception even in the main class:

System.out.println(MyClient.class.getDeclaredMethods());

Body:
Perhaps downloading BCEL's source code and putting a breakpoint at line 135 of this method

org.apache.bcel.verifier.structurals.OperandStack.pop(OperandStack.java:135)

will tell you more. Obviously, there's a problem somewhere with array index manipulation.

From what I see, BCEL is no more in development, so if a bug exists, it might be difficult to have it fixed if you report it.

ASM is a more modern bytecode generation library that's under development. You probably already know this; but if you have that simulator's source code and it isn't using BCEL too much, you might be able to rewrite it using ASM. Of course, stuff like this is usually overkill.


来源: stackexchange

问:
Make form input field take up all the width in a div that isn't occupied by other elements
I have a centered div that contains a header, input, and button in a row.  I would like to make the input field expand so that the total width of the contents of the div take up the entire width allotted to the div.  Is there some CSS way to specify something like width: 100%-other_elems?

答:
Is there some CSS way to specify something like width: 100%-other_elems?

Yes using flex-box. Flexbox part of the browser's layout engine to create dynamic and flexible boxes or divs. See the example below and try resizing. Refer to CSS trick's flexbox tutorial for a complete rundown of flexbox. It's a fantastic reference that I use it all the time.

CSS rundown:

display: flex on .some-container declares that any element with the class some-container will use flexbox.

flex: 1 on .expand declares that in the parent flexbox (i.e. some-container) this element should grow.

.some-container { display: flex; }

.expand { flex: 1; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="some-container">
  <h1>some header</h1>
  <input class="expand" type="text">
  <button>some button</button>
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
Is there some CSS way to specify something like width: 100%-other_elems?

Yes using flex-box. Flexbox part of the browser's layout engine to create dynamic and flexible boxes or divs. See the example below and try resizing. Refer to CSS trick's flexbox tutorial for a complete rundown of flexbox. It's a fantastic reference that I use it all the time.

CSS rundown:

display: flex on .some-container declares that any element with the class some-container will use flexbox.

flex: 1 on .expand declares that in the parent flexbox (i.e. some-container) this element should grow.

.some-container { display: flex; }

.expand { flex: 1; }

<div class="some-container">
  <h1>some header</h1>
  <input class="expand" type="text">
  <button>some button</button>
</div>


问:
How to add a property in to HTML Tag use Jquery?
I am trying to add a Property In to a tag while select that tag

I need to add Invalid property like this  ....aria-readonly="false" invalid>

Page load Code:-

```<code>function setFieldRequired1(field) {

    var dropdownField=$("[data-metatype='dropdown'][name='./jcr:content/metadata/document_type']");

      if (!field.val()) {
        dropdownField.prop('invalid', 'invalid');
        dropdownField.attr('aria-required', 'true');
        dropdownField.attr('aria-invalid', 'true');
        var icons = $(dropdownField.siblings('.coral-Form-fielderror'));
        icons.show();
      }
       else
      {
         dropdownField.attr('aria-required', 'false');
        dropdownField.attr('aria-invalid', 'false');
        dropdownField.removeProp('invalid');
        var icons = $(dropdownField.siblings('.coral-Form-fielderror'));
        icons.hide();
      }

}
</code>```

This code working fine But when I select same dropdown with empty value also i have to add that invalid property?
Any help?

答:
You cannot use attribute names separated by hyphen in javascript.

You have to convert it to camel casing.

For example :

aria-required --> ariaRequired

aria-invalid  --> ariaInvalid

Body:
I am trying to add a Property In to a tag while select that tag

I need to add Invalid property like this  ....aria-readonly="false" invalid>

Page load Code:-

function setFieldRequired1(field) {

    var dropdownField=$("[data-metatype='dropdown'][name='./jcr:content/metadata/document_type']");

      if (!field.val()) {
        dropdownField.prop('invalid', 'invalid');
        dropdownField.attr('aria-required', 'true');
        dropdownField.attr('aria-invalid', 'true');
        var icons = $(dropdownField.siblings('.coral-Form-fielderror'));
        icons.show();
      }
       else
      {
         dropdownField.attr('aria-required', 'false');
        dropdownField.attr('aria-invalid', 'false');
        dropdownField.removeProp('invalid');
        var icons = $(dropdownField.siblings('.coral-Form-fielderror'));
        icons.hide();
      }

}

This code working fine But when I select same dropdown with empty value also i have to add that invalid property?
Any help?


问:
Set theme color dynamically
I am using themes (dynamically) in my android app, like this:

my_layout.xml (extract):

```<code><TextView
    android:id="@+id/myItem"
    style="?my_item_style" />
</code>```

attrs.xml (extract):

```<code><attr name="my_item_style" format="reference" />
</code>```

themes.xml (extract):

```<code><style name="MainTheme.Blue">
      <item name="my_item_style">@style/my_item_style_blue</item>
</style>

<style name="MainTheme.Green">
      <item name="my_item_style">@style/my_item_style_green<item>
</style>
</code>```

styles.xml (extract):

```<code><style name="my_item_style_blue">
      <item name="android:textColor">@color/my_blue</item>
</style>

<style name="my_item_style_green">
      <item name="android:textColor">@color/my_blue</item>
</style>
</code>```

So, as you can see, I am setting themes dynamically. I am using this class:

```<code>public class ThemeUtils {

  private static int sTheme;
  public final static int THEME_BLUE = 1;
  public final static int THEME_GREEN = 2;

  public static void changeToTheme(MainActivity activity, int theme) {
      sTheme = theme;
      activity.startActivity(new Intent(activity, MyActivity.class));
  }

  public static void onActivityCreateSetTheme(Activity activity)
  {
      switch (sTheme)
      {
          default:
          case THEME_DEFAULT:
          case THEME_BLUE:
              activity.setTheme(R.style.MainTheme_Blue);
              break;
          case THEME_GREEN:
              activity.setTheme(R.style.MainTheme_Green);
              break;
      }
  }
</code>```

}

What I want to know, is there a way how to do this (change theme color) in code? For example, I have following code (extract):

```<code>((TextView) findViewById(R.id.myItem)).setTextColor(R.color.blue);
</code>```

It can be done by some helper method, which would use switch command for available themes and return correct color for a theme. But I would like to know if there is some better, nicer and faster way.

Thanks!

答:
Given the fact that every resource is a field into the R class, you can look for them using reflection. That's costly, but since you are going to get an int value, you can store them after you get them and avoid the performance drop. And since the methods that use resources take any int, you can use an int variable as placeholder, and then put the desired color into it.

for getting any resource:

```<code>String awesomeColor = "blue";
int color = getResourceId(R.color, awesomeColor, false);
if(blue>0) ((TextView) findViewById(R.id.myItem)).setTextColor(color);
</code>```

The function:

```<code>public static int getResourceId(Class rClass, String resourceText, boolean showExceptions){

        String key = rClass.getName()+"-"+resourceText;

        if(FailedResourceMap.containsKey(key)) return 0;
        if(ResourceMap.containsKey(key)) return ResourceMap.get(rClass.getName()+"-"+resourceText);

        try {

            String originalText = resourceText;
            if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.GINGERBREAD){
                resourceText = ValidationFunctions.normalizeText(resourceText);
            }
            resourceText = resourceText.replace("?", "").replace("  ", " ").replace(" ", "_").replace("(", "").replace(")", "");

            int resource = rClass.getDeclaredField(resourceText).getInt(null);
            ResourceMap.put(rClass.getName()+"-"+originalText, resource);

            return resource;
        } catch (IllegalAccessException | NullPointerException e) {
            FailedResourceMap.put(key, 0);
            if(showExceptions) e.printStackTrace();
        } catch (NoSuchFieldException e) {
            FailedResourceMap.put(key, 0);
            if(showExceptions) e.printStackTrace();
        }

        return 0;
    }
</code>```

Working version here: https://github.com/fcopardo/AndroidFunctions/blob/master/src/main/java/com/grizzly/functions/TextFunctions.java

This treatment is valid for any android resource. You can set the theme this way too instead of using intermediate variables:

```<code>public static void onActivityCreateSetTheme(Activity activity)
  {
    int theme = getResourceId(R.style, activity.getClass().getSimpleName(), false);
    if(theme > 0) activity.setTheme(theme);
  }
</code>```

Title: Set theme color dynamically

Body:
I am using themes (dynamically) in my android app, like this:

my_layout.xml (extract):

<TextView
    android:id="@+id/myItem"
    style="?my_item_style" />

attrs.xml (extract):

<attr name="my_item_style" format="reference" />

themes.xml (extract):

styles.xml (extract):

So, as you can see, I am setting themes dynamically. I am using this class:

public class ThemeUtils {

  private static int sTheme;
  public final static int THEME_BLUE = 1;
  public final static int THEME_GREEN = 2;

  public static void changeToTheme(MainActivity activity, int theme) {
      sTheme = theme;
      activity.startActivity(new Intent(activity, MyActivity.class));
  }

  public static void onActivityCreateSetTheme(Activity activity)
  {
      switch (sTheme)
      {
          default:
          case THEME_DEFAULT:
          case THEME_BLUE:
              activity.setTheme(R.style.MainTheme_Blue);
              break;
          case THEME_GREEN:
              activity.setTheme(R.style.MainTheme_Green);
              break;
      }
  }

}

What I want to know, is there a way how to do this (change theme color) in code? For example, I have following code (extract):

((TextView) findViewById(R.id.myItem)).setTextColor(R.color.blue);

It can be done by some helper method, which would use switch command for available themes and return correct color for a theme. But I would like to know if there is some better, nicer and faster way.

Thanks!

Body:
Given the fact that every resource is a field into the R class, you can look for them using reflection. That's costly, but since you are going to get an int value, you can store them after you get them and avoid the performance drop. And since the methods that use resources take any int, you can use an int variable as placeholder, and then put the desired color into it.

for getting any resource:

String awesomeColor = "blue";
int color = getResourceId(R.color, awesomeColor, false);
if(blue>0) ((TextView) findViewById(R.id.myItem)).setTextColor(color);

The function:

public static int getResourceId(Class rClass, String resourceText, boolean showExceptions){

        String key = rClass.getName()+"-"+resourceText;

        if(FailedResourceMap.containsKey(key)) return 0;
        if(ResourceMap.containsKey(key)) return ResourceMap.get(rClass.getName()+"-"+resourceText);

        try {

            String originalText = resourceText;
            if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.GINGERBREAD){
                resourceText = ValidationFunctions.normalizeText(resourceText);
            }
            resourceText = resourceText.replace("?", "").replace("  ", " ").replace(" ", "_").replace("(", "").replace(")", "");

            int resource = rClass.getDeclaredField(resourceText).getInt(null);
            ResourceMap.put(rClass.getName()+"-"+originalText, resource);

            return resource;
        } catch (IllegalAccessException | NullPointerException e) {
            FailedResourceMap.put(key, 0);
            if(showExceptions) e.printStackTrace();
        } catch (NoSuchFieldException e) {
            FailedResourceMap.put(key, 0);
            if(showExceptions) e.printStackTrace();
        }

        return 0;
    }

Working version here: https://github.com/fcopardo/AndroidFunctions/blob/master/src/main/java/com/grizzly/functions/TextFunctions.java

This treatment is valid for any android resource. You can set the theme this way too instead of using intermediate variables:

public static void onActivityCreateSetTheme(Activity activity)
  {
    int theme = getResourceId(R.style, activity.getClass().getSimpleName(), false);
    if(theme > 0) activity.setTheme(theme);
  }


问:
FileInfo.Exists not reliable with UNC path
I want to determine if a UNC file exists. I create a FileInfo object, then call FileInfo.Exists. But it'll occasionally return false, even if the file actually exists.

How can I accurately determine if a UNC file exists?

答: You can't do this in a general sense, because as Ben mentions, you might not have ACLs to see if it exists. That being said, the best way to determine if a file exists (based on your scenario) is to attempt to open the file</p>

ContentLicense: CC BY-SA 2.5


问:
Should I use arial-label or a label element that is visually hidden
I am creating a search form that has two elements an input field and a button. The input field does not have an label associated with it.

To make the field more accessible I can add Search and visually hide it so it will e.g. be accessible for screenreaders.

I could also add aria-label="search" to the input field and leave the input field without an label.

I have tested with "Voice Over" on a Mac and I get the same result/output. My question is are these approaches equivalent? Or is one approach better than the other one?

Here is a pen.

答:
Using aria-label is preferable to relying on CSS to visually hide a label element.

(Related Technique: Using aria-label to provide an invisible label where a visible label cannot be used)

But note that you don’t have to provide a label for a search form that only consists of the search field and the submit button. Assuming that you use a button labeled with something like "Search", it already makes clear which purpose the text field has.

(Related Technique: Using an adjacent button to label the purpose of a field)

In that case, while it doesn’t need a label, it should still get a name. One way to provide a name is to use the title attribute on the input element. The Technique Using the title attribute to identify form controls when the label element cannot be used shows this (a search form without label, with title attribute on input) in example 3.


问:
How to search for subarrays with a specific ids and generate a new array from their elements?
I've been trying to organize data into a multidimensional array from a foreach loop but the data is all over the place.

This is what I coded:

```<code>$productIDs = array(
    '0' => array(
        'product_id' => '10',
        'product_name' => 'Test',
        'product_file' => 'file10',
        'product_image' => 'https://i.imgur.com/dXb6.png',
    ),
    '1' => array(
        'product_id' => '20',
        'product_name' => 'Test1',
        'product_file' => 'file20',
        'product_image' => 'https://i.imgur.com/MuP8.png',
    ),
    '2' => array(
        'product_id' => '30',
        'product_name' => 'No product',
        'product_file' => 'file30',
        'product_image' => 'https://i.imgur.com/kWP3.png',
    )
);

$urlIDs  = array(10,20);

function getFiles($productIDs, $urlIDs)
{
    foreach($productIDs as $ids)
    {
        foreach($urlIDs as $products)
        {
            if(in_array($products, $ids)){
                $data1[] = $ids['product_id'];
                $data2[] = $ids['product_file'];
                $data3[] = $ids['product_image'];
            }
        }
    }
    return array($data1, $data2, $data3);
}
$getFiles = getFiles($productIDs, $urlIDs);
</code>```

And the output for the following is:

```<code>Array
(
    [0] => Array
        (
            [0] => 10
            [1] => 20
        )

    [1] => Array
        (
            [0] => file10
            [1] => file20
        )

    [2] => Array
        (
            [0] => https://i.imgur.com/dXb6.png
            [1] => https://i.imgur.com/MuP8.png
        )

)
</code>```

Although what I'm trying to accomplish is:

```<code>Array
(
    [0] => Array
        (
            [id] => 10
            [file] => file10
            [image] => https://i.imgur.com/dXb6.png
        )

    [1] => Array
        (
            [id] => 20
            [file] => file20
            [image] => https://i.imgur.com/MuP8.png
        )

)
</code>```

I tried the following:

```<code>function getFiles($productIDs, $urlIDs)
{
    foreach($productIDs as $ids)
    {
        foreach($urlIDs as $products)
        {
            if(in_array($products, $ids)){
                $data['id'] = $ids['product_id'];
                $data['file'] = $ids['product_file'];
                $data['image'] = $ids['product_image'];
            }
        }
    }
    return array($data);
}
</code>```

Which returns the following without looping through all id's, it should return both arrays since both id's are matching.

```<code>Array
(
    [0] => Array
        (
            [id] => 20
            [file] => file20
            [image] => https://i.imgur.com/MuP8.png
        )

)
</code>```

You could say the first batch of code without the specific key names isn't what I want, but I just wanted to show what I had tried. The last batch works (with key names), but doesn't loop through all of the $urlIDs, and for some reason that I can't understand, the code isn't even returning id = 10, it's returning id = 20, though it's second in the array. If someone could explain why this is happening I'd appreciate it.

In case it's useful: https://eval.in/764083

答:
Leveraging your tried out solution, change your tried solution to this.</p>

```<code>function getFiles($productIDs, $urlIDs)
{

    foreach($productIDs as $ids)
    {
        foreach($urlIDs as $products)
        {
            if(in_array($products, $ids)){
                $data[] = [ "id" => $ids['product_id'],
                            "file" => $ids['product_file'],
                            "image" => $ids['product_image']];
            }
        }
    }
    return $data;
}
</code>```

Body:
I've been trying to organize data into a multidimensional array from a foreach loop but the data is all over the place.

This is what I coded:

$productIDs = array(
    '0' => array(
        'product_id' => '10',
        'product_name' => 'Test',
        'product_file' => 'file10',
        'product_image' => 'https://i.imgur.com/dXb6.png',
    ),
    '1' => array(
        'product_id' => '20',
        'product_name' => 'Test1',
        'product_file' => 'file20',
        'product_image' => 'https://i.imgur.com/MuP8.png',
    ),
    '2' => array(
        'product_id' => '30',
        'product_name' => 'No product',
        'product_file' => 'file30',
        'product_image' => 'https://i.imgur.com/kWP3.png',
    )
);

$urlIDs  = array(10,20);

function getFiles($productIDs, $urlIDs)
{
    foreach($productIDs as $ids)
    {
        foreach($urlIDs as $products)
        {
            if(in_array($products, $ids)){
                $data1[] = $ids['product_id'];
                $data2[] = $ids['product_file'];
                $data3[] = $ids['product_image'];
            }
        }
    }
    return array($data1, $data2, $data3);
}
$getFiles = getFiles($productIDs, $urlIDs);

And the output for the following is:

Array
(
    [0] => Array
        (
            [0] => 10
            [1] => 20
        )

    [1] => Array
        (
            [0] => file10
            [1] => file20
        )

    [2] => Array
        (
            [0] => https://i.imgur.com/dXb6.png
            [1] => https://i.imgur.com/MuP8.png
        )

)

Although what I'm trying to accomplish is:

Array
(
    [0] => Array
        (
            [id] => 10
            [file] => file10
            [image] => https://i.imgur.com/dXb6.png
        )

    [1] => Array
        (
            [id] => 20
            [file] => file20
            [image] => https://i.imgur.com/MuP8.png
        )

)

I tried the following:

function getFiles($productIDs, $urlIDs)
{
    foreach($productIDs as $ids)
    {
        foreach($urlIDs as $products)
        {
            if(in_array($products, $ids)){
                $data['id'] = $ids['product_id'];
                $data['file'] = $ids['product_file'];
                $data['image'] = $ids['product_image'];
            }
        }
    }
    return array($data);
}

Which returns the following without looping through all id's, it should return both arrays since both id's are matching.

Array
(
    [0] => Array
        (
            [id] => 20
            [file] => file20
            [image] => https://i.imgur.com/MuP8.png
        )

)

You could say the first batch of code without the specific key names isn't what I want, but I just wanted to show what I had tried. The last batch works (with key names), but doesn't loop through all of the $urlIDs, and for some reason that I can't understand, the code isn't even returning id = 10, it's returning id = 20, though it's second in the array. If someone could explain why this is happening I'd appreciate it.

In case it's useful: https://eval.in/764083

Body:
Leveraging your tried out solution, change your tried solution to this.

function getFiles($productIDs, $urlIDs)
{

    foreach($productIDs as $ids)
    {
        foreach($urlIDs as $products)
        {
            if(in_array($products, $ids)){
                $data[] = [ "id" => $ids['product_id'],
                            "file" => $ids['product_file'],
                            "image" => $ids['product_image']];
            }
        }
    }
    return $data;
}


问:
Calling an enum inside a function in Swift
I'm absolutely at a loss on this one. What is my instructor looking for? Any suggestions?

Started something like this, but I'm just off..

```<code>enum Color: String {

case blue = "orange"
case red = "green"
case yellow = "purple"

}

func complement(_ color) -> String {
    case
}
</code>```

Question:
Create a type, Color with the three primary colors and the three secondary colors. Then create a function complement which will return the complementary color for a provided color.

```<code>Red's complement is green
Blue's complement is orange
Yellow's complement is purple

complement(.red) -> .green
complement(.orange) -> .blue
</code>```

updated:

```<code>enum Color: String {
    case red = "red"
    case green = "green"
    case blue = "blue"

    case yellow = "yellow"
    case orange = "orange"
    case purple = "purple"
}

func compliment(_ color: Color) -> Color {
    switch color {
    case .red: return .green
    case .green: return .red
    case .blue: return .orange
    break
    }
}

let red = Color.red
let compliment = compliment(red)
print(compliment)

let green = Color.green
let compliment = compliment(green)
print(compliment)

let blue = Color.blue
let compliment = compliment(blue)
print(compliment)
</code>```

error: variable used within its own initial value

```<code>let compliment = compliment(red)
</code>```

It's doing this for every instance

答:
This is more generic. You don't have to create a type with explicit String.

```<code>enum Color {
    case red
    case green
    case blue

    case orange
    case yellow
    case violet
}

func complement(_ color: Color) -> Color {
    switch color {

    case .red: return .green
    case .green: return .red

    case .blue: return .orange
    case .orange: return .blue

    case .yellow: return .violet
    case .violet: return .yellow

    }
}

let red = Color.red
let redComplement = complement(red)
print("Complement of \(red) is \(redComplement)")

let green = Color.green
let greenComplement = complement(green)
print("Complement of \(green) is \(greenComplement)")
</code>```

Body:
I'm absolutely at a loss on this one. What is my instructor looking for? Any suggestions?

Started something like this, but I'm just off..

enum Color: String {

case blue = "orange"
case red = "green"
case yellow = "purple"

}

func complement(_ color) -> String {
    case
}

Question:
Create a type, Color with the three primary colors and the three secondary colors. Then create a function complement which will return the complementary color for a provided color.

Red's complement is green
Blue's complement is orange
Yellow's complement is purple

complement(.red) -> .green
complement(.orange) -> .blue

updated:

enum Color: String {
    case red = "red"
    case green = "green"
    case blue = "blue"

    case yellow = "yellow"
    case orange = "orange"
    case purple = "purple"
}

func compliment(_ color: Color) -> Color {
    switch color {
    case .red: return .green
    case .green: return .red
    case .blue: return .orange
    break
    }
}

let red = Color.red
let compliment = compliment(red)
print(compliment)

let green = Color.green
let compliment = compliment(green)
print(compliment)

let blue = Color.blue
let compliment = compliment(blue)
print(compliment)

error: variable used within its own initial value

let compliment = compliment(red)

It's doing this for every instance

Body:
This is more generic. You don't have to create a type with explicit String.

enum Color {
    case red
    case green
    case blue

    case orange
    case yellow
    case violet
}

func complement(_ color: Color) -> Color {
    switch color {

    case .red: return .green
    case .green: return .red

    case .blue: return .orange
    case .orange: return .blue

    case .yellow: return .violet
    case .violet: return .yellow

    }
}

let red = Color.red
let redComplement = complement(red)
print("Complement of \(red) is \(redComplement)")

let green = Color.green
let greenComplement = complement(green)
print("Complement of \(green) is \(greenComplement)")


问:
How to remove character from last array element
I need to remove the last element comma in Javascript array

```<code>var arr =  ["AAA,","BBB,"];
</code>```

I need the result below

```<code>var arr =  ["AAA,","BBB"];
</code>```

Any help is appreciated...

答:
```<code>arr[arr.length-1] = arr[arr.length-1].slice(0,-1)
</code>```

Body:
I need to remove the last element comma in Javascript array

var arr =  ["AAA,","BBB,"];

I need the result below

var arr =  ["AAA,","BBB"];

Any help is appreciated...


问:
ERROR: Plugin '' not found, or is not a CDVPlugin. Check your plugin mapping in config.xml
I tried to add 'NativeTable' plugin, to display tableview in my phonegap app.

i am getting error as "ERROR: Plugin '' not found, or is not a CDVPlugin. Check your plugin mapping in config.xml".

I have added NativeTable.h and NativeTable.m file in plugins directory, NativeTable.js in www directory.

and also added <plugin name="NativeTable" value="NativeTable" />

in config.xml file, in cordova.plist a key/value pair Key:NativeTable Value:Nativetable is added in plugins dictionary.

Please help me out with a solution.

Thanks in advance

答: I had this same problem with the SQLitePlugin. Try removing and adding your platform again (in my case, it was platform/ios since I am developing for an iPhone). Then rebuild your project. It worked for me.</p>


问:
Python 2.6 from human date to seconds
Since there is no total_seconds() for python 2.6, I use formula  (dt.microseconds + (dt.seconds + dt.days * 24 * 3600) * 10**6) / 10**6 to find total seconds for a number of days that comes from: dt.strptime("date_from_user","%d.%m.%Y %H:%M:%S") - datetime(1970, 1, 1).
I don't understand why for any date_from_user(e.g. "25.07.2015 00:00:00"), I've got back a number of seconds corresponding to the input date but with 2 hours added. In this example "25.07.2015 02:00:00".

答:
To simply convert a human date into seconds from epoch(for unix systems), I used 'Time' module and followed this recommended way from the Python docs, as showed in the table:

https://docs.python.org/2.7/library/time.html

This works for Python 2.6

Title: Python 2.6 from human date to seconds


问:
How to use proxies to download files
I'm downloading a website with heaps of GPL-licensed free content, however my computer exceeds the daily download limit of 20 files (out of some 10,000!)

Is there a proxy service I can use (via PHP) to continue accessing such content?

答:
Yes, this is possible. See PHP's cURL:
- http://php.net/manual/en/book.curl.php

Specifically: http://www.php.net/manual/en/function.curl-setopt.php : CURLOPT_HTTPPROXYTUNNEL

You may want to check that what you're doing is legal. Also, I'd imagine that you'll run into the same download limit, with a proxy.

Title: How to use proxies to download files


问:
Unable to access NIFI REST API using ajax in secured mode
I am trying to access NIFI REST API using ajax call.

I have created access token and passed it using Authorization header.

But it show unauthorized access while accessing.

headers :

```<code>{Authorization : 'Bearer ' + 'access token here'}
</code>```

答:
Achieved it by sending Authorization header in beforeSend event like below
 beforeSend: function(xhr) { xhr.setRequestHeader('Authorization','Bearer ' + "access token");} ,

Body:
I am trying to access NIFI REST API using ajax call.

I have created access token and passed it using Authorization header.

But it show unauthorized access while accessing.

headers :

{Authorization : 'Bearer ' + 'access token here'}


问:
Trigger Onchange event of a dropdownlistFor
I have 3 dropdownlists: Country, State and City. On change of Country dropdown, state dropdown has to populate for selected country, on change of state dropdown, city dropdown has to populate for selected state.

The fuctionality works when the dropdown values are changed from the UI. Now I want to populate the dropdowns with the selected values stored in the database. ie. If my database has values countryId=1, stateId=5, cityId=2 then my dropdown should populate accordingly. For which the dropdown onchanhge has to call directly when selected value is set to it. But the value is getting set for the first dropdown (country dropdown) but state and city does not set the values as country on change is not triggered.

Here is my code:

.cshtml

```<code><div class="row clearfix">
    <div class="col-lg-2 col-md-2 col-sm-4 col-xs-5 form-control-label">
        <label>Country</label>
    </div>
    <div class="col-lg-2 col-md-2 col-sm-8 col-xs-7">
        <div class="form-group">
            <div class="form-line">
                @Html.DropDownListFor(m => m.CountryId, (IEnumerable<SelectListItem>)ViewBag.country, "-- Please select --", new { @class = "form-control show-tick"} )
            </div><label id="CountryListLable" style="color:red;"></label>

        </div>
    </div>

    <div class="col-lg-1 col-md-1 col-sm-4 col-xs-5 form-control-label">
        <label>State</label>
    </div>
    <div class="col-lg-2 col-md-2 col-sm-8 col-xs-7">
        <div class="form-group">
            <div class="form-line">
                <select id="ddState" class="form-control show-tick">
                    <option>-- Please select --</option>
                </select>
            </div>
            <label id="StateListLable" style="color:red;"></label>
        </div>
    </div>
    <div class="col-lg-1 col-md-1 col-sm-4 col-xs-5 form-control-label">
        <label>City</label>
    </div>
    <div class="col-lg-2 col-md-2 col-sm-8 col-xs-7">
        <div class="form-group">
            <div class="form-line">
                <select id="ddCity" name="ddCity" class="form-control show-tick">
                    <option value="0">-- Please select --</option>
                </select>
            </div>
            <label id="CityListLable" style="color:red;"></label>
        </div>
    </div>
</div>
</code>```

Jquery:

```<code> $('#CountryId').change(function () {
        //alert($(this));
        var cN;
        var UserType = $(this).data('type');

            $('#ddState').selectpicker();
            $('#ddState').empty();
            $('#ddState').selectpicker('refresh');
            $('#ddState').append("<option>-- Please select --</option>");
            cN = $('#CountryId').val();
        if (cN === '') {
            return false;
        } else {
            $.ajax({
                url: "/AdminUser/GetStatesForCountry?countryId=" + cN, success: function (result) {
                    console.log(result);
                    $.each(result, function (key, value) {

                            $('#ddState')
                               .append($("<option></option>")
                                          .attr("value", value.stateId)
                                          .text(value.stateName));
                            $('#ddState').selectpicker('refresh');
                            $('#ddState').selectpicker('val', "-- Please select --");
                    });

                }
            });
        }
    });

    $('#ddState').change(function () {
        var UserType = $(this).data('type');

            $('#ddCity').selectpicker();
            $('#ddCity').empty();
            $('#ddCity').selectpicker('refresh');
            $('#ddCity').append("<option>-- Please select --</option>");
            cN = $('#ddState').val();
        if (cN === '') {
            return false;
        } else {
            $.ajax({
                url: "/AdminUser/GetCitiesForState?StateId=" + cN, success: function (result) {
                    console.log(result);
                    $.each(result, function (key, value) {

                            $('#ddCity')
                             .append($("<option></option>")
                                        .attr("value", value.cityId)
                                        .text(value.cityName));
                            $('#ddCity').selectpicker('refresh');
                            $('#ddCity').selectpicker('val', "-- Please select --");
                    });

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

Controller code

```<code>var countryData = new List<CountryData>();
IEnumerable<SelectListItem> countryList = new List<SelectListItem>();
countryData = (List<CountryData>)HttpContext.Cache.Get("countryResponse");
if (countryData == null)
{
    string response = Service.APIHelper_GET(StringConstants.GetCountryDetails);
    if (!response.Equals("Internal Server Error."))
    {
        countryData = new JavaScriptSerializer().Deserialize<List<CountryData>>(response);
        HttpContext.Cache.Insert("countryResponse", countryData);
    }
}
countryList = countryData.Select(m => new SelectListItem() { Text = m.countryName, Value = m.countryId.ToString() });

ViewBag.country = countryList;//new SelectList(countryList);

public JsonResult GetStatesForCountry(int countryId)//get states for countryid = id
{
    Session["CountryId"] = countryId;
    return Json(getStateList(countryId), JsonRequestBehavior.AllowGet);
}

public List<State> getStateList(int countryId)
{
    var stateList = new List<State>();
    stateList = (List<State>)HttpContext.Cache.Get("StateResponseForCountry_" + countryId);
    if (stateList == null)
    {
        var response = (List<CountryData>)HttpContext.Cache.Get("countryResponse"); //this wont b null bcz on page load putting country list to chache
        foreach (var item in response)
        {
            if (item.countryId == countryId)
            {
                stateList = item.states;
            }
        }
        HttpContext.Cache.Insert("StateResponseForCountry_" + countryId, stateList);
    }
    return stateList;
}

public JsonResult GetCitiesForState(int StateId)
{
    var cityList = new List<City>();

    cityList = (List<City>)HttpContext.Cache.Get("CityResponseForState_" + StateId);
    if (cityList == null)
    {
        List<State> stateList = getStateList(Convert.ToInt32(Session["CountryId"]));

        foreach (var item in stateList)
        {
            if (item.stateId == StateId)
            {
                cityList = item.cities;
            }
        }
        HttpContext.Cache.Insert("CityResponseForState_" + StateId, cityList);
    }
    return Json(cityList, JsonRequestBehavior.AllowGet);
}
</code>```

Here is the scenario for better understanding of my issue:
I have a create user page in which user will select from cascaded dropdowns (country, state, city) and save selected valued to database. The problem is in edit user, where I need to populate the dropdowns based on selected values. ie. I need to populate state dropdown with selected values from database.

UPDATE
With the help of @Sagar's solution I have managed to set selected value for the country dropdown. But the state and city dropdowns are still not getting set. Here is the updated code:

cshtml

```<code><div class="row clearfix">
    <div class="col-lg-2 col-md-2 col-sm-4 col-xs-5 form-control-label">
        <label>Country</label>
    </div>
    <div class="col-lg-2 col-md-2 col-sm-8 col-xs-7">
        <div class="form-group">
            <div class="form-line">
                @Html.DropDownListFor(m => m.CountryId, (IEnumerable<SelectListItem>)ViewBag.country, "-- Please select --", new { @class = "form-control show-tick" })
            </div><label id="CountryListLable" style="color:red;"></label>

        </div>
    </div>

    <div class="col-lg-1 col-md-1 col-sm-4 col-xs-5 form-control-label">
        <label>State</label>
    </div>
    <div class="col-lg-2 col-md-2 col-sm-8 col-xs-7">
        <div class="form-group">
            <div class="form-line">
                @Html.DropDownListFor(m => m.StateId, Enumerable.Empty<SelectListItem>(), "-- Please select --", new { @class = "form-control show-tick" })
            </div>
            <label id="StateListLable" style="color:red;"></label>
        </div>
    </div>
    <div class="col-lg-1 col-md-1 col-sm-4 col-xs-5 form-control-label">
        <label>City</label>
    </div>
    <div class="col-lg-2 col-md-2 col-sm-8 col-xs-7">
        <div class="form-group">
            <div class="form-line">
                @Html.DropDownListFor(m => m.fKCityId, Enumerable.Empty<SelectListItem>(), "-- Please select --", new { @class = "form-control show-tick" })
            </div>
            <label id="CityListLable" style="color:red;"></label>
        </div>
    </div>
</div>
</code>```

Jquery

```<code>$(document).ready(function () {
    var countryId = $('#CountryId').val();
    getStates(countryId);

    var StateId = $('#StateId').val();
    alert(StateId);/// here I am not getting correct value -- it passes stateId='-- Please select --'
    getCities(StateId);

    $('#CountryId').change(function () {
        var countryId = $(this).val();
        getStates(countryId);
    });

    $('#StateId').change(function () {
        var StateId = $(this).val();
        getCities(StateId);
    });

});

function getStates(countryId) {
    $('#StateId').selectpicker();
    $('#StateId').empty();
    $('#StateId').selectpicker('refresh');
    $('#StateId').append("<option>-- Please select --</option>");

    if (countryId === '') {
        return false;
    } else {
        $.ajax({
            url: "/AdminUser/GetStatesForCountry?countryId=" + countryId, success: function (result) {
                console.log(result);
                $.each(result, function (key, value) {

                    $('#StateId')
                       .append($("<option></option>")
                                  .attr("value", value.stateId)
                                  .text(value.stateName));
                    $('#StateId').selectpicker('refresh');
                    $('#StateId').selectpicker('val', "-- Please select --");
                });

            }
        });
    }
}

function getCities(stateId)
{
    $('#fKCityId').selectpicker();
    $('#fKCityId').empty();
    $('#fKCityId').selectpicker('refresh');
    $('#fKCityId').append("<option>-- Please select --</option>");
    if (stateId === '') {
        return false;
    } else {
        $.ajax({
            url: "/AdminUser/GetCitiesForState?StateId=" + stateId, success: function (result) {
                console.log(result);
                $.each(result, function (key, value) {

                    $('#fKCityId')
                     .append($("<option></option>")
                                .attr("value", value.cityId)
                                .text(value.cityName));
                    $('#fKCityId').selectpicker('refresh');
                    $('#fKCityId').selectpicker('val', "-- Please select --");
                });

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

答:
I have managed to solve the issue with the help of @StephenMuecke comments.

All I had to do was, to populate the dropdowns while passing the model to the view.

Code:

```<code>Model usersDetail = users.userDetail;
ViewBag.State = getStateList(usersDetail.CountryId).Select(m => new SelectListItem() { Text = m.StateName, Value = m.Id.ToString() });
ViewBag.City = getCityList(usersDetail.StateId).Select(m => new SelectListItem() { Text = m.CityName, Value = m.Id.ToString() });
return View(usersDetail);
</code>```

and modified .cshtml to populate state and city from viewbag:

```<code><div class="row clearfix">
    <div class="col-lg-2 col-md-2 col-sm-4 col-xs-5 form-control-label">
        <label>Country</label>
    </div>
    <div class="col-lg-2 col-md-2 col-sm-8 col-xs-7">
        <div class="form-group">
            <div class="form-line">
                @Html.DropDownListFor(m => m.CountryId, (IEnumerable<SelectListItem>)ViewBag.country, "-- Please select --", new { @class = "form-control show-tick" })
            </div><label id="CountryListLable" style="color:red;"></label>

        </div>
    </div>

    <div class="col-lg-1 col-md-1 col-sm-4 col-xs-5 form-control-label">
        <label>State</label>
    </div>
    <div class="col-lg-2 col-md-2 col-sm-8 col-xs-7">
        <div class="form-group">
            <div class="form-line">
                @Html.DropDownListFor(m => m.StateId, (IEnumerable<SelectListItem>)ViewBag.State, "-- Please select --", new { @class = "form-control show-tick" })
                @*<select id="State" class="form-control show-tick">
                    <option>-- Please select --</option>
                </select>*@
            </div>
            <label id="StateListLable" style="color:red;"></label>
        </div>
    </div>
    <div class="col-lg-1 col-md-1 col-sm-4 col-xs-5 form-control-label">
        <label>City</label>
    </div>
    <div class="col-lg-2 col-md-2 col-sm-8 col-xs-7">
        <div class="form-group">
            <div class="form-line">
                @Html.DropDownListFor(m => m.fKCityId, (IEnumerable<SelectListItem>)ViewBag.City, "-- Please select --", new { @class = "form-control show-tick" })
                @*<select id="ddCity" name="ddCity" class="form-control show-tick">
                    <option value="0">-- Please select --</option>
                </select>*@
            </div>
            <label id="CityListLable" style="color:red;"></label>
        </div>
    </div>
</div>
</code>```

Body:
I have 3 dropdownlists: Country, State and City. On change of Country dropdown, state dropdown has to populate for selected country, on change of state dropdown, city dropdown has to populate for selected state.

The fuctionality works when the dropdown values are changed from the UI. Now I want to populate the dropdowns with the selected values stored in the database. ie. If my database has values countryId=1, stateId=5, cityId=2 then my dropdown should populate accordingly. For which the dropdown onchanhge has to call directly when selected value is set to it. But the value is getting set for the first dropdown (country dropdown) but state and city does not set the values as country on change is not triggered.

Here is my code:

.cshtml

        Country

                @Html.DropDownListFor(m => m.CountryId, (IEnumerable<SelectListItem>)ViewBag.country, "-- Please select --", new { @class = "form-control show-tick"} )

        State

                <select id="ddState" class="form-control show-tick">
                    <option>-- Please select --</option>
                </select>

        City

                <select id="ddCity" name="ddCity" class="form-control show-tick">
                    <option value="0">-- Please select --</option>
                </select>

Jquery:

 $('#CountryId').change(function () {
        //alert($(this));
        var cN;
        var UserType = $(this).data('type');

            $('#ddState').selectpicker();
            $('#ddState').empty();
            $('#ddState').selectpicker('refresh');
            $('#ddState').append("<option>-- Please select --</option>");
            cN = $('#CountryId').val();
        if (cN === '') {
            return false;
        } else {
            $.ajax({
                url: "/AdminUser/GetStatesForCountry?countryId=" + cN, success: function (result) {
                    console.log(result);
                    $.each(result, function (key, value) {

                            $('#ddState')
                               .append($("<option></option>")
                                          .attr("value", value.stateId)
                                          .text(value.stateName));
                            $('#ddState').selectpicker('refresh');
                            $('#ddState').selectpicker('val', "-- Please select --");
                    });

                }
            });
        }
    });

    $('#ddState').change(function () {
        var UserType = $(this).data('type');

            $('#ddCity').selectpicker();
            $('#ddCity').empty();
            $('#ddCity').selectpicker('refresh');
            $('#ddCity').append("<option>-- Please select --</option>");
            cN = $('#ddState').val();
        if (cN === '') {
            return false;
        } else {
            $.ajax({
                url: "/AdminUser/GetCitiesForState?StateId=" + cN, success: function (result) {
                    console.log(result);
                    $.each(result, function (key, value) {

                            $('#ddCity')
                             .append($("<option></option>")
                                        .attr("value", value.cityId)
                                        .text(value.cityName));
                            $('#ddCity').selectpicker('refresh');
                            $('#ddCity').selectpicker('val', "-- Please select --");
                    });

                }
            });
        }
    });

Controller code

var countryData = new List<CountryData>();
IEnumerable<SelectListItem> countryList = new List<SelectListItem>();
countryData = (List<CountryData>)HttpContext.Cache.Get("countryResponse");
if (countryData == null)
{
    string response = Service.APIHelper_GET(StringConstants.GetCountryDetails);
    if (!response.Equals("Internal Server Error."))
    {
        countryData = new JavaScriptSerializer().Deserialize<List<CountryData>>(response);
        HttpContext.Cache.Insert("countryResponse", countryData);
    }
}
countryList = countryData.Select(m => new SelectListItem() { Text = m.countryName, Value = m.countryId.ToString() });

ViewBag.country = countryList;//new SelectList(countryList);

public JsonResult GetStatesForCountry(int countryId)//get states for countryid = id
{
    Session["CountryId"] = countryId;
    return Json(getStateList(countryId), JsonRequestBehavior.AllowGet);
}

public List<State> getStateList(int countryId)
{
    var stateList = new List<State>();
    stateList = (List<State>)HttpContext.Cache.Get("StateResponseForCountry_" + countryId);
    if (stateList == null)
    {
        var response = (List<CountryData>)HttpContext.Cache.Get("countryResponse"); //this wont b null bcz on page load putting country list to chache
        foreach (var item in response)
        {
            if (item.countryId == countryId)
            {
                stateList = item.states;
            }
        }
        HttpContext.Cache.Insert("StateResponseForCountry_" + countryId, stateList);
    }
    return stateList;
}

public JsonResult GetCitiesForState(int StateId)
{
    var cityList = new List<City>();

    cityList = (List<City>)HttpContext.Cache.Get("CityResponseForState_" + StateId);
    if (cityList == null)
    {
        List<State> stateList = getStateList(Convert.ToInt32(Session["CountryId"]));

        foreach (var item in stateList)
        {
            if (item.stateId == StateId)
            {
                cityList = item.cities;
            }
        }
        HttpContext.Cache.Insert("CityResponseForState_" + StateId, cityList);
    }
    return Json(cityList, JsonRequestBehavior.AllowGet);
}

Here is the scenario for better understanding of my issue:
I have a create user page in which user will select from cascaded dropdowns (country, state, city) and save selected valued to database. The problem is in edit user, where I need to populate the dropdowns based on selected values. ie. I need to populate state dropdown with selected values from database.

UPDATE
With the help of @Sagar's solution I have managed to set selected value for the country dropdown. But the state and city dropdowns are still not getting set. Here is the updated code:

cshtml

        Country

                @Html.DropDownListFor(m => m.CountryId, (IEnumerable<SelectListItem>)ViewBag.country, "-- Please select --", new { @class = "form-control show-tick" })

        State

                @Html.DropDownListFor(m => m.StateId, Enumerable.Empty<SelectListItem>(), "-- Please select --", new { @class = "form-control show-tick" })

        City

                @Html.DropDownListFor(m => m.fKCityId, Enumerable.Empty<SelectListItem>(), "-- Please select --", new { @class = "form-control show-tick" })

Jquery

$(document).ready(function () {
    var countryId = $('#CountryId').val();
    getStates(countryId);

    var StateId = $('#StateId').val();
    alert(StateId);/// here I am not getting correct value -- it passes stateId='-- Please select --'
    getCities(StateId);

    $('#CountryId').change(function () {
        var countryId = $(this).val();
        getStates(countryId);
    });

    $('#StateId').change(function () {
        var StateId = $(this).val();
        getCities(StateId);
    });

});

function getStates(countryId) {
    $('#StateId').selectpicker();
    $('#StateId').empty();
    $('#StateId').selectpicker('refresh');
    $('#StateId').append("<option>-- Please select --</option>");

    if (countryId === '') {
        return false;
    } else {
        $.ajax({
            url: "/AdminUser/GetStatesForCountry?countryId=" + countryId, success: function (result) {
                console.log(result);
                $.each(result, function (key, value) {

                    $('#StateId')
                       .append($("<option></option>")
                                  .attr("value", value.stateId)
                                  .text(value.stateName));
                    $('#StateId').selectpicker('refresh');
                    $('#StateId').selectpicker('val', "-- Please select --");
                });

            }
        });
    }
}

function getCities(stateId)
{
    $('#fKCityId').selectpicker();
    $('#fKCityId').empty();
    $('#fKCityId').selectpicker('refresh');
    $('#fKCityId').append("<option>-- Please select --</option>");
    if (stateId === '') {
        return false;
    } else {
        $.ajax({
            url: "/AdminUser/GetCitiesForState?StateId=" + stateId, success: function (result) {
                console.log(result);
                $.each(result, function (key, value) {

                    $('#fKCityId')
                     .append($("<option></option>")
                                .attr("value", value.cityId)
                                .text(value.cityName));
                    $('#fKCityId').selectpicker('refresh');
                    $('#fKCityId').selectpicker('val', "-- Please select --");
                });

            }
        });
    }
}

Body:
I have managed to solve the issue with the help of @StephenMuecke comments.

All I had to do was, to populate the dropdowns while passing the model to the view.

Code:

Model usersDetail = users.userDetail;
ViewBag.State = getStateList(usersDetail.CountryId).Select(m => new SelectListItem() { Text = m.StateName, Value = m.Id.ToString() });
ViewBag.City = getCityList(usersDetail.StateId).Select(m => new SelectListItem() { Text = m.CityName, Value = m.Id.ToString() });
return View(usersDetail);

and modified .cshtml to populate state and city from viewbag:

<div class="row clearfix">
    <div class="col-lg-2 col-md-2 col-sm-4 col-xs-5 form-control-label">
        <label>Country</label>
    </div>
    <div class="col-lg-2 col-md-2 col-sm-8 col-xs-7">
        <div class="form-group">
            <div class="form-line">
                @Html.DropDownListFor(m => m.CountryId, (IEnumerable<SelectListItem>)ViewBag.country, "-- Please select --", new { @class = "form-control show-tick" })
            </div><label id="CountryListLable" style="color:red;"></label>

        </div>
    </div>

    <div class="col-lg-1 col-md-1 col-sm-4 col-xs-5 form-control-label">
        <label>State</label>
    </div>
    <div class="col-lg-2 col-md-2 col-sm-8 col-xs-7">
        <div class="form-group">
            <div class="form-line">
                @Html.DropDownListFor(m => m.StateId, (IEnumerable<SelectListItem>)ViewBag.State, "-- Please select --", new { @class = "form-control show-tick" })
                @*<select id="State" class="form-control show-tick">
                    <option>-- Please select --</option>
                </select>*@
            </div>
            <label id="StateListLable" style="color:red;"></label>
        </div>
    </div>
    <div class="col-lg-1 col-md-1 col-sm-4 col-xs-5 form-control-label">
        <label>City</label>
    </div>
    <div class="col-lg-2 col-md-2 col-sm-8 col-xs-7">
        <div class="form-group">
            <div class="form-line">
                @Html.DropDownListFor(m => m.fKCityId, (IEnumerable<SelectListItem>)ViewBag.City, "-- Please select --", new { @class = "form-control show-tick" })
                @*<select id="ddCity" name="ddCity" class="form-control show-tick">
                    <option value="0">-- Please select --</option>
                </select>*@
            </div>
            <label id="CityListLable" style="color:red;"></label>
        </div>
    </div>
</div>


问:
You need to add a reference to Mono.Android.Export.Dll when you use ExportAttribute or ExportFieldAttribute
My code works fine, but when I added fragments with a new namespace to the project, I began getting the error

You need to add a reference to Mono.Android.Export.Dll when you use ExportAttribute or ExportFieldAttribute

I've searched online and found several mentions of unlinking assemblies, but I've also read that this will cause additional errors.

Does anyone know how to solve this bug?

答: I added reference like @Jeremy Said, it's working


问:
Vim auto-generate ctags
Right now I have the following in my .vimrc:

```<code>au BufWritePost *.c,*.cpp,*.h !ctags -R
</code>```

There are a few problems with this:

It's slow -- regenerates tags for files that haven't changed since the last tag generation.

I have to push the enter button again after writing the file because of an inevitable "press Enter or type command to continue".

When you combine these two issues I end up pushing the additional enter too soon (before ctags -R has finished), then see the annoying error message, and have to push enter again.

I know it doesn't sound like a big deal, but with the amount of file writes I do on a given day it tends to get really annoying. There's gotta be a better way to do it!

答:
I've noticed this is an old thread, however...
Use incron in *nix like environments supporting inotify.  It will always launch commands whenever files in a directory change. i.e.,

```<code>/home/me/Code/c/that_program IN_DELETE,IN_CLOSE_WRITE ctags --sort=yes *.c
</code>```

That's it.

OwnerDisplayName: cdleary

Title: Vim auto-generate ctags

Body:
Right now I have the following in my .vimrc:

au BufWritePost *.c,*.cpp,*.h !ctags -R

There are a few problems with this:

It's slow -- regenerates tags for files that haven't changed since the last tag generation.

I have to push the enter button again after writing the file because of an inevitable "press Enter or type command to continue".

When you combine these two issues I end up pushing the additional enter too soon (before ctags -R has finished), then see the annoying error message, and have to push enter again.

I know it doesn't sound like a big deal, but with the amount of file writes I do on a given day it tends to get really annoying. There's gotta be a better way to do it!

Body:
I've noticed this is an old thread, however...
Use incron in *nix like environments supporting inotify.  It will always launch commands whenever files in a directory change. i.e.,

/home/me/Code/c/that_program IN_DELETE,IN_CLOSE_WRITE ctags --sort=yes *.c

That's it.


问:
Ranking an array's values from 1 to 10, java?
I am trying to rank an array's values into another array.
So the array1, the values(e.g array1[3]) needs to be ranked according to the size of the value and then needs to be assigned to a value from 1 to 10 depending on the size of the number. Ranked between 1 and 10.

I have tried doing selection sort:

```<code>public static int[] doSelectionSort(int[] arr){

for (int i = 1; i < arr.length; i++)
{
    int index = i;
    for (int j = i + 1; j < arr.length - 1; j++)
        if (arr[j] < arr[index])
            index = j;

    int smallerNumber = arr[index];
    arr[index] = arr[i];
    arr[i] = smallerNumber;

}
</code>```

Other than that, I dunno where to go. I tried 2d arrays but that's confusing.
The array1 would be shown in a column on the GUI screen but in a random order according to the program. But the ranking will be shown besides each value from the array1 column in the GUI. The ranking does not need to be shown in order but needs to rank the array1 values and shown besides the value on the next column on the screen.

答:
You can iterate over array1 and store its values in a TreeMap as a key and the iterating counter(array index here) as its value.
TreeMap will sort itself based on the keys provided; you can iterate over the TreeMap and print the values, these are your corresponding ranks.

```<code>int[] array1 = new int[]{10, 22, 45, 6, 7, 25};
TreeMap<Integer,Integer> map = new TreeMap<>();
for(int i=0;i<array1.length;i++) {
    map.put(array1[i],i);
}
for(int value : map.values()) {
    //print ranks in order of array values
    System.out.println(value);
}
</code>```

Body:
I am trying to rank an array's values into another array.
So the array1, the values(e.g array1[3]) needs to be ranked according to the size of the value and then needs to be assigned to a value from 1 to 10 depending on the size of the number. Ranked between 1 and 10.

I have tried doing selection sort:

public static int[] doSelectionSort(int[] arr){

for (int i = 1; i < arr.length; i++)
{
    int index = i;
    for (int j = i + 1; j < arr.length - 1; j++)
        if (arr[j] < arr[index])
            index = j;

    int smallerNumber = arr[index];
    arr[index] = arr[i];
    arr[i] = smallerNumber;

}

Other than that, I dunno where to go. I tried 2d arrays but that's confusing.
The array1 would be shown in a column on the GUI screen but in a random order according to the program. But the ranking will be shown besides each value from the array1 column in the GUI. The ranking does not need to be shown in order but needs to rank the array1 values and shown besides the value on the next column on the screen.

Body:
You can iterate over array1 and store its values in a TreeMap as a key and the iterating counter(array index here) as its value.
TreeMap will sort itself based on the keys provided; you can iterate over the TreeMap and print the values, these are your corresponding ranks.

int[] array1 = new int[]{10, 22, 45, 6, 7, 25};
TreeMap<Integer,Integer> map = new TreeMap<>();
for(int i=0;i<array1.length;i++) {
    map.put(array1[i],i);
}
for(int value : map.values()) {
    //print ranks in order of array values
    System.out.println(value);
}


问:
How to use pdf.js with django
pdf.js in in my static files(as shown below):

/static/js/pdf.js

And i am able to display a pdf located in static folder(as shown below):
/static/sample-pdf.pdf

but i want to be able to show a pdf located in my media folder(as a pdf should be stored as a media file in django)

media folder is in same directory as of static folder(as shown below):

project/static and
project/media

Is it possible ?

Do ask if more clarity is required.

答:
This will display your file in the html page from the directory

```<code><iframe src="../media/sample-pdf.pdf" id = "pdf" style="width:1500px; height:1500px;" frameborder="0"></iframe>
</code>```

check console of browser to check the path is right if its not showing. Its that much simple

Title: How to use pdf.js with django

Body:
This will display your file in the html page from the directory

<iframe src="../media/sample-pdf.pdf" id = "pdf" style="width:1500px; height:1500px;" frameborder="0"></iframe>

check console of browser to check the path is right if its not showing. Its that much simple


问:
How Pass parameters and access them in javascript
```<code><html>
<body>
<form action="">
<script>
 for(i=0;i<50;i++)
 {
  document.writeln("<input type='button' value ='"+i+"'        onclick='clicked(i)'/>");

 }
function clicked(Number x)
{
 alert("selected:" +x);
}
</script>
</form>
</body>
</html>
</code>```

I want to know which button is selected in this code how to perform that please can someone help me

答:
I hope this will work for you

<!DOCTYPE html>

Click the button to know its value.

<button value="1" onclick="myFunction(this.value)">A</button>
<button value="2" onclick="myFunction(this.value)">B</button>
<button value="3" onclick="myFunction(this.value)">C</button>

```

Body:
<form action="">

</form>

I want to know which button is selected in this code how to perform that please can someone help me

Body:
I hope this will work for you

<!DOCTYPE html>
<html>
<body>

<p>Click the button to know its value.</p>

<button value="1" onclick="myFunction(this.value)">A</button>
<button value="2" onclick="myFunction(this.value)">B</button>
<button value="3" onclick="myFunction(this.value)">C</button>

<script>
function myFunction(value) {
 alert(value);
}
</script>

</body>
</html>


问:
VB InputBox Validation Inquiry
I know InputBox isn't the best for validation, but that was one of the specifications on the program I am writing for class. My problem is that despite the if or case statements I make to validate the data entered, it still accepts the data while simultaneously displaying the MsgBox's I have in my code..

Essentially what I would like the case statement to do is to properly filter the data that is entered and not proceed onto the next floor if the data is invalid and request that new data be entered. If the data is valid, proceed onto the next floor.

```<code>    Const ROOMS As Integer = 30
    Const MAX_FLOOR As Integer = 16
    Dim floor As Integer
    Dim StrOccupancy As String
    Dim occupancy As Integer
    Dim occupancyRate As Double
    Dim occupancySum As Integer
    Dim overallRate As Double

    lblOccupancyRate.Text = String.Empty
    lblRoomsOccupied.Text = String.Empty
    output.Items.Clear()

    For floor = 1 To MAX_FLOOR
        If floor = 13 Then
            Continue For

        End If

        StrOccupancy = Integer.TryParse(InputBox("Enter the number of rooms occupied for floor:" & Space(1) & floor), occupancy)

        Select Case occupancy
            Case < 1
                MsgBox("Please enter a number of 1 or more occupants.")
            Case > 30
                MsgBox("Amount of occupants must be between 1-30.")
            Case >= 1 And occupancy <= 30

                occupancyRate = (occupancy / ROOMS)
                occupancySum += occupancy
                overallRate = occupancySum / (ROOMS * 15)

        End Select
        output.Items.Add("Floor: " & floor & " Rooms Occupied: " & occupancy _
                            & " Occupancy Rate: " & occupancyRate.ToString("P2"))
            lblRoomsOccupied.Text = occupancySum.ToString
            lblOccupancyRate.Text = overallRate.ToString("P2")

    Next
    output.Items.Add("")
    output.Items.Add("Total occupancy is" & Space(1) & occupancySum & Space(1) & "and" & Space(1) & overallRate.ToString("P2") & Space(1) & " of rooms are full.")
End Sub
</code>```

答:
Had a little time to check your code and actually you need a Boolean that validates if the occupancy requirements are met and loop if not. The code would be something like this:

```<code>    For floor = 1 To MAX_FLOOR
        'Boolean to validate the occupancy meet the requirements
        Dim goodOccupancy As Boolean = False
        'Do loop enters at least 1 time and runs the code inside it
        Do

            Integer.TryParse(InputBox("Enter the number of rooms occupied for floor:" & Space(1) & floor), occupancy)

            Select Case occupancy
                Case < 1
                    MsgBox("Please enter a number of 1 or more occupants.")
                Case > 30
                    MsgBox("Amount of occupants must be between 1-30.")
                Case >= 1 And occupancy <= 30

                    occupancyRate = (occupancy / ROOMS)
                    occupancySum += occupancy
                    overallRate = occupancySum / (ROOMS * 15)
                    'If the requirements are met we change the Boolean value to continue with the execution
                    goodOccupancy = True
            End Select
            'We loop if the requirements are not met
        Loop Until goodOccupancy = True
        output.Items.Add("Floor: " & floor & " Rooms Occupied: " & occupancy _
                        & " Occupancy Rate: " & occupancyRate.ToString("P2"))
        lblRoomsOccupied.Text = occupancySum.ToString
        lblOccupancyRate.Text = overallRate.ToString("P2")

    Next
</code>```

But please next time try to be more explicit with your code. Most of people won't check what is going on. Do not expect people to solve your problems without guidance. Please read the How to ask guide it will give you a light to use the site as it is supposed to be used

Title: VB InputBox Validation Inquiry

Body:
I know InputBox isn't the best for validation, but that was one of the specifications on the program I am writing for class. My problem is that despite the if or case statements I make to validate the data entered, it still accepts the data while simultaneously displaying the MsgBox's I have in my code..

Essentially what I would like the case statement to do is to properly filter the data that is entered and not proceed onto the next floor if the data is invalid and request that new data be entered. If the data is valid, proceed onto the next floor.

    Const ROOMS As Integer = 30
    Const MAX_FLOOR As Integer = 16
    Dim floor As Integer
    Dim StrOccupancy As String
    Dim occupancy As Integer
    Dim occupancyRate As Double
    Dim occupancySum As Integer
    Dim overallRate As Double

    lblOccupancyRate.Text = String.Empty
    lblRoomsOccupied.Text = String.Empty
    output.Items.Clear()

    For floor = 1 To MAX_FLOOR
        If floor = 13 Then
            Continue For

        End If

        StrOccupancy = Integer.TryParse(InputBox("Enter the number of rooms occupied for floor:" & Space(1) & floor), occupancy)

        Select Case occupancy
            Case < 1
                MsgBox("Please enter a number of 1 or more occupants.")
            Case > 30
                MsgBox("Amount of occupants must be between 1-30.")
            Case >= 1 And occupancy <= 30

                occupancyRate = (occupancy / ROOMS)
                occupancySum += occupancy
                overallRate = occupancySum / (ROOMS * 15)

        End Select
        output.Items.Add("Floor: " & floor & " Rooms Occupied: " & occupancy _
                            & " Occupancy Rate: " & occupancyRate.ToString("P2"))
            lblRoomsOccupied.Text = occupancySum.ToString
            lblOccupancyRate.Text = overallRate.ToString("P2")

    Next
    output.Items.Add("")
    output.Items.Add("Total occupancy is" & Space(1) & occupancySum & Space(1) & "and" & Space(1) & overallRate.ToString("P2") & Space(1) & " of rooms are full.")
End Sub

Body:
Had a little time to check your code and actually you need a Boolean that validates if the occupancy requirements are met and loop if not. The code would be something like this:

    For floor = 1 To MAX_FLOOR
        'Boolean to validate the occupancy meet the requirements
        Dim goodOccupancy As Boolean = False
        'Do loop enters at least 1 time and runs the code inside it
        Do

            Integer.TryParse(InputBox("Enter the number of rooms occupied for floor:" & Space(1) & floor), occupancy)

            Select Case occupancy
                Case < 1
                    MsgBox("Please enter a number of 1 or more occupants.")
                Case > 30
                    MsgBox("Amount of occupants must be between 1-30.")
                Case >= 1 And occupancy <= 30

                    occupancyRate = (occupancy / ROOMS)
                    occupancySum += occupancy
                    overallRate = occupancySum / (ROOMS * 15)
                    'If the requirements are met we change the Boolean value to continue with the execution
                    goodOccupancy = True
            End Select
            'We loop if the requirements are not met
        Loop Until goodOccupancy = True
        output.Items.Add("Floor: " & floor & " Rooms Occupied: " & occupancy _
                        & " Occupancy Rate: " & occupancyRate.ToString("P2"))
        lblRoomsOccupied.Text = occupancySum.ToString
        lblOccupancyRate.Text = overallRate.ToString("P2")

    Next

But please next time try to be more explicit with your code. Most of people won't check what is going on. Do not expect people to solve your problems without guidance. Please read the How to ask guide it will give you a light to use the site as it is supposed to be used


问:
Mahapps title bar change color when application lost focus
I define Title bar color:

```<code><Controls:MetroWindow
...

WindowTitleBrush="Red"
</code>```

But when the application lost focus this color always changed into Gray, is it possible to stop it ?

答:
Its Working on Latest Version also

```<code><Controls:MetroWindow...
.
.
xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
WindowTitleBrush="Red"
</code>```

Body:
I define Title bar color:

<Controls:MetroWindow
...

WindowTitleBrush="Red"

But when the application lost focus this color always changed into Gray, is it possible to stop it ?

Body:
Its Working on Latest Version also

<Controls:MetroWindow...
.
.
xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
WindowTitleBrush="Red"


问:
How to solve git messy code?
I am using "Git log" in Android Studio.

Why my terminal command showed messy code?

And how to solve it?

答:
Launch your Android Studio from a session where your LC_* variable are correctly set.

See "how to show different language characters in git log?" as an example.

If the Android Studio inherit those environment variable, it has a better chance to display unicode characters.

Title: How to solve git messy code?


问:
Javascript: Nested Callbacks/MySQL Results
I am sure this is a basic question, but I have been searching google for awhile and can't find a satisfactory answer..

I am used to programming MySQL select queries in PHP and simply grabbing a result, looping through each row, and within the loop doing further queries based on the column values of each individual row.

However, I'm working with javascript server side code now that relies on a SQL object where you pass the query and then a callback function that will be invoked after the query is run.

I'm confused with some of the scoping issues and how to best cleanly do this. For example, I don't want to do something like:

```<code>SQL.query("select * from blah", function(result) {
  for(var i = 0; i < result.length; i++) {
    SQL.query("select * from blah2 where i =" + result[i].property, function(result2) {
      //now how do I access result from here? I know this isn't scoped correctly
    });
  }
});
</code>```

What is the standard way to write this style of nested SQL query and not have scoping issues/messy code? Thanks!

答:
As others have pointed out result actually will be available all the way down in the nested callback.

But there is a very tricky part to this:

...Because the nested query runs asynchronously, your code will actually fire off a bunch of parallel queries -- one for each row in result -- all running at the same time (!).  This is almost certainly not what you want; and unless result is very small indeed, all the simultaneous queries will use up all your available db connections rather quickly.

To remedy this, you might use something like this:

```<code>SQL.query("select * from blah", function(result) {
    handleBlahRow( result, 0 );
});

function handleBlahRow( result, i ) {
    if( !result || (i >= result.length)) return;

    SQL.query("select * from blah2 where i =" + result[i].property, function(result2) {
        // kick off the next query
        handleBlahRow( result, i+1 );

        // result, i, *and* result2 are all accessible here.
        // do whatever you need to do with them
    });
});
</code>```

The above will run your nested queries 1-at-a-time.  It's fairly easy to adapt the above to introduce limited parallelism (eg. 4-at-a-time), if you want it -- though it's probably not necessary.

Body:
I am sure this is a basic question, but I have been searching google for awhile and can't find a satisfactory answer..

I am used to programming MySQL select queries in PHP and simply grabbing a result, looping through each row, and within the loop doing further queries based on the column values of each individual row.

However, I'm working with javascript server side code now that relies on a SQL object where you pass the query and then a callback function that will be invoked after the query is run.

I'm confused with some of the scoping issues and how to best cleanly do this. For example, I don't want to do something like:

SQL.query("select * from blah", function(result) {
  for(var i = 0; i < result.length; i++) {
    SQL.query("select * from blah2 where i =" + result[i].property, function(result2) {
      //now how do I access result from here? I know this isn't scoped correctly
    });
  }
});

What is the standard way to write this style of nested SQL query and not have scoping issues/messy code? Thanks!

Body:
As others have pointed out result actually will be available all the way down in the nested callback.

But there is a very tricky part to this:

...Because the nested query runs asynchronously, your code will actually fire off a bunch of parallel queries -- one for each row in result -- all running at the same time (!).  This is almost certainly not what you want; and unless result is very small indeed, all the simultaneous queries will use up all your available db connections rather quickly.

To remedy this, you might use something like this:

SQL.query("select * from blah", function(result) {
    handleBlahRow( result, 0 );
});

function handleBlahRow( result, i ) {
    if( !result || (i >= result.length)) return;

    SQL.query("select * from blah2 where i =" + result[i].property, function(result2) {
        // kick off the next query
        handleBlahRow( result, i+1 );

        // result, i, *and* result2 are all accessible here.
        // do whatever you need to do with them
    });
});

The above will run your nested queries 1-at-a-time.  It's fairly easy to adapt the above to introduce limited parallelism (eg. 4-at-a-time), if you want it -- though it's probably not necessary.


问:
In my mvc full calendar, events are not getting displayed
I am facing a problem in rendering events from a SQL Server database. All events are getting fetched using this code but not getting displayed in my calendar, so can anyone please help me?

.cshtml code:

```<code> events: function(start, end, callback) {
                debugger;
                 var startdate=start.format('DD-MM-YYYY HH:mm'),
                     enddate=end.format('DD-MM-YYYY HH:mm'),
                     params={'start_time':startdate,'end_time':enddate};
                 $.ajax({

                type: 'GET',

                url: '@Url.Action("GetAllEvents","Base")',

                success: function (data) {
                        alert("hello");
                        }
            });
            }
            ,
</code>```

my controller code:

```<code>public static List<Task_has_UsersModel> LoadAllTasks(double start, double end)
    {
        var fromDate = ConvertFromUnixTimestamp(start);
        var toDate = ConvertFromUnixTimestamp(end);

        var sql = "SELECT * from task_has_users";
        var data = Database.Open("DefaultConnection").Query(sql);
        List<Task_has_UsersModel> result = new List<Task_has_UsersModel>();
        foreach (var item in data)
        {
            Task_has_UsersModel model = new Task_has_UsersModel();
            model.Task_Id = Convert.ToInt32(item.Task_Id);
            model.Project_Id = Convert.ToInt32(item.Project_Id);
            model.start_time = item.start_time;
            model.end_time = item.end_time;
            result.Add(model);
        }
        return result;
    }
    [HttpPost]
    public JsonResult GetAllEvents(double start, double end)
    {
        var ApptListForDate = LoadAllTasks(start,end);
        var eventList = from e in ApptListForDate
                        select new
                        {
                           id=e.Task_Id,
                           name=e.Project_Id,
                           start=e.start_time.ToString(),
                           end=e.end_time.ToString(),
                           allDay=false,
                           color = "#008000",
                           //allDay=false,
                           className= "label-important" ,
                        };
        var rows = eventList.ToArray();
        return Json(rows, JsonRequestBehavior.AllowGet);
    }

    private static DateTime ConvertFromUnixTimestamp(double timestamp)
        {
            var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return origin.AddSeconds(timestamp);
        }

    }
</code>```

I have tried with (double start,double end ) still my events are not getting displayed in calendar

答:
Finally after 3 days of hard work , i have done this.... No need to write anything in events , just call a function , it will automatically appends the date range and all you are done................... thanks

.cshtml code:

```<code>events:'GetAllEvents',

        eventLimit: 50,
        editable: true,
        droppable: true,

       // timeFormat: 'hh:mm-h:mma ',
        timeFormat: 'hh:mma ',
         displayEventEnd : true,
</code>```

my controller code:

```<code>public static List<Task_has_UsersModel> LoadAllTasks(string start, string       end,string uname)
{

    UsersContext db = new UsersContext();

    var uid = (from i in db.UserProfiles
               where i.UserName == uname
               select i.UserId).FirstOrDefault();
    int userId = Convert.ToInt32(uid);
   // var culture = System.Globalization.CultureInfo.CurrentCulture;
    var sql = "SELECT * from task_has_users where UserId = " + userId;
    var data = Database.Open("DefaultConnection").Query(sql);

    List<Task_has_UsersModel> result = new List<Task_has_UsersModel>();
    foreach (var item in data)
    {
        Task_has_UsersModel model = new Task_has_UsersModel();
        model.Task_Id = Convert.ToInt32(item.Task_Id);
        model.Project_Id = Convert.ToInt32(item.ProjectId);
      //  model.start_time = Convert.ToDateTime(item.start_time);
        model.start_time = (item.start_time).ToString("yyyy-MM-dd HH-mm-ss");
        model.end_time =  (item.end_time).ToString("yyyy-MM-dd HH-mm-ss");
        model.title = item.title;
        result.Add(model);
    }
    return result;
}
[HttpGet]
public JsonResult GetAllEvents(string start, string end)
{
    string uname = (Session["UserName"]).ToString();
    var ApptListForDate = LoadAllTasks(start,end,uname);
    var eventList = from e in ApptListForDate
                    select new
                    {
                       id=e.Task_Id,
                       title=e.title,
                       start=e.start_time,
                       end=e.end_time,
                       allDay=false,
                       color = "#008000",
                       //allDay=false,
                       className= "label-important" ,
                    };
    var rows = eventList.ToArray();

    return Json(rows, JsonRequestBehavior.AllowGet);
}
</code>```

finally done

Body:
I am facing a problem in rendering events from a SQL Server database. All events are getting fetched using this code but not getting displayed in my calendar, so can anyone please help me?

.cshtml code:

 events: function(start, end, callback) {
                debugger;
                 var startdate=start.format('DD-MM-YYYY HH:mm'),
                     enddate=end.format('DD-MM-YYYY HH:mm'),
                     params={'start_time':startdate,'end_time':enddate};
                 $.ajax({

                type: 'GET',

                url: '@Url.Action("GetAllEvents","Base")',

                success: function (data) {
                        alert("hello");
                        }
            });
            }
            ,

my controller code:

public static List<Task_has_UsersModel> LoadAllTasks(double start, double end)
    {
        var fromDate = ConvertFromUnixTimestamp(start);
        var toDate = ConvertFromUnixTimestamp(end);

        var sql = "SELECT * from task_has_users";
        var data = Database.Open("DefaultConnection").Query(sql);
        List<Task_has_UsersModel> result = new List<Task_has_UsersModel>();
        foreach (var item in data)
        {
            Task_has_UsersModel model = new Task_has_UsersModel();
            model.Task_Id = Convert.ToInt32(item.Task_Id);
            model.Project_Id = Convert.ToInt32(item.Project_Id);
            model.start_time = item.start_time;
            model.end_time = item.end_time;
            result.Add(model);
        }
        return result;
    }
    [HttpPost]
    public JsonResult GetAllEvents(double start, double end)
    {
        var ApptListForDate = LoadAllTasks(start,end);
        var eventList = from e in ApptListForDate
                        select new
                        {
                           id=e.Task_Id,
                           name=e.Project_Id,
                           start=e.start_time.ToString(),
                           end=e.end_time.ToString(),
                           allDay=false,
                           color = "#008000",
                           //allDay=false,
                           className= "label-important" ,
                        };
        var rows = eventList.ToArray();
        return Json(rows, JsonRequestBehavior.AllowGet);
    }

    private static DateTime ConvertFromUnixTimestamp(double timestamp)
        {
            var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return origin.AddSeconds(timestamp);
        }

    }

I have tried with (double start,double end ) still my events are not getting displayed in calendar

Body:
Finally after 3 days of hard work , i have done this.... No need to write anything in events , just call a function , it will automatically appends the date range and all you are done................... thanks

.cshtml code:

events:'GetAllEvents',

        eventLimit: 50,
        editable: true,
        droppable: true,

       // timeFormat: 'hh:mm-h:mma ',
        timeFormat: 'hh:mma ',
         displayEventEnd : true,

my controller code:

public static List<Task_has_UsersModel> LoadAllTasks(string start, string       end,string uname)
{

    UsersContext db = new UsersContext();

    var uid = (from i in db.UserProfiles
               where i.UserName == uname
               select i.UserId).FirstOrDefault();
    int userId = Convert.ToInt32(uid);
   // var culture = System.Globalization.CultureInfo.CurrentCulture;
    var sql = "SELECT * from task_has_users where UserId = " + userId;
    var data = Database.Open("DefaultConnection").Query(sql);

    List<Task_has_UsersModel> result = new List<Task_has_UsersModel>();
    foreach (var item in data)
    {
        Task_has_UsersModel model = new Task_has_UsersModel();
        model.Task_Id = Convert.ToInt32(item.Task_Id);
        model.Project_Id = Convert.ToInt32(item.ProjectId);
      //  model.start_time = Convert.ToDateTime(item.start_time);
        model.start_time = (item.start_time).ToString("yyyy-MM-dd HH-mm-ss");
        model.end_time =  (item.end_time).ToString("yyyy-MM-dd HH-mm-ss");
        model.title = item.title;
        result.Add(model);
    }
    return result;
}
[HttpGet]
public JsonResult GetAllEvents(string start, string end)
{
    string uname = (Session["UserName"]).ToString();
    var ApptListForDate = LoadAllTasks(start,end,uname);
    var eventList = from e in ApptListForDate
                    select new
                    {
                       id=e.Task_Id,
                       title=e.title,
                       start=e.start_time,
                       end=e.end_time,
                       allDay=false,
                       color = "#008000",
                       //allDay=false,
                       className= "label-important" ,
                    };
    var rows = eventList.ToArray();

    return Json(rows, JsonRequestBehavior.AllowGet);
}

finally done