问:
Can't compile PrimeFaces demo
I downloaded the PF demo from git at: https://github.com/primefaces/showcase

And run mvn package, but received the following message:

```<code> martin@MyUbuntu:~/study/PrimeFaces/showcase$ mvn package
    [INFO] Scanning for projects...
    [INFO]
    [INFO] ------------------------------------------------------------------------
    [INFO] Building primefaces-showcase 6.0-SNAPSHOT
    [INFO] ------------------------------------------------------------------------
    Downloading: http://repository.primefaces.org/org/primefaces/themes/all-themes/1.0.10/all-themes-1.0.10.pom
    Downloaded: http://repository.primefaces.org/org/primefaces/themes/all-themes/1.0.10/all-themes-1.0.10.pom (10 KB at 8.7 KB/sec)
    Downloading: http://repository.primefaces.org/org/primefaces/themes/themes-project/1.0.10/themes-project-1.0.10.pom
    Downloaded: http://repository.primefaces.org/org/primefaces/themes/themes-project/1.0.10/themes-project-1.0.10.pom (4 KB at 8.1 KB/sec)
    Downloading: http://repository.primefaces.org/org/primefaces/primefaces/6.0-SNAPSHOT/maven-metadata.xml
    Downloading: http://repository.primefaces.org/org/primefaces/primefaces/6.0-SNAPSHOT/primefaces-6.0-SNAPSHOT.pom
    [WARNING] The POM for org.primefaces:primefaces:jar:6.0-SNAPSHOT is missing, no dependency information available
    Downloading: http://repository.primefaces.org/org/primefaces/themes/all-themes/1.0.10/all-themes-1.0.10.jar
    Downloading: http://repository.primefaces.org/org/primefaces/primefaces/6.0-SNAPSHOT/primefaces-6.0-SNAPSHOT.jar
    Downloaded: http://repository.primefaces.org/org/primefaces/themes/all-themes/1.0.10/all-themes-1.0.10.jar (1335 KB at 72.0 KB/sec)
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD FAILURE
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 21.563 s
    [INFO] Finished at: 2016-03-08T16:30:14-08:00
    [INFO] Final Memory: 11M/153M
    [INFO] ------------------------------------------------------------------------
    [ERROR] Failed to execute goal on project showcase: Could not resolve dependencies for project org.primefaces:showcase:war:6.0-SNAPSHOT: Could not find artifact org.primefaces:primefaces:jar:6.0-SNAPSHOT in prime-repo (http://repository.primefaces.org) -> [Help 1]
    [ERROR]
    [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
    [ERROR] Re-run Maven using the -X switch to enable full debug logging.
    [ERROR]
    [ERROR] For more information about the errors and possible solutions, please read the following articles:
    [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException
</code>```

答:
In your pom.xml file under <id>dev</id> fill in the correct version you find at https://repository.primefaces.org/org/primefaces/primefaces/

For the latest build as of today:

```<code><dependency>
  <groupId>org.primefaces</groupId>
  <artifactId>primefaces</artifactId>
  <version>6.1.RC2</version>
</dependency>
</code>```

Title: Can't compile PrimeFaces demo

Body:
I downloaded the PF demo from git at: https://github.com/primefaces/showcase

