问:
How to go back to previous data randomly generated on same view controller
I am new to coding and I am trying to code a random generator that displays random quotes. I am able to do that. But I want to be able to go back to previous quotes that I have generated and cannot find a way to do it. I have no xcode to show. Any help would be greatly appreciated

```<code>var myQuotes = ["Adversity is The Universe's Way of Directing Us Down a Differnt Path", "Pain is Temporary, Glory is Forever", "As You Think, So Shall You Become", "If You Can Dream It, You Can Achieve It", "Dreaming, Afterall, is a Form of Planning"]

var randomGeneratedQuotes = Array <String>()
var currentlyShown : String?
var randomQuote: String {
    let randomNumber = Int(arc4random_uniform(UInt32(myQuotes.count)))
    return myQuotes[randomNumber]

}

var previousRandom: String? {

    if currentlyShown == randomQuote {
        let previous = randomGeneratedQuotes.index(of: currentlyShown!)! - 1
        return randomGeneratedQuotes[previous]
    }

    return randomGeneratedQuotes.last
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    var randomQuote: String {
        let randomNumber = Int(arc4random_uniform(UInt32(myQuotes.count)))
        return myQuotes[randomNumber]

    }
    quotesLabel.text = randomQuote

    func storePrevious() {
        if randomGeneratedQuotes.contains(randomQuote) {return}
        randomGeneratedQuotes.append(randomQuote)
}
}

//right hand button tapped

@IBAction func RHSButton(_ sender: Any) {

    var randomQuote: String {
        let randomNumber = Int(arc4random_uniform(UInt32(myQuotes.count)))
        return myQuotes[randomNumber]

    }
    quotesLabel.text = randomQuote

    func storePrevious() {
        if randomGeneratedQuotes.contains(randomQuote) {return}
        randomGeneratedQuotes.append(randomQuote)
    }

}

//left hand button tapped

@IBAction func LHSButton(_ sender: Any) {

    func pressedBack() {
        currentlyShown = previousRandom

    }

    quotesLabel.text = previousRandom

}
</code>```

}

答:
You can simply create var to hold the previous quote. and return it when user presses back. Or if you want all quotes to come after pressing back. You can keep a separate array for them like var generatedQuotes = Array(). And traverse the elements backward on the action. Just append the random element to the array or hold the lastQuote string in a var.</p>

```<code>class ViewController: UIViewController {
     var myQuotes = ["A","b","c"] // your all quotes stored here.
     var randomGeneratedQuotes = Array<String>() // empty on start
     var currentlyShown : String?
     //use this not so random but will generate a random one
     var randomQuote: String {
       let randomNumber = Int(arc4random_uniform(UInt32(myQuotes.count)))
       return myQuotes[randomNumber]
     }
     var previousRandom: String? {
       if currentlyShown == nil {
          let previous = randomGeneratedQuotes.indexOf(currentlyShown) - 1
          return randomGeneratedQuotes[previous]
       }

       return randomGeneratedQuotes.last
     }
     func storePrevious() {
        if randomGeneratedQuotes.contains(randomQuote) { return } // already has
           randomGeneratedQuotes.append(randomQuote)
     }
     func pressedBack() {
       currentlyShown = previousRandom
       print(previous)

}
</code>```

Body:
I am new to coding and I am trying to code a random generator that displays random quotes. I am able to do that. But I want to be able to go back to previous quotes that I have generated and cannot find a way to do it. I have no xcode to show. Any help would be greatly appreciated

var myQuotes = ["Adversity is The Universe's Way of Directing Us Down a Differnt Path", "Pain is Temporary, Glory is Forever", "As You Think, So Shall You Become", "If You Can Dream It, You Can Achieve It", "Dreaming, Afterall, is a Form of Planning"]

var randomGeneratedQuotes = Array <String>()
var currentlyShown : String?
var randomQuote: String {
    let randomNumber = Int(arc4random_uniform(UInt32(myQuotes.count)))
    return myQuotes[randomNumber]

}

var previousRandom: String? {

    if currentlyShown == randomQuote {
        let previous = randomGeneratedQuotes.index(of: currentlyShown!)! - 1
        return randomGeneratedQuotes[previous]
    }

    return randomGeneratedQuotes.last
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    var randomQuote: String {
        let randomNumber = Int(arc4random_uniform(UInt32(myQuotes.count)))
        return myQuotes[randomNumber]

    }
    quotesLabel.text = randomQuote

    func storePrevious() {
        if randomGeneratedQuotes.contains(randomQuote) {return}
        randomGeneratedQuotes.append(randomQuote)
}
}

//right hand button tapped

@IBAction func RHSButton(_ sender: Any) {

    var randomQuote: String {
        let randomNumber = Int(arc4random_uniform(UInt32(myQuotes.count)))
        return myQuotes[randomNumber]

    }
    quotesLabel.text = randomQuote

    func storePrevious() {
        if randomGeneratedQuotes.contains(randomQuote) {return}
        randomGeneratedQuotes.append(randomQuote)
    }

}

//left hand button tapped

@IBAction func LHSButton(_ sender: Any) {

    func pressedBack() {
        currentlyShown = previousRandom

    }

    quotesLabel.text = previousRandom

}

}

Body:
You can simply create var to hold the previous quote. and return it when user presses back. Or if you want all quotes to come after pressing back. You can keep a separate array for them like var generatedQuotes = Array(). And traverse the elements backward on the action. Just append the random element to the array or hold the lastQuote string in a var.

class ViewController: UIViewController {
     var myQuotes = ["A","b","c"] // your all quotes stored here.
     var randomGeneratedQuotes = Array<String>() // empty on start
     var currentlyShown : String?
     //use this not so random but will generate a random one
     var randomQuote: String {
       let randomNumber = Int(arc4random_uniform(UInt32(myQuotes.count)))
       return myQuotes[randomNumber]
     }
     var previousRandom: String? {
       if currentlyShown == nil {
          let previous = randomGeneratedQuotes.indexOf(currentlyShown) - 1
          return randomGeneratedQuotes[previous]
       }

       return randomGeneratedQuotes.last
     }
     func storePrevious() {
        if randomGeneratedQuotes.contains(randomQuote) { return } // already has
           randomGeneratedQuotes.append(randomQuote)
     }
     func pressedBack() {
       currentlyShown = previousRandom
       print(previous)

}


来源: stackexchange

问:
How to change the case of all characters in a text file to lowercase in java?
So if the contents of a text file is FCCCC, the output of the same text file should be fcccc.

I have written the following code

```<code>  import java.lang.*;
  import java.io.*;
  import java.io.FileWriter;
  import java.io.IOException;
  class A
  {
   public static void main(String args[]) throws IOException
   {
      try
      {
            FileReader reader = new FileReader("doc1.txt");
            FileWriter writer = new FileWriter("doc1.txt", true);
            int character=' ';
            char m;
            while ((character = reader.read()) != -1)
            {
                m=Character.toLowerCase((char)character);
                System.out.println(m);
                writer.write(m);
            }
            reader.close();
            writer.close();
      }
      catch (IOException e)
      {
        e.printStackTrace();
      }
    }
 }
</code>```

In the code above if the contents of the text file are FCCCC then the output is FCCCCfcccc.

What is the mistake in the code?

答:
Your writer is writing to the same text file that your reader is reading from.

Try writing to a different text file.

ContentLicense: CC BY-SA 3.0

Body:
So if the contents of a text file is FCCCC, the output of the same text file should be fcccc.

I have written the following code

  import java.lang.*;
  import java.io.*;
  import java.io.FileWriter;
  import java.io.IOException;
  class A
  {
   public static void main(String args[]) throws IOException
   {
      try
      {
            FileReader reader = new FileReader("doc1.txt");
            FileWriter writer = new FileWriter("doc1.txt", true);
            int character=' ';
            char m;
            while ((character = reader.read()) != -1)
            {
                m=Character.toLowerCase((char)character);
                System.out.println(m);
                writer.write(m);
            }
            reader.close();
            writer.close();
      }
      catch (IOException e)
      {
        e.printStackTrace();
      }
    }
 }

In the code above if the contents of the text file are FCCCC then the output is FCCCCfcccc.

What is the mistake in the code?


问:
jquery animate rotate div multiple times on click
I would like to rotate this div on click using animate (not rotate, no plugins), and also set how many times it can rotate. Here is the code

$('#foo').animate({  borderSpacing: -90 }, {
    step: function(now,fx) {
      $(this).css('-webkit-transform','rotate('+now+'deg)');
      $(this).css('-moz-transform','rotate('+now+'deg)');
      $(this).css('transform','rotate('+now+'deg)');
    },
    duration:'slow'
},'linear');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    font-family: sans-serif;
}

#foo {
    width:100px;
    height:100px;
    position:absolute;
    top:100px;
    left:100px;
    border-spacing: 0;
    background-color:red;
}</code>```

Text

See inspiration```

答:
Here is solution snipet. hope you like it.

$('#act').on('click',function(){
    $(this).animate({  borderSpacing: -90 }, {
        step: function(now,fx) {
            $(this).css('-webkit-transform','rotate('+now+'deg)');
            $(this).css('-moz-transform','rotate('+now+'deg)');
            $(this).css('transform','rotate('+now+'deg)');
        },
        duration:'slow'
    },'linear');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    font-family: sans-serif;
}

#act {
    width:100px;
    height:100px;
    position:absolute;
    top:100px;
    left:100px;
    border-spacing: 0;
    background-color:red;
}</code>```

Text

See inspiration```

Hope this will fulfill your requirement.

Greetings!

Body:
I would like to rotate this div on click using animate (not rotate, no plugins), and also set how many times it can rotate. Here is the code

$('#foo').animate({  borderSpacing: -90 }, {
    step: function(now,fx) {
      $(this).css('-webkit-transform','rotate('+now+'deg)');
      $(this).css('-moz-transform','rotate('+now+'deg)');
      $(this).css('transform','rotate('+now+'deg)');
    },
    duration:'slow'
},'linear');

body {
    font-family: sans-serif;
}

#foo {
    width:100px;
    height:100px;
    position:absolute;
    top:100px;
    left:100px;
    border-spacing: 0;
    background-color:red;
}

Text

See inspiration

Body:
Here is solution snipet. hope you like it.

$('#act').on('click',function(){
    $(this).animate({  borderSpacing: -90 }, {
        step: function(now,fx) {
            $(this).css('-webkit-transform','rotate('+now+'deg)');
            $(this).css('-moz-transform','rotate('+now+'deg)');
            $(this).css('transform','rotate('+now+'deg)');
        },
        duration:'slow'
    },'linear');
});

body {
    font-family: sans-serif;
}

#act {
    width:100px;
    height:100px;
    position:absolute;
    top:100px;
    left:100px;
    border-spacing: 0;
    background-color:red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="act">Text</div>
<p>See <a href="http://jsfiddle.net/ryleyb/ERRmd/">inspiration</a>

Hope this will fulfill your requirement.

Greetings!


问:
client-side synchronous service invocation
I am talking about synchronous on the client side. That means, the service requester is blocking after sending a message to the service.

