问:
output differences between 2 texts when lines are dissimilar
I am relatively new to Python so apologies in advance for sounding a bit ditzy sometimes. I'll try took google and attempt your tips as much as I can before asking even more questions.
Here is my situation: I am working with R and stylometry to find out the (likely) authorship of a text. What I'd like to do is see if there is a difference in the stylometry of a novel in the second edition, after one of the (assumed) co-authors died and therefore could not have contributed. In order to research that I need

Text edition 1

Text edition 2

and for python to output

words that appear in text 1 but not in text 2

words that appear in text 2 but not in text 1

And I would like to have the words each time they appear so not just 'the' once, but every time the program encounters it when it differs from the first edition (yep I know I'm asking for a lot sorry)

I have tried approaching this via

```<code>file1 = open("FRANKENST18.txt", "r")
file2 = open("FRANKENST31.txt", "r")
file3 = open("frankoutput.txt", "w")
list1 = file1.readlines()
list2 = file2.readlines()
file3.write("here: \n")
for i in list1:
    for j in list2:
        if  i==j:
            file3.write(i)
</code>```

but of course this doesn't work because the texts are two giant balls of texts and not separate lines that can be compared, plus the first text has far more lines than the second one. Is there a way to go from lines to 'words' or the text in general to overcome that? Can I put an entire novel in a string lol? I assume not.
I have also attempted to use difflib, but I've only started coding a few weeks ago and I find it quite complicated. For example, I used fraxel's script as a base for:

```<code>from difflib import Differ

s1 = open("FRANKENST18.txt", "r")
s1 = open("FRANKENST31.txt", "r")

def appendBoldChanges(s1, s2):
#"Adds <b></b> tags to words that are changed"
    l1 = s1.split(' ')
    l2 = s2.split(' ')
dif = list(Differ().compare(l1, l2))
return " ".join(['<b>'+i[2:]+'</b>' if i[:1] == '+' else i[2:] for i in dif
                                                       if not i[:1] in '-?'])

print appendBoldChanges
</code>```

but I couldn't get it to work.

So my question is is there any way to output the differences between texts that are not similar in lines like this? It sounded quite do-able but I've greatly underestimated how difficult I found Python haha.
Thanks for reading, any help is appreciated!

EDIT: posting my current code just in case it might help fellow learners that are googling for answers:

```<code>file1 = open("1stein.txt")
originaltext1 = file1.read()
wordlist1={}

import string
text1 = [x.strip(string.punctuation) for x in originaltext1.split()]
text1 = [x.lower() for x in text1]

for word1 in text1:
    if word1 not in wordlist1:
        wordlist1[word1] = 1
    else:
        wordlist1[word1] += 1

for k,v in sorted(wordlist1.items()):
    #print "%s %s" % (k, v)
    col1 = ("%s %s" % (k, v))
    print col1

file2 = open("2stein.txt")
originaltext2 = file2.read()
wordlist2={}

import string
text2 = [x.strip(string.punctuation) for x in originaltext2.split()]
text2 = [x.lower() for x in text2]

for word2 in text2:
    if word2 not in wordlist2:
        wordlist2[word2] = 1
    else:
        wordlist2[word2] += 1

for k,v in sorted(wordlist2.items()):
    #print "%s %s" % (k, v)
    col2 = ("%s %s" % (k, v))
    print col2
</code>```

what I hope still to edit and output is something like this:
using the dictionaries' key and value system (applied to col1 and col2): {apple 3, bridge 7, chair 5} - {apple 1, bridge 9, chair 5} = {apple 2, bridge -2, chair 5}?

答:
You want to output:

words that appear in text 1 but not in text 2

words that appear in
text 2 but not in text 1

Interesting. A set difference is what you need.

```<code>import re
s1 = open("FRANKENST18.txt", "r").read()
s1 = open("FRANKENST31.txt", "r").read()

words_s1 = re.findall("[A-Za-z]",s1)
words_s2 = re.findall("[A-Za-z]",s2)

set_s1 = set(words_s1)
set_s2 = set(words_s2)

words_in_s1_but_not_in_s2 = set_s1 - set_s2
words_in_s2_but_not_in_s1 = set_s2 - set_s1

words_in_s1 = '\n'.join(words_in_s1_but_not_in_s2)
words_in_s2 = '\n'.join(words_in_s2_but_not_in_s1)

with open("s1_output","w") as s1_output:
    s1_output.write(words_in_s1)

with open("s2_output","w") as s2_output:
    s2_output.write(words_in_s2)
</code>```

Body:
I am relatively new to Python so apologies in advance for sounding a bit ditzy sometimes. I'll try took google and attempt your tips as much as I can before asking even more questions.
Here is my situation: I am working with R and stylometry to find out the (likely) authorship of a text. What I'd like to do is see if there is a difference in the stylometry of a novel in the second edition, after one of the (assumed) co-authors died and therefore could not have contributed. In order to research that I need

Text edition 1

Text edition 2

and for python to output

words that appear in text 1 but not in text 2

words that appear in text 2 but not in text 1

And I would like to have the words each time they appear so not just 'the' once, but every time the program encounters it when it differs from the first edition (yep I know I'm asking for a lot sorry)

I have tried approaching this via

file1 = open("FRANKENST18.txt", "r")
file2 = open("FRANKENST31.txt", "r")
file3 = open("frankoutput.txt", "w")
list1 = file1.readlines()
list2 = file2.readlines()
file3.write("here: \n")
for i in list1:
    for j in list2:
        if  i==j:
            file3.write(i)

but of course this doesn't work because the texts are two giant balls of texts and not separate lines that can be compared, plus the first text has far more lines than the second one. Is there a way to go from lines to 'words' or the text in general to overcome that? Can I put an entire novel in a string lol? I assume not.
I have also attempted to use difflib, but I've only started coding a few weeks ago and I find it quite complicated. For example, I used fraxel's script as a base for:

from difflib import Differ

s1 = open("FRANKENST18.txt", "r")
s1 = open("FRANKENST31.txt", "r")

def appendBoldChanges(s1, s2):
#"Adds  tags to words that are changed"
    l1 = s1.split(' ')
    l2 = s2.split(' ')
dif = list(Differ().compare(l1, l2))
return " ".join([''+i[2:]+'' if i[:1] == '+' else i[2:] for i in dif
                                                       if not i[:1] in '-?'])

print appendBoldChanges

but I couldn't get it to work.

So my question is is there any way to output the differences between texts that are not similar in lines like this? It sounded quite do-able but I've greatly underestimated how difficult I found Python haha.
Thanks for reading, any help is appreciated!

EDIT: posting my current code just in case it might help fellow learners that are googling for answers:

file1 = open("1stein.txt")
originaltext1 = file1.read()
wordlist1={}

import string
text1 = [x.strip(string.punctuation) for x in originaltext1.split()]
text1 = [x.lower() for x in text1]

for word1 in text1:
    if word1 not in wordlist1:
        wordlist1[word1] = 1
    else:
        wordlist1[word1] += 1

for k,v in sorted(wordlist1.items()):
    #print "%s %s" % (k, v)
    col1 = ("%s %s" % (k, v))
    print col1

file2 = open("2stein.txt")
originaltext2 = file2.read()
wordlist2={}

import string
text2 = [x.strip(string.punctuation) for x in originaltext2.split()]
text2 = [x.lower() for x in text2]

for word2 in text2:
    if word2 not in wordlist2:
        wordlist2[word2] = 1
    else:
        wordlist2[word2] += 1

for k,v in sorted(wordlist2.items()):
    #print "%s %s" % (k, v)
    col2 = ("%s %s" % (k, v))
    print col2

what I hope still to edit and output is something like this:
using the dictionaries' key and value system (applied to col1 and col2): {apple 3, bridge 7, chair 5} - {apple 1, bridge 9, chair 5} = {apple 2, bridge -2, chair 5}?

Body:
You want to output:

words that appear in text 1 but not in text 2

words that appear in
text 2 but not in text 1

Interesting. A set difference is what you need.

import re
s1 = open("FRANKENST18.txt", "r").read()
s1 = open("FRANKENST31.txt", "r").read()

words_s1 = re.findall("[A-Za-z]",s1)
words_s2 = re.findall("[A-Za-z]",s2)

set_s1 = set(words_s1)
set_s2 = set(words_s2)

words_in_s1_but_not_in_s2 = set_s1 - set_s2
words_in_s2_but_not_in_s1 = set_s2 - set_s1

words_in_s1 = '\n'.join(words_in_s1_but_not_in_s2)
words_in_s2 = '\n'.join(words_in_s2_but_not_in_s1)

with open("s1_output","w") as s1_output:
    s1_output.write(words_in_s1)

with open("s2_output","w") as s2_output:
    s2_output.write(words_in_s2)


来源: stackexchange

问:
codeigniter encryption on production server and local server
Will a encrypted password using codeigniter's encryption class produce the same encrypted password on two different machines?  For example, I have a production site online with some host and i have the local install on my computer.  But the passwords don't match when i restore the database from one to the other.</p>

答:
Without seeing your code, it's impossible to tell what the problem may be (this is why you have no answers yet). However, if you're encrypting the string in the same way, as long as you're using the same encryption key, it should be the same. In CI's encryption class (see here), you can do this in the config.php file like this:

```<code>$config['encryption_key'] = "YOUR KEY";
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Without seeing your code, it's impossible to tell what the problem may be (this is why you have no answers yet). However, if you're encrypting the string in the same way, as long as you're using the same encryption key, it should be the same. In CI's encryption class (see here), you can do this in the config.php file like this:

$config['encryption_key'] = "YOUR KEY";


问:
Why is my button as a toggle not working when I try to update the state of the button?
When I try to change the state of the button after it is pressed, nothing works. I do this with the line prev = current;

```<code>#include <Servo.h>;

//HIGH not pressed
//LOW pressed

int pushD3 = 3;
int pushD4 = 4;
int pushD5 = 5;
int pushD6 = 6;
int val4 = 0;
int val5 = 0;
int ledPin = 13;
int prev = 0;
int current = 0;
Servo ZServo;

void setup() {
  ZServo.attach(9);
  pinMode(pushD3, INPUT_PULLUP);
  digitalWrite(3, HIGH);
  pinMode(pushD4, INPUT_PULLUP);
  digitalWrite(4, HIGH);
  pinMode(pushD5, INPUT_PULLUP);
  digitalWrite(5, HIGH);
  pinMode(pushD6, INPUT_PULLUP);
  digitalWrite(6, HIGH);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  if (digitalRead(3) == LOW) {
    current = 1 - current;
  }
  if (current == 1 && prev == 0) {
    checkButtons_slow();
    delay(100);
  }
  if (current == 0 && prev == 1) {
    //ZServo.write(110);
    delay(500); //half a second
  }
  prev = current;
}

void checkButtons_slow() {
  val4 = digitalRead(pushD4);
  val5 = digitalRead(pushD5);
  if (val4 == LOW) {
    ZServo.write(87);
  } else if (val5 == LOW) {
    ZServo.write(99);
  } else {
    ZServo.write(91); //GUESSED ON 92; SHOULD TECHNICALLY BE 90
  }
}
</code>```

答:
You update your toggle state even when your button is not pushed.  That's why the logic doesn't work.  You also need to keep track of when the button is released for the toggle button logic.

You may also be the next victim of switch bounce.  A typical switch will not go cleanly from open to close, and can produce small, quick open/close signals when pushed (and released).  While this doesn't affect much simple pressed/depressed buttons operation, it is a killer for multiple states switches.

An easy way to avoid this is to limit the rate at which you read the switches.  I've found that a 30ms rate is pretty good.

```<code>int last_time = 0;
bool was_pushed = false;

void loop() {

  if (millis() - last_time > 30)  // filter out signal bounce.
  {
    last_time = millis();
    if (digitalRead(3) == LOW)
    {
      if (!was_pushed)            // prevent toggling until button is released.
        current = !current;
      was_pushed = true;
    }
    else
    {
      was_pushed = false;
    }
    if (current != prev)
    {
       prev = current;           // keep the previous toggle state only on change.
       if (current)
       {
         checkButtons_slow();
         delay(100);
       }
       else
       {
         //ZServo.write(110);
         delay(500); //half a second
       }
    }
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
When I try to change the state of the button after it is pressed, nothing works. I do this with the line prev = current;

#include <Servo.h>;

//HIGH not pressed
//LOW pressed

int pushD3 = 3;
int pushD4 = 4;
int pushD5 = 5;
int pushD6 = 6;
int val4 = 0;
int val5 = 0;
int ledPin = 13;
int prev = 0;
int current = 0;
Servo ZServo;

void setup() {
  ZServo.attach(9);
  pinMode(pushD3, INPUT_PULLUP);
  digitalWrite(3, HIGH);
  pinMode(pushD4, INPUT_PULLUP);
  digitalWrite(4, HIGH);
  pinMode(pushD5, INPUT_PULLUP);
  digitalWrite(5, HIGH);
  pinMode(pushD6, INPUT_PULLUP);
  digitalWrite(6, HIGH);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  if (digitalRead(3) == LOW) {
    current = 1 - current;
  }
  if (current == 1 && prev == 0) {
    checkButtons_slow();
    delay(100);
  }
  if (current == 0 && prev == 1) {
    //ZServo.write(110);
    delay(500); //half a second
  }
  prev = current;
}

void checkButtons_slow() {
  val4 = digitalRead(pushD4);
  val5 = digitalRead(pushD5);
  if (val4 == LOW) {
    ZServo.write(87);
  } else if (val5 == LOW) {
    ZServo.write(99);
  } else {
    ZServo.write(91); //GUESSED ON 92; SHOULD TECHNICALLY BE 90
  }
}

Body:
You update your toggle state even when your button is not pushed.  That's why the logic doesn't work.  You also need to keep track of when the button is released for the toggle button logic.

You may also be the next victim of switch bounce.  A typical switch will not go cleanly from open to close, and can produce small, quick open/close signals when pushed (and released).  While this doesn't affect much simple pressed/depressed buttons operation, it is a killer for multiple states switches.

An easy way to avoid this is to limit the rate at which you read the switches.  I've found that a 30ms rate is pretty good.

int last_time = 0;
bool was_pushed = false;

void loop() {

  if (millis() - last_time > 30)  // filter out signal bounce.
  {
    last_time = millis();
    if (digitalRead(3) == LOW)
    {
      if (!was_pushed)            // prevent toggling until button is released.
        current = !current;
      was_pushed = true;
    }
    else
    {
      was_pushed = false;
    }
    if (current != prev)
    {
       prev = current;           // keep the previous toggle state only on change.
       if (current)
       {
         checkButtons_slow();
         delay(100);
       }
       else
       {
         //ZServo.write(110);
         delay(500); //half a second
       }
    }
  }
}


问:
hide UIButtons when UITableView is empty
```<code>  func numberOfSections(in tableView: UITableView) -> Int {
        if carts.count > 0 {
            self.tableView.backgroundView = nil
            self.tableView.separatorStyle = .singleLine
            return 1

        }

        let rect = CGRect(x: 0,
                          y: 0,
                          width: self.tableView.bounds.size.width,
                          height: self.tableView.bounds.size.height)
        let noDataLabel: UILabel = UILabel(frame: rect)

        noDataLabel.text = "nothing, the table is empty"
        noDataLabel.textColor = UIColor.white
        noDataLabel.textAlignment = NSTextAlignment.center
        self.tableView.backgroundView = noDataLabel
        self.tableView.separatorStyle = .none
      self.total.isHidden = true
       self.proceedbtn.isHidden = true
        self.totalLab.isHidden = true

        return 1
    }
</code>```

the code above will hide the objects when the tableView is empty. However, when I add items in it ( it's supposed to be a cart) the total proceedbtn and totalLab are still hidden !!

Is there a way to reload the table and check if it's empty ?

Note :

My cells are slidable and I can delete the cell by sliding.

```<code>func deleteMail(_ path:IndexPath) {
    guard carts.count > path.row else {
        print("Index out of range")
        return
    }

    let entry = carts[path.row]
    deletItem(id: entry.meal_id)// call api to delete items
    carts.remove(at: (path as NSIndexPath).row);
    tableView.deleteRows(at: [path], with: .left);
    print("delete")

}
</code>```

UPDATE

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    if carts.isEmpty == true {

        proceedbtn.isHidden = true
    } else {
        if carts.isEmpty == false {
            if proceedbtn.isHidden == true {

            proceedbtn.isHidden = false
        }
    }
    }
</code>```

get data :

```<code>func getData () {

    Alamofire.request(url!, method: .post, parameters: param,encoding: URLEncoding.default, headers: headers).responseJSON { response in
        if let value: AnyObject = response.result.value as AnyObject? {
       // get data

                 self.price = subJson["price"].stringValue
                 self.qty = subJson["qty"].stringValue
                 let id = subJson["id"].stringValue

              self.id = id
              self.name = subJson["meal"]["name"].stringValue

                let info = Cart(meal_id: self.id, qty: self.qty, meal_name: self.name, price: self.price)

                self.carts.append(info)
          }

        }
        self.tableView.reloadData()

    }

}
</code>```

答:
Enable/Disable buttons based on the cards array count.

```<code>func numberOfSections(in tableView: UITableView) -> Int {

       self.total.isHidden = carts.isEmpty
       self.proceedbtn.isHidden = carts.isEmpty
       self.totalLab.isHidden = carts.isEmpty

        if carts.count > 0 {
            self.tableView.backgroundView = nil
            self.tableView.separatorStyle = .singleLine
            return 1

        }

        let rect = CGRect(x: 0,
                          y: 0,
                          width: self.tableView.bounds.size.width,
                          height: self.tableView.bounds.size.height)
        let noDataLabel: UILabel = UILabel(frame: rect)

        noDataLabel.text = "nothing, the table is empty"
        noDataLabel.textColor = UIColor.white
        noDataLabel.textAlignment = NSTextAlignment.center
        self.tableView.backgroundView = noDataLabel
        self.tableView.separatorStyle = .none

        return 1
    }
</code>```

While delete a cell by sliding :

You have to disable the button while delete the cells from cart table view, by checking the count of carts array

```<code>func deleteMail(_ path:IndexPath) {
    guard carts.count > path.row else {
        print("Index out of range")
        return
    }

    let entry = carts[path.row]
    deletItem(id: entry.meal_id)// call api to delete items
    carts.remove(at: (path as NSIndexPath).row);

      //You have to disable the button while delete the cells from cart table view
      if (carts.isEmpty) {
         self.total.isHidden = true
         self.proceedbtn.isHidden = true
         self.totalLab.isHidden = true
      }

    tableView.deleteRows(at: [path], with: .left);
    print("delete")

}
</code>```

Body:
  func numberOfSections(in tableView: UITableView) -> Int {
        if carts.count > 0 {
            self.tableView.backgroundView = nil
            self.tableView.separatorStyle = .singleLine
            return 1

        }

        let rect = CGRect(x: 0,
                          y: 0,
                          width: self.tableView.bounds.size.width,
                          height: self.tableView.bounds.size.height)
        let noDataLabel: UILabel = UILabel(frame: rect)

        noDataLabel.text = "nothing, the table is empty"
        noDataLabel.textColor = UIColor.white
        noDataLabel.textAlignment = NSTextAlignment.center
        self.tableView.backgroundView = noDataLabel
        self.tableView.separatorStyle = .none
      self.total.isHidden = true
       self.proceedbtn.isHidden = true
        self.totalLab.isHidden = true

        return 1
    }

the code above will hide the objects when the tableView is empty. However, when I add items in it ( it's supposed to be a cart) the total proceedbtn and totalLab are still hidden !!

Is there a way to reload the table and check if it's empty ?

Note :

My cells are slidable and I can delete the cell by sliding.

func deleteMail(_ path:IndexPath) {
    guard carts.count > path.row else {
        print("Index out of range")
        return
    }

    let entry = carts[path.row]
    deletItem(id: entry.meal_id)// call api to delete items
    carts.remove(at: (path as NSIndexPath).row);
    tableView.deleteRows(at: [path], with: .left);
    print("delete")

}

UPDATE

override func viewDidLoad() {
    super.viewDidLoad()

    if carts.isEmpty == true {

        proceedbtn.isHidden = true
    } else {
        if carts.isEmpty == false {
            if proceedbtn.isHidden == true {

            proceedbtn.isHidden = false
        }
    }
    }

get data :

func getData () {

    Alamofire.request(url!, method: .post, parameters: param,encoding: URLEncoding.default, headers: headers).responseJSON { response in
        if let value: AnyObject = response.result.value as AnyObject? {
       // get data

                 self.price = subJson["price"].stringValue
                 self.qty = subJson["qty"].stringValue
                 let id = subJson["id"].stringValue

              self.id = id
              self.name = subJson["meal"]["name"].stringValue

                let info = Cart(meal_id: self.id, qty: self.qty, meal_name: self.name, price: self.price)

                self.carts.append(info)
          }

        }
        self.tableView.reloadData()

    }

}

Body:
Enable/Disable buttons based on the cards array count.

func numberOfSections(in tableView: UITableView) -> Int {

       self.total.isHidden = carts.isEmpty
       self.proceedbtn.isHidden = carts.isEmpty
       self.totalLab.isHidden = carts.isEmpty

        if carts.count > 0 {
            self.tableView.backgroundView = nil
            self.tableView.separatorStyle = .singleLine
            return 1

        }

        let rect = CGRect(x: 0,
                          y: 0,
                          width: self.tableView.bounds.size.width,
                          height: self.tableView.bounds.size.height)
        let noDataLabel: UILabel = UILabel(frame: rect)

        noDataLabel.text = "nothing, the table is empty"
        noDataLabel.textColor = UIColor.white
        noDataLabel.textAlignment = NSTextAlignment.center
        self.tableView.backgroundView = noDataLabel
        self.tableView.separatorStyle = .none

        return 1
    }

While delete a cell by sliding :

You have to disable the button while delete the cells from cart table view, by checking the count of carts array

func deleteMail(_ path:IndexPath) {
    guard carts.count > path.row else {
        print("Index out of range")
        return
    }

    let entry = carts[path.row]
    deletItem(id: entry.meal_id)// call api to delete items
    carts.remove(at: (path as NSIndexPath).row);

      //You have to disable the button while delete the cells from cart table view
      if (carts.isEmpty) {
         self.total.isHidden = true
         self.proceedbtn.isHidden = true
         self.totalLab.isHidden = true
      }

    tableView.deleteRows(at: [path], with: .left);
    print("delete")

}


问:
How can I get my .NET XML Documentation Comments into Conflunce
I'd like to import my .Net XML Documentation Comments (the documentation based on the code tags, automatically generated by the compiler with the /doc switch) into Atlassian Confluence.

I've used Doxygen to generate some HTML which looks great, but I'd love to have something I can dump straight into Confluence.

Any ideas?

答:
The straighforward and easy to maintain option would be to call the Confluence API to upload content; it is well documented so it should be the same as calling any REST API from .Net, once you have the content as you indicate.

https://docs.atlassian.com/confluence/REST/latest/#content-createContent

EDIT: while there are many questions in SO addressing how to call an API from .Net, just to have the full reference:

https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client


问:
need to modify my sort pipe so that it is a passthrough (like cat)
I have a script that as a pipe step  |sort $sortstring| .  The sortstring contains different types of sort depending upon arguments to the script.  I recently added nosort as an argument and my sortstring is -m (meaning merge and do not sort).  This seems to work, however it is inefficient.   I do not want to write a test around this code such as if [[ $arg == "nosort" ]]; then do steps w/out sort pipe injected; else do steps w sort pipe injected as the steps are very complicated (a large awk script proceeds it).  I could make the "sort $sortstring" into a shell variable and set this shell variable to "cat" in the nosort case.  However, this is very complicated.  I guess good programming would suggest fictionalizing the script (place the proceeding complicated command in a function).  Can someone suggest an efficient alternative to allow nosort?</p>

答:
You can pipe your input through an if statement, which is a command like any other.

```<code>... | if [[ $arg == nosort ]]; then cat; else sort ...; fi | ...
</code>```

The commands following then, elif, or else inherit their file descriptors from the if statement.

Body:
You can pipe your input through an if statement, which is a command like any other.

... | if [[ $arg == nosort ]]; then cat; else sort ...; fi | ...

The commands following then, elif, or else inherit their file descriptors from the if statement.


问:
Java generics - ArrayList initialization
It is known that arraylist init. should be like this

```<code>ArrayList<A> a = new ArrayList<A>();
ArrayList<Integer> a = new ArrayList<Number>(); // compile-time error
</code>```

so, why does java allow these ?

```<code>1. ArrayList<? extends Object> a1 = new ArrayList<Object>();
2. ArrayList<?> a2 = new ArrayList<Integer>();
</code>```

then, if they are correct why doesn't allow these ?

```<code>1. a1.add(3);
2. a2.add(3);
</code>```

the compiler message is : The method add(int, capture#1-of ? extends Object) in the type ArrayList is not applicable for the arguments (int)

more general

```<code>  1. a1.add(null e);
  2. a2.add(? e);
</code>```

I read about this but it is good to hear from you. thanks

the other amusing point is :

```<code> ArrayList<ArrayList<?>> a = new ArrayList<ArrayList<?>>(); // correct
 ArrayList<?> a = new ArrayList<?>(); // wrong. I know it's reason but I have some
question in my mind that mentioned above
</code>```

答:
You have strange expectations. If you gave the chain of arguments that led you to them, we might spot the flaw in them. As it is, I can only give a short primer on generics, hoping to touch on the points you might have misunderstood.

ArrayList<? extends Object> is an ArrayList whose type parameter is known to be Object or a subtype thereof. (Yes, extends in type bounds has a meaning other than direct subclass). Since only reference types can be type parameters, this is actually equivalent to ArrayList<?>.

That is, you can put an ArrayList<String> into a variable declared with ArrayList<?>. That's why a1.add(3) is a compile time error. a1's declared type permits a1 to be an ArrayList<String>, to which no Integer can be added.

Clearly, an ArrayList<?> is not very useful, as you can only insert null into it. That might be why the Java Spec forbids it:

It is a compile-time error if any of
  the type arguments used in a class
  instance creation expression are
  wildcard type arguments

ArrayList<ArrayList<?>> in contrast is a functional data type. You can add all kinds of ArrayLists into it, and retrieve them. And since ArrayList<?> only contains but is not a wildcard type, the above rule does not apply.

Body:
It is known that arraylist init. should be like this

ArrayList a = new ArrayList();
ArrayList<Integer> a = new ArrayList<Number>(); // compile-time error

so, why does java allow these ?

1. ArrayList<? extends Object> a1 = new ArrayList<Object>();
2. ArrayList<?> a2 = new ArrayList<Integer>();

then, if they are correct why doesn't allow these ?

1. a1.add(3);
2. a2.add(3);

the compiler message is : The method add(int, capture#1-of ? extends Object) in the type ArrayList is not applicable for the arguments (int)

more general

  1. a1.add(null e);
  2. a2.add(? e);

I read about this but it is good to hear from you. thanks

the other amusing point is :

 ArrayList<ArrayList<?>> a = new ArrayList<ArrayList<?>>(); // correct
 ArrayList<?> a = new ArrayList<?>(); // wrong. I know it's reason but I have some
question in my mind that mentioned above


问:
How to simulate network delay on a local port?
I want to see how a HTTP client reacts to connection timeouts, i.e. where there's a server listening on a port, but the process of setting up the connection is so slow that the client gives up and returns a connection timeout. The connection shouldn't be refused, and it shouldn't be accepted and then followed by a socket timeout.

So far, I've attempted to introduce network delay by overriding ServerSocket, imagining that I would be able to write something like this...

```<code>public SlowServerSocket extends ServerSocket {
    // (This method doesn't actually exist).
    @Override
    public void processBytesPassedOnByOperatingSystem(byte[] bytes) {
        Thread.sleep(delay);
        // Client has already returned a connection timeout.
        super.processBytesPassedOnByOperatingSystem(bytes);
    }
}
</code>```

...but I run into a dead end when I get to that level of abstraction (it seems to be hidden in a native method). My fake server accepts connections and then does nothing, causing a socket timeout.

I've also looked for solutions online, and I came across SlowSocket from the JMeter library, but it seems to be used on the client-side (and I don't think I'll be able to override the client so that it uses SlowSocket).

Any suggestions?

答:
I want to see how a HTTP client reacts to connection timeouts, i.e. where there's a server listening on a port, but the process of setting up the connection is so slow that the client gives up and returns a connection timeout.

Your requirement embodies a contradiction in terms. A connect timeout occurs when the peer host doesn't respond at all, usually because of a firewall. It has nothing to do with the server application being slow. The server doesn't 'set up the connection': the TCP stack does.

The connection shouldn't be refused

It won't be if there is a listening process, except as below.

and it shouldn't be accepted and then followed by a socket timeout.

This is exactly what the code you have written will produce.

However, and if and only if the server platform isn't Windows, there is another way to produce a connect timeout: let the backlog queue fill up. To produce that, have the server execute all the normal socket setup steps but never call accept() at all, and have the client execute a large number of connect attempts. But if the server platform is Windows, this will produce connection refusals.

Body:
I want to see how a HTTP client reacts to connection timeouts, i.e. where there's a server listening on a port, but the process of setting up the connection is so slow that the client gives up and returns a connection timeout. The connection shouldn't be refused, and it shouldn't be accepted and then followed by a socket timeout.

So far, I've attempted to introduce network delay by overriding ServerSocket, imagining that I would be able to write something like this...

public SlowServerSocket extends ServerSocket {
    // (This method doesn't actually exist).
    @Override
    public void processBytesPassedOnByOperatingSystem(byte[] bytes) {
        Thread.sleep(delay);
        // Client has already returned a connection timeout.
        super.processBytesPassedOnByOperatingSystem(bytes);
    }
}

...but I run into a dead end when I get to that level of abstraction (it seems to be hidden in a native method). My fake server accepts connections and then does nothing, causing a socket timeout.

I've also looked for solutions online, and I came across SlowSocket from the JMeter library, but it seems to be used on the client-side (and I don't think I'll be able to override the client so that it uses SlowSocket).

Any suggestions?


问:
Grails 2.x class from src/java not resolving in plugin
As it is known that the  org.codehaus.groovy.grails.commons.ApplicationHolder class has been deprecated in grails 2.3.x onwards. But there are many plugin that use it.
In one of my application I happen to use https://grails.org/plugin/excel-import?skipRedirect=true which is deprecated and no equivalent exists for grails 2.4 (though there is one for grails 3).
My application uses this plugin and I would prefer not having to refractor it to use the latest version. So is there a way so that the org.codehaus.groovy.grails.commons.ApplicationHolder resolves to  Holders.grailsApplication ?

I have already created a org.codehaus.groovy.grails.commons.ApplicationHolder in src/java folder which has this content:

```<code>/*
 * Copyright 2004-2005 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.codehaus.groovy.grails.commons;

import grails.util.GrailsUtil;
import grails.util.Holders;

/**
 * Static singleton holder for the GrailsApplication instance.
 *
 * @author Marc Palmer (marc@anyware.co.uk)
 *
 * @deprecated Use dependency injection or implement GrailsApplicationAware instead
 */
@Deprecated
public abstract class ApplicationHolder {

    /**
     * @return The GrailsApplication instance
     * @deprecated Use dependency injection instead
     */
    @Deprecated
    public static GrailsApplication getApplication() {
        GrailsUtil.deprecated("Method ApplicationHolder.getApplication() is deprecated and will be removed in a future version of Grails.");
        return Holders.getGrailsApplication();
    }

    /**
     * @param application The application to set
     * @deprecated Use dependency injection instead
     */
    @Deprecated
    public static void setApplication(GrailsApplication application) {
        Holders.setGrailsApplication(application);
    }
}
</code>```

But still when I run the project I get this error:

```<code>..myapproot\target\work\plugins\excel-import-1.0.0\grails-app\services\org\grails\plugins\excelimport\ExcelImportService.groovy: 13: unable to resolve class org.codehaus.groovy.grails.commons.ApplicationHolder
 @ line 13, column 1.
   import org.codehaus.groovy.grails.commons.ApplicationHolder
   ^

1 error
</code>```

So not sure how do I make the excel-import plugin use this class(as its not able to find ApplicationHolder class from grails 2.4.4 which my application uses)?

EDIT
I even tried running with grails command line instead of intellij. Same result!

答:
So is there a way so that the
  org.codehaus.groovy.grails.commons.ApplicationHolder resolves to
  Holders.grailsApplication ?

If you really need to use the older version of the plugin, one hackus-majoris would be to add your own ApplicationHolder class under src/groovy/org/codehaus/groovy/grails/commons/ApplicationHolder.groovy (or .java).

Body:
As it is known that the  org.codehaus.groovy.grails.commons.ApplicationHolder class has been deprecated in grails 2.3.x onwards. But there are many plugin that use it.
In one of my application I happen to use https://grails.org/plugin/excel-import?skipRedirect=true which is deprecated and no equivalent exists for grails 2.4 (though there is one for grails 3).
My application uses this plugin and I would prefer not having to refractor it to use the latest version. So is there a way so that the org.codehaus.groovy.grails.commons.ApplicationHolder resolves to  Holders.grailsApplication ?

I have already created a org.codehaus.groovy.grails.commons.ApplicationHolder in src/java folder which has this content:

/*
 * Copyright 2004-2005 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.codehaus.groovy.grails.commons;

import grails.util.GrailsUtil;
import grails.util.Holders;

/**
 * Static singleton holder for the GrailsApplication instance.
 *
 * @author Marc Palmer (marc@anyware.co.uk)
 *
 * @deprecated Use dependency injection or implement GrailsApplicationAware instead
 */
@Deprecated
public abstract class ApplicationHolder {

    /**
     * @return The GrailsApplication instance
     * @deprecated Use dependency injection instead
     */
    @Deprecated
    public static GrailsApplication getApplication() {
        GrailsUtil.deprecated("Method ApplicationHolder.getApplication() is deprecated and will be removed in a future version of Grails.");
        return Holders.getGrailsApplication();
    }

    /**
     * @param application The application to set
     * @deprecated Use dependency injection instead
     */
    @Deprecated
    public static void setApplication(GrailsApplication application) {
        Holders.setGrailsApplication(application);
    }
}

But still when I run the project I get this error:

..myapproot\target\work\plugins\excel-import-1.0.0\grails-app\services\org\grails\plugins\excelimport\ExcelImportService.groovy: 13: unable to resolve class org.codehaus.groovy.grails.commons.ApplicationHolder
 @ line 13, column 1.
   import org.codehaus.groovy.grails.commons.ApplicationHolder
   ^

1 error

So not sure how do I make the excel-import plugin use this class(as its not able to find ApplicationHolder class from grails 2.4.4 which my application uses)?

EDIT
I even tried running with grails command line instead of intellij. Same result!


问:
How to push a new page when clicking ion-item and retrieve data
I am using Ionic 2 and a list of clickable ion-item with details arrow:

```<code><ion-item-group>
    <button ion-item (click)="onWhenItemClick()">
      Quand
      <ion-note item-end>{{ date }}</ion-note>
    </button>
    <button ion-item (click)="onWhereItemClick()">
      Où
      <ion-note item-end>{{ location }}</ion-note>
    </button>
  </ion-item-group>
</code>```

As there is this arrow I would expect (as a user) to see a new page sliding from right to left when clicking on of these items.

For your information, each ion-item should bring me to a page that only displays a list of radio items.

I would like to recreate the same mechanisms as a select or a modal but with a page.

So basically I want to push a new page (easy) and be able to pop/dismiss it and handle this dismissal with as function like onDismiss().

How would you do that?
Pushing the new page is not

答:
You're going to want to use Ionic's navController. It behaves very much like a stack, where you push new views onto the stack, and then pop them off to go 'back'

So to navigate to a new page you would

```<code>navCtrl.push(myComponent)
</code>```

Then to go back you would remove that view from the stack with

```<code>navCtrl.pop()
</code>```

You can also use navCtrl.popToRoot() to jump all the way back to your root view controller

Please see their docs for more examples and information at https://ionicframework.com/docs/api/navigation/NavController/

Body:
I am using Ionic 2 and a list of clickable ion-item with details arrow:

<ion-item-group>
    <button ion-item (click)="onWhenItemClick()">
      Quand
      <ion-note item-end>{{ date }}</ion-note>
    </button>
    <button ion-item (click)="onWhereItemClick()">
      Où
      <ion-note item-end>{{ location }}</ion-note>
    </button>
  </ion-item-group>

As there is this arrow I would expect (as a user) to see a new page sliding from right to left when clicking on of these items.

For your information, each ion-item should bring me to a page that only displays a list of radio items.

I would like to recreate the same mechanisms as a select or a modal but with a page.

So basically I want to push a new page (easy) and be able to pop/dismiss it and handle this dismissal with as function like onDismiss().

How would you do that?
Pushing the new page is not

Body:
You're going to want to use Ionic's navController. It behaves very much like a stack, where you push new views onto the stack, and then pop them off to go 'back'

So to navigate to a new page you would

navCtrl.push(myComponent)

Then to go back you would remove that view from the stack with

navCtrl.pop()

You can also use navCtrl.popToRoot() to jump all the way back to your root view controller

Please see their docs for more examples and information at https://ionicframework.com/docs/api/navigation/NavController/


问:
Get max value from a map with keys corresponding to a list in Java 7
I have a Map<String, Double> and a List<String>.

The list actually contains possible keys for the map.
Now, I want the max value in the map corresponding to the list of keys.

For eg:

Map

(a, 3),
  (b, 4),
  (c, 5),
  (d, 6),
  (e, 7)

List

b,
  d

Output should be = 6

Current solution:

```<code>public Double getMaxValue(final List<String> list, final Map<String,Double> map) {
    Double maxDiscount = 0d;

    for (String key : list) {
        Double discount = map.get(key);
        if (discount > maxDiscount) {
            maxDiscount = discount;
        }
    }
    return maxDiscount;
}
</code>```

How can I do it more efficiently?

答:
This should do it:</p>

```<code>public Double getMaxValue(final List<String> list, final Map<String,Double> map) {
    return Collections.max(
            map.entrySet().stream().filter(
                    item -> list.contains(item.getKey())
            ).collect(Collectors.toMap(
                    e -> e.getKey(),
                    e -> e.getValue())
            ).values()
    );
}
</code>```

Body:
I have a Map<String, Double> and a List<String>.

The list actually contains possible keys for the map.
Now, I want the max value in the map corresponding to the list of keys.

For eg:

Map

(a, 3),
  (b, 4),
  (c, 5),
  (d, 6),
  (e, 7)

List

b,
  d

Output should be = 6

Current solution:

public Double getMaxValue(final List<String> list, final Map<String,Double> map) {
    Double maxDiscount = 0d;

    for (String key : list) {
        Double discount = map.get(key);
        if (discount > maxDiscount) {
            maxDiscount = discount;
        }
    }
    return maxDiscount;
}

How can I do it more efficiently?

Body:
This should do it:

public Double getMaxValue(final List<String> list, final Map<String,Double> map) {
    return Collections.max(
            map.entrySet().stream().filter(
                    item -> list.contains(item.getKey())
            ).collect(Collectors.toMap(
                    e -> e.getKey(),
                    e -> e.getValue())
            ).values()
    );
}


问:
Is it bad practice to make a setter return "this"?
Is it a good or bad idea to make setters in java return "this"?

```<code>public Employee setName(String name){
   this.name = name;
   return this;
}
</code>```

This pattern can be useful because then you can chain setters like this:

```<code>list.add(new Employee().setName("Jack Sparrow").setId(1).setFoo("bacon!"));
</code>```

instead of this:

```<code>Employee e = new Employee();
e.setName("Jack Sparrow");
...and so on...
list.add(e);
</code>```

...but it sort of goes against standard convention. I suppose it might be worthwhile just because it can make that setter do something else useful. I've seen this pattern used some places (e.g. JMock, JPA), but it seems uncommon, and only generally used for very well defined APIs where this pattern is used everywhere.

Update:

What I've described is obviously valid, but what I am really looking for is some thoughts on whether this is generally acceptable, and if there are any pitfalls or related best practices. I know about the Builder pattern but it is a little more involved then what I am describing - as Josh Bloch describes it there is an associated static Builder class for object creation.

答:
I prefer using 'with' methods for this:

```<code>public String getFoo() { return foo; }
public void setFoo(String foo) { this.foo = foo; }
public Employee withFoo(String foo) {
  setFoo(foo);
  return this;
}
</code>```

Thus:

```<code>list.add(new Employee().withName("Jack Sparrow")
                       .withId(1)
                       .withFoo("bacon!"));
</code>```

Warning: this withX syntax is commonly used to provide "setters" for immutable objects, so callers of these methods might reasonably expect them to create new objects rather than to mutate the existing instance. Maybe a more reasonable wording would be something like:

```<code>list.add(new Employee().chainsetName("Jack Sparrow")
                       .chainsetId(1)
                       .chainsetFoo("bacon!"));
</code>```

With the chainsetXyz() naming convention virtually everyone should be happy.

Body:
Is it a good or bad idea to make setters in java return "this"?

public Employee setName(String name){
   this.name = name;
   return this;
}

This pattern can be useful because then you can chain setters like this:

list.add(new Employee().setName("Jack Sparrow").setId(1).setFoo("bacon!"));

instead of this:

Employee e = new Employee();
e.setName("Jack Sparrow");
...and so on...
list.add(e);

...but it sort of goes against standard convention. I suppose it might be worthwhile just because it can make that setter do something else useful. I've seen this pattern used some places (e.g. JMock, JPA), but it seems uncommon, and only generally used for very well defined APIs where this pattern is used everywhere.

Update:

What I've described is obviously valid, but what I am really looking for is some thoughts on whether this is generally acceptable, and if there are any pitfalls or related best practices. I know about the Builder pattern but it is a little more involved then what I am describing - as Josh Bloch describes it there is an associated static Builder class for object creation.

Body:
I prefer using 'with' methods for this:

public String getFoo() { return foo; }
public void setFoo(String foo) { this.foo = foo; }
public Employee withFoo(String foo) {
  setFoo(foo);
  return this;
}

Thus:

list.add(new Employee().withName("Jack Sparrow")
                       .withId(1)
                       .withFoo("bacon!"));

Warning: this withX syntax is commonly used to provide "setters" for immutable objects, so callers of these methods might reasonably expect them to create new objects rather than to mutate the existing instance. Maybe a more reasonable wording would be something like:

list.add(new Employee().chainsetName("Jack Sparrow")
                       .chainsetId(1)
                       .chainsetFoo("bacon!"));

With the chainsetXyz() naming convention virtually everyone should be happy.

ContentLicense: CC BY-SA 4.0


问:
WPF Changing ListBox background color, enabled and disabled
I'm searching how to change the background color of my WPF Listbox, nothing worked...  I don't want to change the background of the Item Template, but of the ListBox himself.

I tried the differents solutions answered here Answers

Here is my Listbox :

```<code><ListBox Name="myListBox" ScrollViewer.VerticalScrollBarVisibility="Visible" SelectionChanged="myListBox_SelectionChanged" Background="#FFC3DDF7" Margin="0,0,0,10">
                <ListBox.ItemContainerStyle>
                    <Style TargetType="ListBoxItem">
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding Value.IsOk}" Value="True">
                                <Setter Property="Background" Value="Green"/>
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </ListBox.ItemContainerStyle>
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <StackPanel Width="200">
                                <TextBlock FontSize="10" FontWeight="Bold" VerticalAlignment="Center" Text="{Binding Path=Key}" />
                                <TextBlock FontSize="10" VerticalAlignment="Center" TextWrapping="Wrap">
                                    <TextBlock.Text>
                                        <MultiBinding StringFormat="{}{0} {1} {2}">
                                            <Binding Path="Value.TextA" />
                                            <Binding Path="Value.TextB" />
                                            <Binding Path="Value.TextC" />
                                        </MultiBinding>
                                    </TextBlock.Text>
                                </TextBlock>
                            </StackPanel>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
</code>```

Maybe the item template is on the foreground ?

Tried these codes :

```<code><ListBox.Style>
<Style TargetType="{x:Type ListBox}">
    <Style.Resources>
        <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Blue"/>
    </Style.Resources>
</Style>
</code>```

and

```<code> <ListBox>
    <ListBox.Style>
        <Style TargetType="{x:Type ListBox}">
            <Style.Triggers>
                <Trigger Property="IsEnabled" Value="False">
                    <Setter Property="Background" Value="Blue" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </ListBox.Style>
</ListBox>
</code>```

Not working. The down right corner, between the two scrollbars, became blue... But that's all !

答:
As Anthony pointed out, your style trigger will never set the Background of your ListBox because you have set a local value. It's called "Dependency Property Precedence". Take a look at this link: https://learn.microsoft.com/en-us/dotnet/framework/wpf/advanced/dependency-property-value-precedence.

"Local" values have higher precedence over "style trigger" values. However, "style trigger" values have higher precedence over "style setter" values. This means that if you want to have an initial value for the property and change it based on a trigger, just set it in the style initially, instead of setting it locally like your code does.

Body:
I'm searching how to change the background color of my WPF Listbox, nothing worked...  I don't want to change the background of the Item Template, but of the ListBox himself.

I tried the differents solutions answered here Answers

Here is my Listbox :

<ListBox Name="myListBox" ScrollViewer.VerticalScrollBarVisibility="Visible" SelectionChanged="myListBox_SelectionChanged" Background="#FFC3DDF7" Margin="0,0,0,10">
                <ListBox.ItemContainerStyle>

                    </Style>
                </ListBox.ItemContainerStyle>
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <StackPanel Width="200">
                                <TextBlock FontSize="10" FontWeight="Bold" VerticalAlignment="Center" Text="{Binding Path=Key}" />
                                <TextBlock FontSize="10" VerticalAlignment="Center" TextWrapping="Wrap">
                                    <TextBlock.Text>
                                        <MultiBinding StringFormat="{}{0} {1} {2}">
                                            <Binding Path="Value.TextA" />
                                            <Binding Path="Value.TextB" />
                                            <Binding Path="Value.TextC" />
                                        </MultiBinding>
                                    </TextBlock.Text>
                                </TextBlock>
                            </StackPanel>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

Maybe the item template is on the foreground ?

Tried these codes :

<ListBox.Style>

</Style>

and

 <ListBox>
    <ListBox.Style>

        </Style>
    </ListBox.Style>
</ListBox>

Not working. The down right corner, between the two scrollbars, became blue... But that's all !


问:
Can't submit the app with storyboard launch images to the App Store: Your binary is not optimized for iPhone 5
I am trying to submit my first app to the App Store but when I try I am getting the following error:

ERROR ITMS-9000: "Your binary is not optimized for iPhone 5 - New
  iPhone apps and app updates submitted must support the 4-inch display
  on iPhone 5 and must include a launch image referenced in the
  info.plist under UILaunchImage with a UILaunchImageSize value set to
  {320, 568}. Launch images must be PNG files and located at the
  top-level of your bundle, or provided within each .lproj folder if you
  localize your launch images.

I'm using SDK 8.1. Deployment target is 8.0. Launch images are set by storyboard launch screen file. There is no obsolete launch screen images and I don't plan to add them because target system is iOS 8+.

What is wrong? Xcode version 6.1 (6A1052d).

答:
This issue happens because you don't add launch image whose size is 640x1136 (iphone 5) correctly.

After editing Contents.json below, I can upload to iTunesConnect normally

```<code>{
  "images" : [
{
  "orientation" : "portrait",
  "idiom" : "iphone",
  "filename" : "splash-480h.png",
  "extent" : "full-screen",
  "scale" : "1x"
},
{
  "orientation" : "portrait",
  "idiom" : "iphone",
  "filename" : "splash-480h@2x.png",
  "extent" : "full-screen",
  "scale" : "2x"
},
{
  "orientation" : "portrait",
  "idiom" : "iphone",
  "filename" : "splash-568h@2x.png",
  "extent" : "full-screen",
  "subtype" : "retina4",
  "scale" : "2x"
},
{
  "extent" : "full-screen",
  "idiom" : "iphone",
  "subtype" : "736h",
  "filename" : "splash-736h@3x.png",
  "minimum-system-version" : "8.0",
  "orientation" : "portrait",
  "scale" : "3x"
},
{
  "extent" : "full-screen",
  "idiom" : "iphone",
  "subtype" : "736h",
  "filename" : "splash-landscape-736h@3x.png",
  "minimum-system-version" : "8.0",
  "orientation" : "landscape",
  "scale" : "3x"
},
{
  "extent" : "full-screen",
  "idiom" : "iphone",
  "subtype" : "667h",
  "filename" : "splash-667h@2x.png",
  "minimum-system-version" : "8.0",
  "orientation" : "portrait",
  "scale" : "2x"
},
{
  "orientation" : "portrait",
  "idiom" : "iphone",
  "extent" : "full-screen",
  "filename" : "splash-480h@2x.png",
  "minimum-system-version" : "7.0",
  "scale" : "2x"
},
{
  "extent" : "full-screen",
  "idiom" : "iphone",
  "subtype" : "retina4",
  "filename" : "splash-568h@2x.png",
  "minimum-system-version" : "7.0",
  "orientation" : "portrait",
  "scale" : "2x"
}
   ],
  "info" : {
"version" : 1,
"author" : "xcode"
  }
}
</code>```

Body:
This issue happens because you don't add launch image whose size is 640x1136 (iphone 5) correctly.

After editing Contents.json below, I can upload to iTunesConnect normally

{
  "images" : [
{
  "orientation" : "portrait",
  "idiom" : "iphone",
  "filename" : "splash-480h.png",
  "extent" : "full-screen",
  "scale" : "1x"
},
{
  "orientation" : "portrait",
  "idiom" : "iphone",
  "filename" : "splash-480h@2x.png",
  "extent" : "full-screen",
  "scale" : "2x"
},
{
  "orientation" : "portrait",
  "idiom" : "iphone",
  "filename" : "splash-568h@2x.png",
  "extent" : "full-screen",
  "subtype" : "retina4",
  "scale" : "2x"
},
{
  "extent" : "full-screen",
  "idiom" : "iphone",
  "subtype" : "736h",
  "filename" : "splash-736h@3x.png",
  "minimum-system-version" : "8.0",
  "orientation" : "portrait",
  "scale" : "3x"
},
{
  "extent" : "full-screen",
  "idiom" : "iphone",
  "subtype" : "736h",
  "filename" : "splash-landscape-736h@3x.png",
  "minimum-system-version" : "8.0",
  "orientation" : "landscape",
  "scale" : "3x"
},
{
  "extent" : "full-screen",
  "idiom" : "iphone",
  "subtype" : "667h",
  "filename" : "splash-667h@2x.png",
  "minimum-system-version" : "8.0",
  "orientation" : "portrait",
  "scale" : "2x"
},
{
  "orientation" : "portrait",
  "idiom" : "iphone",
  "extent" : "full-screen",
  "filename" : "splash-480h@2x.png",
  "minimum-system-version" : "7.0",
  "scale" : "2x"
},
{
  "extent" : "full-screen",
  "idiom" : "iphone",
  "subtype" : "retina4",
  "filename" : "splash-568h@2x.png",
  "minimum-system-version" : "7.0",
  "orientation" : "portrait",
  "scale" : "2x"
}
   ],
  "info" : {
"version" : 1,
"author" : "xcode"
  }
}


问:
Cron job failing with firebase in google cloud app engine
I have used to below firebase blog link to execute a cron job on google cloud app engine for firebase functions but i am getting the below error.

Firebase Blog link

Please help..

```<code>22:47:33.468
 (/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py:263)
Traceback (most recent call last):
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 240, in Handle
    handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
    handler, path, err = LoadObject(self._handler)
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 85, in LoadObject
    obj = __import__(path[0])
  File "/base/data/home/apps/s~updateroom-1a8fe/20170705t224250.402458509646721682/main.py", line 18, in <module>
    import pubsub_utils
  File "/base/data/home/apps/s~updateroom-1a8fe/20170705t224250.402458509646721682/pubsub_utils.py", line 23, in <module>
    import httplib2
  File "./lib/httplib2/__init__.py", line 352
    print('%s:' % h, end=' ', file=self._fp)
                        ^
SyntaxError: invalid syntax
</code>```

答:
print('%s:' % h, end=' ', file=self._fp) is valid python3, but not valid python2.

You can either do a future import to use this syntax in python2:

from __future__ import print_function

or use the old print syntax.

UPDATE

Reviewing this, I noticed that the offending line of code is in library code: ./lib/httplib2/__init__.py

So the problem is that your httplib2 installation is the python3 version rather than the python2 version.

You can try reinstalling your vendored packages to fix this; the command will be

pip install -r <name-of-your-vendored-requirements-file> -t lib

Ensure that you are using the right version of pip: pip --version should point to a location within a python2 installation.

Body:
I have used to below firebase blog link to execute a cron job on google cloud app engine for firebase functions but i am getting the below error.

Firebase Blog link

Please help..

22:47:33.468
 (/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py:263)
Traceback (most recent call last):
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 240, in Handle
    handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
    handler, path, err = LoadObject(self._handler)
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 85, in LoadObject
    obj = __import__(path[0])
  File "/base/data/home/apps/s~updateroom-1a8fe/20170705t224250.402458509646721682/main.py", line 18, in <module>
    import pubsub_utils
  File "/base/data/home/apps/s~updateroom-1a8fe/20170705t224250.402458509646721682/pubsub_utils.py", line 23, in <module>
    import httplib2
  File "./lib/httplib2/__init__.py", line 352
    print('%s:' % h, end=' ', file=self._fp)
                        ^
SyntaxError: invalid syntax


问:
Best way to remove = and ? from get method in PHP?
What's the best way to remove the = and ? in a URL from the get method in PHP? I'm working on the pagination structure of my website and currently this is what the URLs look like:

```<code>www.example/test/?page=3
</code>```

I want it to look like this:

```<code>www.example/test/3
</code>```

Can this be addressed directly in the PHP get method with some extra code or does it have to be done through an htaccess file?

This is what my htaccess file looks like right now:

```<code>RewriteBase /
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html
RewriteCond %{REQUEST_URI} /index\.html?$ [NC]
RewriteRule ^(.*)index\.html?$ "/$1" [NC,R=301,NE,L]
</code>```

答:
You can do this by using an intermediate page, say index.php and apply .htaccess rewrite only for index and load page based on GET[] on index.php.

You can refer this:
URL rewriting in PHP without htaccess

Body:
What's the best way to remove the = and ? in a URL from the get method in PHP? I'm working on the pagination structure of my website and currently this is what the URLs look like:

www.example/test/?page=3

I want it to look like this:

www.example/test/3

Can this be addressed directly in the PHP get method with some extra code or does it have to be done through an htaccess file?

This is what my htaccess file looks like right now:

RewriteBase /
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html
RewriteCond %{REQUEST_URI} /index\.html?$ [NC]
RewriteRule ^(.*)index\.html?$ "/$1" [NC,R=301,NE,L]


问:
Unique Key Constraint
What's the best practice in handling data insertion/update on a table with unique key constraints at the application level? These are what I came up with:

1. Run a query on the table before inserting data to see if it will violate the constraint.

Pros

You have full control so you don't have to deal with any DBMS specific error messages.

Addtional layer of data integrity check

Cons

There might be a performance hit since there will be no constraint violation most of the time.

You will need to lock the table while you run the query for duplicate data.

2. Do nothing. Update the table and see what sticks.

Pros

Simple!

Faster overall since you don't have to run an additional query everytime you update a table.

Cons

Your validation routine depends on the database layer.

If the data doesn't stick, you have to wade through the stack trace to find the cause.

Which one is the more widely accepted solution? Are there alternatives to these?

I'm using Java, JPA, Hibernate, and Spring BTW. Any suggestions, even framework specific, are welcome!

Thanks!

答:
You've already pretty much sum it up. If performance is a concern, go for 2nd way. If integrity is a concern, go for 1st way.

I personally favor integrity over performance. Hardware is pretty cheap, integrity not.

Related questions:

Java - MySQL integrity violation handling

Title: Unique Key Constraint


问:
Multithreading - Calculations between all pairs in a set
I have n elements (e.g. A, B, C and D) and need to do calculations between all of those.

```<code>Calculation 1 = A with B
Calculation 2 = A with C
Calculation 3 = A with D
Calculation 4 = B with C
Calculation 5 = B with D
Calculation 6 = C with D
</code>```

In reality there are more than 1000 elements and I want to parallelise the process.

Note that I can't access an element from 2 threads simultaneously. This for example makes it impossible to do Calculation 1 and Calculation 2 at the same time because they both use the element A.

Edit: I could access an element from 2 threads but it makes everything very slow if i just split up the calculations and depend on locks for threadsafety.

Is there already an distribution algorithm for these kind of problems?

It seems like a lot of people must have had the same problem already but i couldn't find anything in the great internet. ;)

Single thread example code:

```<code>for (int i = 0; i < elementCount; i++)
{
   for (int j = i + 1; j < elementCount; j++)
   {
      Calculate(element[i], element[j]);
   }
}
</code>```

答:
You can apply round-robin tournament algorithm that allows to organize all possible pairs (N*(N-1) results).

All set elements (players) form two rows, column is pair at the
current round. First element is fixed, others are shifted in cyclic manner.

So you can run up to N/2 threads to get results for the first pairs set, then reorder indexes and continue

Excerpt from wiki:

```<code>The circle method is the standard algorithm to create a schedule for a round-robin tournament. All competitors are assigned to numbers, and then paired in the first round:
Round 1. (1 plays 14, 2 plays 13, ... )
 1  2  3  4  5  6  7
 14 13 12 11 10 9  8

then fix one of the contributors in the first or last column of the table (number one in this example) and rotate the others clockwise one position
Round 2. (1 plays 13, 14 plays 12, ... )
 1  14 2  3  4  5  6
 13 12 11 10 9  8  7
Round 3. (1 plays 12, 13 plays 11, ... )
 1  13 14 2  3  4  5
 12 11 10 9  8  7  6

until you end up almost back at the initial position
Round 13. (1 plays 2, 3 plays 14, ... )
 1  3  4  5  6  7  8
 2 14  13 12 11 10 9
</code>```

Body:
I have n elements (e.g. A, B, C and D) and need to do calculations between all of those.

Calculation 1 = A with B
Calculation 2 = A with C
Calculation 3 = A with D
Calculation 4 = B with C
Calculation 5 = B with D
Calculation 6 = C with D

In reality there are more than 1000 elements and I want to parallelise the process.

Note that I can't access an element from 2 threads simultaneously. This for example makes it impossible to do Calculation 1 and Calculation 2 at the same time because they both use the element A.

Edit: I could access an element from 2 threads but it makes everything very slow if i just split up the calculations and depend on locks for threadsafety.

Is there already an distribution algorithm for these kind of problems?

It seems like a lot of people must have had the same problem already but i couldn't find anything in the great internet. ;)

Single thread example code:

for (int i = 0; i < elementCount; i++)
{
   for (int j = i + 1; j < elementCount; j++)
   {
      Calculate(element[i], element[j]);
   }
}

Body:
You can apply round-robin tournament algorithm that allows to organize all possible pairs (N*(N-1) results).

All set elements (players) form two rows, column is pair at the
current round. First element is fixed, others are shifted in cyclic manner.

So you can run up to N/2 threads to get results for the first pairs set, then reorder indexes and continue

Excerpt from wiki:

The circle method is the standard algorithm to create a schedule for a round-robin tournament. All competitors are assigned to numbers, and then paired in the first round:
Round 1. (1 plays 14, 2 plays 13, ... )
 1  2  3  4  5  6  7
 14 13 12 11 10 9  8

then fix one of the contributors in the first or last column of the table (number one in this example) and rotate the others clockwise one position
Round 2. (1 plays 13, 14 plays 12, ... )
 1  14 2  3  4  5  6
 13 12 11 10 9  8  7
Round 3. (1 plays 12, 13 plays 11, ... )
 1  13 14 2  3  4  5
 12 11 10 9  8  7  6

until you end up almost back at the initial position
Round 13. (1 plays 2, 3 plays 14, ... )
 1  3  4  5  6  7  8
 2 14  13 12 11 10 9


问:
Performance issue in bulk importing data in Dynamics CRM
I am importing data to Dynamics CRM using C# console application. I am using following code:

```<code>    public static void Main(string[] args)
    {
            int totalRecords = dbcon.GetDataCount();
            int rowCount = totalRecords / 10;

            for (int i = 1, j = 1; i <= totalRecords; i = i + rowCount, j = j + 1)
            {
                Task myTask = new Task(() => TestMethod(i, (rowCount * j)));
                myTask.Start();
            }
          Task.WaitAll();
     }

public static void TestMethod(int startSeqNo, int endSeqNo)
{
   IOrganizationService service = getServiceProxcy();
    DBConnection dbcon = new DBConnection();
    DataTable dt = dbcon.GetData(startSeqNo, endSeqNo);
    // Insert Commented
    BulkCreate(service, dt);
 }

public static void BulkCreate(IOrganizationService service, DataTable dt)
{
  // Create an ExecuteMultipleRequest object.
  ExecuteMultipleRequest multipleRequest = new ExecuteMultipleRequest()
  {
    // Assign settings that define execution behavior: continue on error, return responses.
    Settings = new ExecuteMultipleSettings()
    {
        ContinueOnError = false,
        ReturnResponses = true
    },
    // Create an empty organization request collection.
    Requests = new OrganizationRequestCollection()
};

foreach (DataRow row in dt.Rows)
{
    Entity entity = new Entity("new_dataimporttest");
    entity["new_name"] = row["name"].ToString();
    entity["new_telephone"] = row["telephone1"].ToString();
    if (multipleRequest.Requests.Count == 1000)
    {
        // Execute all the requests in the request collection using a single web method call.
        ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)service.Execute(multipleRequest);
        multipleRequest.Requests.Clear();
    }
    CreateRequest createRequest = new CreateRequest { Target = entity };
    multipleRequest.Requests.Add(createRequest);
}

// Execute all the requests in the request collection using a single web method call.
if (multipleRequest.Requests.Count > 0)
{
    ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)service.Execute(multipleRequest);
}
}
</code>```

I am using Task Parallel Library. It works fine but issue is that when following line is executed it takes time.

```<code>// Execute all the requests in the request collection using a single web method call.
    //            ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)service.Execute(multipleRequest);
</code>```

I want to improve performance of code as I am importing large amount of data nearly 1 million records. Currently it takes 1h 50 mins. How do I improve code to reduce execution time.

答:
You could have two methods execute multiplerequest in the same process(500 for each), using that you can cut the time by half.

Analize in which part it is wasting more time in the execution or in the foreach create. And write here so I can't help you in a better way

Body:
I am importing data to Dynamics CRM using C# console application. I am using following code:

    public static void Main(string[] args)
    {
            int totalRecords = dbcon.GetDataCount();
            int rowCount = totalRecords / 10;

            for (int i = 1, j = 1; i <= totalRecords; i = i + rowCount, j = j + 1)
            {
                Task myTask = new Task(() => TestMethod(i, (rowCount * j)));
                myTask.Start();
            }
          Task.WaitAll();
     }

public static void TestMethod(int startSeqNo, int endSeqNo)
{
   IOrganizationService service = getServiceProxcy();
    DBConnection dbcon = new DBConnection();
    DataTable dt = dbcon.GetData(startSeqNo, endSeqNo);
    // Insert Commented
    BulkCreate(service, dt);
 }

public static void BulkCreate(IOrganizationService service, DataTable dt)
{
  // Create an ExecuteMultipleRequest object.
  ExecuteMultipleRequest multipleRequest = new ExecuteMultipleRequest()
  {
    // Assign settings that define execution behavior: continue on error, return responses.
    Settings = new ExecuteMultipleSettings()
    {
        ContinueOnError = false,
        ReturnResponses = true
    },
    // Create an empty organization request collection.
    Requests = new OrganizationRequestCollection()
};

foreach (DataRow row in dt.Rows)
{
    Entity entity = new Entity("new_dataimporttest");
    entity["new_name"] = row["name"].ToString();
    entity["new_telephone"] = row["telephone1"].ToString();
    if (multipleRequest.Requests.Count == 1000)
    {
        // Execute all the requests in the request collection using a single web method call.
        ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)service.Execute(multipleRequest);
        multipleRequest.Requests.Clear();
    }
    CreateRequest createRequest = new CreateRequest { Target = entity };
    multipleRequest.Requests.Add(createRequest);
}

// Execute all the requests in the request collection using a single web method call.
if (multipleRequest.Requests.Count > 0)
{
    ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)service.Execute(multipleRequest);
}
}

I am using Task Parallel Library. It works fine but issue is that when following line is executed it takes time.

// Execute all the requests in the request collection using a single web method call.
    //            ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)service.Execute(multipleRequest);

I want to improve performance of code as I am importing large amount of data nearly 1 million records. Currently it takes 1h 50 mins. How do I improve code to reduce execution time.


问:
Restrict assignment of property to a set of constants in C#
Say I had a property

```<code>public string RestrictedString {get; set;}
</code>```

and I had a few static constant strings defined

```<code>public const string String1 = "First String";
public const string String2 = "Second String";
</code>```

is there a way to only allow RestrictedString to be assigned to String1 or String2?

答:
Conceptually you're wanting to have a new type, so create a new Type that represents the valid values.  In your case you want there to only be two possible valid values for your type, so construct those and don't allow any more to be constructed:

```<code>public class SomeMeaningfulName
{
    private SomeMeaningfulName(string value)
    {
        Value = value;
    }

    public string Value { get; }

    public static SomeMeaningfulName String1 = new SomeMeaningfulName("First String");
    public static SomeMeaningfulName String2 = new SomeMeaningfulName("Second String");
}
</code>```

Now you can change the type of that property to your new type, and know that it's only one of those two values (for which you can get the string value out of it).

Body:
Say I had a property

public string RestrictedString {get; set;}

and I had a few static constant strings defined

public const string String1 = "First String";
public const string String2 = "Second String";

is there a way to only allow RestrictedString to be assigned to String1 or String2?

Body:
Conceptually you're wanting to have a new type, so create a new Type that represents the valid values.  In your case you want there to only be two possible valid values for your type, so construct those and don't allow any more to be constructed:

public class SomeMeaningfulName
{
    private SomeMeaningfulName(string value)
    {
        Value = value;
    }

    public string Value { get; }

    public static SomeMeaningfulName String1 = new SomeMeaningfulName("First String");
    public static SomeMeaningfulName String2 = new SomeMeaningfulName("Second String");
}

Now you can change the type of that property to your new type, and know that it's only one of those two values (for which you can get the string value out of it).


问:
Insert a symbol ">" between the characters in a list of strings
I have a column in Excel like this:

```<code>ABC
BCD
BA
</code>```

How can I put the symbols ">" between every letters in the strings? The expected output should be like this:

```<code>A>B>C
B>C>D
B>A
</code>```

Or could we do this in Matlab ?

答:
If the words are of same length, you can directly use the formula :-

MID(A1,1,1)&">"&MID(A1,2,2)&">".....

This will extract the characters and insert ">" between them.

If the words aren't of the same length, you can write a simple macro. The pseudo-code would be :-

for i = 1 to len(string)

Range("B1")=mid(A1,i,i)&">"

next i

and then remove the last > sign using left(txt,len(txt)-1).

Body:
I have a column in Excel like this:

ABC
BCD
BA

How can I put the symbols ">" between every letters in the strings? The expected output should be like this:

A>B>C
B>C>D
B>A

Or could we do this in Matlab ?


答:
There's no event for passing data back on dismiss of pages and haven't seen anything or any news about they implementing this functionality, you would really need to create modal instead of simply pushing a page.

So import modal on your page and add it to your constructor and do the following

```<code>onWhereItemClick(){
  let modal = this.modalCtrl.create('YourPage');
  modal.onDidDismiss(data => {
    // HANDLE THE DATA YOU WANT TO PASS BACK
  });
  modal.present();
};
</code>```

Then, in YourPage you'll import ViewController, add it to constructor and then

```<code>dismissModal(){
  let myData = ''; // THIS IS THE CONTENT YOU WANT TO PASS BACK
  this.viewCtrl.dismiss(myData);
};
</code>```

With this you'll be able to send data back to your page and handle it.

Hope this helps.

EDIT

A workaround would be saving the data of your dismiss in localStorage or another way to persist it and then, when the user go back to the page you get it, something like this:

Your Page

```<code>ionViewWillEnter(){
  this.storage.get('dataYouWant').then(data =>{
    if(data){
      // HANDLE DATA
    }
  });
}

ionViewWillLeave(){
  this.storage.remove('dataYouWant');
  // REMOVE THE DATA SO IF YOU COME BACK TO THIS PAGE FROM ANOTHER WAY IT DOESN'T LOAD DATA YOU DON'T WANT
};
</code>```

Pushed Page

```<code>ionViewWillUnload(){
  this.storage.set('dataYouWant', dataYouWant);
  // SAVE DATA YOU WANT TO USE
}
</code>```

The way when the second page is going to unload it'll save data on a localStorage to be used in your first page. If there's any concurrence problems you can try using ionViewDidEnter() on the first page instead of ionViewWillEnter()

Title: How to push a new page when clicking ion-item and retrieve data

Body:
There's no event for passing data back on dismiss of pages and haven't seen anything or any news about they implementing this functionality, you would really need to create modal instead of simply pushing a page.

So import modal on your page and add it to your constructor and do the following

onWhereItemClick(){
  let modal = this.modalCtrl.create('YourPage');
  modal.onDidDismiss(data => {
    // HANDLE THE DATA YOU WANT TO PASS BACK
  });
  modal.present();
};

Then, in YourPage you'll import ViewController, add it to constructor and then

dismissModal(){
  let myData = ''; // THIS IS THE CONTENT YOU WANT TO PASS BACK
  this.viewCtrl.dismiss(myData);
};

With this you'll be able to send data back to your page and handle it.

Hope this helps.

EDIT

A workaround would be saving the data of your dismiss in localStorage or another way to persist it and then, when the user go back to the page you get it, something like this:

Your Page

ionViewWillEnter(){
  this.storage.get('dataYouWant').then(data =>{
    if(data){
      // HANDLE DATA
    }
  });
}

ionViewWillLeave(){
  this.storage.remove('dataYouWant');
  // REMOVE THE DATA SO IF YOU COME BACK TO THIS PAGE FROM ANOTHER WAY IT DOESN'T LOAD DATA YOU DON'T WANT
};

Pushed Page

ionViewWillUnload(){
  this.storage.set('dataYouWant', dataYouWant);
  // SAVE DATA YOU WANT TO USE
}

The way when the second page is going to unload it'll save data on a localStorage to be used in your first page. If there's any concurrence problems you can try using ionViewDidEnter() on the first page instead of ionViewWillEnter()


问:
Why don't Scala Lists have an Ordering?
Is there a reason why there is no implicit Ordering for Lists in Scala?

```<code>val lists = List(List(2, 3, 1), List(2, 1, 3))
lists.sorted

error: could not find implicit value for parameter ord: Ordering[List[Int]]
</code>```

EDIT

Yes, my question is why there is no built-in Ordering that's already implicitly in scope. To me, it seems obvious that the second list should be "less than" the first list since the items at 0 are equal and the second list has the lower item at 1. I was wondering if maybe it's that there's no good answer when the Lists are two different sizes.

答:
What you have is a list of lists, not a list of integers. What you are missing is a criteria for determining whether a list is <= another list, or not.

That's what the error message says: I can't find a way to compare a list to another list, you should provide one explicitly.

If your question was "why don't list have a built-in comparison method against other lists", well, that's just the way it is.

Title: Why don't Scala Lists have an Ordering?

Body:
Is there a reason why there is no implicit Ordering for Lists in Scala?

val lists = List(List(2, 3, 1), List(2, 1, 3))
lists.sorted

error: could not find implicit value for parameter ord: Ordering[List[Int]]

EDIT

Yes, my question is why there is no built-in Ordering that's already implicitly in scope. To me, it seems obvious that the second list should be "less than" the first list since the items at 0 are equal and the second list has the lower item at 1. I was wondering if maybe it's that there's no good answer when the Lists are two different sizes.


问:
trying to format date variable with moment and pass it to datetimepicker which results indeprecation warning
I am trying to format date variable and pass it to eonasdan datetimepicker for angular but no matter what I try to do I get

Deprecation warning: moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info.
  Arguments:

below are my tryouts:

date from ajax - Wed, 05 Jul 2017 00:00:00 GMT

```<code>/*example1*/
angular.forEach(tickets, function(value, key){
    $scope.startDate = new Date(value.start_date);
    $scope.endDate = new Date(value.end_date);
});

/*example2*/
angular.forEach(tickets, function(value, key){
    $scope.startDate = moment(startDate, "YYYY-MM-DD");
    $scope.endDate = moment(value.end_date, "YYYY-MM-DD");
});
</code>```

here are datetimepicker options

```<code>$scope.calendarWidgetOptions = {
   format: 'YYYY-MM-DD',
   minDate: moment().startOf('d')
};
</code>```

I tried other stuff but can not make it work, and get rid of deprecation warning hence date is now visible in some browsers/timezones.

答:
The implied question is 'Why am I getting this deprecation warning', and the answer is because you're making use of the moment function in a way that's deprecated and no longer officially supported.

From the link you provided:

"...moment construction using a non-iso string is deprecated. What this means is you can safely do..."

```<code>> moment("2014-04-25T01:32:21.196Z");  // iso string, utc timezone
> moment("2014-04-25T01:32:21.196+0600");  // iso string with timezone
> moment("2014 04 25", "YYYY MM DD"); // string with format
</code>```

You're calling moment like this:

```<code>moment(value.end_date, "YYYY-MM-DD");
</code>```

Which doesn't conform exactly to one of the strict signatures listed above, and so will be handled by the fuzzy handler that tries to resolve whatever value is passed in and return something usable, which is the functionality that's been deprecated.

You may be able to resolve this simply by matching the formatter exactly:

```<code>moment(value.end_date, "YYYY MM DD");
</code>```

However you're also passing a Date object into moment, when it looks like it's expecting a String, so what you most likely want is to convert the Date to a string and then pass that and the correct formatter to moment.

```<code>moment(value.end_date.toISOString(), "YYYY MM DD");
</code>```

or

```<code>moment(value.end_date.toISOString());
</code>```

This will effectively submit something like this:

```<code>moment("2017-07-05T17:22:49.396Z", "YYYY MM DD");
</code>```

or

```<code>moment("2017-07-05T17:22:49.396Z");
</code>```

And this does match the expected signature and shouldn't throw the warning.

Body:
I am trying to format date variable and pass it to eonasdan datetimepicker for angular but no matter what I try to do I get

Deprecation warning: moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info.
  Arguments:

below are my tryouts:

date from ajax - Wed, 05 Jul 2017 00:00:00 GMT

/*example1*/
angular.forEach(tickets, function(value, key){
    $scope.startDate = new Date(value.start_date);
    $scope.endDate = new Date(value.end_date);
});

/*example2*/
angular.forEach(tickets, function(value, key){
    $scope.startDate = moment(startDate, "YYYY-MM-DD");
    $scope.endDate = moment(value.end_date, "YYYY-MM-DD");
});

here are datetimepicker options

$scope.calendarWidgetOptions = {
   format: 'YYYY-MM-DD',
   minDate: moment().startOf('d')
};

I tried other stuff but can not make it work, and get rid of deprecation warning hence date is now visible in some browsers/timezones.

Body:
The implied question is 'Why am I getting this deprecation warning', and the answer is because you're making use of the moment function in a way that's deprecated and no longer officially supported.

From the link you provided:

"...moment construction using a non-iso string is deprecated. What this means is you can safely do..."

> moment("2014-04-25T01:32:21.196Z");  // iso string, utc timezone
> moment("2014-04-25T01:32:21.196+0600");  // iso string with timezone
> moment("2014 04 25", "YYYY MM DD"); // string with format

You're calling moment like this:

moment(value.end_date, "YYYY-MM-DD");

Which doesn't conform exactly to one of the strict signatures listed above, and so will be handled by the fuzzy handler that tries to resolve whatever value is passed in and return something usable, which is the functionality that's been deprecated.

You may be able to resolve this simply by matching the formatter exactly:

moment(value.end_date, "YYYY MM DD");

However you're also passing a Date object into moment, when it looks like it's expecting a String, so what you most likely want is to convert the Date to a string and then pass that and the correct formatter to moment.

moment(value.end_date.toISOString(), "YYYY MM DD");

or

moment(value.end_date.toISOString());

This will effectively submit something like this:

moment("2017-07-05T17:22:49.396Z", "YYYY MM DD");

or

moment("2017-07-05T17:22:49.396Z");

And this does match the expected signature and shouldn't throw the warning.


问:
Is it possible to change an inherited access modifier in ActionScript 3?
I'm currently working on a project where I have a ton of classes inheriting from other classes which inherit from other classes and so on. It's probably more complex than it should be, but I am a sucker for abstraction.

Anyway, at times I need to change a getter/setter from being public to private. I suppose it's not really a need, but a desire to cut off things that are preset in child classes, but still need to be publicly accessible in the parent classes.

So an example would be:

```<code>Class Base {
    public function set label( value:String ):void{};
}

Class A extends Base {}

Class B extends A {
    public function B() {
        super();
        this.label = "stuff";
    }

    override public function set label( value:String ):void {
        //this setter should not be publicly available since the label should not be possible to change in this class
    }
}
</code>```

Currently, I am doing one of two things in these cases:

override the setter to do nothing or set it to the default value so that it can still update/render/whatever

throw an error saying it is unavailable in that class

I've done some searching and everything seems to point to this being impossible, but I've never found it explicitly stated that it is impossible. So is it possible to change the access modifier on an inherited property/function?

答:
These are all valid points, but...
There are cases where they are all void.
Given a base class that comes from an external source. Like, say, mx:Panel.
It has the property 'titleIcon:Class'
The derived class inherits all properties and functions. But people using it shall never set the titleIcon directly, because part of the derived class' functionality depends on the availability of an icon name being known. It provides a property iconName:String. Setting it will also set the titleIcon.
Now how to prevent people from still setting the icon directly? The UI is offering the old property for AS3 and MXML, and the compiler will (of course) not complain.

If titleIcon is a setter/getter pair (in this case, it is), and not final, then the derived class can override the setter and throw an error, while the iconName setter will assign the icon class to super.titleIcon.
However, this is clumsy and will not work for final functions or variables.

If there were a way to at least tell the UI to not offer the property anymore or show a warning...

Body:
I'm currently working on a project where I have a ton of classes inheriting from other classes which inherit from other classes and so on. It's probably more complex than it should be, but I am a sucker for abstraction.

Anyway, at times I need to change a getter/setter from being public to private. I suppose it's not really a need, but a desire to cut off things that are preset in child classes, but still need to be publicly accessible in the parent classes.

So an example would be:

Class Base {
    public function set label( value:String ):void{};
}

Class A extends Base {}

Class B extends A {
    public function B() {
        super();
        this.label = "stuff";
    }

    override public function set label( value:String ):void {
        //this setter should not be publicly available since the label should not be possible to change in this class
    }
}

Currently, I am doing one of two things in these cases:

override the setter to do nothing or set it to the default value so that it can still update/render/whatever

throw an error saying it is unavailable in that class

I've done some searching and everything seems to point to this being impossible, but I've never found it explicitly stated that it is impossible. So is it possible to change the access modifier on an inherited property/function?


问:
Onclick JS function call, returns "Can't find variable" only in Safari Console
So I have a very simple JS function written that works like the following.

There is a button that has the following code:

```<code><button type="submit" class="large button" onclick="addCart(76,95,73,96);">
    <i class="icon-shopping-cart"></i> Add to Cart
</button>
</code>```

Now when that is clicked there is a very simple function added to the page below that looks like the following:

```<code><script type="text/javascript">
    function addCart(pid, pattr, pval, pscent = 0) {
    ...
    }
</script>
</code>```

This works perfectly in Chrome, Firefox, Chrome for Mobile, Safari for Mobile.

But this does not seem to work on Safari on Mac. Instead I get the following error:

ReferenceError: Can't find variable: addCart

I cannot figure out why. It's hard for me to add a listener because there are 7 buttons and a wide arrange of variables that are being sent, and I'd rather send that like I'm currently doing.

答: Looks like you are submitting a form since the input type is "submit".  Have you tried testing it with the input type set to "button"?</p>

Body:
So I have a very simple JS function written that works like the following.

There is a button that has the following code:

<button type="submit" class="large button" onclick="addCart(76,95,73,96);">
     Add to Cart
</button>

Now when that is clicked there is a very simple function added to the page below that looks like the following:

This works perfectly in Chrome, Firefox, Chrome for Mobile, Safari for Mobile.

But this does not seem to work on Safari on Mac. Instead I get the following error:

ReferenceError: Can't find variable: addCart

I cannot figure out why. It's hard for me to add a listener because there are 7 buttons and a wide arrange of variables that are being sent, and I'd rather send that like I'm currently doing.


问:
Show different Xib files based on the user's phone in Swift 3?
I'm using a Xib file and code programmatically to create a custom keyboard. I want different buttons based on the phone the user uses. Vary for traits does not exactly work for what I want. I'd rather make multiple Xib files and have them show based on the on the phone size of the user. Anyone have any idea how I can do this?</p>

答:
You can use this answer to grab the user's device model: Device Model and then load in your Xib according to what the user is currently using.</p>

```<code>let vc = UIViewController(nibName: "name", bundle: nil)
</code>```

Body:
You can use this answer to grab the user's device model: Device Model and then load in your Xib according to what the user is currently using.

let vc = UIViewController(nibName: "name", bundle: nil)


问:
Help convert .asp to .php
How can I rewrite this from .asp to .php?

```<code><%
' Url of the webpage we want to retrieve
thisURL = "pagerequest.jsp"

' Creation of the xmlHTTP object
Set GetConnection = CreateObject("Microsoft.XMLHTTP")

' Connection to the URL
GetConnection.Open "get", thisURL, False
GetConnection.Send

' ResponsePage now have the response of the remote web server
ResponsePage = GetConnection.responseText

' We write out now the content of the ResponsePage var
Response.ContentType = "text/xml"
Response.write (ResponsePage)

Set GetConnection = Nothing
</code>```

%>

答:
How? What you need to do is learn PHP and then write it.

If you already know PHP, then I suspect you'll want to investigate:

Whether or not you have remote file_get_contents support. (See the other answers.)

Failing that, whether or not you can use the CURL functions, although you should first check that your production environment has curl support. (If it doesn't, you'll need to rectify this.)

Failing all of those, you'll need to create a socket connection and send the relevant HTTP headers to request the remote content.

Of the above, I'd almost recommend CURL above file_get_contents, as it can transparently handle re-directs (if you tell it to) and will expose more of the under-pinnings, which may prove useful in the future.

Title: Help convert .asp to .php

Body:
How can I rewrite this from .asp to .php?

<%
' Url of the webpage we want to retrieve
thisURL = "pagerequest.jsp"

' Creation of the xmlHTTP object
Set GetConnection = CreateObject("Microsoft.XMLHTTP")

' Connection to the URL
GetConnection.Open "get", thisURL, False
GetConnection.Send

' ResponsePage now have the response of the remote web server
ResponsePage = GetConnection.responseText

' We write out now the content of the ResponsePage var
Response.ContentType = "text/xml"
Response.write (ResponsePage)

Set GetConnection = Nothing

%>