And run mvn package, but received the following message:

 martin@MyUbuntu:~/study/PrimeFaces/showcase$ mvn package
    [INFO] Scanning for projects...
    [INFO]
    [INFO] ------------------------------------------------------------------------
    [INFO] Building primefaces-showcase 6.0-SNAPSHOT
    [INFO] ------------------------------------------------------------------------
    Downloading: http://repository.primefaces.org/org/primefaces/themes/all-themes/1.0.10/all-themes-1.0.10.pom
    Downloaded: http://repository.primefaces.org/org/primefaces/themes/all-themes/1.0.10/all-themes-1.0.10.pom (10 KB at 8.7 KB/sec)
    Downloading: http://repository.primefaces.org/org/primefaces/themes/themes-project/1.0.10/themes-project-1.0.10.pom
    Downloaded: http://repository.primefaces.org/org/primefaces/themes/themes-project/1.0.10/themes-project-1.0.10.pom (4 KB at 8.1 KB/sec)
    Downloading: http://repository.primefaces.org/org/primefaces/primefaces/6.0-SNAPSHOT/maven-metadata.xml
    Downloading: http://repository.primefaces.org/org/primefaces/primefaces/6.0-SNAPSHOT/primefaces-6.0-SNAPSHOT.pom
    [WARNING] The POM for org.primefaces:primefaces:jar:6.0-SNAPSHOT is missing, no dependency information available
    Downloading: http://repository.primefaces.org/org/primefaces/themes/all-themes/1.0.10/all-themes-1.0.10.jar
    Downloading: http://repository.primefaces.org/org/primefaces/primefaces/6.0-SNAPSHOT/primefaces-6.0-SNAPSHOT.jar
    Downloaded: http://repository.primefaces.org/org/primefaces/themes/all-themes/1.0.10/all-themes-1.0.10.jar (1335 KB at 72.0 KB/sec)
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD FAILURE
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 21.563 s
    [INFO] Finished at: 2016-03-08T16:30:14-08:00
    [INFO] Final Memory: 11M/153M
    [INFO] ------------------------------------------------------------------------
    [ERROR] Failed to execute goal on project showcase: Could not resolve dependencies for project org.primefaces:showcase:war:6.0-SNAPSHOT: Could not find artifact org.primefaces:primefaces:jar:6.0-SNAPSHOT in prime-repo (http://repository.primefaces.org) -> [Help 1]
    [ERROR]
    [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
    [ERROR] Re-run Maven using the -X switch to enable full debug logging.
    [ERROR]
    [ERROR] For more information about the errors and possible solutions, please read the following articles:
    [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException

Body:
In your pom.xml file under <id>dev</id> fill in the correct version you find at https://repository.primefaces.org/org/primefaces/primefaces/

For the latest build as of today:

<dependency>
  <groupId>org.primefaces</groupId>
  <artifactId>primefaces</artifactId>
  <version>6.1.RC2</version>
</dependency>


来源: stackexchange

问:
How to open link in new tab from left side of current tab?
I'm working on an HTML project, and I can't find out how to open the new link from left side of the current tab, its by default open from right side, so I want to open in a new tab from left side. Any ideas please ??

```<code><a href="#" target="_blank">Link</a>
</code>```

答:
```<code><html>
    <head></head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
       $('#link').click(function(){
           var win = window.open('demo.html', '_blank');
           win.focus(); // opens current page in new tab
       });
    });
    </script>
    <body>
        <a id="link" href="new.html" target="_top">Ads link</a>
    </body>
</html>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm working on an HTML project, and I can't find out how to open the new link from left side of the current tab, its by default open from right side, so I want to open in a new tab from left side. Any ideas please ??

Link

ContentLicense: CC BY-SA 3.0


问:
Show white header show when navigate page in Ionic
When I navigate from one page to another in place of header show white header(Reload header) every time.

I remove cache: false from every piece of code, but still it shows.

Please help me. It's annoying.

答:
I simply use below CSS code and my problem solved :)</p>

```<code>ion-view{
 background-color: #2f354a !important; //use color which is used in header color
}
</code>```

Body:
I simply use below CSS code and my problem solved :)

ion-view{
 background-color: #2f354a !important; //use color which is used in header color
}


问:
Supress the intersection of two dataframe
I understand it is basic in python but I didn't find a proper way to do the following thing...

I have 2 dataframe made of dates.
The first one contain 300 dates arround, the second contain 20 dates arround.

I want to create a new dataframe made of the 300 dates without the 20 contained in the second dataframe.

```<code>[in] Dates1
[out]
1    2017-03-10
2    2017-03-09
3    2017-03-08
4    2017-03-07
5    2017-03-06
6    2017-03-03
7    2017-03-02
8    2017-03-01
9    2017-02-28
10   2017-02-27
etc...

[in] Dates2
[out]
 1    2017-03-03
 2    2017-03-01

expectedResult
[out]
1    2017-03-10
2    2017-03-09
3    2017-03-08
4    2017-03-07
5    2017-03-06
6    2017-03-02
7    2017-02-28
8    2017-02-27
</code>```

Thank you very much!

Body:
I understand it is basic in python but I didn't find a proper way to do the following thing...

I have 2 dataframe made of dates.
The first one contain 300 dates arround, the second contain 20 dates arround.

I want to create a new dataframe made of the 300 dates without the 20 contained in the second dataframe.

[in] Dates1
[out]
1    2017-03-10
2    2017-03-09
3    2017-03-08
4    2017-03-07
5    2017-03-06
6    2017-03-03
7    2017-03-02
8    2017-03-01
9    2017-02-28
10   2017-02-27
etc...

[in] Dates2
[out]
 1    2017-03-03
 2    2017-03-01

expectedResult
[out]
1    2017-03-10
2    2017-03-09
3    2017-03-08
4    2017-03-07
5    2017-03-06
6    2017-03-02
7    2017-02-28
8    2017-02-27

Thank you very much!

Body:
Using ~isin

Dates1.loc[~Dates1.iloc[:, 0].isin(Dates2.iloc[:, 0])]

            1
0
1  2017-03-10
2  2017-03-09
3  2017-03-08
4  2017-03-07
5  2017-03-06
7  2017-03-02
9  2017-02-28
10 2017-02-27


问:
How can I pass a return value of a Function to another Function as Parameter?
How to pass a value returned by one function to another function.

```<code>function myFunction(){
    $a = "Hello World";
    return $a;
}

function anotherFunction(????){
    //how can I call the return value of myFunction() as parameter in this function?
}
</code>```

答:
You can use this call to pass return to another:

```<code>anotherFunction(myFunction());
</code>```

And anotherFunction you need declare as below:

```<code>function anotherFunction($val) {
    // your code here
}
</code>```

This will pass return value of myFunction into $val parameter.

Hope this help you!

Body:
How to pass a value returned by one function to another function.

function myFunction(){
    $a = "Hello World";
    return $a;
}

function anotherFunction(????){
    //how can I call the return value of myFunction() as parameter in this function?
}

Body:
You can use this call to pass return to another:

anotherFunction(myFunction());

And anotherFunction you need declare as below:

function anotherFunction($val) {
    // your code here
}

This will pass return value of myFunction into $val parameter.

Hope this help you!


问:
How can I count number of clicks anywhere on screen in C#?
I am trying to have a C# program running in the background on Windows that will print "Hello!" after seeing that the user has clicked his or her mouse 10 times. But not just in the console window, anywhere on the screen.

The following event handler for click-tracking is from msdn.microsoft.com:

```<code>private void OnMouseDownClickCount(object sender, MouseButtonEventArgs e) {
    // Checks the number of clicks.
    if (e.ClickCount == 1) {
        // Single Click occurred.
        lblClickCount.Content = "Single Click";
    }
    if (e.ClickCount == 2) {
        // Double Click occurred.
        lblClickCount.Content = "Double Click";
    }
    if (e.ClickCount >= 3) {
        // Triple Click occurred.
        lblClickCount.Content = "Triple Click";
    }
}
</code>```

But, I'm not sure how to actually use this. When I add this function anywhere, the MouseButtonEventArgs type is undefined.

What "using" statements do I need? How do I actually get this code to run properly -- do I call it once from main? What do I do to call it?

EDIT: Here is a picture showing Visual Studio not understanding MouseButtonEventArgs:

答:
Initially You have to select the form and go to properties, Here you have to go events area and there is MouseClick event. Click that Mouse click. Go to Code behind window. there is the click event generated automatically. In that Form_MouseClick event you can count the number of clicks.

Initially declare a variable

```<code>int count = 0;
</code>```

In method

```<code>Private void Form_MouseClick(object sender, MouseEventArgs e)
{
    count++;
    //add lable which will displays the count value
    label.Text=count.ToString();
}
</code>```

I think which will helps to count the clicks in the form.

Body:
I am trying to have a C# program running in the background on Windows that will print "Hello!" after seeing that the user has clicked his or her mouse 10 times. But not just in the console window, anywhere on the screen.

The following event handler for click-tracking is from msdn.microsoft.com:

private void OnMouseDownClickCount(object sender, MouseButtonEventArgs e) {
    // Checks the number of clicks.
    if (e.ClickCount == 1) {
        // Single Click occurred.
        lblClickCount.Content = "Single Click";
    }
    if (e.ClickCount == 2) {
        // Double Click occurred.
        lblClickCount.Content = "Double Click";
    }
    if (e.ClickCount >= 3) {
        // Triple Click occurred.
        lblClickCount.Content = "Triple Click";
    }
}

But, I'm not sure how to actually use this. When I add this function anywhere, the MouseButtonEventArgs type is undefined.

What "using" statements do I need? How do I actually get this code to run properly -- do I call it once from main? What do I do to call it?

EDIT: Here is a picture showing Visual Studio not understanding MouseButtonEventArgs:

Body:
Initially You have to select the form and go to properties, Here you have to go events area and there is MouseClick event. Click that Mouse click. Go to Code behind window. there is the click event generated automatically. In that Form_MouseClick event you can count the number of clicks.

Initially declare a variable

int count = 0;

In method

Private void Form_MouseClick(object sender, MouseEventArgs e)
{
    count++;
    //add lable which will displays the count value
    label.Text=count.ToString();
}

I think which will helps to count the clicks in the form.


问:
Convert string to int[,]
I have weird requirement in matrix clustering.

My inputs are like

```<code>string param = "1100,1110,0110,0001";
</code>```

and what I want is

```<code> var matrix = new[,]
        {
              {1,1,0,0},
              {1,1,1,0},
              {0,1,1,0},
              {0,0,0,1}
        };
</code>```

so It should be array of int[4,4].

What I tried?

I tried many ways for this conversation.

First Of all I convert my string to string[], using below code.

```<code>string[] resultantArray = param.Split(',').ToArray();
</code>```

And then I tried to convert my string[] to int[], using below code.

```<code>var intArray = resultantArray .Select(int.Parse).ToArray();
</code>```

but I ended up with removed leading zeros.

Is there any way,
 I can achieve int[4,4] array from string?

答:
I have modified the answers of Vandita and added some code from the answer of Santosh.

Also I checked for the highest length of resultantArray.

```<code> string param = "1100,1110,0110,0001";
 string[] resultantArray = param.Split(',').ToArray();

  var max = resultantArray.OrderByDescending(s => s.Length).First();

  int n = resultantArray.Length;
  int m = max.Length;

  var matrix = new int[n, m];

  for (int i = 0; i < resultantArray.Count(); i++)
  {
     string str = resultantArray[i];
     char[] allChars = str.ToCharArray();
     for (int j = 0; j < allChars.Count(); j++)
     {
          matrix[i, j] = Convert.ToInt32(allChars[j].ToString());
     }
  }
</code>```

Still, I am looking for better answers..

Title: Convert string to int[,]

Body:
I have weird requirement in matrix clustering.

My inputs are like

string param = "1100,1110,0110,0001";

and what I want is

 var matrix = new[,]
        {
              {1,1,0,0},
              {1,1,1,0},
              {0,1,1,0},
              {0,0,0,1}
        };

so It should be array of int[4,4].

What I tried?

I tried many ways for this conversation.

First Of all I convert my string to string[], using below code.

string[] resultantArray = param.Split(',').ToArray();

And then I tried to convert my string[] to int[], using below code.

var intArray = resultantArray .Select(int.Parse).ToArray();

but I ended up with removed leading zeros.

Is there any way,
 I can achieve int[4,4] array from string?

Body:
I have modified the answers of Vandita and added some code from the answer of Santosh.

Also I checked for the highest length of resultantArray.

 string param = "1100,1110,0110,0001";
 string[] resultantArray = param.Split(',').ToArray();

  var max = resultantArray.OrderByDescending(s => s.Length).First();

  int n = resultantArray.Length;
  int m = max.Length;

  var matrix = new int[n, m];

  for (int i = 0; i < resultantArray.Count(); i++)
  {
     string str = resultantArray[i];
     char[] allChars = str.ToCharArray();
     for (int j = 0; j < allChars.Count(); j++)
     {
          matrix[i, j] = Convert.ToInt32(allChars[j].ToString());
     }
  }

Still, I am looking for better answers..


问:
Change UITabBar badge color
Is it possible to change the tab bar badge color of an Objective-C iPhone app built from Xcode? It always comes in red. Can anyone direct me to sort it out?

Thanks

答:
The easiest way to set the color of badge post iOS 10

```<code>if #available(iOS 10, *)
{
    UITabBarItem.appearance().badgeColor = .green
}
</code>```

Title: Change UITabBar badge color

Body:
The easiest way to set the color of badge post iOS 10

if #available(iOS 10, *)
{
    UITabBarItem.appearance().badgeColor = .green
}


答:
You got 2 choices:

save your return value in a parameter e.g.

$value = myFunction();
anotherFunction ($value);

anotherFunction ( myFunction() );

Title: How can I pass a return value of a Function to another Function as Parameter?


问:
Is there an Android Spotify developers API?
I was looking into building an android app that utilizes the Spotify API but when i looked on this page it doesn't list an android API? is there one out there somewhere? if not are there any other streaming music services that have API's for android?

http://developer.spotify.com/en/libspotify/overview/

答: looks like there is sdk now GitHub</p>

Body: looks like there is sdk now GitHub


问:
Fetch Products Count for specific week in mysql
I have 3 tables

```<code>Orders
id | name | order_date | total
------------------------------
1  | ABCD | 2017-03-29 | 60
2  | KJHS | 2017-03-29 | 80
3  | HGGG | 2017-03-30 | 90

item_orders

id | order_id | item_id
-----------------------
1  | 1        | 1
2  | 1        | 2
3  | 2        | 1
4  | 2        | 2

items
id  | item_name  | desc | price |
---------------------------------
1   | Brown      | jdsa | 20
      Cardigan XL
---------------------------------
2   | Red Socks  | sada | 30
---------------------------------
</code>```

My Query which I have wrote is

```<code>SELECT orders.*, item_orders.item_id,items.item_name,items.description,items.price
FROM ((orders
INNER JOIN item_orders ON orders.id = item_orders.item_id)
INNER JOIN items ON item_orders.item_id = items.id)
WHERE WEEKOFYEAR(orders.order_date)=WEEKOFYEAR(NOW());
</code>```

Now I wanted to bring item_count total from orders table of current week with its total.
Something like these shows current week stats

```<code>BrownCardigan XL    12  $200
Red Socks           15  $350
</code>```

Something like these.
I am bringing data from orders table by above query and Now I am stuck of how to count the items from order table and sum of prices for the current week.

答:
you could use aggreagation function and group by </p>

```<code>  SELECT items.item_name, sum(orders.total), sum(orders.total*items.price)
  FROM orders
  INNER JOIN item_orders ON orders.id = item_orders.item_id
  INNER JOIN items ON item_orders.item_id = items.id
  WHERE WEEKOFYEAR(orders.order_date)=WEEKOFYEAR(NOW()
  GROUP BY  items.item_name
  ;
</code>```

Body:
I have 3 tables

Orders
id | name | order_date | total
------------------------------
1  | ABCD | 2017-03-29 | 60
2  | KJHS | 2017-03-29 | 80
3  | HGGG | 2017-03-30 | 90

item_orders

id | order_id | item_id
-----------------------
1  | 1        | 1
2  | 1        | 2
3  | 2        | 1
4  | 2        | 2

items
id  | item_name  | desc | price |
---------------------------------
1   | Brown      | jdsa | 20
      Cardigan XL
---------------------------------
2   | Red Socks  | sada | 30
---------------------------------

My Query which I have wrote is

SELECT orders.*, item_orders.item_id,items.item_name,items.description,items.price
FROM ((orders
INNER JOIN item_orders ON orders.id = item_orders.item_id)
INNER JOIN items ON item_orders.item_id = items.id)
WHERE WEEKOFYEAR(orders.order_date)=WEEKOFYEAR(NOW());

Now I wanted to bring item_count total from orders table of current week with its total.
Something like these shows current week stats

BrownCardigan XL    12  $200
Red Socks           15  $350

Something like these.
I am bringing data from orders table by above query and Now I am stuck of how to count the items from order table and sum of prices for the current week.

Body:
you could use aggreagation function and group by

  SELECT items.item_name, sum(orders.total), sum(orders.total*items.price)
  FROM orders
  INNER JOIN item_orders ON orders.id = item_orders.item_id
  INNER JOIN items ON item_orders.item_id = items.id
  WHERE WEEKOFYEAR(orders.order_date)=WEEKOFYEAR(NOW()
  GROUP BY  items.item_name
  ;


问:
Define Model Parameter as Variable
I am attempting to define the parameter of a model (block) as a variable. For example:

```<code>Real WallThickness = 0.5;
Real WallConductance = 10*WallThickness;
Modelica.Thermal.HeatTransfer.Components.ThermalConductor TopPanelConductor(G=WallConductance);
</code>```

I would like to define "G" so that it remains constant throughout the simulation but the coefficient is updated prior to the simulation based on the other variable "WallThickness". When defining the ThermalConductor parameter "G" as a variable in the model, which is being calculated elsewhere, I get the error message:

```<code>The variability of the definition equation:
TopPanelConductor.G = WallConductance;
is higher than the declared variability of the variables.
</code>```

I would like to define the parameters of a model as a variable. This allows me to create parametric definitions as the geometry of the all changes. Is there a way I can make this definition work?

答:
An alternative to re-writing the component models is to make the parameter study/variation outside the simulation model. There are at least three approaches:

Export your system model as an FMU (Co-simulation). Import it in Python w. PyFmi and write for loops that vary the parameter value for each iteration. See for example http://www.jmodelica.org/assimulo_home/pyfmi_1.0/pyfmi.examples.html. This is not as complicated as it might sound.

Make the parameter variation loop in a Modelica Script (mos file). I don't have much experience with this though.

If you are varying geometrical parameters in order to find an optimum of some kind you can use the Optimization Library which is shipped with Dymola (as of version 2017 FD01).

Using one of the above suggestions you can reuse all the components from MSL out of the box.

Best regards,
Rene Just Nielsen

Title: Define Model Parameter as Variable

Body:
I am attempting to define the parameter of a model (block) as a variable. For example:

Real WallThickness = 0.5;
Real WallConductance = 10*WallThickness;
Modelica.Thermal.HeatTransfer.Components.ThermalConductor TopPanelConductor(G=WallConductance);

I would like to define "G" so that it remains constant throughout the simulation but the coefficient is updated prior to the simulation based on the other variable "WallThickness". When defining the ThermalConductor parameter "G" as a variable in the model, which is being calculated elsewhere, I get the error message:

The variability of the definition equation:
TopPanelConductor.G = WallConductance;
is higher than the declared variability of the variables.

I would like to define the parameters of a model as a variable. This allows me to create parametric definitions as the geometry of the all changes. Is there a way I can make this definition work?


问:
How to play an array of audioclips to be repeated at a set delay?
This is the segment of the code in where the audio clip is played when space is held, right now it delays the initial sound but I want to be able to delay the sounds when they are repeated.

I am aware of audio.PlayDelayed but Could not figure out how to get it to work.

```<code>void AudioEnable()
{
    if (Input.GetKey(KeyCode.Space))
    {
        Invoke("Audio", audioDelay);

    }
}

void Audio()
{
    AudioSource audio = GetComponent<AudioSource>(); // play fire sounds from array when space is pressed
    audio.PlayOneShot(fireSounds[Random.Range(0, fireSounds.Length)]);
}
</code>```

I will continue looking for a solution but in the meantime help would be appreciated.

答:
Try this</p>

```<code>    void AudioEnable()
    {
        if (SoundPLaying)
            return;

        if (Input.GetKey(KeyCode.Space))
        {
            SoundPLaying = true;
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.AutoReset = true;
            timer.Interval = 1000;  //1000 milliseconds. Ajust this time to be equal to length of fire sound.

            timer.Elapsed += (s, e) => { SoundPLaying = false; timer.Dispose(); };
            timer.Start();

            Invoke("Audio", audioDelay);
        }
    }

    void Audio()
    {
        AudioSource audio = GetComponent<AudioSource>(); // play fire sounds from array when space is pressed
        audio.PlayOneShot(fireSounds[Random.Range(0, fireSounds.Length)]);
    }
</code>```

Body:
This is the segment of the code in where the audio clip is played when space is held, right now it delays the initial sound but I want to be able to delay the sounds when they are repeated.

I am aware of audio.PlayDelayed but Could not figure out how to get it to work.

void AudioEnable()
{
    if (Input.GetKey(KeyCode.Space))
    {
        Invoke("Audio", audioDelay);

    }
}

void Audio()
{
    AudioSource audio = GetComponent<AudioSource>(); // play fire sounds from array when space is pressed
    audio.PlayOneShot(fireSounds[Random.Range(0, fireSounds.Length)]);
}

I will continue looking for a solution but in the meantime help would be appreciated.

Body:
Try this

    void AudioEnable()
    {
        if (SoundPLaying)
            return;

        if (Input.GetKey(KeyCode.Space))
        {
            SoundPLaying = true;
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.AutoReset = true;
            timer.Interval = 1000;  //1000 milliseconds. Ajust this time to be equal to length of fire sound.

            timer.Elapsed += (s, e) => { SoundPLaying = false; timer.Dispose(); };
            timer.Start();

            Invoke("Audio", audioDelay);
        }
    }

    void Audio()
    {
        AudioSource audio = GetComponent<AudioSource>(); // play fire sounds from array when space is pressed
        audio.PlayOneShot(fireSounds[Random.Range(0, fireSounds.Length)]);
    }


问:
How to query a replicated sharded database via Azure Elastic Scale?
I'm converting an existing solution to use multi-tenant shards instead of a single database.

My primary database is replicated to a secondary Azure region (active geo-replication). We use this replicated database to fetch some data to reduce load on a primary database.

I'd like to replicate all shards together with a Shard Manager database so that I can connect to a replicated tenant database via replicated Shard Manager db.

The issue is that the replicated Shard Manager database still returns connections to shards located on a primary database server.

Is there any way I can force the replicated Shard Manager DB to return connections to replicated shards?

答:
We ended up creating a connection string by getting original shard location from ShardMap and then change the database server.</p>

```<code>var replicatedConnectionString = new SqlConnectionStringBuilder(shardedConnectionString);
replicatedConnectionString.DataSource = "replicated-db.database.windows.net";

replicatedConnectionString.InitialCatalog = shardMap.AsListShardMap<int>()
                                                    .GetMappingForKey(shardingKey)
                                                    .Shard
                                                    .Location
                                                    .Database;
</code>```

Body:
We ended up creating a connection string by getting original shard location from ShardMap and then change the database server.

var replicatedConnectionString = new SqlConnectionStringBuilder(shardedConnectionString);
replicatedConnectionString.DataSource = "replicated-db.database.windows.net";

replicatedConnectionString.InitialCatalog = shardMap.AsListShardMap<int>()
                                                    .GetMappingForKey(shardingKey)
                                                    .Shard
                                                    .Location
                                                    .Database;


问:
Testing interactive ICommand in C#
I want to test some commands in my WPF project which contain user interaction needed parts.

This is the viewmodel:

```<code>class MainViewModel : ViewModelBase
{
    public ICommand Export { get; private set; }
    public MainViewModel()
    {
        Export = SynchronousCommand.Create((o) => ExportModel(o));
    }

    private void ExportModel(object parameter)
    {
        string exportPath = null;
        SaveFileDialog fileDialog = new SaveFileDialog();
        fileDialog.Filter = "UDPROJ (*.udproj) |*.udproj";
        if (fileDialog.ShowDialog() == true)
        {
            exportPath = fileDialog.FileName;
        }

        // Other logic which should run in test...
    }
}
</code>```

So I want to call this Export command from a test project without calling the SaveFileDialog. My first idea was that I have to send some command parameters through parameter but I would like to ask you, is there a more elegant way (becuase I have to get the command parameters in every case where the command contains some dialog calling)?

答:
your method has got an object parameter which is not used; consider testing it; if empty display the dialog else use it as the dialog result filename

by the way; it is not MVVM compliant to put dialogs in the viewmodel - consider finding code about that

Title: Testing interactive ICommand in C#

Body:
I want to test some commands in my WPF project which contain user interaction needed parts.

This is the viewmodel:

class MainViewModel : ViewModelBase
{
    public ICommand Export { get; private set; }
    public MainViewModel()
    {
        Export = SynchronousCommand.Create((o) => ExportModel(o));
    }

    private void ExportModel(object parameter)
    {
        string exportPath = null;
        SaveFileDialog fileDialog = new SaveFileDialog();
        fileDialog.Filter = "UDPROJ (*.udproj) |*.udproj";
        if (fileDialog.ShowDialog() == true)
        {
            exportPath = fileDialog.FileName;
        }

        // Other logic which should run in test...
    }
}

So I want to call this Export command from a test project without calling the SaveFileDialog. My first idea was that I have to send some command parameters through parameter but I would like to ask you, is there a more elegant way (becuase I have to get the command parameters in every case where the command contains some dialog calling)?


问:
Run Bash script against a Google Compute instance by ssh, from your machine
I am trying to run a script that is on my machine on a Google Compute instance. I'd like the script to connect in and do its work, and was surprised to see behavior from below:

```<code>#!/bin/bash

gcloud compute ssh myinstance

echo "blah" > /tmp/test.txt
</code>```

This script does connect to myinstance, but it writes /tmp/test.txt on my machine, not the compute instance. The ssh connection remains when the script ends, my terminal is connected.

I had expected it to connect, write the file to the compute instance, and disconnect from ssh. How do I maintain scripts on my machine and run then against various compute instances easily, by ssh? The main use case is going from Mac to Ubuntu.

答:
The command you want to run on the remote server should be as an argument to ssh:

```<code>gcloud compute ssh myinstance 'echo "blah" > /tmp/test.txt'
</code>```

Body:
I am trying to run a script that is on my machine on a Google Compute instance. I'd like the script to connect in and do its work, and was surprised to see behavior from below:

#!/bin/bash

gcloud compute ssh myinstance

echo "blah" > /tmp/test.txt

This script does connect to myinstance, but it writes /tmp/test.txt on my machine, not the compute instance. The ssh connection remains when the script ends, my terminal is connected.

I had expected it to connect, write the file to the compute instance, and disconnect from ssh. How do I maintain scripts on my machine and run then against various compute instances easily, by ssh? The main use case is going from Mac to Ubuntu.

Body:
The command you want to run on the remote server should be as an argument to ssh:

gcloud compute ssh myinstance 'echo "blah" > /tmp/test.txt'


问:
Cannot convert value of type '(Date?, Bool, inout UnsafeMutablePointer<ObjCBool>?) to expected argument type '(Date?, Bool, inout Bool)
```<code>  var nextScheduleDate:NSDate?
  calendar.enumerateDates(startingAfter: referenceDate, matching: components, matchingPolicy: .nextTimePreservingSmallerComponents) {

    (scheduleDate: Date?, exactMatch: Bool, stop: inout UnsafeMutablePointer<ObjCBool>?) in
</code>```

答:
Do not annotate types in (callback) closures, that resolves the issue

```<code>calendar.enumerateDates(startingAfter: referenceDate,
                             matching: components,
                       matchingPolicy: .nextTimePreservingSmallerComponents) {
                                          (scheduleDate, exactMatch, stop) in
...
</code>```

An easy way to find out the proper syntax is to comment out the line, retype the first characters and use code completion, you will see that the actual closure signature is

(Date?, Bool, inout Bool)

That is exactly the signature the error message is referring to.

By the way, in Swift 3 there is a native struct Date for dates:

```<code>var nextScheduleDate: Date?
</code>```

Body:
Do not annotate types in (callback) closures, that resolves the issue

calendar.enumerateDates(startingAfter: referenceDate,
                             matching: components,
                       matchingPolicy: .nextTimePreservingSmallerComponents) {
                                          (scheduleDate, exactMatch, stop) in
...

An easy way to find out the proper syntax is to comment out the line, retype the first characters and use code completion, you will see that the actual closure signature is

(Date?, Bool, inout Bool)

That is exactly the signature the error message is referring to.

By the way, in Swift 3 there is a native struct Date for dates:

var nextScheduleDate: Date?


问:
Could anyone point to me the error here i can't find it
So this is my last task for FreeCodeCamp, i've asked on the chat room but nobody could point me the error. The problem is that the pattern the computer plays starts with the last element, then goes from start to finish, repeating the last element, which is confusing for the player.

```<code>$(document).ready( function() {

  var gamestarted = false;
  var arrTones = []; // track all game tones from the begining
  var arrPlayer = []; // track all user tones played
  var arrComp = []; // track all comp tones played
  var steps = null;
  var playerTurns = null;
  var strict = null;

  function playAudio(id) {
    var audio = 'audio' + id ;
    audio = document.getElementById(audio);
    audio.play();
  }

  $('.audio').click(function () {
    var id = Number( $(this).attr('id') );
    playAudio(id);
    if(gamestarted) {
      arrPlayer.push(id);
      if ( arrPlayer[playerTurns] != arrComp[playerTurns] ) {
        if(strict) {
          alert('Start a new game');
          setTimeout( start, 1000 );
        } else {
          alert('Here is the pattern again');
          setTimeout( nextstep, 1000 );
        }
      } else if ( arrPlayer.length < arrComp.length ) {
        playerTurns++;
      } else if ( arrPlayer.length == arrComp.length && steps < 20) {
        steps++;
        setTimeout( nextstep , 1000);

      }

    }
  });

  function start() {

//     reset of all arrays and the steps
    arrTones = [];
    arrPlayer = [];
    arrComp = [];
    steps = 0;
    gamestarted = true;
    strict = $('#strict').prop('checked');

//     generate all moves for this game
    for (var i=1; i<=20; i++) {
      val = Math.floor(Math.random() * (4 - 1 + 1) + 1);
      arrTones.push(val);
    }

//     get first comp move
    nextstep();

  }

  $('#start').click(function () {
    start();
  });

  function nextstep() {

    var tones = 0;

    arrComp = [];
    for (var x=0; x<=steps; x++) {
      arrComp.push(arrTones[x]);
    }

    var moves = setInterval(function() {

      compTurn(arrComp[tones]);

      tones++;

      if ( tones >= arrComp.legth ) {
        clearInterval(moves);
      }

    }, 1000);

    playerTurn();
  }

  function compTurn(id) {
    var button = '#'+id;
    $(button).addClass('btn-outline-secondary');
    playAudio(id);
    setTimeout( function () {
      $(button).removeClass('btn-outline-secondary');
    }, 300);
  }

  function playerTurn() {
    arrPlayer = [];
    playerTurns=0;
  }

});
</code>```

Here is the codepen code for this Simon Game

答:
You have misspelled property name 'length'

```<code>if ( tones >= arrComp.legth ) {
    clearInterval(moves);
  }
</code>```

change it to arrComp.length it will work.

Body:
So this is my last task for FreeCodeCamp, i've asked on the chat room but nobody could point me the error. The problem is that the pattern the computer plays starts with the last element, then goes from start to finish, repeating the last element, which is confusing for the player.

$(document).ready( function() {

  var gamestarted = false;
  var arrTones = []; // track all game tones from the begining
  var arrPlayer = []; // track all user tones played
  var arrComp = []; // track all comp tones played
  var steps = null;
  var playerTurns = null;
  var strict = null;

  function playAudio(id) {
    var audio = 'audio' + id ;
    audio = document.getElementById(audio);
    audio.play();
  }

  $('.audio').click(function () {
    var id = Number( $(this).attr('id') );
    playAudio(id);
    if(gamestarted) {
      arrPlayer.push(id);
      if ( arrPlayer[playerTurns] != arrComp[playerTurns] ) {
        if(strict) {
          alert('Start a new game');
          setTimeout( start, 1000 );
        } else {
          alert('Here is the pattern again');
          setTimeout( nextstep, 1000 );
        }
      } else if ( arrPlayer.length < arrComp.length ) {
        playerTurns++;
      } else if ( arrPlayer.length == arrComp.length && steps < 20) {
        steps++;
        setTimeout( nextstep , 1000);

      }

    }
  });

  function start() {

//     reset of all arrays and the steps
    arrTones = [];
    arrPlayer = [];
    arrComp = [];
    steps = 0;
    gamestarted = true;
    strict = $('#strict').prop('checked');

//     generate all moves for this game
    for (var i=1; i<=20; i++) {
      val = Math.floor(Math.random() * (4 - 1 + 1) + 1);
      arrTones.push(val);
    }

//     get first comp move
    nextstep();

  }

  $('#start').click(function () {
    start();
  });

  function nextstep() {

    var tones = 0;

    arrComp = [];
    for (var x=0; x<=steps; x++) {
      arrComp.push(arrTones[x]);
    }

    var moves = setInterval(function() {

      compTurn(arrComp[tones]);

      tones++;

      if ( tones >= arrComp.legth ) {
        clearInterval(moves);
      }

    }, 1000);

    playerTurn();
  }

  function compTurn(id) {
    var button = '#'+id;
    $(button).addClass('btn-outline-secondary');
    playAudio(id);
    setTimeout( function () {
      $(button).removeClass('btn-outline-secondary');
    }, 300);
  }

  function playerTurn() {
    arrPlayer = [];
    playerTurns=0;
  }

});

Here is the codepen code for this Simon Game

Body:
You have misspelled property name 'length'

if ( tones >= arrComp.legth ) {
    clearInterval(moves);
  }

change it to arrComp.length it will work.


问:
Google Analytics eCommerce Report Local Currency
new here and looking for help.

I'm trying to get the amount people are spending on a products for a website in local currency.

I'm looking at a GA page for someone overseas and the currency values from itemRevenue for each productName I'm seeing in my report in Sheets are not looking like they're local to that store but rather my countries currency. I've tried localItemRevenue but that gave an error saying the dimensions and metrics can't be used together. I've got date/hour included as well in the report.

I tried to use itemRevenue with currencyCode to get around this but they couldn't be used together either.

I thought I could use transactionRevenue along with productName/date/hour/minute but that didn't work (I realised because more than one item can be bought per transaction).

Could someone tell me what GoogleAnalytics uses for currency here and if it can be solved easily?

答:
Your question is not quite clear to me.

However I am assuming that you want to set local currency of your client's country in Google Analytics account.
You can change your currency:

1) Login to your Google Analytics Account

2) Select the View & Click on View Settings.

3) Set "Currency displayed as" -> currency of your choice.

Unless and until you set your desired currency here, you won't be able to get it in Web Interface, Query Explorer, Sheets or API.

I hope this helps.


答:
By reading your comments, you need a cool down timer. A timer that counts. If the timer reaches the set value, you can shoot. When you shoot, you reset the timer. In this case, you can increase or decrease coolDownTime since it will control how many bullets are shot.

Also, rename the audio variable to something else. There is a variable with this name from MonoBehaviour, in the latest version of Unity and you will get warnings for this.

Finally, cache the AudioSource  component in the Start() function so that you don't have to do  GetComponent<AudioSource>(); every time you shoot.

```<code>public AudioClip[] fireSounds;
AudioSource bulletAudio;

//Every 0.5 seconds(Change this to your needs)
const float coolDownTime = 0.5f;
float startingTime = 0f;

void Start()
{
    bulletAudio = GetComponent<AudioSource>();
    startingTime = Time.time;
}

void Update()
{

    if (Input.GetKey(KeyCode.Space))
    {
        //Check if we have reached the cool down timer
        if (Time.time > startingTime + coolDownTime)
        {
            //We have. Now reset timer
            startingTime = Time.time;

            playAudio();
        }
    }
}

void playAudio()
{
    bulletAudio.PlayOneShot(fireSounds[UnityEngine.Random.Range(0, fireSounds.Length)]);
    UnityEngine.Debug.Log("Shot");
}
</code>```

Title: How to play an array of audioclips to be repeated at a set delay?

Body:
By reading your comments, you need a cool down timer. A timer that counts. If the timer reaches the set value, you can shoot. When you shoot, you reset the timer. In this case, you can increase or decrease coolDownTime since it will control how many bullets are shot.

Also, rename the audio variable to something else. There is a variable with this name from MonoBehaviour, in the latest version of Unity and you will get warnings for this.

Finally, cache the AudioSource  component in the Start() function so that you don't have to do  GetComponent<AudioSource>(); every time you shoot.

public AudioClip[] fireSounds;
AudioSource bulletAudio;

//Every 0.5 seconds(Change this to your needs)
const float coolDownTime = 0.5f;
float startingTime = 0f;

void Start()
{
    bulletAudio = GetComponent<AudioSource>();
    startingTime = Time.time;
}

void Update()
{

    if (Input.GetKey(KeyCode.Space))
    {
        //Check if we have reached the cool down timer
        if (Time.time > startingTime + coolDownTime)
        {
            //We have. Now reset timer
            startingTime = Time.time;

            playAudio();
        }
    }
}

void playAudio()
{
    bulletAudio.PlayOneShot(fireSounds[UnityEngine.Random.Range(0, fireSounds.Length)]);
    UnityEngine.Debug.Log("Shot");
}


问:
Error while declaring a list of lists in django
I am trying to declare an array in django, however I need one more column, since in my case the array position [0] [0] should be empty for better table display but when I will declare the array in my view

```<code>Matrice = [[0 for i in range (len (evaluators) +1)] for j in range (len (candidates))]
</code>```

And I refresh the page I get the error:

Need 2 values to unpack in for loop; Got 3.

The problem is in "len (evaluators) +1" because when I shoot +1 it works perfectly.

Why am I not able to declare the array this way? In the shell (python3 mana.py shell) this worked without problems ...

views.py

```<code>from django.shortcuts import render, get_object_or_404
from .models import Candidate, Criterion, Evaluation
from django import forms
from .forms import CandForm
from .forms import EvalForm
from .forms import TestForm
from django.shortcuts import redirect
from django.db import IntegrityError

def canditate_list(request):
    candidates = Candidate.objects.all()

    eva = Evaluation.objects.all()
    eval_cand_list = []                                     #aqui guarda uma lista com os FK candidates convertidos p/ str
    var = 0
    var2 = {'v1':2}
    context = {
        'candidates': candidates,
        'eva': eva,
        'var': var,
        'var2':var2
    }
    return render(request, 'app/candidate_list.html',context)

def candidate_detail(request, pk):
    candidate = get_object_or_404(Candidate, pk=pk)
    c_name = candidate.name                                 #pega o nome (string) do candidato
    c1 = Evaluation.objects.all()                           #guarda tds Evaluation na variavel
    scores = []                                             #declara a array que vai receber as notas
    for c in c1:
        cand = str(c.candidate)                             #guarda o nome do candidato do Evaluation atual
        if cand == c_name:                                  #confere se o Evaluation atual corresponde ao candidate atual(pk)
            scores += [c.score]

    soma = 0                                                #variavel que guardara a soma declarada
    for s in scores:
        soma += s                                           #faz a soma dos scores

    average = 0
    if len(scores) > 0:
        average = soma/len(scores)                              #tira a média

    context = {
        'candidate': candidate,
        'average': average,
    }

    return render(request, 'app/candidate_detail.html', context)

"""
def evaluation(request):
    list_evaluation = Evaluation.objects.all()
    form2 = EvalForm()
    cont = 0

    if request.method == "POST":
        form2 = EvalForm(request.POST)
        if form2.is_valid():
            for ev in list_evaluation:
                cont += 1
"""
def evaluation(request):
    # form2 initialization
    list_evaluation = Evaluation.objects.all()
    form2 = EvalForm()
    marker = False

    if request.method == "POST":
        form2 = EvalForm(request.POST)
        if form2.is_valid() == True:
            for e in list_evaluation:
                if e.appraiser == form2.cleaned_data['appraiser'] and e.candidate == form2.cleaned_data['candidate']:
                    marker = True
                    break
            if marker == False:
                post = form2.save(commit=False)
                post.save()
                return redirect('canditate_list')
            else:
                form2 = EvalForm()
                error = 'Você já valiou esse candidato'
                return render(request, 'app/evaluation.html', {'criterions': form2,'error':error})
    else:
        form2 = EvalForm()
    return render(request, 'app/evaluation.html', {'criterions': form2,})

def register(request):
    list_evaluation = Evaluation.objects.all()

    if request.method == "POST":
        form = CandForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.save()
            return redirect('candidate_detail', pk=post.pk)
    else:
        form = CandForm()
    return render(request, 'app/register.html', {'form': form})

def grid(request):
    evaluation = Evaluation.objects.all()           #queryset com tds os obj avaliação
    cont = 0
    evaluators = []                                 #lista que guarda os avaliadores sem repeti-los
    for evaluator in evaluation:
        cont = 0
        for e in evaluators:
            if e != evaluator.appraiser:
                cont += 1

        if cont == len(evaluators):
            evaluators += [evaluator.appraiser]

    cont = 0
    candidates = []                                 #lista que guarda os avaliador sem repeti-los
    for cand in evaluation:
        cont = 0
        for c in candidates:
            if c != cand.candidate:
                cont += 1

        if cont == len(candidates):
            candidates += [cand.candidate]

    colunas = len(evaluators)+1
    #                           Numero de colunas               Numero de linhas
    matrice = [[0 for i in range(len(evaluators)+1)] for j in range(len(candidates))]

    cont = 0
    context = {                                     #aqui eh o nome que as variaveis terao la no template
            'evaluators':evaluators,
            'evaluation':evaluation,
            'candidates':candidates,
            'cont':cont,
            'matrice':matrice,
        }

    return render(request, 'app/grade.html', context)
</code>```

template

```<code></!DOCTYPE html>
<html>
<head>
  <title></title>
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>

<p>{{ evaluators }}</p>
<p>{{ candidates }}</p>
<p>{{ matrice }}</p>

{% for m,n in matrice %}
<p>{{m}},{{n}}</p>
{%endfor%}
</body>
</html>
</code>```

答:
You need to do something like this</p>

```<code>{% for nodes in matrices %}
  <p>
  {% for node in nodes %}
    {{node}},
  {% endfor %}
  </p>
{% endfor %}
</code>```

Body:
I am trying to declare an array in django, however I need one more column, since in my case the array position [0] [0] should be empty for better table display but when I will declare the array in my view

Matrice = [[0 for i in range (len (evaluators) +1)] for j in range (len (candidates))]

And I refresh the page I get the error:

Need 2 values to unpack in for loop; Got 3.

The problem is in "len (evaluators) +1" because when I shoot +1 it works perfectly.

Why am I not able to declare the array this way? In the shell (python3 mana.py shell) this worked without problems ...

views.py

from django.shortcuts import render, get_object_or_404
from .models import Candidate, Criterion, Evaluation
from django import forms
from .forms import CandForm
from .forms import EvalForm
from .forms import TestForm
from django.shortcuts import redirect
from django.db import IntegrityError

def canditate_list(request):
    candidates = Candidate.objects.all()

    eva = Evaluation.objects.all()
    eval_cand_list = []                                     #aqui guarda uma lista com os FK candidates convertidos p/ str
    var = 0
    var2 = {'v1':2}
    context = {
        'candidates': candidates,
        'eva': eva,
        'var': var,
        'var2':var2
    }
    return render(request, 'app/candidate_list.html',context)

def candidate_detail(request, pk):
    candidate = get_object_or_404(Candidate, pk=pk)
    c_name = candidate.name                                 #pega o nome (string) do candidato
    c1 = Evaluation.objects.all()                           #guarda tds Evaluation na variavel
    scores = []                                             #declara a array que vai receber as notas
    for c in c1:
        cand = str(c.candidate)                             #guarda o nome do candidato do Evaluation atual
        if cand == c_name:                                  #confere se o Evaluation atual corresponde ao candidate atual(pk)
            scores += [c.score]

    soma = 0                                                #variavel que guardara a soma declarada
    for s in scores:
        soma += s                                           #faz a soma dos scores

    average = 0
    if len(scores) > 0:
        average = soma/len(scores)                              #tira a média

    context = {
        'candidate': candidate,
        'average': average,
    }

    return render(request, 'app/candidate_detail.html', context)

"""
def evaluation(request):
    list_evaluation = Evaluation.objects.all()
    form2 = EvalForm()
    cont = 0

    if request.method == "POST":
        form2 = EvalForm(request.POST)
        if form2.is_valid():
            for ev in list_evaluation:
                cont += 1
"""
def evaluation(request):
    # form2 initialization
    list_evaluation = Evaluation.objects.all()
    form2 = EvalForm()
    marker = False

    if request.method == "POST":
        form2 = EvalForm(request.POST)
        if form2.is_valid() == True:
            for e in list_evaluation:
                if e.appraiser == form2.cleaned_data['appraiser'] and e.candidate == form2.cleaned_data['candidate']:
                    marker = True
                    break
            if marker == False:
                post = form2.save(commit=False)
                post.save()
                return redirect('canditate_list')
            else:
                form2 = EvalForm()
                error = 'Você já valiou esse candidato'
                return render(request, 'app/evaluation.html', {'criterions': form2,'error':error})
    else:
        form2 = EvalForm()
    return render(request, 'app/evaluation.html', {'criterions': form2,})

def register(request):
    list_evaluation = Evaluation.objects.all()

    if request.method == "POST":
        form = CandForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.save()
            return redirect('candidate_detail', pk=post.pk)
    else:
        form = CandForm()
    return render(request, 'app/register.html', {'form': form})

def grid(request):
    evaluation = Evaluation.objects.all()           #queryset com tds os obj avaliação
    cont = 0
    evaluators = []                                 #lista que guarda os avaliadores sem repeti-los
    for evaluator in evaluation:
        cont = 0
        for e in evaluators:
            if e != evaluator.appraiser:
                cont += 1

        if cont == len(evaluators):
            evaluators += [evaluator.appraiser]

    cont = 0
    candidates = []                                 #lista que guarda os avaliador sem repeti-los
    for cand in evaluation:
        cont = 0
        for c in candidates:
            if c != cand.candidate:
                cont += 1

        if cont == len(candidates):
            candidates += [cand.candidate]

    colunas = len(evaluators)+1
    #                           Numero de colunas               Numero de linhas
    matrice = [[0 for i in range(len(evaluators)+1)] for j in range(len(candidates))]

    cont = 0
    context = {                                     #aqui eh o nome que as variaveis terao la no template
            'evaluators':evaluators,
            'evaluation':evaluation,
            'candidates':candidates,
            'cont':cont,
            'matrice':matrice,
        }

    return render(request, 'app/grade.html', context)

template

</!DOCTYPE html>

  <title></title>
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

{{ evaluators }}

{{ candidates }}

{{ matrice }}

{% for m,n in matrice %}

{{m}},{{n}}

{%endfor%}

Body:
You need to do something like this

{% for nodes in matrices %}
  <p>
  {% for node in nodes %}
    {{node}},
  {% endfor %}
  </p>
{% endfor %}


问:
Add Dependency to Slim 3 Framework
I'm new using Slim 3 Framework. I want to add this dependency faisalman/simple-excel-php. I installed via Composer but I don't know how to use it in my Controller. Do I need to add it to the container?

This is my composer.json file:

```<code>"require": {
    "slim/slim": "^3.8",
    "slim/php-view": "^2.2",
    "slim/twig-view": "^2.2",
    "illuminate/database": "^5.4",
    "faisalman/simple-excel-php": "^0.3.15"
},
"autoload":{
    "psr-4":{
        "App\\":"app"
    }
}
</code>```

My project Structure is

App

1.1. Controllers

Bootstrap

2.1 app.php (here i instanse my app)

vendor

答:
Having done a composer require faisalman/simple-excel-php, you now have the library installed in your application and available via autoload.

The next step is using it.

There is no direct need to integrate this library into the Slim DI container or worry about the bootstrap file. You can follow the example in the library's readme and instantiate directly:

```<code>use SimpleExcel\SimpleExcel

$excel = new SimpleExcel('CSV');
$excel->parser->loadFile('test.csv');
</code>```

in whatever file makes the most sense for your project.

Title: Add Dependency to Slim 3 Framework

Body:
I'm new using Slim 3 Framework. I want to add this dependency faisalman/simple-excel-php. I installed via Composer but I don't know how to use it in my Controller. Do I need to add it to the container?

This is my composer.json file:

"require": {
    "slim/slim": "^3.8",
    "slim/php-view": "^2.2",
    "slim/twig-view": "^2.2",
    "illuminate/database": "^5.4",
    "faisalman/simple-excel-php": "^0.3.15"
},
"autoload":{
    "psr-4":{
        "App\\":"app"
    }
}

My project Structure is

App

1.1. Controllers

Bootstrap

2.1 app.php (here i instanse my app)

vendor

Body:
Having done a composer require faisalman/simple-excel-php, you now have the library installed in your application and available via autoload.

The next step is using it.

There is no direct need to integrate this library into the Slim DI container or worry about the bootstrap file. You can follow the example in the library's readme and instantiate directly:

use SimpleExcel\SimpleExcel

$excel = new SimpleExcel('CSV');
$excel->parser->loadFile('test.csv');

in whatever file makes the most sense for your project.


问:
Can only Drive apps use the Drive API?
I want to write a program that downloads files from my Drive systematically, and uploads them elsewhere in my Drive. In order to use the Drive API, does my program have to be on the Drive app store? Or can it simply be used privately and locally on my computer.</p>

答:
The Google Drive API is just a rest api.

REST-compliant Web services allow requesting systems to access and manipulate textual representations of Web resources using a uniform and predefined set of stateless operations.

Which basically means access runs over a webserver.  Any programing language that can handle a HTTP POST and HTTP Get can access these rest APIs.   You can write an application in java or C# that sits on your local pc and accesses Google drive API.

I am not sure what you mean by drive app store. To my knowledge drive does not have its own dedicated app store.

Note: to access Google APIs you must register your application on Google Developer console

Title: Can only Drive apps use the Drive API?


问:
Get Date from a long var char milliseconds value stored in oracle Database
I have a date store in data base as a long value in varchar eg: 1230748200000.
I need to get the year out from it withing the oracle query..how can i please do it in oracle? is there a way that i can covert that in to a Date so that i can get the year? The problem is i cant use to_char(SYSTIMESTAMP,'yyyy')  or to_Date because i dont have the date in Timestamp or Date format...instead having it as long varchar

Thank You.

Edit:
Can you please give a solution for the following scenario. I have 1262284398000 in my table save as var char.so as i said i need to get year i use the following sql which return year as 2009

```<code>    select
to_char(
to_date('01-JAN-1970','DD-MM-YYYY HH24:MI SS') + ( 1262284398000 / (1000*60 * 60 * 24) ) ,'YYYY')
from dual ;
</code>```

But in java code same value returns date as 2010 so the year is get diferent,

```<code>Calendar c = Calendar.getInstance();
  c.setTimeInMillis(1262284398000l);
  System.out.println(c.getTime());
  System.out.println(c.get(Calendar.YEAR));
</code>```

Which date return as Fri Jan 01 00:03:18 IST2010                                                                                Why is the difference here please?

答:
Have a look here for further information

```<code>select epoch_time, extract(year from epoch_time) as year
from (
  select date '1970-01-01' + 1291116794/86400 as epoch_time
  from dual
)
</code>```

There may be issues around time zones etc since I believe the epoch time will be in UTC but that is beyond my ken.

Also, it looks like your value is 13 digits long rather than 10, so you maybe just need to add some additional zeroes, i.e. divide by 86400000 rather than 86400.

EDIT:As I said above.... there may be time zone issues. It looks like the Java code is taking 1970-01-01 (in UTC, as it should be) adding the offset and converting it to local time. You will need to do that with the database query as well.

I'm a little unclear about how Oracle handles time zones but after a bit of experimenting I came up with the following examples

```<code>alter session set time_zone = 'Asia/Calcutta';
select
  sessiontimezone,
  to_char(to_date('01-JAN-1970','DD-MM-YYYY HH24:MI SS') +
    ( 1262284398000 / (1000*60 * 60 * 24) ) ,'YYYY'),
  extract(year from cast(timestamp '1970-01-01 00:00:00 +00:00' at local +
    numtodsinterval(1262284398000 / 1000, ' SECOND') as timestamp with time zone)),
  to_char(timestamp '1970-01-01 00:00:00 +00:00' at local +
    numtodsinterval(1262284398000 / 1000, ' SECOND'), 'YYYY'),
  extract(year from cast(timestamp '1970-01-01 00:00:00 +00:00' at local +
    numtodsinterval(1262284398000 / 1000, ' SECOND') as timestamp with local time
    zone))
from dual;
</code>```

In the example above, the first two columns (after sessiontimezone) should be 2009 and the last two should be 2010. Although this has all just been found through experimentation so your mileage may vary.

ContentLicense: CC BY-SA 2.5

Body:
I have a date store in data base as a long value in varchar eg: 1230748200000.
I need to get the year out from it withing the oracle query..how can i please do it in oracle? is there a way that i can covert that in to a Date so that i can get the year? The problem is i cant use to_char(SYSTIMESTAMP,'yyyy')  or to_Date because i dont have the date in Timestamp or Date format...instead having it as long varchar

Thank You.

Edit:
Can you please give a solution for the following scenario. I have 1262284398000 in my table save as var char.so as i said i need to get year i use the following sql which return year as 2009

    select
to_char(
to_date('01-JAN-1970','DD-MM-YYYY HH24:MI SS') + ( 1262284398000 / (1000*60 * 60 * 24) ) ,'YYYY')
from dual ;

But in java code same value returns date as 2010 so the year is get diferent,

Calendar c = Calendar.getInstance();
  c.setTimeInMillis(1262284398000l);
  System.out.println(c.getTime());
  System.out.println(c.get(Calendar.YEAR));

Which date return as Fri Jan 01 00:03:18 IST2010                                                                                Why is the difference here please?

Body:
Have a look here for further information

select epoch_time, extract(year from epoch_time) as year
from (
  select date '1970-01-01' + 1291116794/86400 as epoch_time
  from dual
)

There may be issues around time zones etc since I believe the epoch time will be in UTC but that is beyond my ken.

Also, it looks like your value is 13 digits long rather than 10, so you maybe just need to add some additional zeroes, i.e. divide by 86400000 rather than 86400.

EDIT:As I said above.... there may be time zone issues. It looks like the Java code is taking 1970-01-01 (in UTC, as it should be) adding the offset and converting it to local time. You will need to do that with the database query as well.

I'm a little unclear about how Oracle handles time zones but after a bit of experimenting I came up with the following examples

alter session set time_zone = 'Asia/Calcutta';
select
  sessiontimezone,
  to_char(to_date('01-JAN-1970','DD-MM-YYYY HH24:MI SS') +
    ( 1262284398000 / (1000*60 * 60 * 24) ) ,'YYYY'),
  extract(year from cast(timestamp '1970-01-01 00:00:00 +00:00' at local +
    numtodsinterval(1262284398000 / 1000, ' SECOND') as timestamp with time zone)),
  to_char(timestamp '1970-01-01 00:00:00 +00:00' at local +
    numtodsinterval(1262284398000 / 1000, ' SECOND'), 'YYYY'),
  extract(year from cast(timestamp '1970-01-01 00:00:00 +00:00' at local +
    numtodsinterval(1262284398000 / 1000, ' SECOND') as timestamp with local time
    zone))
from dual;

In the example above, the first two columns (after sessiontimezone) should be 2009 and the last two should be 2010. Although this has all just been found through experimentation so your mileage may vary.


问:
How may i connect ruby on rails with sql server on windows
Want to use sql server as a database instead of mysql in Windows.What configuration i need to change in database.yml file and what all gems are needed for installation.Please help.</p>

答:
Sorry to disappoint you, but there are no easy solutions for using Rails on a Windows platform. It was not designed to run on Windows and I don't think I would recommend Windows as a platform for a Rails app. Not to say it hasn't been done, but in my experience it would be far easier to setup and run on a Linux platform as it was designed to do.

There is support for MS SQL server and Rails and you can checkout this project for more information.

My recommendation is to learn more about Rails and setting it up the environment, because a red flag to me is that you want to deploy a Rails app and yet do not know how to set it for production. This should be Rails 101 knowledge. Production is just another environment for Rails, there are things you need to be aware of when running a Rails app in production and this information can be found on easily rubyonrails.org.

Put some more time into learning Rails and perhaps setup a Linux virtual machine, deploy your Rails app, and experiment. Once you learn how to deploy Rails on a Linux platform them perhaps it may be a little easier to understand how to go about doing it on Windows.

please refer :-- https://github.com/rails-sqlserver/activerecord-sqlserver-adapter

Or else you can try with this

What is left is to learn is how to use database engine that is probably of the most interest for developers who work on Windows – Microsoft's SQL Server. If you do not have MS SQL Server installed go ahead and download MS SQL Server Express installer from Microsoft's site. I will use version 2014 in this book. Let's first create database that we will use in our Rails application:

osql -b -S localhost -U  -P  -Q "CREATE DATABASE RwinBookDevel COLLATE SQL_Latin1_General_CP1_CS_AS"

Newest rails adapter for MS SQL Server uses tiny_tds library to connect to MS SQL server and its usage is almost straigtforward. First thing we have to do is to add following two lines to Gemfile:

```<code>gem 'tiny_tds'

gem 'activerecord-sqlserver-adapter'
</code>```

And run bundle install.

With all prerequisites met we can now configure our Ruby on Rails application to use SQL Server. Connection options are displayed below:

development:

```<code>adapter: sqlserver
mode: dblib
host: localhost
port: 1433
username: <your_db_user_name>
password: <your_db_password>
database: ABC
</code>```

Hope this will help you......

Body:
Sorry to disappoint you, but there are no easy solutions for using Rails on a Windows platform. It was not designed to run on Windows and I don't think I would recommend Windows as a platform for a Rails app. Not to say it hasn't been done, but in my experience it would be far easier to setup and run on a Linux platform as it was designed to do.

There is support for MS SQL server and Rails and you can checkout this project for more information.

My recommendation is to learn more about Rails and setting it up the environment, because a red flag to me is that you want to deploy a Rails app and yet do not know how to set it for production. This should be Rails 101 knowledge. Production is just another environment for Rails, there are things you need to be aware of when running a Rails app in production and this information can be found on easily rubyonrails.org.

Put some more time into learning Rails and perhaps setup a Linux virtual machine, deploy your Rails app, and experiment. Once you learn how to deploy Rails on a Linux platform them perhaps it may be a little easier to understand how to go about doing it on Windows.

please refer :-- https://github.com/rails-sqlserver/activerecord-sqlserver-adapter

Or else you can try with this

What is left is to learn is how to use database engine that is probably of the most interest for developers who work on Windows – Microsoft's SQL Server. If you do not have MS SQL Server installed go ahead and download MS SQL Server Express installer from Microsoft's site. I will use version 2014 in this book. Let's first create database that we will use in our Rails application:

osql -b -S localhost -U  -P  -Q "CREATE DATABASE RwinBookDevel COLLATE SQL_Latin1_General_CP1_CS_AS"

Newest rails adapter for MS SQL Server uses tiny_tds library to connect to MS SQL server and its usage is almost straigtforward. First thing we have to do is to add following two lines to Gemfile:

gem 'tiny_tds'

gem 'activerecord-sqlserver-adapter'

And run bundle install.

With all prerequisites met we can now configure our Ruby on Rails application to use SQL Server. Connection options are displayed below:

development:

adapter: sqlserver
mode: dblib
host: localhost
port: 1433
username: <your_db_user_name>
password: <your_db_password>
database: ABC

Hope this will help you......


问:
Ionic App not installing in android device
I am a newbie in Ionic. I just made a simple app in Ionic that ran well on browser. So, I converted it into an .apk file using Android studios that generated an android-release-unsigned.apk file. I transfered it to my device and on trying to install it I encountered that it was not being installed. I am not able to figure out the cause. Need some assistance.</p>

答: The most probable reason I can think of is that your application is not signed. As Sampath mentioned try to build a debug version and not release version of your application and then install it on your device. You can can use 'ionic run android' and copy/paste manually the output android-debug.apk file to your device.</p>


问:
Remove duplicates as well as original row
Removing duplicates is no problem, i am hitting an issue where i want to remove not only the duplicate but the original row that incurred the duplicate in a SELECT statement.

```<code>ItemNUMBER  ID    from_DATE   to_DATE   fancy_code
1           100   3/28/2015   4/10/2015    Z5111
2           100   4/18/2015   4/21/2015    Z5112
3           100   5/2/2015    5/5/2015     Z5111
4           100   5/31/2015   6/2/2015     Z5111
5           100   7/31/2015   8/16/2015    A400       --remove
6           100   7/31/2015   8/16/2015    A400       --remove
</code>```

Above is my table, and --remove is what the end goal is.  Any help would be much appreciated!

答:
Easiest way to do it by using CTE and count(*).</p>

```<code>WITH cte AS
(
  SELECT fkledgeraccid,  ROW_NUMBER() OVER (PARTITION BY ID,from_DATE,to_DATE,fancy_code) AS row
  FROM TABLE1
)
Select * from cte where row=1
</code>```

Body:
Removing duplicates is no problem, i am hitting an issue where i want to remove not only the duplicate but the original row that incurred the duplicate in a SELECT statement.

ItemNUMBER  ID    from_DATE   to_DATE   fancy_code
1           100   3/28/2015   4/10/2015    Z5111
2           100   4/18/2015   4/21/2015    Z5112
3           100   5/2/2015    5/5/2015     Z5111
4           100   5/31/2015   6/2/2015     Z5111
5           100   7/31/2015   8/16/2015    A400       --remove
6           100   7/31/2015   8/16/2015    A400       --remove

Above is my table, and --remove is what the end goal is.  Any help would be much appreciated!

Body:
Easiest way to do it by using CTE and count(*).

WITH cte AS
(
  SELECT fkledgeraccid,  ROW_NUMBER() OVER (PARTITION BY ID,from_DATE,to_DATE,fancy_code) AS row
  FROM TABLE1
)
Select * from cte where row=1


问:
Start an external activity to scan barcode
I want to start the barcode scanner from my app and get the tag

Here is what I have so far :

scan.h

```<code>class DecodeBarCode : public QObject
{
    Q_OBJECT

    BarCodeReceiver *m_receiver;

public:
    explicit DecodeBarCode(QObject *parent = 0);
    ~DecodeBarCode();

    Q_INVOKABLE void useZXingApp();

signals:
    void tagFound(QString tag);
};

class BarCodeReceiver : public QAndroidActivityResultReceiver
{
    DecodeBarCode *m_decoder;
public:
    BarCodeReceiver(DecodeBarCode *decoder) : m_decoder(decoder) {}

    virtual void handleActivityResult(int receiverRequestCode, int resultCode, const QAndroidJniObject &data) {
        emit m_decoder->tagFound("Receiver worked");
    }

};
</code>```

scan.cpp

```<code>DecodeBarCode::DecodeBarCode(QObject *parent) : QObject(parent)
{
    m_receiver = new BarCodeReceiver(this);
}

DecodeBarCode::~DecodeBarCode()
{
    delete m_receiver;
}

void DecodeBarCode::useZXingApp()
{
    QAndroidJniObject intent = QAndroidJniObject::fromString("com/google/zxing/client/android/SCAN");
    if (intent.isValid()) {
        QtAndroid::startActivity(intent,0,m_receiver); // CRASH HERE
    } else {
        emit tagFound("Invalid"); // TEMP
    }
}
</code>```

That is the first time I use JNI, never used it in java nor c++/Qt

There must be something very wrong, what is it ?

答:
This is my example of using intent to share text from application:

```<code>void Sharer::share(const QString &content)
 {
     qDebug() << "sharing text: " << content;
 #ifdef Q_OS_ANDROID
     auto ACTION_SEND = QAndroidJniObject::getStaticObjectField("android/content/Intent", "ACTION_SEND", "Ljava/lang/String;");
     auto EXTRA_TEXT = QAndroidJniObject::getStaticObjectField("android/content/Intent", "EXTRA_TEXT", "Ljava/lang/String;");
     auto intent = QAndroidJniObject("android/content/Intent", "(Ljava/lang/String;)V", ACTION_SEND.object());

     // Intent  Intent.putExtra(String name, String value)
     intent.callObjectMethod("putExtra", "(Ljava/lang/String;Ljava/lang/String;)Landroid/content/Intent;", EXTRA_TEXT.object(), QAndroidJniObject::fromString(content).object());

     // Intent  Intent.setType(String type)
     intent.callObjectMethod("setType", "(Ljava/lang/String;)Landroid/content/Intent;", QAndroidJniObject::fromString(QString("text/plain")).object());
     qDebug() << intent.toString();

     // static Intent Intent.createChooser(Intent target, CharSequence title)
     auto chooserIntent = QAndroidJniObject::callStaticObjectMethod("android/content/Intent", "createChooser", "(Landroid/content/Intent;Ljava/lang/CharSequence;)Landroid/content/Intent;", intent.object(), QAndroidJniObject::fromString(QString("It's Time To Choose...")).object());
     qDebug() << chooserIntent.toString();

     QtAndroid::startActivity(chooserIntent, 0, nullptr);

 #endif
 }
</code>```

as you see, you need to create intent by yourself, retrieving all needed objects.

Body:
I want to start the barcode scanner from my app and get the tag

Here is what I have so far :

scan.h

class DecodeBarCode : public QObject
{
    Q_OBJECT

    BarCodeReceiver *m_receiver;

public:
    explicit DecodeBarCode(QObject *parent = 0);
    ~DecodeBarCode();

    Q_INVOKABLE void useZXingApp();

signals:
    void tagFound(QString tag);
};

class BarCodeReceiver : public QAndroidActivityResultReceiver
{
    DecodeBarCode *m_decoder;
public:
    BarCodeReceiver(DecodeBarCode *decoder) : m_decoder(decoder) {}

    virtual void handleActivityResult(int receiverRequestCode, int resultCode, const QAndroidJniObject &data) {
        emit m_decoder->tagFound("Receiver worked");
    }

};

scan.cpp

DecodeBarCode::DecodeBarCode(QObject *parent) : QObject(parent)
{
    m_receiver = new BarCodeReceiver(this);
}

DecodeBarCode::~DecodeBarCode()
{
    delete m_receiver;
}

void DecodeBarCode::useZXingApp()
{
    QAndroidJniObject intent = QAndroidJniObject::fromString("com/google/zxing/client/android/SCAN");
    if (intent.isValid()) {
        QtAndroid::startActivity(intent,0,m_receiver); // CRASH HERE
    } else {
        emit tagFound("Invalid"); // TEMP
    }
}

That is the first time I use JNI, never used it in java nor c++/Qt

There must be something very wrong, what is it ?

Body:
This is my example of using intent to share text from application:

void Sharer::share(const QString &content)
 {
     qDebug() << "sharing text: " << content;
 #ifdef Q_OS_ANDROID
     auto ACTION_SEND = QAndroidJniObject::getStaticObjectField("android/content/Intent", "ACTION_SEND", "Ljava/lang/String;");
     auto EXTRA_TEXT = QAndroidJniObject::getStaticObjectField("android/content/Intent", "EXTRA_TEXT", "Ljava/lang/String;");
     auto intent = QAndroidJniObject("android/content/Intent", "(Ljava/lang/String;)V", ACTION_SEND.object());

     // Intent  Intent.putExtra(String name, String value)
     intent.callObjectMethod("putExtra", "(Ljava/lang/String;Ljava/lang/String;)Landroid/content/Intent;", EXTRA_TEXT.object(), QAndroidJniObject::fromString(content).object());

     // Intent  Intent.setType(String type)
     intent.callObjectMethod("setType", "(Ljava/lang/String;)Landroid/content/Intent;", QAndroidJniObject::fromString(QString("text/plain")).object());
     qDebug() << intent.toString();

     // static Intent Intent.createChooser(Intent target, CharSequence title)
     auto chooserIntent = QAndroidJniObject::callStaticObjectMethod("android/content/Intent", "createChooser", "(Landroid/content/Intent;Ljava/lang/CharSequence;)Landroid/content/Intent;", intent.object(), QAndroidJniObject::fromString(QString("It's Time To Choose...")).object());
     qDebug() << chooserIntent.toString();

     QtAndroid::startActivity(chooserIntent, 0, nullptr);

 #endif
 }

as you see, you need to create intent by yourself, retrieving all needed objects.


问:
Audio file not play in objective C
```<code>- (void)play {
    NSURL *imgPath = [[NSBundle mainBundle] URLForResource:@"sound" withExtension:@"mp3"];
    NSString *path = [imgPath path];
    NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];
    NSLog(@"%@",data);
    NSError *error;
    self.avPlayer = [[AVAudioPlayer alloc] initWithData:data error:&error];
    [self.avPlayer play];
    }
</code>```

答:
Your code works fine. The problem is while you try to Log the Data.
Or else try with initWithContentsOfURL method.

```<code>#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface ViewController ()

@property (nonatomic, strong) AVAudioPlayer *avPlayer;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSURL *imgPath = [[NSBundle mainBundle] URLForResource:@"1" withExtension:@"mp3"];

    NSString *path = [imgPath path];

    NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];

   // NSLog(@"%@",data);

    NSError *error;

    self.avPlayer = [[AVAudioPlayer alloc] initWithData:data error:&error];

 //   self.avPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:imgPath error:&error];

    [self.avPlayer play];

}
</code>```

Title: Audio file not play in objective C

Body:
Your code works fine. The problem is while you try to Log the Data.
Or else try with initWithContentsOfURL method.

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface ViewController ()

@property (nonatomic, strong) AVAudioPlayer *avPlayer;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSURL *imgPath = [[NSBundle mainBundle] URLForResource:@"1" withExtension:@"mp3"];

    NSString *path = [imgPath path];

    NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];

   // NSLog(@"%@",data);

    NSError *error;

    self.avPlayer = [[AVAudioPlayer alloc] initWithData:data error:&error];

 //   self.avPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:imgPath error:&error];

    [self.avPlayer play];

}


问:
Jquery custom trigger anchor tag
Hello every one I am creating custom multistep form but when I click on next button it can't trigger related  anchor tag ( auto click )

Please help me to resolve my issue

Thanks in Advance

$(function() {
  $("#nextBtn").click(function() {
    var $tabs = $("li");
    $tabs.each(function() {

      var activeTab = $(this).hasClass("active");
      if (activeTab == true) {
        //var activeAnch = $(this).children().attr("href");
        alert($(this).next('li').children().attr("href"));
        var nextId = $(this).next('li').children().attr("id");
        //$("#"+nextId).click();// trigger click to #menu 1
      }
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Case</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

<body>
  <ul class="nav nav-pills">
    <li class="active">Home</li>
    <li>Menu 1</li>
    <li>Menu 2</li>
    <li>Menu 3</li>
  </ul>

  <div class="tab-content">
    <div id="home" class="tab-pane fade in active">
      <h3>HOME</h3>
      <span>Form 1</span>
    </div>
    <div id="menu1" class="tab-pane fade">
      <h3>Menu 1</h3>
      <span>Form 2</span>
    </div>
    <div id="menu2" class="tab-pane fade">
      <h3>Menu 2</h3>
      <span>Form 3</span>
    </div>
    <div id="menu3" class="tab-pane fade">
      <h3>Menu 3</h3>
      <span>Form 4</span>
    </div>
  </div>

  <button id="nextBtn">Next</button>

</body>

</html></code>```

答:
Simple use with [clas='active'] match

$(function() {
$("#nextBtn").click(function() {
var nextId = $("li[class='active']").next('li').children('a').attr("href")
if(nextId){
  $('a[href="'+nextId+'"]').trigger('click');
  }
  else{
  $('ul').children('li').eq(0).children('a').trigger('click');

  }
});
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Case</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
  <ul class="nav nav-pills">
    <li class="active">Home</li>
    <li>Menu 1</li>
    <li>Menu 2</li>
    <li>Menu 3</li>
  </ul>

  <div class="tab-content">
    <div id="home" class="tab-pane fade in active">
      <h3>HOME</h3>
      <span>Form 1</span>
    </div>
    <div id="menu1" class="tab-pane fade">
      <h3>Menu 1</h3>
      <span>Form 2</span>
    </div>
    <div id="menu2" class="tab-pane fade">
      <h3>Menu 2</h3>
      <span>Form 3</span>
    </div>
    <div id="menu3" class="tab-pane fade">
      <h3>Menu 3</h3>
      <span>Form 4</span>
    </div>
  </div>

<button id="nextBtn">Next</button>

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

Title: Jquery custom trigger anchor tag

Body:
Hello every one I am creating custom multistep form but when I click on next button it can't trigger related  anchor tag ( auto click )

Please help me to resolve my issue

Thanks in Advance

$(function() {
  $("#nextBtn").click(function() {
    var $tabs = $("li");
    $tabs.each(function() {

      var activeTab = $(this).hasClass("active");
      if (activeTab == true) {
        //var activeAnch = $(this).children().attr("href");
        alert($(this).next('li').children().attr("href"));
        var nextId = $(this).next('li').children().attr("id");
        //$("#"+nextId).click();// trigger click to #menu 1
      }
    });
  });
});

<!DOCTYPE html>

  <title>Bootstrap Case</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Home

Menu 1

Menu 2

Menu 3

HOME

      Form 1

Menu 1

      Form 2

Menu 2

      Form 3

Menu 3

      Form 4

  <button id="nextBtn">Next</button>

Body:
Simple use with [clas='active'] match

$(function() {
$("#nextBtn").click(function() {
var nextId = $("li[class='active']").next('li').children('a').attr("href")
if(nextId){
  $('a[href="'+nextId+'"]').trigger('click');
  }
  else{
  $('ul').children('li').eq(0).children('a').trigger('click');

  }
});
});

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Case</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
  <ul class="nav nav-pills">
    <li class="active"><a data-toggle="pill" href="#home">Home</a></li>
    <li><a data-toggle="pill" href="#menu1">Menu 1</a></li>
    <li><a data-toggle="pill" href="#menu2">Menu 2</a></li>
    <li><a data-toggle="pill" href="#menu3">Menu 3</a></li>
  </ul>

  <div class="tab-content">
    <div id="home" class="tab-pane fade in active">
      <h3>HOME</h3>
      <span>Form 1</span>
    </div>
    <div id="menu1" class="tab-pane fade">
      <h3>Menu 1</h3>
      <span>Form 2</span>
    </div>
    <div id="menu2" class="tab-pane fade">
      <h3>Menu 2</h3>
      <span>Form 3</span>
    </div>
    <div id="menu3" class="tab-pane fade">
      <h3>Menu 3</h3>
      <span>Form 4</span>
    </div>
  </div>

<button id="nextBtn">Next</button>

</body>
</html>


问:
FieldLevelValidationForm - How to make it configurable
I am running into this situation:

I want to apply multiple validations on a field which like example below:

```<code><Field name="username" type="text"
    component={renderField} label="Username"
    validate={[ required, maxLength15 ]}
 />
</code>```

But I want to make the 15 as a configure number instead.

For example, userNameValidatiorConfig = [required, {maxLength: 15}]

Any ideas on this?

答:
The validate prop of Field contains usual javascript functions. Thus you could do something like

```<code>validate={(value) => maxLength(15)(value)}
</code>```

That is if your validation functions look like

```<code>const maxLength = (max) => (value) => value && value.length > max ? "Bad input!" : undefined;
</code>```

Body:
I am running into this situation:

I want to apply multiple validations on a field which like example below:

<Field name="username" type="text"
    component={renderField} label="Username"
    validate={[ required, maxLength15 ]}
 />

But I want to make the 15 as a configure number instead.

For example, userNameValidatiorConfig = [required, {maxLength: 15}]

Any ideas on this?

Body:
The validate prop of Field contains usual javascript functions. Thus you could do something like

validate={(value) => maxLength(15)(value)}

That is if your validation functions look like

const maxLength = (max) => (value) => value && value.length > max ? "Bad input!" : undefined;


问:
IE 6 and Silverlight
Does Silverlight work with IE 6, are there any gotchas?

Just wondering if this is an alternative for customers stuck with IE 6.

答:
For client OSs the answer is yes
More detail on wikipedia about compatible OSs and browsers</p>

Title: IE 6 and Silverlight