my question is: is it related to the -a -s parameter of wsdl2java tool, Since -a generate async style code and -s generate sync style code.

Or the client side blocking or not is totally controlled by the client logic?

Thanks

答: If you're using netbeans to generate your web service client, the operation generated is already synchronous by default. If you want to toggle it to be asynchronous call or vice versa, you can follow these steps easily : https://netbeans.org/kb/docs/websvc/client.html#asynch-creatingtheclient</p>

ContentLicense: CC BY-SA 2.5


问:
Can I know jdwp transport port from inside JVM?
I am starting java with the following arguments:

-Xdebug -Xrunjdwp:transport=dt_socket,address=0,server=y,suspend=n

 and I get the following output:

Listening for transport dt_socket at address: 59183

Is it possible to find the port from inside the same JVM, without reading standard output?

答:
```<code>import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Method;
import java.util.Properties;

@Slf4j
public class RuntimeDebugger {

    static private int jdwpListenerPort;

    static public int getJdwpListenerPort() {
        if(jdwpListenerPort == 0) {
            jdwpListenerPort = readJdwpListenerPort();
        }
        return jdwpListenerPort;
    }

    static private int readJdwpListenerPort() {
        String listenerAddress = null;
        try {
            Class<?> theClass = Class.forName("sun.misc.VMSupport");
            Method m = theClass.getMethod("getAgentProperties");
            Properties p = (Properties) m.invoke(null);
            listenerAddress = p.getProperty("sun.jdwp.listenerAddress");
            if (listenerAddress != null) {
                listenerAddress = StringUtils.substringAfter(listenerAddress, ":");
                return Integer.parseInt(listenerAddress);
            }
        } catch (Exception ex) {
            log.error("Failed to read sun.jdwp.listenerAddress, ignore");
        }
        return -1;
    }
}
</code>```


问:
Why use only static classes to test rest endpoints while using Jersey Test?
I have been using JerseyTest framework to test endpoints in my application. I am fairly new to this.

I studied a few other test cases written by other developers of my company. They do not test the Resource class directly but rather write a static class within the test case and test the static class.

Even in the Jersey Guide, I notice examples of only testing static classes.

I do not understand the purpose of writing test cases like this because my goal was to test my resource class so what will we achieve if we write a static class and test that?

Class to be tested is below

```<code>class SomeController {

@Post
@path("/someResponse")
private SomeResponseObject doSomeWork(@NotNull SomeObjectParameter parameter) {
   //Code for processing request and prepares the response object
   return someResponseObject;
}
}
</code>```

But the class tested within the unit test class

```<code>public class SomeControllerTest extends JerseyTest {

@Path("/path")
public static class ControllerResource {
    @Post
    public SomeResponseObject getSomeWork() {
        //Prepared SomeResponseObject
        return someResponseObject;
    }
}

@Override
protected Application configure() {
    return new ResourceConfig(ControllerResource.class);
}

@Test
public void test() {
    SomeResponseObject response = target("hello").request().post(SomeResponseObject.class);
    //Do assertions
}
}
</code>```

Now if you notice the Configure method, the class that is added is the static class that is created within the test class rather than the class to be tested which is SomeController.class

What is the point of writing the unit test here if we are not testing the SomeController class? What are we trying to achieve?

答: This is a unit test used with Jersey test framework which contain already an embedded container so trying to test the ressource itself doesn't really need to instanciate the controller class , its members will be accessed anyway.</p>

Body:
I have been using JerseyTest framework to test endpoints in my application. I am fairly new to this.

I studied a few other test cases written by other developers of my company. They do not test the Resource class directly but rather write a static class within the test case and test the static class.

Even in the Jersey Guide, I notice examples of only testing static classes.

I do not understand the purpose of writing test cases like this because my goal was to test my resource class so what will we achieve if we write a static class and test that?

Class to be tested is below

class SomeController {

@Post
@path("/someResponse")
private SomeResponseObject doSomeWork(@NotNull SomeObjectParameter parameter) {
   //Code for processing request and prepares the response object
   return someResponseObject;
}
}

But the class tested within the unit test class

public class SomeControllerTest extends JerseyTest {

@Path("/path")
public static class ControllerResource {
    @Post
    public SomeResponseObject getSomeWork() {
        //Prepared SomeResponseObject
        return someResponseObject;
    }
}

@Override
protected Application configure() {
    return new ResourceConfig(ControllerResource.class);
}

@Test
public void test() {
    SomeResponseObject response = target("hello").request().post(SomeResponseObject.class);
    //Do assertions
}
}

Now if you notice the Configure method, the class that is added is the static class that is created within the test class rather than the class to be tested which is SomeController.class

What is the point of writing the unit test here if we are not testing the SomeController class? What are we trying to achieve?


问:
Hypen in response data is throwing error when setting as global variable
I have a post man request. Which returns a response data as:

```<code>{
    "app-token": "VcdQeqG1aJYrlNH40VuRfjyedQEC"
}
</code>```

I need to extract the value of the app-token and set as global variable.

here is my code:

```<code>var jsonData = JSON.parse(responseBody);
postman.setGlobalVariable("token", jsonData.app-token);
</code>```

But I am getting error. Can some one help me.

答:
You should use bracket notation for properties that contain hyphens or other operators instead of dot notation.

Because compiler will interpret jsonData.app-token as a subtraction operation like jsonData.app - token

Use this one instead:

postman.setGlobalVariable("token", jsonData["app-token"]);

Body:
I have a post man request. Which returns a response data as:

{
    "app-token": "VcdQeqG1aJYrlNH40VuRfjyedQEC"
}

I need to extract the value of the app-token and set as global variable.

here is my code:

var jsonData = JSON.parse(responseBody);
postman.setGlobalVariable("token", jsonData.app-token);

But I am getting error. Can some one help me.


问:
Fetching from Database: Property or Method?
I've got a class that I'd like to let it get a record from a database. I need to make sure that there's at most one record. The record should be a single match to the class, based on the OrderId.

I feel like a property getter would make more sense than a method, but I know that property getters should avoid throwing Exceptions and .Single()/.SingleOrDefault() could end up throwing one. I feel like the method might make people think that it was fetching from the database each time. Either way, I'd have the result cached in a local field.

What is the best practice for something like this? I have an example of what my code is like below.

N.B.: I know that ideally we'd have a unique index on the DB column to make sure it's unique, it's not possible to do with the vendor database we're using.

```<code>class OrderDetails
{
    DbOrder _order;
    string OrderId { get; set; }

    DbOrder Order // property way
    {
        get{
            if (this._order == null)
                this._order = dbContext.Where(x => x.OrderId == this.OrderId).SingleOrDefault();
            return _order;
        }
    }

    DbOrder GetOrder() // method way
    {
        if (this._order == null)
            this._order = dbContext.Where(x => x.OrderId == this.OrderId).SingleOrDefault();
        return _order;
    }
}
</code>```

答:
I'd say a property should always raise an exception if it's needed, same as anywhere (just as similarly as it should be avoided if possible). </p>

<p>More to the point, I think it's that properties shouldn't have "side effects", and although yours does not strictly, this is the closest thing I can liken it to. It seems like "a lot to do" (open db connection, queried data, piped results) for a property when a method could be more descriptive: you kind of expect a method will do more legwork ad hoc </p>

Body:
I've got a class that I'd like to let it get a record from a database. I need to make sure that there's at most one record. The record should be a single match to the class, based on the OrderId.

I feel like a property getter would make more sense than a method, but I know that property getters should avoid throwing Exceptions and .Single()/.SingleOrDefault() could end up throwing one. I feel like the method might make people think that it was fetching from the database each time. Either way, I'd have the result cached in a local field.

What is the best practice for something like this? I have an example of what my code is like below.

N.B.: I know that ideally we'd have a unique index on the DB column to make sure it's unique, it's not possible to do with the vendor database we're using.

class OrderDetails
{
    DbOrder _order;
    string OrderId { get; set; }

    DbOrder Order // property way
    {
        get{
            if (this._order == null)
                this._order = dbContext.Where(x => x.OrderId == this.OrderId).SingleOrDefault();
            return _order;
        }
    }

    DbOrder GetOrder() // method way
    {
        if (this._order == null)
            this._order = dbContext.Where(x => x.OrderId == this.OrderId).SingleOrDefault();
        return _order;
    }
}

Body:
I'd say a property should always raise an exception if it's needed, same as anywhere (just as similarly as it should be avoided if possible).

More to the point, I think it's that properties shouldn't have "side effects", and although yours does not strictly, this is the closest thing I can liken it to. It seems like "a lot to do" (open db connection, queried data, piped results) for a property when a method could be more descriptive: you kind of expect a method will do more legwork ad hoc


问:
How do I repeat the number of times in a PHP loop?
There is an array of any with the keys permissible from 1 to 10.

There is a cycle from 1 to the current day (let's say the number today is 7 every day corresponds to a new day).

How to make it so that in the cycle from one to today we receive the body of the array by the key?

From 1 to 10 it is understandable, but how to repeat the array keys in a loop. Suppose there will be a thirtieth day, it should show the body of the array with key 10.

```<code>        public function getRation($getration)
{
    //ration - it's day
    $ration = RationDay::all()->toArray();
    $count = count($ration);
    $s=1;
    for ($i=0; $i<$getration; $i++)
    {
        $kekes = $s++;
        if($s<=$count){
         if($kekes>=$count){
             $kekes = 1;
         }else{
        if(isset($ration[$kekes])){
                $s=1;
        }else{
            $kek = $ration[$kekes];
        }
        }
    }
</code>```

This is one of several solutions.

Thank you in advance!

P.S. The day goes separately from the array, the day I get from angularjs through request. If the day is larger than the array, then it should repeat the output of the keys is valid. Example: Day 13 - Key = 3.

I for example tried to do it all through for, but something is not successful.

Upd. There was an interesting idea, to receive the remainder of the division. But the remainder of the division will not work, because if there is an array with keys from 1 to 6. Then let's say it does not work out that 9 day is the key 3.

UPD 2. Here's the solution if anyone should. Thank you all for the response!

```<code>//get array
$ration = RationDay::all()->toArray();

$count = count($ration);
//getration - it day
$day = $getration;

if ($day >= ($maxDay = max(array_keys($ration)))) {
    $day = $day % $maxDay;
}

$getting = $ration[$day];

return $getting;
</code>```

答:
I would say you would have the best luck if you had your counter have a base 10. </p>

```<code>$count = 0
for ($day = 1; $day <= $limit; $day++) {
   if ($count = 10) {
      $count = 0;
   }
   $count++;
   echo $array[$count];
}
</code>```

Body:
There is an array of any with the keys permissible from 1 to 10.

There is a cycle from 1 to the current day (let's say the number today is 7 every day corresponds to a new day).

How to make it so that in the cycle from one to today we receive the body of the array by the key?

From 1 to 10 it is understandable, but how to repeat the array keys in a loop. Suppose there will be a thirtieth day, it should show the body of the array with key 10.

        public function getRation($getration)
{
    //ration - it's day
    $ration = RationDay::all()->toArray();
    $count = count($ration);
    $s=1;
    for ($i=0; $i<$getration; $i++)
    {
        $kekes = $s++;
        if($s<=$count){
         if($kekes>=$count){
             $kekes = 1;
         }else{
        if(isset($ration[$kekes])){
                $s=1;
        }else{
            $kek = $ration[$kekes];
        }
        }
    }

This is one of several solutions.

Thank you in advance!

P.S. The day goes separately from the array, the day I get from angularjs through request. If the day is larger than the array, then it should repeat the output of the keys is valid. Example: Day 13 - Key = 3.

I for example tried to do it all through for, but something is not successful.

Upd. There was an interesting idea, to receive the remainder of the division. But the remainder of the division will not work, because if there is an array with keys from 1 to 6. Then let's say it does not work out that 9 day is the key 3.

UPD 2. Here's the solution if anyone should. Thank you all for the response!

//get array
$ration = RationDay::all()->toArray();

$count = count($ration);
//getration - it day
$day = $getration;

if ($day >= ($maxDay = max(array_keys($ration)))) {
    $day = $day % $maxDay;
}

$getting = $ration[$day];

return $getting;

Body:
I would say you would have the best luck if you had your counter have a base 10.

$count = 0
for ($day = 1; $day <= $limit; $day++) {
   if ($count = 10) {
      $count = 0;
   }
   $count++;
   echo $array[$count];
}


问:
how to divide a string, I mean convert 0123456789 into "01","12","23","34","45","56","67","78","89"
I want to know how to split numbers, such as we fill 0123456789 data as the processing.
I want the results to come out.
 "01","12","23","34","45","56","67","78","89"
I found the problem is Bad Request (#400)
Unable to verify your data submission.
mycontroller

```<code>public function actionAbout() {
    $datas = yii::$app->request->post();
    $n = isset($datas['n']) ? $datas['n'] : NULL;
    $m = $n;

    return $this->render('about', [
                'n' => $n,
                'm' => $m,
    ]);
}
</code>```

view

```<code><form method="POST">
<div class="col-md-2">
    <?php echo Html::textInput('n', $n); ?>
</div>
<button class='btn-danger btn-md'>ตกลง »</button>
</code>```

```<code><?php
$data = $m;
$substr = null;
for ($i = 0; $i < strlen($data) - 1; $i++) {
    $substr = substr($data, $i, 2);
    echo $substr . ", ";}?>
</code>```

答:
Use sprintf to format the number: </p>

```<code>$str = "0123456789";

preg_match_all('/(.)/', $str, $numbers);

$numbers = $numbers[0];
array_walk($numbers, function( & $item, $key) {
    $item = sprintf("%02d", $item);
});
echo '```' . print_r($numbers, true) . '```';
</code>```

Body:
I want to know how to split numbers, such as we fill 0123456789 data as the processing.
I want the results to come out.
 "01","12","23","34","45","56","67","78","89"
I found the problem is Bad Request (#400)
Unable to verify your data submission.
mycontroller

public function actionAbout() {
    $datas = yii::$app->request->post();
    $n = isset($datas['n']) ? $datas['n'] : NULL;
    $m = $n;

    return $this->render('about', [
                'n' => $n,
                'm' => $m,
    ]);
}

view

<form method="POST">

    <?php echo Html::textInput('n', $n); ?>

<button class='btn-danger btn-md'>ตกลง »</button>

<?php
$data = $m;
$substr = null;
for ($i = 0; $i < strlen($data) - 1; $i++) {
    $substr = substr($data, $i, 2);
    echo $substr . ", ";}?>

Body:
Use sprintf to format the number:

$str = "0123456789";

preg_match_all('/(.)/', $str, $numbers);

$numbers = $numbers[0];
array_walk($numbers, function( & $item, $key) {
    $item = sprintf("%02d", $item);
});
echo '<pre>' . print_r($numbers, true) . '</pre>';


问:
Want to change opacity with react native refs on click
Here is my code. I want to change the opacity of refs when i click on any TouchableOpacity component.Please guide me how i can change opacity or change colour in react native with refs.
When i click my redirect function calls so i wanna change the opacity of particular ref in redirect function, i am passing ref and routename is redirect function.

i

```<code>mport React, { Component } from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet
} from 'react-native';
export default class Navigation extends Component {
  redirect(routeName,ref)
  {
      console.log(this.refs[ref]]);
      this.props.navigator.push({
      ident: routeName
     });
  }
  render() {
    return (
      <View style={style.navigation}>
        <View style={[style.navBar,styles.greenBack]}>
          <TouchableOpacity style={style.navPills} onPress={ this.redirect.bind(this,"AddItem","a")} ref="a">
            <Text style={[style.navText,style.activeNav]}>HOME</Text></TouchableOpacity>
          <TouchableOpacity style={style.navPills} onPress={ this.redirect.bind(this,"AddItem","b")} ref="b">
            <Text style={style.navText}>ORDER</Text></TouchableOpacity>
          <TouchableOpacity style={style.navPills} onPress={ this.redirect.bind(this,"ListItem","c")} ref="c">
            <Text style={style.navText}>SHOP LIST</Text></TouchableOpacity>
          <TouchableOpacity style={style.navPills} onPress={ this.redirect.bind(this,"ListItem","d")} ref="d">
            <Text style={style.navText}>DUES</Text></TouchableOpacity>
        </View>
        <View style={style.titleBar}>
          <Text style={style.titleBarText}>{this.props.title}</Text>
        </View>
      </View>
    );
  }
}
const style = StyleSheet.create({
 navigation:{
    top:0,
    right:0,
    left:0,
    position:'absolute'
  },
  navBar:{
    flexDirection:'row',
    padding:10,
    paddingTop:15,
    paddingBottom:15,
  },
  navPills:{
    flex:1,
    alignItems:'center'
  },
  navText:{
    flex:1,
    textAlign:'center',
    fontSize:16,
    fontWeight:'bold',
    color:'#ffffff',
    opacity:0.7
  },
  titleBar:{
    backgroundColor:'#ffffff',
    flex:1,
    padding:8,
    alignItems:'center',
    borderBottomWidth:1,
    borderBottomColor:'#dddddd'
  },
  titleBarText:{
    fontSize:18
  },
  activeNav:{
    opacity:1
  }
});
</code>```

答:
I'm not a fan of inline styles at all. So, for my purposes in a recent project I set the style of an element using its 'ref' value, then triggered a state change merely to cause the render function to be called. This is what I believe you're asking for and this sample code should point you in the right direction, otherwise perhaps this will help someone else in the future.

```<code>toggleDisplay() {
  if (this.refs.blah.style.display === "") {  // currently visible
    this.refs.blah.style.display = "none";
    this.setState({showBlah = false});
  } else {  // currently not visible
    this.refs.blah.style.display = "";
    this.setState({showBlah: true});
  }
}

render() {
  // Some element defined with the ref value used above.
  return (<div>
      <div ref="blah">Now you see me...</div>
      <button onClick="this.toggleDisplay">Toggle Me</button>
    </div>);
}
</code>```

Nothing in my render function changed by adding the toggle functionality, other than adding a button somewhere to call the function.  As I already indicated, that state value is only used to trigger the render process.

Body:
Here is my code. I want to change the opacity of refs when i click on any TouchableOpacity component.Please guide me how i can change opacity or change colour in react native with refs.
When i click my redirect function calls so i wanna change the opacity of particular ref in redirect function, i am passing ref and routename is redirect function.

i

mport React, { Component } from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet
} from 'react-native';
export default class Navigation extends Component {
  redirect(routeName,ref)
  {
      console.log(this.refs[ref]]);
      this.props.navigator.push({
      ident: routeName
     });
  }
  render() {
    return (
      <View style={style.navigation}>
        <View style={[style.navBar,styles.greenBack]}>
          <TouchableOpacity style={style.navPills} onPress={ this.redirect.bind(this,"AddItem","a")} ref="a">
            <Text style={[style.navText,style.activeNav]}>HOME</Text></TouchableOpacity>
          <TouchableOpacity style={style.navPills} onPress={ this.redirect.bind(this,"AddItem","b")} ref="b">
            <Text style={style.navText}>ORDER</Text></TouchableOpacity>
          <TouchableOpacity style={style.navPills} onPress={ this.redirect.bind(this,"ListItem","c")} ref="c">
            <Text style={style.navText}>SHOP LIST</Text></TouchableOpacity>
          <TouchableOpacity style={style.navPills} onPress={ this.redirect.bind(this,"ListItem","d")} ref="d">
            <Text style={style.navText}>DUES</Text></TouchableOpacity>
        </View>
        <View style={style.titleBar}>
          <Text style={style.titleBarText}>{this.props.title}</Text>
        </View>
      </View>
    );
  }
}
const style = StyleSheet.create({
 navigation:{
    top:0,
    right:0,
    left:0,
    position:'absolute'
  },
  navBar:{
    flexDirection:'row',
    padding:10,
    paddingTop:15,
    paddingBottom:15,
  },
  navPills:{
    flex:1,
    alignItems:'center'
  },
  navText:{
    flex:1,
    textAlign:'center',
    fontSize:16,
    fontWeight:'bold',
    color:'#ffffff',
    opacity:0.7
  },
  titleBar:{
    backgroundColor:'#ffffff',
    flex:1,
    padding:8,
    alignItems:'center',
    borderBottomWidth:1,
    borderBottomColor:'#dddddd'
  },
  titleBarText:{
    fontSize:18
  },
  activeNav:{
    opacity:1
  }
});

Body:
I'm not a fan of inline styles at all. So, for my purposes in a recent project I set the style of an element using its 'ref' value, then triggered a state change merely to cause the render function to be called. This is what I believe you're asking for and this sample code should point you in the right direction, otherwise perhaps this will help someone else in the future.

toggleDisplay() {
  if (this.refs.blah.style.display === "") {  // currently visible
    this.refs.blah.style.display = "none";
    this.setState({showBlah = false});
  } else {  // currently not visible
    this.refs.blah.style.display = "";
    this.setState({showBlah: true});
  }
}

render() {
  // Some element defined with the ref value used above.
  return (<div>
      <div ref="blah">Now you see me...</div>
      <button onClick="this.toggleDisplay">Toggle Me</button>
    </div>);
}

Nothing in my render function changed by adding the toggle functionality, other than adding a button somewhere to call the function.  As I already indicated, that state value is only used to trigger the render process.


问:
how to change some values in defaultConfig in gradle script?
I need to build the application for many brands. How to change applicationId in defaultConfig?

```<code>    compileSdkVersion 19
    buildToolsVersion '25.0.0'
    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/DEPENDENCIES'
    }
    defaultConfig {
        multiDexEnabled false
        applicationId = ""
        minSdkVersion 14
        targetSdkVersion 19
        signingConfig signingConfigs.config
    }
</code>```

And Gradle script like, but it's not working

```<code>    task buildForBrand {
       applicationId = "abc.${newBrand}"
    }
</code>```

答:
You can simply use Build Variants. Its overwrite your defaultConfig & you can also add more variable like base_url etc. For Ex:

```<code>android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.yourApp.pkg"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    productFlavors {
        buildFlavor1 {
            applicationId "com.yourApp.pkg1"
        }
        buildFlavor2 {
            applicationId "com.yourApp.pkg2"
        }
    }
}
</code>```

For more details go this link.

Body:
I need to build the application for many brands. How to change applicationId in defaultConfig?

    compileSdkVersion 19
    buildToolsVersion '25.0.0'
    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/DEPENDENCIES'
    }
    defaultConfig {
        multiDexEnabled false
        applicationId = ""
        minSdkVersion 14
        targetSdkVersion 19
        signingConfig signingConfigs.config
    }

And Gradle script like, but it's not working

    task buildForBrand {
       applicationId = "abc.${newBrand}"
    }

Body:
You can simply use Build Variants. Its overwrite your defaultConfig & you can also add more variable like base_url etc. For Ex:

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.yourApp.pkg"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    productFlavors {
        buildFlavor1 {
            applicationId "com.yourApp.pkg1"
        }
        buildFlavor2 {
            applicationId "com.yourApp.pkg2"
        }
    }
}

For more details go this link.


问:
undefined method `click' for "2":String, Rails error when using Mechanize
```<code>class ScraperController < ApplicationController

 def show
  mechanize = Mechanize.new

  website = mechanize.get('https://website.com/')
  $max = 2
  $counter = 0
  $link_to_click = 2

  @names = []

  while $counter <= $max do
    @names.push(website.css('.memName').text.strip)
    website.link_with(:text => '2').text.strip.click
    $link_to_click += 1
    $counter += 1
  end
 end
end
</code>```

I am trying to scrape 20 items off of each page and then click on the link at the bottom (1, 2, 3, 4, 5, etc.). However, I get the error as seen in the title which tells me that I cannot click the string. So it recognizes that the button '2' exists but will tell me if cannot click it. Ideally, once this is sorted out, I wanted to the use the $link_to_click variable as a way to replace the '2' so that it will increment each time but it always comes back as nil. I have also changed it to .to_s with the same result.

If I remove the click all together, it will scrape the same page 3 times instead of moving onto the next page. I have also removed the text.strip part before the .click and it will do the same thing. I have tried many variations but have had no luck.

I would really appreciate any advice you could offer.

答:
I ended up reviewing the articles I was referencing to solve this and came to this conclusion.

I changed the website_link to website = website.link_with(:text => $link_to_click.to_s).click (because it only worked as a string) and it printed out the first page, second and each one thereafter.

These are the articles that I was referencing to learn how to do this.

http://docs.seattlerb.org/mechanize/GUIDE_rdoc.html

and

https://readysteadycode.com/howto-scrape-websites-with-ruby-and-mechanize

Body:
class ScraperController < ApplicationController

 def show
  mechanize = Mechanize.new

  website = mechanize.get('https://website.com/')
  $max = 2
  $counter = 0
  $link_to_click = 2

  @names = []

  while $counter <= $max do
    @names.push(website.css('.memName').text.strip)
    website.link_with(:text => '2').text.strip.click
    $link_to_click += 1
    $counter += 1
  end
 end
end

I am trying to scrape 20 items off of each page and then click on the link at the bottom (1, 2, 3, 4, 5, etc.). However, I get the error as seen in the title which tells me that I cannot click the string. So it recognizes that the button '2' exists but will tell me if cannot click it. Ideally, once this is sorted out, I wanted to the use the $link_to_click variable as a way to replace the '2' so that it will increment each time but it always comes back as nil. I have also changed it to .to_s with the same result.

If I remove the click all together, it will scrape the same page 3 times instead of moving onto the next page. I have also removed the text.strip part before the .click and it will do the same thing. I have tried many variations but have had no luck.

I would really appreciate any advice you could offer.


问:
Input validation for cell phones and email on iOS safari
So I've been working on a custom online form and the required & pattern attributes don't seem to be supported by IOS Safari even though they say they do. What I'm trying to achieve is when the user tries to submit I want the input of the email and contact to be checked if they pass a certain format(like a regex for example) before submitting. Anybody know of a javascript/jquery solution to this?

Some sample code:

```<code><h3>Email Address</h3>
<div class="row">
    <div class="col-sm-3">
        <div class="form-group">
            <input id="emailAddress" name="email" placeholder="example@something.com" class="form-control" required>
        </div>
    </div>
</div>

<h3>Contact Number(Cell Phone Preferred!)Format: xxx-xxx-xxxx</h3>
<div class="row">
    <div class="col-sm-3">
        <div class="form-group">
            <input id="number" name="phone" placeholder="XXX-XXX-XXXX" class="form-control" required>
        </div>
    </div>
</div>
</code>```

答:
You can use jQuery Validation Plugin to validate your field.You can use addMethod for pattern . For sample I use this on phone field.

Plugin

$( "#myform" ).validate({
  rules: {
    email: {
      required: true
    },
    phone: { required: true, regex : /^[\d\s]+$/, minlength: 5 }
  }
});
$.validator.addMethod(
"regex",
function(value, element, regexp) {
    var check = false;
    return this.optional(element) || regexp.test(value);
},
"Please check your input."
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<form id="myform">
  <h3>Email Address</h3>
  <div class="row">
    <div class="col-sm-3">
      <div class="form-group">
        <input id="emailAddress" name="email" placeholder="example@something.com" class="form-control" required>
      </div>
    </div>
  </div>

  <h3>Contact Number(Cell Phone Preferred!)Format: xxx-xxx-xxxx</h3>
  <div class="row">
    <div class="col-sm-3">
      <div class="form-group">
        <input id="number" name="phone" placeholder="XXX-XXX-XXXX" class="form-control" required>
      </div>
    </div>
  </div>
  <input type="submit" value="Validate!">
</form></code>```

Body:
So I've been working on a custom online form and the required & pattern attributes don't seem to be supported by IOS Safari even though they say they do. What I'm trying to achieve is when the user tries to submit I want the input of the email and contact to be checked if they pass a certain format(like a regex for example) before submitting. Anybody know of a javascript/jquery solution to this?

Some sample code:

Email Address

            <input id="emailAddress" name="email" placeholder="example@something.com" class="form-control" required>

Contact Number(Cell Phone Preferred!)Format: xxx-xxx-xxxx

            <input id="number" name="phone" placeholder="XXX-XXX-XXXX" class="form-control" required>

Body:
You can use jQuery Validation Plugin to validate your field.You can use addMethod for pattern . For sample I use this on phone field.

Plugin

$( "#myform" ).validate({
  rules: {
    email: {
      required: true
    },
    phone: { required: true, regex : /^[\d\s]+$/, minlength: 5 }
  }
});
$.validator.addMethod(
"regex",
function(value, element, regexp) {
    var check = false;
    return this.optional(element) || regexp.test(value);
},
"Please check your input."
);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<form id="myform">
  <h3>Email Address</h3>
  <div class="row">
    <div class="col-sm-3">
      <div class="form-group">
        <input id="emailAddress" name="email" placeholder="example@something.com" class="form-control" required>
      </div>
    </div>
  </div>

  <h3>Contact Number(Cell Phone Preferred!)Format: xxx-xxx-xxxx</h3>
  <div class="row">
    <div class="col-sm-3">
      <div class="form-group">
        <input id="number" name="phone" placeholder="XXX-XXX-XXXX" class="form-control" required>
      </div>
    </div>
  </div>
  <input type="submit" value="Validate!">
</form>


问:
R - Apply a function based on logical vector
I have the following code, but it throws the following error:

```<code>the condition has length > 1 and only the first element will be used
</code>```

Obviously this means that I am misusing the if (condition) {action} construction, so I'm looking for a more elegant way to do this:

```<code>if (grepl("Spring", data$Survey)) {data["Season"] <- "Spring"}
if (grepl("Summer", data$Survey)) {data["Season"] <- "Summer"}
if (grepl("Fall", data$Survey)) {data["Season"] <- "Fall"}
</code>```

Basically, I would like to input a logical vector, and for every TRUE, apply a function to a data set of the same length (in this case, assigning a string value to that row of a dataframe).

答:
We can use base R to do this

```<code>data$Season <-  regmatches(data$Survey, regexpr("\\b(Spring|Survey|Fall)\\b", data$Survey))
data$Season
#[1] "Spring" "Spring" "Fall"   "Fall"   "Spring" "Spring" "Fall"   "Spring" "Fall"   "Spring" "Spring"
#[12] "Fall"   "Spring" "Fall"
</code>```

data

```<code>data <- data.frame(Survey = sample(c("it's Spring yay",
                                 "it's Summer yay",
                                 "it's Fall yay"),
                        20, replace = TRUE))
</code>```

Body:
I have the following code, but it throws the following error:

the condition has length > 1 and only the first element will be used

Obviously this means that I am misusing the if (condition) {action} construction, so I'm looking for a more elegant way to do this:

if (grepl("Spring", data$Survey)) {data["Season"] <- "Spring"}
if (grepl("Summer", data$Survey)) {data["Season"] <- "Summer"}
if (grepl("Fall", data$Survey)) {data["Season"] <- "Fall"}

Basically, I would like to input a logical vector, and for every TRUE, apply a function to a data set of the same length (in this case, assigning a string value to that row of a dataframe).

Body:
We can use base R to do this

data$Season <-  regmatches(data$Survey, regexpr("\\b(Spring|Survey|Fall)\\b", data$Survey))
data$Season
#[1] "Spring" "Spring" "Fall"   "Fall"   "Spring" "Spring" "Fall"   "Spring" "Fall"   "Spring" "Spring"
#[12] "Fall"   "Spring" "Fall"

data

data <- data.frame(Survey = sample(c("it's Spring yay",
                                 "it's Summer yay",
                                 "it's Fall yay"),
                        20, replace = TRUE))


问:
AngularJS $http-post - convert binary to excel file and download
I've created an application in Angular JS for downloading an Excel workbook through $http post.

In the below code I'm passing the information in the form of JSON , and send it to the server REST web service (java) through an angular $http post. The web service uses the information from the JSON and produces an Excel workbook. In the response within the success body of $http post, I'm getting binary data within that data variable, but don't know how to convert it and download as an Excel file.

Can anyone please tell me some solution for this for converting the binary to Excel file and download?

My code is as given below:

```<code>$http({
        url: 'myweb.com/myrestService',
        method: "POST",
        data: json, //this is your json data string
        headers: {
           'Content-type': 'application/json'
        }
    }).success(function (data, status, headers, config) {

        // Here i'm getting excel sheet binary datas in 'data'

    }).error(function (data, status, headers, config) {

    });
</code>```

答:
I created a service that will do this for you.

Pass in a standard $http object, and add some extra parameters.

1) A "type" parameter.  Specifying the type of file you're retrieving.  Defaults to: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'

2) A "fileName" parameter.  This is required, and should include the extension.

Example:

```<code>httpDownloader({
  method : 'POST',
  url : '--- enter the url that returns a file here ---',
  data : ifYouHaveDataEnterItHere,
  type : 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // this is the default
  fileName : 'YourFileName.xlsx'
}).then(res => {}).catch(e => {});
</code>```

That's all you need.  The file will be downloaded to the user's device without a popup.

Here's the git repo: https://github.com/stephengardner/ngHttpDownloader

Body:
I've created an application in Angular JS for downloading an Excel workbook through $http post.

In the below code I'm passing the information in the form of JSON , and send it to the server REST web service (java) through an angular $http post. The web service uses the information from the JSON and produces an Excel workbook. In the response within the success body of $http post, I'm getting binary data within that data variable, but don't know how to convert it and download as an Excel file.

Can anyone please tell me some solution for this for converting the binary to Excel file and download?

My code is as given below:

$http({
        url: 'myweb.com/myrestService',
        method: "POST",
        data: json, //this is your json data string
        headers: {
           'Content-type': 'application/json'
        }
    }).success(function (data, status, headers, config) {

        // Here i'm getting excel sheet binary datas in 'data'

    }).error(function (data, status, headers, config) {

    });

Body:
I created a service that will do this for you.

Pass in a standard $http object, and add some extra parameters.

1) A "type" parameter.  Specifying the type of file you're retrieving.  Defaults to: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'

2) A "fileName" parameter.  This is required, and should include the extension.

Example:

httpDownloader({
  method : 'POST',
  url : '--- enter the url that returns a file here ---',
  data : ifYouHaveDataEnterItHere,
  type : 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // this is the default
  fileName : 'YourFileName.xlsx'
}).then(res => {}).catch(e => {});

That's all you need.  The file will be downloaded to the user's device without a popup.

Here's the git repo: https://github.com/stephengardner/ngHttpDownloader


问:
Rails 'link_to' to Download An Image Immediately Instead of Opening it in the Browser
I have a link_to Rails helper that downloads a wallpaper when clicked. But the image is loading in the browser instead of being downloaded immediately.

```<code><%= link_to "1920x1080", @download.wallpapers[1].wallpaper.url %>
</code>```

But at the same time I have a link_to Rails helper that downloads a screensaver of .exe format but here it works as inteded: file being downloaded immediately.

```<code><%= link_to "720p", @download.screensavers.first.screensaver.url %>
</code>```

What should I add or do so that the images will not be opened in the browser but instead be downloaded immediately?

Thanks!

答:
Here's a simple solution using the HTML5 download attribute with paperclip </p>

```<code><%= link_to item.name, item.asset.url, download: item.asset.original_filename %>
</code>```

Body:
I have a link_to Rails helper that downloads a wallpaper when clicked. But the image is loading in the browser instead of being downloaded immediately.

<%= link_to "1920x1080", @download.wallpapers[1].wallpaper.url %>

But at the same time I have a link_to Rails helper that downloads a screensaver of .exe format but here it works as inteded: file being downloaded immediately.

<%= link_to "720p", @download.screensavers.first.screensaver.url %>

What should I add or do so that the images will not be opened in the browser but instead be downloaded immediately?

Thanks!

Body:
Here's a simple solution using the HTML5 download attribute with paperclip

<%= link_to item.name, item.asset.url, download: item.asset.original_filename %>


问:
Different ways about Passing 2D array of pointer to function C
I met some problems when passing 2d-array to functions today, later I found some solutions like A and B.
I knew that 2d-array is stored in a continuous memory as 1d. So in my opinion, there is no 2 dimensional points in fact, compiler split this continuous numbers and made '2 dimensional' concept.

My question is: in C after I explicitly told compiler the parameter is a 'int**', why it did not pass a '2 dimensional' point?

Someone may point out "in C you did not told compiler the group-length", I think it knew this information because if you try to reexplain the 12 elements' plain memory into arr[2][6] it will be error like "void printArr(int _arr[][6], int _columns, int _rows)".

A little confused please help...

```<code>int arr[][3]={{1,2,3},{5,6,7},{9,10,11},{13,14,15}};

void printArr(int _arr[][3], int _columns, int _rows){ //----->A
void printArr(int (* _arr)[3], int _columns, int _rows){//---->B
void printArr(int** _arr, int _columns, int _rows){//--------->C
    for(int r=0; r< _rows; r++){
        for (int c=0; c<_columns; c++)
            //printf("%4d,", _arr[r][c]);
            printf("%4d,", *(*(_arr+r)+c));
    }
}
int main(){
    printArr(arr, columns, rows);
}
</code>```

答:
Arrays decay into pointers, that means if you have an array of arrays int arr[x][y] it can decay into a pointer to array int (*arr)[y].

int ** arr therefore would be a version of decayed array of pointers int *arr[x], which is an incompatible type with your array.

Body:
I met some problems when passing 2d-array to functions today, later I found some solutions like A and B.
I knew that 2d-array is stored in a continuous memory as 1d. So in my opinion, there is no 2 dimensional points in fact, compiler split this continuous numbers and made '2 dimensional' concept.

My question is: in C after I explicitly told compiler the parameter is a 'int**', why it did not pass a '2 dimensional' point?

Someone may point out "in C you did not told compiler the group-length", I think it knew this information because if you try to reexplain the 12 elements' plain memory into arr[2][6] it will be error like "void printArr(int _arr[][6], int _columns, int _rows)".

A little confused please help...

int arr[][3]={{1,2,3},{5,6,7},{9,10,11},{13,14,15}};

void printArr(int _arr[][3], int _columns, int _rows){ //----->A
void printArr(int (* _arr)[3], int _columns, int _rows){//---->B
void printArr(int** _arr, int _columns, int _rows){//--------->C
    for(int r=0; r< _rows; r++){
        for (int c=0; c<_columns; c++)
            //printf("%4d,", _arr[r][c]);
            printf("%4d,", *(*(_arr+r)+c));
    }
}
int main(){
    printArr(arr, columns, rows);
}


问:
dalvik.system.PathClassLoader cannot be cast to java.net.URLClassLoader
Android - Adding jar file dynamically to a ClassLoader like:

```<code>String strJarfile = "/data/data/com.example.classloader/files/apps/Calc/SumAndSub.jar";
URLClassLoader sysloader = (URLClassLoader) ClassLoader
                .getSystemClassLoader();
        try
        {
            File f = new File(strJarfile);
            URL u = f.toURI().toURL();

            Class[] parameters = new Class[] { URL.class };
            Method method = URLClassLoader.class.getDeclaredMethod("addURL",
                    parameters);
            method.setAccessible(true);
            method.invoke(sysloader, new Object[] { u });
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
</code>```

And, error:

```<code>Caused by: java.lang.ClassCastException: dalvik.system.PathClassLoader cannot be cast to java.net.URLClassLoader
</code>```

This code work fine in java-core, but not with android.
What is solution?
Thanks,

答: The solution is not to assume that the system class loader is a URLClassLoader. There's nothing anywhere that says it is. If your code ever worked you got lucky.

Body:
Android - Adding jar file dynamically to a ClassLoader like:

String strJarfile = "/data/data/com.example.classloader/files/apps/Calc/SumAndSub.jar";
URLClassLoader sysloader = (URLClassLoader) ClassLoader
                .getSystemClassLoader();
        try
        {
            File f = new File(strJarfile);
            URL u = f.toURI().toURL();

            Class[] parameters = new Class[] { URL.class };
            Method method = URLClassLoader.class.getDeclaredMethod("addURL",
                    parameters);
            method.setAccessible(true);
            method.invoke(sysloader, new Object[] { u });
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

And, error:

Caused by: java.lang.ClassCastException: dalvik.system.PathClassLoader cannot be cast to java.net.URLClassLoader

This code work fine in java-core, but not with android.
What is solution?
Thanks,


问:
Panel List Php not showing all data
I am trying to create a panel list that shows certain rows from my database, however when I'm trying to call it, it only shows 1 data in the row even though i limit it by 5.

Here is my script:

```<code><?php
$link = mysqli_connect("localhost", "root", "", "test");
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT * FROM updates order by id desc limit 5";
if($result = mysqli_query($link, $sql)){
    if($list=mysqli_fetch_array($result)){
                echo "<div class=\"container\">";
        echo "<table>";
            echo "<tr>";
            echo "</tr>";

        echo "<div class=\"col-md-4\">";
        echo "<div class=\"panel panel-primary\">";
        echo "<div class=\"panel-heading\">Updates";
        echo "</div>";
        echo "<ul class=\"list-group\">";
        echo "<li class=\"list-group-item\">";
        echo "<b><h4>{$list["updates"]}</b></h4>";
        echo "</li>";
        echo "</div>";
        echo "</div>";
        echo "</div>";
        echo "</div>";
}
        echo "</table>";
        mysqli_free_result($result);
    } else{
        echo "No records matching your query were found.";
    }
{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
?>
</code>```

答:
You use sql to get five data, but you use mysqli_fetch_array() function only took out a line.

error line 8;

Title: Panel List Php not showing all data

Body:
I am trying to create a panel list that shows certain rows from my database, however when I'm trying to call it, it only shows 1 data in the row even though i limit it by 5.

Here is my script:

<?php
$link = mysqli_connect("localhost", "root", "", "test");
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT * FROM updates order by id desc limit 5";
if($result = mysqli_query($link, $sql)){
    if($list=mysqli_fetch_array($result)){
                echo "
";
        echo "
";
            echo "
";
            echo "
";

        echo "
";
        echo "
";
        echo "
Updates";
        echo "
";
        echo "
";
        echo "
";
        echo "
{$list["updates"]}
";
        echo "
";
        echo "
";
        echo "
";
        echo "
";
        echo "
";
}
        echo "
";
        mysqli_free_result($result);
    } else{
        echo "No records matching your query were found.";
    }
{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
?>


问:
C++ Passing array into function
I'm relatively new to C++ and am having a tough time passing my array into a separate function. Apologies for re-asking a question that has no doubt been answered a dozen times before, but I couldn't find any questions similar to the problem I have with my code.</p>

```<code>int main()
{
    Array<int> intarray(10);
    int grow_size = 0;

    intarray[0] = 42;
    intarray[1] = 12;
    intarray[9] = 88;

    intarray.Resize(intarray.Size()+2);
    intarray.Insert(10, 6);

    addToArray(intarray);

    int i = intarray[0];

    for (i=0;i<intarray.Size();i++)
    cout<<i<<'\t'<<intarray[i]<<endl;

    Sleep(5000);
}

void addToArray(Array<int> intarray)
{
    int newValue;
    int newIndex;

    cout<<"What do you want to add to the array?"<<endl;
    cin >> newValue;
    cout<<"At what point should this value be added?"<<endl;
    cin >> newIndex;

    intarray.Insert(newValue, newIndex);
}
</code>```

答:
My suggestion is use pointer, as usual declare the function

```<code>void yourFunction(int * arrayPointer);
</code>```

In main() function you should input

```<code>int yourArray[8] = {11, -2, 45, 37, 18, 35};
int * arrayPointer = &yourFunction[0];
yourFunction(yourArray); // call your function
</code>```

Finally in yourFunction()

```<code>void yourFunction(int * arrayPointer)
{
    // print all number in the array
    for(int x = 0; x < 6; x++)
    {
        cout << *arrayPointer << " ";
        arrayPointer++;
    }
}
</code>```

This at least work for me, hope this will help

Title: C++ Passing array into function

Body:
I'm relatively new to C++ and am having a tough time passing my array into a separate function. Apologies for re-asking a question that has no doubt been answered a dozen times before, but I couldn't find any questions similar to the problem I have with my code.

int main()
{
    Array<int> intarray(10);
    int grow_size = 0;

    intarray[0] = 42;
    intarray[1] = 12;
    intarray[9] = 88;

    intarray.Resize(intarray.Size()+2);
    intarray.Insert(10, 6);

    addToArray(intarray);

    int i = intarray[0];

    for (i=0;i<intarray.Size();i++)
    cout<<i<<'\t'<<intarray[i]<<endl;

    Sleep(5000);
}

void addToArray(Array<int> intarray)
{
    int newValue;
    int newIndex;

    cout<<"What do you want to add to the array?"<<endl;
    cin >> newValue;
    cout<<"At what point should this value be added?"<<endl;
    cin >> newIndex;

    intarray.Insert(newValue, newIndex);
}

Body:
My suggestion is use pointer, as usual declare the function

void yourFunction(int * arrayPointer);

In main() function you should input

int yourArray[8] = {11, -2, 45, 37, 18, 35};
int * arrayPointer = &yourFunction[0];
yourFunction(yourArray); // call your function

Finally in yourFunction()

void yourFunction(int * arrayPointer)
{
    // print all number in the array
    for(int x = 0; x < 6; x++)
    {
        cout << *arrayPointer << " ";
        arrayPointer++;
    }
}

This at least work for me, hope this will help


问:
Is it a Security Issue in Codeigniter which Allow to Run Controller Functions using URL?
I am not sure that this is a security  issue or I understand something wrongly? That's why I ask this question.

As I understood, Anyone can run any controller function using URL. Assume that I have a controller function called delete in controller called user.

So anyone can run that function using

```<code>http://example.com/index.php/user/delete
</code>```

Is it a securty issue?

I mean in pure PHP, you can't run any function via URL even you know the custom function name.

But seems like anyone can run any function in Codeigniter Controller if they know the controller name and function name. Is it a security issue or I understand something wrongly?

答:
You're misunderstanding. When you pass a URL to CodeIgniter, you aren't directly executing a custom function. CI takes the URL, breaks it into pieces and figures out how to route it based on default handling and any custom routing that you have configured. You can throw together a quick and dirty setup that works in a similar fashion without using CI. This kind of setup isn't unique to CI or even to PHP itself.

This behavior is not a security concern. USER INPUT+DEVELOPER RESPONSE is the security concern. How you handle that delete call and the data that's passed into is where the potential security problem becomes relevant.

Body:
I am not sure that this is a security  issue or I understand something wrongly? That's why I ask this question.

As I understood, Anyone can run any controller function using URL. Assume that I have a controller function called delete in controller called user.

So anyone can run that function using

http://example.com/index.php/user/delete

Is it a securty issue?

I mean in pure PHP, you can't run any function via URL even you know the custom function name.

But seems like anyone can run any function in Codeigniter Controller if they know the controller name and function name. Is it a security issue or I understand something wrongly?


问:
Angular2 Can't get data from response using promise?
I'm trying to get data out of response but I can't seem to get the result I want.

```<code>facebookLogin(): void {

    this.fb.login()
        .then((res: LoginResponse) => {
            this.accessToken = res.authResponse.accessToken;
            this.expiresIn = res.authResponse.expiresIn;
            this.signedRequest = res.authResponse.signedRequest;
            this.userId = res.authResponse.userID;
            console.log('Logged In', res, this.accessToken); //works without problem
            this.router.navigate(['../other-register']);
        })
        .catch(this.handleError);

    console.log(this.accessToken) //printing 'undefined'
}
</code>```

Here within then => { }, console.log seems to print the data in res without any problem. I can see data I want but when I console.log outside of then =>{ }, it's giving me undefined.

what am I doing wrong? I need to use data inside response and pass them to other component but I can't seem to figure out what I'm doing wrong.

Can anyone help me? Thanks

答:
This is the expected behavior actually.

this.fb.login() is a Promise.  This means that the value of the result/response (res) will not readily be available right when it is called, but it 'promises' that it will have a value once some action is taken or a response is returned and 'then' it will do something.  In this case that action would be connecting to the Facebook API and having data returned.  This is just like Ajax in jQuery if you have experience with that, Promises are a more evolved version of callbacks.

What is happening is that you function is being executed in this order:

this.fb.login() is called.  Doesn't have a value yet so it allows the script to continue.

console.log() is called.

this.fb.login's value is returned and the then() closure is executed.

If you want to know when the value is return or perform a specific action once it is returned you can call a function within .then() or look into observables (RxJS) to notify other parts of your application that login was successful (or wasn't).

Observables Example

Here is one example on Observables, however, I would do more research as there are multiple Subjects to select from, all which have slightly different behavior.  Also, this kind of pattern works better in Angular2+ if this is performed in a service, that way other components will be able to access the information provided by Facebook.

```<code>import { AsyncSubject } from 'rxjs/AsyncSubject';

// ...

response: AsyncSubject<any> = new AsyncSubject();

facebookLogin(): void {

    this.fb.login()
        .then((res: LoginResponse) => {
            this.response.next(res);
            this.response.complete();
            this.router.navigate(['../other-register']);
        })
        .catch(this.handleError);

}
</code>```

You then retrieve the data from within response like this:

```<code>this.response.subscribe(result => {
    console.log(result);
})
</code>```

Pass Data Example

Since you already have a function in the service designed to receive the data, this may be a wiser implementation in your case.

```<code>facebookLogin(): void {

    this.fb.login()
        .then((res: LoginResponse) => {
            this.user_service.passData(res.authResponse.accessToken);
            this.router.navigate(['../other-register']);
        })
        .catch(this.handleError);

}
</code>```

Body:
I'm trying to get data out of response but I can't seem to get the result I want.

facebookLogin(): void {

    this.fb.login()
        .then((res: LoginResponse) => {
            this.accessToken = res.authResponse.accessToken;
            this.expiresIn = res.authResponse.expiresIn;
            this.signedRequest = res.authResponse.signedRequest;
            this.userId = res.authResponse.userID;
            console.log('Logged In', res, this.accessToken); //works without problem
            this.router.navigate(['../other-register']);
        })
        .catch(this.handleError);

    console.log(this.accessToken) //printing 'undefined'
}

Here within then => { }, console.log seems to print the data in res without any problem. I can see data I want but when I console.log outside of then =>{ }, it's giving me undefined.

what am I doing wrong? I need to use data inside response and pass them to other component but I can't seem to figure out what I'm doing wrong.

Can anyone help me? Thanks

Body:
This is the expected behavior actually.

this.fb.login() is a Promise.  This means that the value of the result/response (res) will not readily be available right when it is called, but it 'promises' that it will have a value once some action is taken or a response is returned and 'then' it will do something.  In this case that action would be connecting to the Facebook API and having data returned.  This is just like Ajax in jQuery if you have experience with that, Promises are a more evolved version of callbacks.

What is happening is that you function is being executed in this order:

this.fb.login() is called.  Doesn't have a value yet so it allows the script to continue.

console.log() is called.

this.fb.login's value is returned and the then() closure is executed.

If you want to know when the value is return or perform a specific action once it is returned you can call a function within .then() or look into observables (RxJS) to notify other parts of your application that login was successful (or wasn't).

Observables Example

Here is one example on Observables, however, I would do more research as there are multiple Subjects to select from, all which have slightly different behavior.  Also, this kind of pattern works better in Angular2+ if this is performed in a service, that way other components will be able to access the information provided by Facebook.

import { AsyncSubject } from 'rxjs/AsyncSubject';

// ...

response: AsyncSubject<any> = new AsyncSubject();

facebookLogin(): void {

    this.fb.login()
        .then((res: LoginResponse) => {
            this.response.next(res);
            this.response.complete();
            this.router.navigate(['../other-register']);
        })
        .catch(this.handleError);

}

You then retrieve the data from within response like this:

this.response.subscribe(result => {
    console.log(result);
})

Pass Data Example

Since you already have a function in the service designed to receive the data, this may be a wiser implementation in your case.

facebookLogin(): void {

    this.fb.login()
        .then((res: LoginResponse) => {
            this.user_service.passData(res.authResponse.accessToken);
            this.router.navigate(['../other-register']);
        })
        .catch(this.handleError);

}


问:
Why would SQL be very slow when doing updates?
Suddenly doing updates into a few tables have gotten 10 times slower than they used to be.  What are some good recommendations to determine root cause and optimization?  Could it be that indexing certain columns are causing updates to be slow?  Any other recommendations?

I guess more important than guesses would be help on the process of identifying the root cause or metrics around performance.

Is there anything in Fluent NHibernate that you can use to help identify the root cause of performance issues?

答:
Causes...

Too many indexes

Growing number of records

Bad index covarage of the where-clause of the update query

Locking issues due to multiple updates (table-lock)

Hardware issues (disk controller, network, etc.)


问:
Python - How can I build a correct statement?
Im fresh here and with Python, I have this challenge in python 3.
1 - Check if the internet connection is working fine.
2 - If condition one is true call a service
3 - Repeat

This code is uded to check if the ping is working:

```<code>import os
hostname = ('https://fmolinaclouds0000000000trial.hanatrial.ondemand.com/demoApp/demo0
1/app02/SHIOT_02/services/putSensorReading.xsjs?id=TEST&value=999')

while true:
response = os.system('ping -c 1 ' + hostname)

#and then check the response...
if response == 0:
   print('is up!')
else:
print('is down!')
</code>```

This is the code that call the service:

```<code>from sense_hat import SenseHat
sense = SenseHat()
import requests
import time

temp = sense.temp
payload_temp = {'id': 'TEMP', 'value': sense.get_temperature()}
payload_press = {'id': 'PRESS', 'value': sense.get_pressure()}
payload_humit = {'id': 'HUMIT', 'value': sense.get_humidity()}
payload_ts = {'id': 'TS', 'value': time.time()}

while True:

# Wait for 60 seconds

    temp = sense.temp
    requests.get('https://fmolinaclouds0008215086trial.hanatrial.ondemand.com/demoApp/demo01/app02/SHIOT_02/services/putSensorReading.xsjs', params=payload_temp)
    r = requests.get('https://fmolinaclouds0008215086trial.hanatrial.ondemand.com/demoApp/demo01/app02/SHIOT_02/services/putSensorReading.xsjs', params=payload_press)
    r = requests.get('https://fmolinaclouds0008215086trial.hanatrial.ondemand.com/demoApp/demo01/app02/SHIOT_02/services/putSensorReading.xsjs', params=payload_humit)

    print(payload_temp)
    print(payload_press)
    print(payload_humit)
#    print(payload_ts)

time.sleep(60)
</code>```

So, how can put all of this together?

答:
You'll want to define a function and then call that from your main program, e.g

```<code>def check_internet(hostname):
    return os.system("ping --count 1 " + hostname) == 0:
# step 1
internet_okay = check_internet("localhost")
if internet_okay:  # step 2
    do_other_stuff()  # step3
</code>```

For further assistance here, check out these directions.

Body:
Im fresh here and with Python, I have this challenge in python 3.
1 - Check if the internet connection is working fine.
2 - If condition one is true call a service
3 - Repeat

This code is uded to check if the ping is working:

import os
hostname = ('https://fmolinaclouds0000000000trial.hanatrial.ondemand.com/demoApp/demo0
1/app02/SHIOT_02/services/putSensorReading.xsjs?id=TEST&value=999')

while true:
response = os.system('ping -c 1 ' + hostname)

#and then check the response...
if response == 0:
   print('is up!')
else:
print('is down!')

This is the code that call the service:

from sense_hat import SenseHat
sense = SenseHat()
import requests
import time

temp = sense.temp
payload_temp = {'id': 'TEMP', 'value': sense.get_temperature()}
payload_press = {'id': 'PRESS', 'value': sense.get_pressure()}
payload_humit = {'id': 'HUMIT', 'value': sense.get_humidity()}
payload_ts = {'id': 'TS', 'value': time.time()}

while True:

# Wait for 60 seconds

    temp = sense.temp
    requests.get('https://fmolinaclouds0008215086trial.hanatrial.ondemand.com/demoApp/demo01/app02/SHIOT_02/services/putSensorReading.xsjs', params=payload_temp)
    r = requests.get('https://fmolinaclouds0008215086trial.hanatrial.ondemand.com/demoApp/demo01/app02/SHIOT_02/services/putSensorReading.xsjs', params=payload_press)
    r = requests.get('https://fmolinaclouds0008215086trial.hanatrial.ondemand.com/demoApp/demo01/app02/SHIOT_02/services/putSensorReading.xsjs', params=payload_humit)

    print(payload_temp)
    print(payload_press)
    print(payload_humit)
#    print(payload_ts)

time.sleep(60)

So, how can put all of this together?

Body:
You'll want to define a function and then call that from your main program, e.g

def check_internet(hostname):
    return os.system("ping --count 1 " + hostname) == 0:
# step 1
internet_okay = check_internet("localhost")
if internet_okay:  # step 2
    do_other_stuff()  # step3

For further assistance here, check out these directions.


问:
Windows bat: loop files in directories
I'm working on Windows. I have many jpg files in subdirectories of a directory. I don't know exactly the architecture of the directory, meaning that I don't know how many levels the subdirectories have. What I need to do is to process jpg files according to their paths. Here is an example:

```<code>dir
 |---sub dir1
 |      |-----sub dir11
 |               |-----a.jpg
 |               |-----b.jpg
 |---sub dir2
        |-----c.jpg
        |-----d.jpg
</code>```

So I need to execute commands as below:

```<code>process.bat C:\dir\sub dir1\sub dir11\a.jpg C:\dir\sub dir1\sub dir11\b.jpg
process.bat C:\dir\sub dir2\c.jpg C:\dir\sub dir2\d.jpg
</code>```

I don't know how to write such a bat file especially a bat processing paths contains spaces. I don't know if spaces will make some trouble.

I've tried as below but it doesn't work:

```<code>@Echo off&SetLocal EnableExtensions EnableDelayedExpansion

For /d %%A in (C:\dir\*) Do (
    Set "Files="
    For /f %%B in ("%%~fA\*.jpg") Do Set Files=!Files! "%%~fB"
    If defined Files echo process.bat %%~fA\*.jpg
)

pause
</code>```

When I execute the script, I get the result as below:

```<code>process.bat C:\dir\sub dir1\*.jpg
process.bat C:\dir\sub dir2\*.jpg
</code>```

It seems that * is regarded as a normal character.

答:
```<code>@Echo off&SetLocal EnableExtensions EnableDelayedExpansion

For /d %%A in (C:\dir\*) Do (
    Set "Files="
    For /F "delims=" %%B in ('dir /S /B "%%~fA\*.jpg"') Do Set Files=!Files! "%%~fB"
    If defined Files echo process.bat !Files!
)

pause
</code>```

Title: Windows bat: loop files in directories

Body:
I'm working on Windows. I have many jpg files in subdirectories of a directory. I don't know exactly the architecture of the directory, meaning that I don't know how many levels the subdirectories have. What I need to do is to process jpg files according to their paths. Here is an example:

dir
 |---sub dir1
 |      |-----sub dir11
 |               |-----a.jpg
 |               |-----b.jpg
 |---sub dir2
        |-----c.jpg
        |-----d.jpg

So I need to execute commands as below:

process.bat C:\dir\sub dir1\sub dir11\a.jpg C:\dir\sub dir1\sub dir11\b.jpg
process.bat C:\dir\sub dir2\c.jpg C:\dir\sub dir2\d.jpg

I don't know how to write such a bat file especially a bat processing paths contains spaces. I don't know if spaces will make some trouble.

I've tried as below but it doesn't work:

@Echo off&SetLocal EnableExtensions EnableDelayedExpansion

For /d %%A in (C:\dir\*) Do (
    Set "Files="
    For /f %%B in ("%%~fA\*.jpg") Do Set Files=!Files! "%%~fB"
    If defined Files echo process.bat %%~fA\*.jpg
)

pause

When I execute the script, I get the result as below:

process.bat C:\dir\sub dir1\*.jpg
process.bat C:\dir\sub dir2\*.jpg

It seems that * is regarded as a normal character.


问:
in ruby Create a program that asks a user for 10 numbers and then returns the sum
```<code>puts "Im gonna ask you for 10 numbers and then give you the sum"
puts "Give me the first number"
first_number= gets.chomp
puts "Give me the second number"
second_number=gets.chomp
puts "Give me the third number "
third_number=gets.chomp
puts "Give me the fourth number"
fourth_number= gets.chomp
puts "Give me the fifth number"
fifth_number=gets.chomp
puts "Give me the sixth number"
sixth_number=gets.chomp
puts "Give me the seventh number"
seventh_number=gets.chomp
puts "Give me the eighth number"
eighth_number=gets.chomp
puts "Give me the ninth number"
ninth_number=gets.chomp
puts "Give me the tenth number"
tenth_number= gets.chomp
puts "The Sum of all your TEN numbers is:"
puts first_number.to_i + second_number.to_i+ third_number.to_i + fourth_number.to_i + fifth_number.to_i + sixth_number.to_i+ seventh_number.to_i+ eighth_number.to_i+ ninth_number.to_i + tenth_number.to_i
</code>```

答:
```<code> sum = 10.times.inject(0) do|sum,i|
         puts "Enter #{i+1}th number"
         sum = sum + gets.chomp.to_f
       end
 puts "The sum is #{sum}"
</code>```

This example works well with decimal and integer you pass.

You are missing the point that, you are a software writer. You write softwares for end-users and its up to the users, how many numbers they want to enter. So I suggest you to learn writing dynamic softwares. Do not just hard-code everything. Make things flexible so that its easily tweak-able.

One idea is, you can even ask user how many numbers they want to enter.

Body:
 sum = 10.times.inject(0) do|sum,i|
         puts "Enter #{i+1}th number"
         sum = sum + gets.chomp.to_f
       end
 puts "The sum is #{sum}"

This example works well with decimal and integer you pass.

You are missing the point that, you are a software writer. You write softwares for end-users and its up to the users, how many numbers they want to enter. So I suggest you to learn writing dynamic softwares. Do not just hard-code everything. Make things flexible so that its easily tweak-able.

One idea is, you can even ask user how many numbers they want to enter.


问:
splitting multiple values in one column into multiple rows R
I have a data frame which for the most part is one observation per row. However, some rows have multiple values:

```<code># A tibble: 3 x 2
          `number`   abilities
             <dbl>       <chr>
1               51       b1261
2               57        d710
3               57 b1301; d550

structure(list(`number` = c(51, 57, 57), abilities = c("b1261",
"d710", "b1301; d550")), .Names = c("number", "abilities"
), row.names = c(NA, -3L), class = c("tbl_df", "tbl", "data.frame"
))
</code>```

I'd like to get the following:

```<code># A tibble: 3 x 2
          `number`   abilities
             <dbl>       <chr>
1               51       b1261
2               57        d710
3               57        d550
4               57       b1301
</code>```

It's straight forward enough to split on the ; but I'm not sure how to easily add a new row, especially as abilities might contain more than 2 values.

This is very similar to: R semicolon delimited a column into rows but doesn't need to remove duplicates

答:
Another option is cSplit

```<code> library(splitstackshape)
 cSplit(df1, 'abilities', '; ', 'long')
 #   number abilities
 #1:     51     b1261
 #2:     57      d710
 #3:     57     b1301
 #4:     57      d550
</code>```

Body:
I have a data frame which for the most part is one observation per row. However, some rows have multiple values:

# A tibble: 3 x 2
          `number`   abilities
             <dbl>       <chr>
1               51       b1261
2               57        d710
3               57 b1301; d550

structure(list(`number` = c(51, 57, 57), abilities = c("b1261",
"d710", "b1301; d550")), .Names = c("number", "abilities"
), row.names = c(NA, -3L), class = c("tbl_df", "tbl", "data.frame"
))

I'd like to get the following:

# A tibble: 3 x 2
          `number`   abilities
             <dbl>       <chr>
1               51       b1261
2               57        d710
3               57        d550
4               57       b1301

It's straight forward enough to split on the ; but I'm not sure how to easily add a new row, especially as abilities might contain more than 2 values.

This is very similar to: R semicolon delimited a column into rows but doesn't need to remove duplicates

Body:
Another option is cSplit

 library(splitstackshape)
 cSplit(df1, 'abilities', '; ', 'long')
 #   number abilities
 #1:     51     b1261
 #2:     57      d710
 #3:     57     b1301
 #4:     57      d550


问:
Getting values of textfields on page
Lets just say that I have some (many many many) text fields on a page... and i enter a new value in one of them, then click a button... How can I update the database with just that new value? Or, if it would be easier... How can I update all of those textfields to the database?

Thanks :)

答:
you can use jquery data(), to store the first state ,

when you want to post it, post only the textbox that has been changed .

see this post

Title: Getting values of textfields on page


问:
Codename one: Dont allow to create dual app on same device
I have created app using codename one which can be installed on same device two times with dual app features which provided by android.
I dont want to allow my app to install multiple time on same device so I want that my app should not support that dual app feature so what should i do for that?can you help me to solve this problem?
thanks in advance.</p>

答:
It doesn't seem to be an Android feature but rather a vendor customization. As far as I can tell the whole idea is to hide the fact that this is the same phone from the app developer so there is probably no easy way to detect this.

If you find native Android code that detects it I can explain how you would do this in Codename One.


问:
how to hide or delete the button on top_right statusBar?
when i use universal links in weixin, the domain appear on the top_right of statusbar, how to hide or delete the button?

enter image description here

答: That's a new feature in iOS 9. I don't think its possible.</p>


问:
What case is better?
I have a list of MyClass:

```<code>struct MyClass {
     bool is_old_result(int lifetime);
};
std::list<MyClass> results;
int lifetime = 50; // or something else
</code>```

What case of removing is better (c++ design and perfomance):

```<code>results.remove_if(
    std::bind2nd(std::mem_fun_ref(&MyClass::is_old_result), lifetime));
</code>```

or

```<code>results.remove_if(boost::bind(&MyClass::is_old_result, _1, lifetime));
</code>```

or

```<code>struct RemoveFunctor {
   RemoveFunctor (int lifetime) : lifetime(lifetime) {}
   bool operator()(const MyClass & m) { return m.is_old_result(lifetime); }
private:
   int lifetime;
};
results.remove_if(RemoveFunctor(lifetime));
</code>```

and why?

P.S. Please, no lambda-function and no C++0x.

答:
In terms of design, the one using bind is definitely the clearest. (followed by the explicit function object). Why? Succinct.

In terms of performance, the function object should be unbeatable (everything can be easily analysed and inlined). Depending on how the compiler optimizes, the one using bind could possibly match it (the call to is_old_result may or may not be through a pointer, depending on the compiler's analysis).

Title: What case is better?

Body:
I have a list of MyClass:

struct MyClass {
     bool is_old_result(int lifetime);
};
std::list<MyClass> results;
int lifetime = 50; // or something else

What case of removing is better (c++ design and perfomance):

results.remove_if(
    std::bind2nd(std::mem_fun_ref(&MyClass::is_old_result), lifetime));

or

results.remove_if(boost::bind(&MyClass::is_old_result, _1, lifetime));

or

struct RemoveFunctor {
   RemoveFunctor (int lifetime) : lifetime(lifetime) {}
   bool operator()(const MyClass & m) { return m.is_old_result(lifetime); }
private:
   int lifetime;
};
results.remove_if(RemoveFunctor(lifetime));

and why?

P.S. Please, no lambda-function and no C++0x.


问:
Why is this RewriteRule altering QUERY_STRING, but leaving REQUEST_URI untouched?
I have a copy of Concrete5, a PHP-based CMS, running on example.com.

Concrete5 comes with the following basic instructions for pretty URLs (redirecting all URLs to a central index.php)

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} !^/c5.7
RewriteRule ^.*$ c5.7/$0 [L]    # Concrete5 is running in the c5.7/ subdirectory
</IfModule>
</code>```

Pretty straightforward.

Now I have a certain set of URLs that take the form

```<code> /product/{productname}
</code>```

that I need to forward to the Concrete5 (virtual) URL

```<code>/products/details?name={productname}
</code>```

That URL is set up and works as expected when I enter it manually in the browser.

So I added a line to the htaccess file and it now looks like this:

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

# New rule for products
RewriteCond %{REQUEST_URI} ^/product/
RewriteRule ^product/(.+)$ /products/details?name=$1 [QSA]

RewriteCond %{REQUEST_URI} !^/c5.7
RewriteRule ^.*$ c5.7/$0 [L]

</IfModule>
</code>```

I can confirm the RewriteRule gets triggered when I choose a random, external URL as the redirection target.

But whenever it is an internal redirect like above, what happens is, I get a 404 inside Concrete5. When I inspect what was passed to it, I see:

```<code> REQUEST_URI:  /product/my-random-product
 QUERY_STRING: name=my-random-product
</code>```

So it appears that the rule is triggered and does some rewriting, but REQUEST_URI remains unchanged!

Why?

Is it because PHP 7.1 is running via CGI?

I have tried a zillion variations and all the flags in the book, with little success.

答:
The REQUEST_URI in PHP is not the same as the REQUEST_URI within mod_rewrite, so you can't do it like this. In PHP it always contains the original URL. So you can't change it like this if your CMS is working off that.

You should set up your CMS to use the URLs you want, rather than trying to augment your CMS's URL rewriting like this.

If you inspect REDIRECT_URL in PHP you will see the last rewritten URI.

Body:
I have a copy of Concrete5, a PHP-based CMS, running on example.com.

Concrete5 comes with the following basic instructions for pretty URLs (redirecting all URLs to a central index.php)

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} !^/c5.7
RewriteRule ^.*$ c5.7/$0 [L]    # Concrete5 is running in the c5.7/ subdirectory
</IfModule>

Pretty straightforward.

Now I have a certain set of URLs that take the form

 /product/{productname}

that I need to forward to the Concrete5 (virtual) URL

/products/details?name={productname}

That URL is set up and works as expected when I enter it manually in the browser.

So I added a line to the htaccess file and it now looks like this:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

# New rule for products
RewriteCond %{REQUEST_URI} ^/product/
RewriteRule ^product/(.+)$ /products/details?name=$1 [QSA]

RewriteCond %{REQUEST_URI} !^/c5.7
RewriteRule ^.*$ c5.7/$0 [L]

</IfModule>

I can confirm the RewriteRule gets triggered when I choose a random, external URL as the redirection target.

But whenever it is an internal redirect like above, what happens is, I get a 404 inside Concrete5. When I inspect what was passed to it, I see:

 REQUEST_URI:  /product/my-random-product
 QUERY_STRING: name=my-random-product

So it appears that the rule is triggered and does some rewriting, but REQUEST_URI remains unchanged!

Why?

Is it because PHP 7.1 is running via CGI?

I have tried a zillion variations and all the flags in the book, with little success.


问:
What to gitignore from the .idea folder?

Possible Duplicate:

  Intellij Idea 9/10, what folders to check into (or not check into) source control?

I started using WebStorm for web development and am not sure what to add and what to exclude from our Git repository. Clearly some files inside the .idea folder are meant to be version controlled like the external library settings (jsLibraryMappings.xml) but others will probably change very often and are developer-specific (e.g., workspace.xml).

What is the recommended .gitignore pattern for WebStorm / IntelliJ IDEA?

P.S. There are already questions about this but usually focus only on whether to include the whole .idea folder or whether to fully exclude it. I think some of the files inside the .idea folder should be version controlled while others shouldn't and I'm trying to find out which ones.

答:
Remove .idea folder

```<code>$rm -R .idea/
</code>```

Add rule

```<code>$echo ".idea/*" >> .gitignore
</code>```

Commit .gitignore file

```<code>$git commit -am "remove .idea"
</code>```

Next commit will be ok

ContentLicense: CC BY-SA 4.0

Body:
Remove .idea folder

$rm -R .idea/

Add rule

$echo ".idea/*" >> .gitignore

Commit .gitignore file

$git commit -am "remove .idea"

Next commit will be ok


问:
compare the information between two matrices R
I have two matrices, one is generated out of the other by deleting some rows. For example:

```<code>m = matrix(1:18, 6, 3)
m1 = m[c(-1, -3, -6),]
</code>```

Suppose I do not know which rows in m were eliminated to create m1, how should I find it out by comparing the two matrices? The result I want looks like this:

```<code>1, 3, 6
</code>```

The actual matrix I am dealing with is very big. I was wondering if there is any efficient way of conducting it.

答:
Here are some approaches:

1) If we can assume that there are no duplicated rows in m -- this is the case in the example in the question -- then:

```<code>which(tail(!duplicated(rbind(m1, m)), nrow(m)))
## [1] 1 3 6
</code>```

2) Transpose m and m1 giving tm and tm1 since it is more efficient to work on columns than rows.

Define match_indexes(i) which returns a vector r such that each row in m[r, ] matches m1[i, ].

Apply that to each i in 1:n1 and remove the result from 1:n.

```<code>n <- nrow(m); n1 <- nrow(m1)
tm <- t(m); tm1 <- t(m1)

match_indexes <- function(i) which(colSums(tm1[, i] == tm) == n1)
setdiff(1:n, unlist(lapply(1:n1, match_indexes)))
## [1] 1 3 6
</code>```

3)  Calculate an interaction vector for each matrix and then use setdiff and finally match to get the indexes:

```<code>i <- interaction(as.data.frame(m))
i1 <- interaction(as.data.frame(m1))
match(setdiff(i, i1), i)
## [1] 1 3 6
</code>```

Added If there can be duplicates in m then (1) and (3) will only return the first of any multiply occurring row in m not in m1.

```<code>m <- matrix(1:18, 6, 3)
m1 <- m[c(2, 4, 5),]
m <- rbind(m, m[1:2, ])
# 1
which(tail(!duplicated(rbind(m1, m)), nrow(m)))
## 1 3 6

# 2
n <- nrow(m); n1 <- nrow(m1)
tm <- t(m); tm1 <- t(m1)
match_indexes <- function(i) which(colSums(tm1[, i] == tm) == n1)
setdiff(1:n, unlist(lapply(1:n1, match_indexes)))
## 1 3 6 7

# 3
i <- interaction(as.data.frame(m))
i1 <- interaction(as.data.frame(m1))
match(setdiff(i, i1), i)
## 1 3 6
</code>```

Body:
I have two matrices, one is generated out of the other by deleting some rows. For example:

m = matrix(1:18, 6, 3)
m1 = m[c(-1, -3, -6),]

Suppose I do not know which rows in m were eliminated to create m1, how should I find it out by comparing the two matrices? The result I want looks like this:

1, 3, 6

The actual matrix I am dealing with is very big. I was wondering if there is any efficient way of conducting it.

Body:
Here are some approaches:

1) If we can assume that there are no duplicated rows in m -- this is the case in the example in the question -- then:

which(tail(!duplicated(rbind(m1, m)), nrow(m)))
## [1] 1 3 6

2) Transpose m and m1 giving tm and tm1 since it is more efficient to work on columns than rows.

Define match_indexes(i) which returns a vector r such that each row in m[r, ] matches m1[i, ].

Apply that to each i in 1:n1 and remove the result from 1:n.

n <- nrow(m); n1 <- nrow(m1)
tm <- t(m); tm1 <- t(m1)

match_indexes <- function(i) which(colSums(tm1[, i] == tm) == n1)
setdiff(1:n, unlist(lapply(1:n1, match_indexes)))
## [1] 1 3 6

3)  Calculate an interaction vector for each matrix and then use setdiff and finally match to get the indexes:

i <- interaction(as.data.frame(m))
i1 <- interaction(as.data.frame(m1))
match(setdiff(i, i1), i)
## [1] 1 3 6

Added If there can be duplicates in m then (1) and (3) will only return the first of any multiply occurring row in m not in m1.

m <- matrix(1:18, 6, 3)
m1 <- m[c(2, 4, 5),]
m <- rbind(m, m[1:2, ])
# 1
which(tail(!duplicated(rbind(m1, m)), nrow(m)))
## 1 3 6

# 2
n <- nrow(m); n1 <- nrow(m1)
tm <- t(m); tm1 <- t(m1)
match_indexes <- function(i) which(colSums(tm1[, i] == tm) == n1)
setdiff(1:n, unlist(lapply(1:n1, match_indexes)))
## 1 3 6 7

# 3
i <- interaction(as.data.frame(m))
i1 <- interaction(as.data.frame(m1))
match(setdiff(i, i1), i)
## 1 3 6