问:
ipywidgets use container inside Tab
Need to set an ipywidget container widget(HBox, VBox, ect.) inside a Tab
The following is a dummy example of what I trying to do just using a list of Text widgets as a stand in for any other widget

Create a list of what will be in the VBox widget, bind this list of widgets to a VBox, then display that resulting VBox; and this works as expected:

```<code>import ipywidgets as widgets
from IPython.display import display

#just "dummy" widgets for exsample
subwids=[widgets.Text(value='Hello City'),
 widgets.Text(value='Hello State'),
 widgets.Text(value='Hello country '),
 widgets.Text(value='Hello Contant'),
 widgets.Text(value='Hello Continent')
]

#bind the dummy widgets to a VBox
BOX=widgets.VBox(subwids)
#display the VBox
display(BOX)
</code>```

Now I am trying to set the existing VBox in a Tab in the Tab widget, and this is where it won't work and throws an error that can be seen when running the following:

```<code>tab=widgets.Tab(BOX)
tab.set_title(0, 'GeoLevels')
display(tab)
</code>```

But what I would want it to do is except the VBox in the tab just like I would do in Qt

答:
When I reproduced your example I ran into:

TraitError: The 'children' trait of a Tab instance must be a tuple, but a value of class 'ipywidgets.widgets.widget_box.VBox' was specified.

Following which, I passed it as a tuple:

```<code>tab=widgets.Tab((BOX,))
tab.set_title(0, 'GeoLevels')
display(tab)
</code>```

Now it displays the tab.

Title: ipywidgets use container inside Tab

Body:
Need to set an ipywidget container widget(HBox, VBox, ect.) inside a Tab
The following is a dummy example of what I trying to do just using a list of Text widgets as a stand in for any other widget

Create a list of what will be in the VBox widget, bind this list of widgets to a VBox, then display that resulting VBox; and this works as expected:

import ipywidgets as widgets
from IPython.display import display

#just "dummy" widgets for exsample
subwids=[widgets.Text(value='Hello City'),
 widgets.Text(value='Hello State'),
 widgets.Text(value='Hello country '),
 widgets.Text(value='Hello Contant'),
 widgets.Text(value='Hello Continent')
]

#bind the dummy widgets to a VBox
BOX=widgets.VBox(subwids)
#display the VBox
display(BOX)

Now I am trying to set the existing VBox in a Tab in the Tab widget, and this is where it won't work and throws an error that can be seen when running the following:

tab=widgets.Tab(BOX)
tab.set_title(0, 'GeoLevels')
display(tab)

But what I would want it to do is except the VBox in the tab just like I would do in Qt

Body:
When I reproduced your example I ran into:

TraitError: The 'children' trait of a Tab instance must be a tuple, but a value of class 'ipywidgets.widgets.widget_box.VBox' was specified.

Following which, I passed it as a tuple:

tab=widgets.Tab((BOX,))
tab.set_title(0, 'GeoLevels')
display(tab)

Now it displays the tab.


来源: stackexchange

问:
Excel VBA-- Creating macro to change cell color and call other macros based on cell value
I am trying to write a macro that calls different macros and changes cell colors. So, if a cell(s) in the entire column D (D4:D446) equals a certain value, THIS macro will call a separate macro associated with that value.

In other words, What I want is, for example, if any or multiple cells in range (D7:D446) = "1000ABC", "1000EFG", or "1000HIJ" any/all cells in column F7:F446 will turn red to indicate to the user that they need to click on that cell in F7:F446 and when the user clicks on that cell in column F, it will call the correct macro I already created.

Example: if cell D25="1000EFG" cell F25 will turn red and when the user bring their cursor over cell F25 and clicks on cell F25, it will take them to the macro associated with the value 1000EFG. I have already created the other macros associated with those particular values, I just need the cells in the F column to change color and become clickable to the user and when clicked, call a certain macro.
I will post the code I have tried below. ANY help is very much appreciated. You guys are awesome, Thanks!

```<code>Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
  Dim c As Range
  c = Range("D7:D446")
  For Each c In Intersect(ActiveCell, Range("D7:D446")) 'this is where the error is occuring
    Select Case c.Value
     Case "1000GP", "1000MM", "19FEST", "20IEDU", "20PART", "20PRDV", "20SPPR", "22DANC", "22LFLC", "22MEDA", "530CCH", "60POUBL", "74GA01", "74GA17", "74GA99", "78REDV"
            Cells(c.Row, "F").Interior.ColorIndex = 3
      Case Else
        Cells(c.Row, "F").Interior.ColorIndex = 0
    End Select
  Next c
End Sub
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
  If Target.Column = 6 And Target.Cells.Count = 1 And Target.Interior.ColorIndex = 3 Then
      Cancel = True
      ' Now call the appropriate routine according to column C
      Select Case Target.Offset(0, -3).Value2
        Case "1000GP": gotoref1
        Case "1000MM": gotoref2
        Case "19FEST": gotoref3
        Case "20IEDU": gotoref4
        Case "20ONLC": gotoref5
        Case "20PART": gotoref6
        Case "20PRDV": gotoref7
        Case "20SPPR": gotoref8
        Case "22DANC": gotoref9
        Case "22LFLC": gotoref10
        Case "22MEDA": gotoref11
        Case "530CCH": gotoref12
        Case "60PUBL": gotoref13
        Case "74GA01": gotoref14
        Case "74GA17": gotoref15
        Case "74GA99": gotoref16
        Case "78REDV": gotoref17
      End Select
  End If
End Sub
</code>```

答:
Adjust the Worksheet_Change event For structure to this:

```<code>Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

  If Not Intersect(Target, Range("D7:D446")) is Nothing Then

      Dim c As Range

      For Each c In Target

          Select Case c.Value
              Case "1000GP", "1000MM", "19FEST", "20IEDU", "20PART", "20PRDV", "20SPPR", "22DANC", "22LFLC", "22MEDA", "530CCH", "60POUBL", "74GA01", "74GA17", "74GA99", "78REDV"
                  Cells(c.Row, "F").Interior.ColorIndex = 3
              Case Else
                 Cells(c.Row, "F").Interior.ColorIndex = 0
          End Select

      Next c

 End If

End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to write a macro that calls different macros and changes cell colors. So, if a cell(s) in the entire column D (D4:D446) equals a certain value, THIS macro will call a separate macro associated with that value.

In other words, What I want is, for example, if any or multiple cells in range (D7:D446) = "1000ABC", "1000EFG", or "1000HIJ" any/all cells in column F7:F446 will turn red to indicate to the user that they need to click on that cell in F7:F446 and when the user clicks on that cell in column F, it will call the correct macro I already created.

Example: if cell D25="1000EFG" cell F25 will turn red and when the user bring their cursor over cell F25 and clicks on cell F25, it will take them to the macro associated with the value 1000EFG. I have already created the other macros associated with those particular values, I just need the cells in the F column to change color and become clickable to the user and when clicked, call a certain macro.
I will post the code I have tried below. ANY help is very much appreciated. You guys are awesome, Thanks!

Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
  Dim c As Range
  c = Range("D7:D446")
  For Each c In Intersect(ActiveCell, Range("D7:D446")) 'this is where the error is occuring
    Select Case c.Value
     Case "1000GP", "1000MM", "19FEST", "20IEDU", "20PART", "20PRDV", "20SPPR", "22DANC", "22LFLC", "22MEDA", "530CCH", "60POUBL", "74GA01", "74GA17", "74GA99", "78REDV"
            Cells(c.Row, "F").Interior.ColorIndex = 3
      Case Else
        Cells(c.Row, "F").Interior.ColorIndex = 0
    End Select
  Next c
End Sub
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
  If Target.Column = 6 And Target.Cells.Count = 1 And Target.Interior.ColorIndex = 3 Then
      Cancel = True
      ' Now call the appropriate routine according to column C
      Select Case Target.Offset(0, -3).Value2
        Case "1000GP": gotoref1
        Case "1000MM": gotoref2
        Case "19FEST": gotoref3
        Case "20IEDU": gotoref4
        Case "20ONLC": gotoref5
        Case "20PART": gotoref6
        Case "20PRDV": gotoref7
        Case "20SPPR": gotoref8
        Case "22DANC": gotoref9
        Case "22LFLC": gotoref10
        Case "22MEDA": gotoref11
        Case "530CCH": gotoref12
        Case "60PUBL": gotoref13
        Case "74GA01": gotoref14
        Case "74GA17": gotoref15
        Case "74GA99": gotoref16
        Case "78REDV": gotoref17
      End Select
  End If
End Sub

Body:
Adjust the Worksheet_Change event For structure to this:

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

  If Not Intersect(Target, Range("D7:D446")) is Nothing Then

      Dim c As Range

      For Each c In Target

          Select Case c.Value
              Case "1000GP", "1000MM", "19FEST", "20IEDU", "20PART", "20PRDV", "20SPPR", "22DANC", "22LFLC", "22MEDA", "530CCH", "60POUBL", "74GA01", "74GA17", "74GA99", "78REDV"
                  Cells(c.Row, "F").Interior.ColorIndex = 3
              Case Else
                 Cells(c.Row, "F").Interior.ColorIndex = 0
          End Select

      Next c

 End If

End Sub


问:
Getting error: expression not assignable
I'm new to C and I can't find any answers on why it's giving me an error: expression is not assignable on lines 11 and 20.

This is a simple code for creating a random array and then sort it using a subroutine. I'm still learning C and couldn't find a solution with any research.

Here is my code:

```<code>#include <stdio.h>
#include <stdlib.h>
int myArray[100];
int* ptr = myArray;
int i;
int n = sizeof(myArray);
int SortedArray[100];

int MakeRandArray(ptr, i)
{
    for (i = 0; i < n; i++) {
        (ptr + i) = rand()
    }
}

int SortArray(ptr)
{
    int a;
    int j = (i + 1);
    for (i = 0; i < n; i++) {
        if ((ptr + i) > (ptr + j)) {
            (ptr + i) = (ptr + j)
        }
    }
}

int main()
{
    MakeRandArray(*ptr, i);
    SortArray(*ptr);
}
</code>```

答:
You're using old-style (pre-standard, K&R style) function definitions.  You should be using the faintly modern C90 and later prototype style function definitions.

You wrote:

```<code>int MakeRandArray(ptr, i)
{
    for (i = 0; i < n; i++) {
        (ptr + i) = rand()
    }
}
</code>```

In this function as shown, the type of ptr is int, as is the type of i — they are implicitly typed to int because you didn't specify the type.  (Note that these variables are unrelated to the global variables ptr and i — they simply hide the global variables.  They do not inherit the same type as the global variables.)  You should pass n to the function and should not pass i to the function.  You should avoid all those global variables.

You immediate compilation error is because you omit the * from *(ptr + i) and you also omit the ; at the end of the statement.  You should use ptr[i] because it is simpler, easy to type, easier to read, more reliable, and generally more beneficial to everyone than the alternative.

You claim your function returns an int; it returns nothing.

Thus, your code for this function should be:

```<code>void MakeRandArray(int *ptr, int n)
{
    for (int i = 0; i < n; i++)
        ptr[i] = rand();
}
</code>```

You can put the braces around the body of the loop if you prefer; personally, I don't prefer that.  Defining i in the loop like that requires a compiler that handles C99 mode.  If you were really stuck, you could define int i; before the loop and remove int from the loop control line.  However, you're on a Mac; you are not that stuck.

There are similar issues throughout the code.

```<code>// Syntactically valid; semantically dubious - it does not sort!
void SortArray(int *ptr, int n)
{
    for (int i = 0; i < n; i++)
    {
        int j = i + 1;
        if (ptr[i] > ptr[j])
            ptr[i] = ptr[j];
    }
}

int main(void)
{
    MakeRandArray(myArray, 100);
    SortArray(myArray, 100);
}
</code>```

Note that even though it should compile, it won't sort the array.  Of course, you've not shown any printing code, so you can't demonstrate that the array is, or is not, sorted.  You'd need to do that.  You could write a function to check that the array is sorted.

Your sort function will need a second loop inside it, iterating j.  You will need to swap elements, not simply overwrite them.

Your definition of n is:

```<code>int n = sizeof(myArray);
</code>```

This probably sets n to 400.  If you want the size of an array, you need int n = sizeof(myArray) / sizeof(myArray[0]); which gives the correct answer in this context.  You should be able to do without that variable, and the global i, ptr.  You don't use SortedArray at all.  The myArray could be local to main() — which means you need no global variables at all.  Try to avoid global variables; they are often not a good idea.

Body:
I'm new to C and I can't find any answers on why it's giving me an error: expression is not assignable on lines 11 and 20.

This is a simple code for creating a random array and then sort it using a subroutine. I'm still learning C and couldn't find a solution with any research.

Here is my code:

#include <stdio.h>
#include <stdlib.h>
int myArray[100];
int* ptr = myArray;
int i;
int n = sizeof(myArray);
int SortedArray[100];

int MakeRandArray(ptr, i)
{
    for (i = 0; i < n; i++) {
        (ptr + i) = rand()
    }
}

int SortArray(ptr)
{
    int a;
    int j = (i + 1);
    for (i = 0; i < n; i++) {
        if ((ptr + i) > (ptr + j)) {
            (ptr + i) = (ptr + j)
        }
    }
}

int main()
{
    MakeRandArray(*ptr, i);
    SortArray(*ptr);
}

Body:
You're using old-style (pre-standard, K&R style) function definitions.  You should be using the faintly modern C90 and later prototype style function definitions.

You wrote:

int MakeRandArray(ptr, i)
{
    for (i = 0; i < n; i++) {
        (ptr + i) = rand()
    }
}

In this function as shown, the type of ptr is int, as is the type of i — they are implicitly typed to int because you didn't specify the type.  (Note that these variables are unrelated to the global variables ptr and i — they simply hide the global variables.  They do not inherit the same type as the global variables.)  You should pass n to the function and should not pass i to the function.  You should avoid all those global variables.

You immediate compilation error is because you omit the * from *(ptr + i) and you also omit the ; at the end of the statement.  You should use ptr[i] because it is simpler, easy to type, easier to read, more reliable, and generally more beneficial to everyone than the alternative.

You claim your function returns an int; it returns nothing.

Thus, your code for this function should be:

void MakeRandArray(int *ptr, int n)
{
    for (int i = 0; i < n; i++)
        ptr[i] = rand();
}

You can put the braces around the body of the loop if you prefer; personally, I don't prefer that.  Defining i in the loop like that requires a compiler that handles C99 mode.  If you were really stuck, you could define int i; before the loop and remove int from the loop control line.  However, you're on a Mac; you are not that stuck.

There are similar issues throughout the code.

// Syntactically valid; semantically dubious - it does not sort!
void SortArray(int *ptr, int n)
{
    for (int i = 0; i < n; i++)
    {
        int j = i + 1;
        if (ptr[i] > ptr[j])
            ptr[i] = ptr[j];
    }
}

int main(void)
{
    MakeRandArray(myArray, 100);
    SortArray(myArray, 100);
}

Note that even though it should compile, it won't sort the array.  Of course, you've not shown any printing code, so you can't demonstrate that the array is, or is not, sorted.  You'd need to do that.  You could write a function to check that the array is sorted.

Your sort function will need a second loop inside it, iterating j.  You will need to swap elements, not simply overwrite them.

Your definition of n is:

int n = sizeof(myArray);

This probably sets n to 400.  If you want the size of an array, you need int n = sizeof(myArray) / sizeof(myArray[0]); which gives the correct answer in this context.  You should be able to do without that variable, and the global i, ptr.  You don't use SortedArray at all.  The myArray could be local to main() — which means you need no global variables at all.  Try to avoid global variables; they are often not a good idea.


问:
How to extract a certain amount of char from a long string until the end of the string
Lets say I have the following string:

1111000011001101

How can I extract substrings of 4 chars until the end of the string so that I have the following array ?

```<code>|1111|0000|1100|1101|
</code>```

答:
Playing around with LinqPad I get the following:

```<code>var s = "1111000011001101";

var substrings = Enumerable
  .Range(0, s.Length / 4)
  .Select(i => s.Substring(i * 4, 4))
  .ToArray();

substrings.Dump();
</code>```

Output:

```<code>String[] (4 items)
1111
0000

1100
1101
</code>```

EDIT: Just noticed this is a duplicate of answer -- see link in the comments of OP. See that link as it gives a general solution.

Body:
Lets say I have the following string:

1111000011001101

How can I extract substrings of 4 chars until the end of the string so that I have the following array ?

|1111|0000|1100|1101|

Body:
Playing around with LinqPad I get the following:

var s = "1111000011001101";

var substrings = Enumerable
  .Range(0, s.Length / 4)
  .Select(i => s.Substring(i * 4, 4))
  .ToArray();

substrings.Dump();

Output:

String[] (4 items)
1111
0000

1100
1101

EDIT: Just noticed this is a duplicate of answer -- see link in the comments of OP. See that link as it gives a general solution.


问:
how to treat ruby symbols in cross language object serialization
I'm currently working on a project where I need to transfer objects from ruby to python and back again, obviously serialization is the way to go. I've looked at things like yaml but decided to write my own as I didn't want to deal with the dependencies of the libraries and such when it came time to distribute.  I've wrote up how this serialization format works here.

my question is that as this format is intended to work cross language between ruby and python,
how should I serialize ruby's symbols? I'm not aware of a object that works the same way in python. should a dump containing a symbol fail? should I just serialize it as a string? what would be best?

答: If symbols are a stumbling block then you have three choices, don't allow them, convert them to strings on the fly or figure out a way to make them universal and/or innocuous in other languages.</p>

ContentLicense: CC BY-SA 2.5


问:
UICollectionViewCells not populating
I am trying to create a message app. When I try to display the cells, containing the messages in a UICollectionView they are not showing up.
I first want to give the cells a red background and display the items from my model. I have in messages array. Can anyone tell me why they are not populating?

```<code>import UIKit
import Firebase

class ChatLogController: UICollectionViewController,
UITextFieldDelegate, UICollectionViewDelegateFlowLayout{

    var messages = [Message]()

    var user: User?{
        didSet{
            navigationItem.title = user?.name
            navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(handleBackBtnPressed))

            observeMessages()
        }
    }

    lazy var inputTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder  = "Enter Message..."
        textField.translatesAutoresizingMaskIntoConstraints = false
        textField.delegate = self

        return textField
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView?.backgroundColor = UIColor.white
         collectionView?.register(ChatMessageCell.self, forCellWithReuseIdentifier: "cell")
        collectionView?.delegate = self
        collectionView?.dataSource = self
        setupInputComponents()

    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return messages.count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ChatMessageCell

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        //set the size
        return CGSize(width: self.view.frame.width, height: 80)
    }

    func setupInputComponents(){
        let containerView = UIView()
        containerView.translatesAutoresizingMaskIntoConstraints = false

        view.addSubview(containerView)

        //constraints
        containerView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        containerView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        containerView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
        containerView.heightAnchor.constraint(equalToConstant: 50).isActive = true
        containerView.backgroundColor = UIColor.white

        let sendBtn = UIButton(type: .system)
        sendBtn.setTitle("Send", for: .normal)
        sendBtn.translatesAutoresizingMaskIntoConstraints = false
        sendBtn.addTarget(self, action: #selector(handleSend), for: .touchUpInside)
        containerView.addSubview(sendBtn)
        sendBtn.rightAnchor.constraint(equalTo: containerView.rightAnchor).isActive = true
        sendBtn.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
        sendBtn.widthAnchor.constraint(equalToConstant: 80).isActive = true
        sendBtn.heightAnchor.constraint(equalTo: containerView.heightAnchor).isActive = true

        containerView.addSubview(inputTextField)

        inputTextField.leftAnchor.constraint(equalTo: containerView.leftAnchor, constant: 8).isActive = true
        inputTextField.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
        inputTextField.rightAnchor.constraint(equalTo: sendBtn.leftAnchor).isActive = true
        inputTextField.heightAnchor.constraint(equalTo: containerView.heightAnchor).isActive = true

        let separator = UIView()
        separator.backgroundColor =  UIColor.lightGray
        separator.translatesAutoresizingMaskIntoConstraints = false
        containerView.addSubview(separator)

        separator.leftAnchor.constraint(equalTo: containerView.leftAnchor).isActive = true
        separator.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true
        separator.widthAnchor.constraint(equalTo:containerView.widthAnchor).isActive = true
        separator.heightAnchor.constraint(equalToConstant: 1).isActive = true

    }

    func handleSend(){
        let reference = FIRDatabase.database().reference().child("messages")
        let childRef = reference.childByAutoId()
        let toId = user!.id!
        let fromId = FIRAuth.auth()!.currentUser!.uid
        let timeStamp = Date().timeIntervalSince1970
        let values = ["text":inputTextField.text!,"toId":toId,"fromId":fromId,"timeStamp":timeStamp] as [String : AnyObject]
        childRef.updateChildValues(values) { (error, ref) in
            if error != nil{
                print(error?.localizedDescription ?? "")
                return
            }
            let userMessagesRef = FIRDatabase.database().reference().child("user-messages").child(fromId)
            let messageId = childRef.key
            userMessagesRef.updateChildValues([messageId:1])

            let recipientUserMessageRef = FIRDatabase.database().reference().child("user-messages").child(toId)
            recipientUserMessageRef.updateChildValues([messageId:1])
        }
    }

    func handleBackBtnPressed(){
        let messageController = MessagesVC()
        let navController = UINavigationController(rootViewController: messageController)
        self.present(navController, animated: true, completion: nil)
    }

    func observeMessages(){
        guard let uid = FIRAuth.auth()?.currentUser?.uid else{
            return
        }

        let ref = FIRDatabase.database().reference().child("user-messages").child(uid)
        ref.observe(.childAdded, with: { (snapshot) in

            let messageId = snapshot.key
            let messagesRef = FIRDatabase.database().reference().child("messages").child(messageId)
            messagesRef.observeSingleEvent(of: .value, with: { (snapshot) in

                guard let dictionary = snapshot.value as? [String:AnyObject] else{
                    return
                }

                let message = Message()
                message.setValuesForKeys(dictionary)
                self.messages.append(message)

                DispatchQueue.main.async {
                    self.collectionView?.reloadData()
                }
            })
        })
    }

}
</code>```

and here is the ChatMessageCell

```<code>import UIKit

class ChatMessageCell: UICollectionViewCell {
    let textView: UITextView = {
        let tv = UITextView()
        tv.text = "my text"
        tv.font = UIFont.systemFont(ofSize: 16)
        return tv
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)

        backgroundColor = UIColor.red
    }
}
</code>```

答: Try to check if your messages array is not empty after fetching from Firebase database.. put break point in observeMessages func. If you array is not empty and you successfully fetched data from firebase database, then you have problem with setting collectionView..

Title: UICollectionViewCells not populating

Body:
I am trying to create a message app. When I try to display the cells, containing the messages in a UICollectionView they are not showing up.
I first want to give the cells a red background and display the items from my model. I have in messages array. Can anyone tell me why they are not populating?

import UIKit
import Firebase

class ChatLogController: UICollectionViewController,
UITextFieldDelegate, UICollectionViewDelegateFlowLayout{

    var messages = [Message]()

    var user: User?{
        didSet{
            navigationItem.title = user?.name
            navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(handleBackBtnPressed))

            observeMessages()
        }
    }

    lazy var inputTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder  = "Enter Message..."
        textField.translatesAutoresizingMaskIntoConstraints = false
        textField.delegate = self

        return textField
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView?.backgroundColor = UIColor.white
         collectionView?.register(ChatMessageCell.self, forCellWithReuseIdentifier: "cell")
        collectionView?.delegate = self
        collectionView?.dataSource = self
        setupInputComponents()

    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return messages.count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ChatMessageCell

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        //set the size
        return CGSize(width: self.view.frame.width, height: 80)
    }

    func setupInputComponents(){
        let containerView = UIView()
        containerView.translatesAutoresizingMaskIntoConstraints = false

        view.addSubview(containerView)

        //constraints
        containerView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        containerView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        containerView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
        containerView.heightAnchor.constraint(equalToConstant: 50).isActive = true
        containerView.backgroundColor = UIColor.white

        let sendBtn = UIButton(type: .system)
        sendBtn.setTitle("Send", for: .normal)
        sendBtn.translatesAutoresizingMaskIntoConstraints = false
        sendBtn.addTarget(self, action: #selector(handleSend), for: .touchUpInside)
        containerView.addSubview(sendBtn)
        sendBtn.rightAnchor.constraint(equalTo: containerView.rightAnchor).isActive = true
        sendBtn.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
        sendBtn.widthAnchor.constraint(equalToConstant: 80).isActive = true
        sendBtn.heightAnchor.constraint(equalTo: containerView.heightAnchor).isActive = true

        containerView.addSubview(inputTextField)

        inputTextField.leftAnchor.constraint(equalTo: containerView.leftAnchor, constant: 8).isActive = true
        inputTextField.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
        inputTextField.rightAnchor.constraint(equalTo: sendBtn.leftAnchor).isActive = true
        inputTextField.heightAnchor.constraint(equalTo: containerView.heightAnchor).isActive = true

        let separator = UIView()
        separator.backgroundColor =  UIColor.lightGray
        separator.translatesAutoresizingMaskIntoConstraints = false
        containerView.addSubview(separator)

        separator.leftAnchor.constraint(equalTo: containerView.leftAnchor).isActive = true
        separator.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true
        separator.widthAnchor.constraint(equalTo:containerView.widthAnchor).isActive = true
        separator.heightAnchor.constraint(equalToConstant: 1).isActive = true

    }

    func handleSend(){
        let reference = FIRDatabase.database().reference().child("messages")
        let childRef = reference.childByAutoId()
        let toId = user!.id!
        let fromId = FIRAuth.auth()!.currentUser!.uid
        let timeStamp = Date().timeIntervalSince1970
        let values = ["text":inputTextField.text!,"toId":toId,"fromId":fromId,"timeStamp":timeStamp] as [String : AnyObject]
        childRef.updateChildValues(values) { (error, ref) in
            if error != nil{
                print(error?.localizedDescription ?? "")
                return
            }
            let userMessagesRef = FIRDatabase.database().reference().child("user-messages").child(fromId)
            let messageId = childRef.key
            userMessagesRef.updateChildValues([messageId:1])

            let recipientUserMessageRef = FIRDatabase.database().reference().child("user-messages").child(toId)
            recipientUserMessageRef.updateChildValues([messageId:1])
        }
    }

    func handleBackBtnPressed(){
        let messageController = MessagesVC()
        let navController = UINavigationController(rootViewController: messageController)
        self.present(navController, animated: true, completion: nil)
    }

    func observeMessages(){
        guard let uid = FIRAuth.auth()?.currentUser?.uid else{
            return
        }

        let ref = FIRDatabase.database().reference().child("user-messages").child(uid)
        ref.observe(.childAdded, with: { (snapshot) in

            let messageId = snapshot.key
            let messagesRef = FIRDatabase.database().reference().child("messages").child(messageId)
            messagesRef.observeSingleEvent(of: .value, with: { (snapshot) in

                guard let dictionary = snapshot.value as? [String:AnyObject] else{
                    return
                }

                let message = Message()
                message.setValuesForKeys(dictionary)
                self.messages.append(message)

                DispatchQueue.main.async {
                    self.collectionView?.reloadData()
                }
            })
        })
    }

}

and here is the ChatMessageCell

import UIKit

class ChatMessageCell: UICollectionViewCell {
    let textView: UITextView = {
        let tv = UITextView()
        tv.text = "my text"
        tv.font = UIFont.systemFont(ofSize: 16)
        return tv
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)

        backgroundColor = UIColor.red
    }
}


问:
pick first item of repeated in rxjs
I am receiving a bunch of streams from socket and want to merge repeated streams into one stream (or pick the first item)

In summary I want do this by rxjs:

```<code>In:  1 - 1 - 1 - 2 - 2 - 3 - 3 - 1 - 1 - 1 - 2 - 2 - 2 - 1 - 2 - 2 - 3 - 3
Out: 1 - - - - - 2 - - - 3 - - - 1 - - - - - 2 - - - - - 1 - 2 - - - 3 - -
</code>```

Title: pick first item of repeated in rxjs

Body:
I am receiving a bunch of streams from socket and want to merge repeated streams into one stream (or pick the first item)

In summary I want do this by rxjs:

In:  1 - 1 - 1 - 2 - 2 - 3 - 3 - 1 - 1 - 1 - 2 - 2 - 2 - 1 - 2 - 2 - 3 - 3
Out: 1 - - - - - 2 - - - 3 - - - 1 - - - - - 2 - - - - - 1 - 2 - - - 3 - -

Body:
you can try this

var arr = [1,1,1,2,2,3,3,1,1,1,2,2,2,2,1,2,2,3,3];
for (i = 1; i < arr.length; i++) {
    if (arr[i]==arr[i-1]){ arr.splice(i,1);i--;}
}

OUT : [1, 2, 3, 1, 2, 1, 2, 3]


问:
Get all subsets of a Python dictionary with restrictions
I have the following dictionary:

```<code>intervals = {'param1': [0, 1],
             'param2_hi': [4, 5, 6, 7, 8, 9],
             'param2_lo': [0, 1, 2, 3, 4, 5],
             'param3_hi': [9, 10, 11, 12, 13, 14, 15],
             'param3_lo': [5, 6, 7, 8, 9, 10],
             'param4': [0, 1],
             'param5_hi': [4, 5, 6, 7, 8, 9],
             'param5_lo': [0, 1, 2, 3, 4, 5]}
</code>```

How would I create all possible subsets of this dictionary where I must have exactly one of each number x for 'paramx'? Meaning that I can only have one entry for param1 (_lo or _hi), one entry for param2 (_lo or _hi), and so on, and that each subset must include every paramx that does not have a _lo or _hi.

Here are two possible subsets:

```<code>subset_one = {'param1': [0, 1],
              'param2_hi': [4, 5, 6, 7, 8, 9],
              'param3_hi': [9, 10, 11, 12, 13, 14, 15],
              'param4': [0, 1],
              'param5_hi': [4, 5, 6, 7, 8, 9]}

subset_two = {'param1': [0, 1],
              'param2_lo': [0, 1, 2, 3, 4, 5],
              'param3_lo': [5, 6, 7, 8, 9, 10],
              'param4': [0, 1],
              'param5_lo': [0, 1, 2, 3, 4, 5]}

# Example of mixed '_hi' and '_lo' intervals
subset_three = {'param1': [0, 1],
                'param2_lo': [0, 1, 2, 3, 4, 5],
                'param3_hi': [9, 10, 11, 12, 13, 14, 15],
                'param4': [0, 1],
                'param5_lo': [0, 1, 2, 3, 4, 5]}

...
</code>```

Note: I want to preserve key, value pairs.

Edit: Added subset_three to show the possibility of having mixed '_lo' and '_hi' intervals.

答:
I think the best tool to use is itertools.product, one solution would be this:</p>

```<code>intervals = {'param1': [0, 1],
             'param2_hi': [4, 5, 6, 7, 8, 9],
             'param2_lo': [0, 1, 2, 3, 4, 5],
             'param3_hi': [9, 10, 11, 12, 13, 14, 15],
             'param3_lo': [5, 6, 7, 8, 9, 10],
             'param4': [0, 1],
             'param5_hi': [4, 5, 6, 7, 8, 9],
             'param5_lo': [0, 1, 2, 3, 4, 5]}

import itertools

def get_subsets(intervals):

   params_list = set(key.split('_')[0] for key in intervals.keys())

   list_keys = [[x for x in intervals.keys() if x.startswith(param)] for param in params_list]

   subsets = [{x : intervals[x] for x in sublist} for sublist in itertools.product(*list_keys)]

   return subsets

get_subsets(intervals)

# [{'param2_lo': [0, 1, 2, 3, 4, 5], 'param3_hi': [9, 10, 11, 12, 13, 14, 15], 'param5_lo': [0, 1, 2, 3, 4, 5], 'param1': [0, 1], 'param4': [0, 1]}, {'param2_lo': [0, 1, 2, 3, 4, 5], 'param3_hi': [9, 10, 11, 12, 13, 14, 15], 'param1': [0, 1], 'param4': [0, 1], 'param5_hi': [4, 5, 6, 7, 8, 9]}, ...
</code>```

Body:
I have the following dictionary:

intervals = {'param1': [0, 1],
             'param2_hi': [4, 5, 6, 7, 8, 9],
             'param2_lo': [0, 1, 2, 3, 4, 5],
             'param3_hi': [9, 10, 11, 12, 13, 14, 15],
             'param3_lo': [5, 6, 7, 8, 9, 10],
             'param4': [0, 1],
             'param5_hi': [4, 5, 6, 7, 8, 9],
             'param5_lo': [0, 1, 2, 3, 4, 5]}

How would I create all possible subsets of this dictionary where I must have exactly one of each number x for 'paramx'? Meaning that I can only have one entry for param1 (_lo or _hi), one entry for param2 (_lo or _hi), and so on, and that each subset must include every paramx that does not have a _lo or _hi.

Here are two possible subsets:

subset_one = {'param1': [0, 1],
              'param2_hi': [4, 5, 6, 7, 8, 9],
              'param3_hi': [9, 10, 11, 12, 13, 14, 15],
              'param4': [0, 1],
              'param5_hi': [4, 5, 6, 7, 8, 9]}

subset_two = {'param1': [0, 1],
              'param2_lo': [0, 1, 2, 3, 4, 5],
              'param3_lo': [5, 6, 7, 8, 9, 10],
              'param4': [0, 1],
              'param5_lo': [0, 1, 2, 3, 4, 5]}

# Example of mixed '_hi' and '_lo' intervals
subset_three = {'param1': [0, 1],
                'param2_lo': [0, 1, 2, 3, 4, 5],
                'param3_hi': [9, 10, 11, 12, 13, 14, 15],
                'param4': [0, 1],
                'param5_lo': [0, 1, 2, 3, 4, 5]}

...

Note: I want to preserve key, value pairs.

Edit: Added subset_three to show the possibility of having mixed '_lo' and '_hi' intervals.

Body:
I think the best tool to use is itertools.product, one solution would be this:

intervals = {'param1': [0, 1],
             'param2_hi': [4, 5, 6, 7, 8, 9],
             'param2_lo': [0, 1, 2, 3, 4, 5],
             'param3_hi': [9, 10, 11, 12, 13, 14, 15],
             'param3_lo': [5, 6, 7, 8, 9, 10],
             'param4': [0, 1],
             'param5_hi': [4, 5, 6, 7, 8, 9],
             'param5_lo': [0, 1, 2, 3, 4, 5]}

import itertools

def get_subsets(intervals):

   params_list = set(key.split('_')[0] for key in intervals.keys())

   list_keys = [[x for x in intervals.keys() if x.startswith(param)] for param in params_list]

   subsets = [{x : intervals[x] for x in sublist} for sublist in itertools.product(*list_keys)]

   return subsets

get_subsets(intervals)

# [{'param2_lo': [0, 1, 2, 3, 4, 5], 'param3_hi': [9, 10, 11, 12, 13, 14, 15], 'param5_lo': [0, 1, 2, 3, 4, 5], 'param1': [0, 1], 'param4': [0, 1]}, {'param2_lo': [0, 1, 2, 3, 4, 5], 'param3_hi': [9, 10, 11, 12, 13, 14, 15], 'param1': [0, 1], 'param4': [0, 1], 'param5_hi': [4, 5, 6, 7, 8, 9]}, ...


问:
Will avoid drawing half pixel in HTML5 canvas improve speed?
I am drawing a sprite (of a ball) on a canvas element. As the ball moves however, the x or y position of the ball may become a fraction, eg. (20.153; 63.638). When canvas is used to draw this image, it attempts to use transparent pixels to make the ball appear in it's position more accurately.

I was wondering whether I should use Math.round() before drawing the ball to avoid the transparent pixel stuff, and possibly speeding up the game a lot. Will this help much? The game is a sorta complex pong game.

The image below should help with my explanation:

答:
At least this guy seems to believe so. As Gabe mentioned, it depends on the implementation.

Note that some sort anti-aliasing seems to kick in if you are using regular coords (1, 14, etc.). For this reason some guides (Dive Into HTML5 mainly) seem to suggest that you are better off by rending using half pixels (ie. 1.5, 14.5, etc.). I don't know if this makes any difference to performance, though. It's noticeable on render result at least.

You might also want to experiment with various layering schemes. See this question for more information. Depending on your situation you might want to treat your objects as separate canvases even and just offset them on top of the background.

Alternatively you could try to render it all on one canvas. In this case you have some extra stuff to keep track of. This library seems to handle all the bookkeeping for you.


问:
How to check conditions without multiple if statements?
I am working on a game for android in Xamarin, but I have two specific sections that are extremly DRY (don't repeat yourself).

The first section is when I want to change the soundtrack(audioplay) or background, where I have three different pitches for the same soundtrack based on level, and the same for background where the background canvas alternates.

For these methods the condition is based on an integer level that equals the level the player is in.

Example code

```<code>private void SetBackgrounds()
{
    if (level == 5)
    {
        gameAreaCanvas.SetBackgroundResource(Resource.Drawable.LevelUpOneBackground);

    }
    else if (level == 10)
    {
        gameAreaCanvas.SetBackgroundResource(Resource.Drawable.LevelUpTwoBackground);

    }
    else if (level == 15)
    {
        gameAreaCanvas.SetBackgroundResource(Resource.Drawable.LevelUpThreeBackground);

    }
}
</code>```

The same goes for different parts of the code where alot is based on an integer value which is the level. Every time the player advances the level integer increments by one, and then the activity has methods that checks what the integer level is. The code is working but is very inefficient obviously, because there is a lot of duplicated code with a small tweak.

For instance a level looks like this.

```<code>        if(level == 1) {

            levelDisplay.Text = "LEVEL 1";
            timer = new Timer();
            timer.Interval = 2000; /// DIFFERENT
            timer.Enabled = true;
            timer.Elapsed += Level1; /// DIFFERENT
            timer.Start();
        }
        ///LEVEL 2
        if (level == 2)
        {
            levelDisplay.Text = "LEVEL 2";
            timer = new Timer();
            timer.Interval = 2000; /// DIFFERENT
            timer.Enabled = true;
            timer.Elapsed += Level2; /// DIFFERENT
            timer.Start();
        }
</code>```

Is there a way to make this code less DRY? Input is appreciated.

答:
Are you looking for a dictionary?

```<code>//TODO: please, check dictionary's value type
private static Dictionary<int, Resource.Drawable> s_Backgrounds =
  new Dictionary<int, Resource.Drawable>() {
    {5, Resource.Drawable.LevelUpOneBackground},
    {10, Resource.Drawable.LevelUpTwoBackground},
    {15, Resource.Drawable.LevelUpThreeBackground},
};

...

private void SetBackgrounds() {
  gameAreaCanvas.SetBackgroundResource(s_Backgrounds[level]);
}
</code>```

Edit: same idea with level; the only difference is that you have three values that correspond to each key. The simplest solution is to organize these values into a Tuple (a custom class will be a better choice, however):

```<code>// I've used Tuple<string, int, int> to store three values
// you may want to change it to a custom class
private static Dictionary<int, Tuple<string, int, int>> s_Levels =
  new Dictionary<int, Tuple<string, int, int>>() {
    {1, new Tuple<string, int, int>("LEVEL 1", 2000, Level1)},
    {2, new Tuple<string, int, int>("LEVEL 2", 2000, Level2)},
};

...

levelDisplay.Text = s_Levels[level].Item1;
timer = new Timer();
timer.Interval = s_Levels[level].Item2; /// DIFFERENT
timer.Enabled = true;
timer.Elapsed += s_Levels[level].Item3; /// DIFFERENT
imer.Start();
</code>```

Body:
I am working on a game for android in Xamarin, but I have two specific sections that are extremly DRY (don't repeat yourself).

The first section is when I want to change the soundtrack(audioplay) or background, where I have three different pitches for the same soundtrack based on level, and the same for background where the background canvas alternates.

For these methods the condition is based on an integer level that equals the level the player is in.

Example code

private void SetBackgrounds()
{
    if (level == 5)
    {
        gameAreaCanvas.SetBackgroundResource(Resource.Drawable.LevelUpOneBackground);

    }
    else if (level == 10)
    {
        gameAreaCanvas.SetBackgroundResource(Resource.Drawable.LevelUpTwoBackground);

    }
    else if (level == 15)
    {
        gameAreaCanvas.SetBackgroundResource(Resource.Drawable.LevelUpThreeBackground);

    }
}

The same goes for different parts of the code where alot is based on an integer value which is the level. Every time the player advances the level integer increments by one, and then the activity has methods that checks what the integer level is. The code is working but is very inefficient obviously, because there is a lot of duplicated code with a small tweak.

For instance a level looks like this.

        if(level == 1) {

            levelDisplay.Text = "LEVEL 1";
            timer = new Timer();
            timer.Interval = 2000; /// DIFFERENT
            timer.Enabled = true;
            timer.Elapsed += Level1; /// DIFFERENT
            timer.Start();
        }
        ///LEVEL 2
        if (level == 2)
        {
            levelDisplay.Text = "LEVEL 2";
            timer = new Timer();
            timer.Interval = 2000; /// DIFFERENT
            timer.Enabled = true;
            timer.Elapsed += Level2; /// DIFFERENT
            timer.Start();
        }

Is there a way to make this code less DRY? Input is appreciated.

Body:
Are you looking for a dictionary?

//TODO: please, check dictionary's value type
private static Dictionary<int, Resource.Drawable> s_Backgrounds =
  new Dictionary<int, Resource.Drawable>() {
    {5, Resource.Drawable.LevelUpOneBackground},
    {10, Resource.Drawable.LevelUpTwoBackground},
    {15, Resource.Drawable.LevelUpThreeBackground},
};

...

private void SetBackgrounds() {
  gameAreaCanvas.SetBackgroundResource(s_Backgrounds[level]);
}

Edit: same idea with level; the only difference is that you have three values that correspond to each key. The simplest solution is to organize these values into a Tuple (a custom class will be a better choice, however):

// I've used Tuple<string, int, int> to store three values
// you may want to change it to a custom class
private static Dictionary<int, Tuple<string, int, int>> s_Levels =
  new Dictionary<int, Tuple<string, int, int>>() {
    {1, new Tuple<string, int, int>("LEVEL 1", 2000, Level1)},
    {2, new Tuple<string, int, int>("LEVEL 2", 2000, Level2)},
};

...

levelDisplay.Text = s_Levels[level].Item1;
timer = new Timer();
timer.Interval = s_Levels[level].Item2; /// DIFFERENT
timer.Enabled = true;
timer.Elapsed += s_Levels[level].Item3; /// DIFFERENT
imer.Start();


问:
I can't put String on the first position of a string array
Please I have a proble, this is my code so far

```<code>    System.out.println("Please give alue for the table");
    int value = scanner.nextInt();

    String[] StringArray = new String[value];

    for (int i=0; i<value; i++)
    {
        System.out.println("Please insert string for the position:"+(i+1));
        StringArray[i] = scanner.nextLine();
    }
}
</code>```

And my output is that

```<code>Please give alue for the table
3
Please insert string for the position:1
Please insert string for the position:2
</code>```

Why i can't insert String to the position 1 and my program goes me in position 2 and after??
Please I need help, I can't unsterstand.
Thanks for your time.

答:
Because reading an int does not consume the entire buffer, which still has an \n left. As per the documentation, nextLine reads until \n, so the first time you'll just get an empty string.

You can easily solve this by adding scanner.nextLine() right after the nextInt():

```<code>System.out.println("Please give alue for the table");
int value = scanner.nextInt();

scanner.nextLine(); // get rid of everything else left in the buffer

String[] StringArray = new String[value];

for (int i=0; i<value; i++)
{
    System.out.println("Please insert string for the position:"+(i+1));
    StringArray[i] = scanner.nextLine();
}
</code>```

Body:
Please I have a proble, this is my code so far

    System.out.println("Please give alue for the table");
    int value = scanner.nextInt();

    String[] StringArray = new String[value];

    for (int i=0; i<value; i++)
    {
        System.out.println("Please insert string for the position:"+(i+1));
        StringArray[i] = scanner.nextLine();
    }
}

And my output is that

Please give alue for the table
3
Please insert string for the position:1
Please insert string for the position:2

Why i can't insert String to the position 1 and my program goes me in position 2 and after??
Please I need help, I can't unsterstand.
Thanks for your time.

Body:
Because reading an int does not consume the entire buffer, which still has an \n left. As per the documentation, nextLine reads until \n, so the first time you'll just get an empty string.

You can easily solve this by adding scanner.nextLine() right after the nextInt():

System.out.println("Please give alue for the table");
int value = scanner.nextInt();

scanner.nextLine(); // get rid of everything else left in the buffer

String[] StringArray = new String[value];

for (int i=0; i<value; i++)
{
    System.out.println("Please insert string for the position:"+(i+1));
    StringArray[i] = scanner.nextLine();
}


问:
Why is System.out.println so slow?
Is this something common to all programming languages? Doing multiple print followed by a println seems faster  but moving everything to a string and just printing that seems fastest. Why?

EDIT: For example, Java can find all the prime numbers up to 1 million in less than a second - but printing then all out each on their own println can take minutes! Up to a 10 billion can hours to print!

EX:

```<code>package sieveoferatosthenes;
public class Main {
    public static void main(String[] args) {
        int upTo = 10000000;
        boolean primes[] = new boolean[upTo];
        for( int b = 0; b < upTo; b++ ){
            primes[b] = true;
        }
        primes[0] = false;
        primes[1] = false;

        int testing = 1;

        while( testing <= Math.sqrt(upTo)){
            testing ++;
            int testingWith = testing;
            if( primes[testing] ){
                while( testingWith < upTo ){
                    testingWith = testingWith + testing;
                    if ( testingWith >= upTo){
                    }
                    else{
                        primes[testingWith] = false;
                    }

                }
            }
        }
        for( int b = 2; b < upTo; b++){
            if( primes[b] ){
                System.out.println( b );
            }
        }
    }
}
</code>```

答:
I believe this is because of buffering. A quote from the article:

Another aspect of buffering concerns
  text output to a terminal window. By
  default, System.out (a PrintStream) is
  line buffered, meaning that the output
  buffer is flushed when a newline
  character is encountered. This is
  important for interactivity, where
  you'd like to have an input prompt
  displayed before actually entering any
  input.

A quote explaining buffers from wikipedia:

In computer science, a buffer is a
  region of memory used to temporarily
  hold data while it is being moved from
  one place to another. Typically, the
  data is stored in a buffer as it is
  retrieved from an input device (such
  as a Mouse) or just before it is sent
  to an output device (such as Speakers)

```<code>public void println()
</code>```

Terminate the current line by writing
  the line separator string. The line
  separator string is defined by the
  system property line.separator, and is
  not necessarily a single newline
  character ('\n').

So the buffer get's flushed when you do println which means new memory has to be allocated etc which makes printing slower. The other methods you specified require lesser flushing of buffers thus are faster.

Title: Why is System.out.println so slow?

Body:
Is this something common to all programming languages? Doing multiple print followed by a println seems faster  but moving everything to a string and just printing that seems fastest. Why?

EDIT: For example, Java can find all the prime numbers up to 1 million in less than a second - but printing then all out each on their own println can take minutes! Up to a 10 billion can hours to print!

EX:

package sieveoferatosthenes;
public class Main {
    public static void main(String[] args) {
        int upTo = 10000000;
        boolean primes[] = new boolean[upTo];
        for( int b = 0; b < upTo; b++ ){
            primes[b] = true;
        }
        primes[0] = false;
        primes[1] = false;

        int testing = 1;

        while( testing <= Math.sqrt(upTo)){
            testing ++;
            int testingWith = testing;
            if( primes[testing] ){
                while( testingWith < upTo ){
                    testingWith = testingWith + testing;
                    if ( testingWith >= upTo){
                    }
                    else{
                        primes[testingWith] = false;
                    }

                }
            }
        }
        for( int b = 2; b < upTo; b++){
            if( primes[b] ){
                System.out.println( b );
            }
        }
    }
}

Body:
I believe this is because of buffering. A quote from the article:

Another aspect of buffering concerns
  text output to a terminal window. By
  default, System.out (a PrintStream) is
  line buffered, meaning that the output
  buffer is flushed when a newline
  character is encountered. This is
  important for interactivity, where
  you'd like to have an input prompt
  displayed before actually entering any
  input.

A quote explaining buffers from wikipedia:

In computer science, a buffer is a
  region of memory used to temporarily
  hold data while it is being moved from
  one place to another. Typically, the
  data is stored in a buffer as it is
  retrieved from an input device (such
  as a Mouse) or just before it is sent
  to an output device (such as Speakers)

public void println()

Terminate the current line by writing
  the line separator string. The line
  separator string is defined by the
  system property line.separator, and is
  not necessarily a single newline
  character ('\n').

So the buffer get's flushed when you do println which means new memory has to be allocated etc which makes printing slower. The other methods you specified require lesser flushing of buffers thus are faster.


问:
NSUserDefaults - How to tell if a key exists
I'm working on a small iPhone app, and I am using NSUserDefaults as my data persistence.  It only has to keep track of a few things, such as some names and some numbers so I figure I might as well keep it simple.

I found this page for some reference, but I don't think it can answer my question.  Basically, I want to be able to check if a value (or a key) already exists in the NSUserDefaults and then do something accordingly.

Some examples: The app starts up, if this is the first time it starts up it outputs an alert saying welcome.  To tell if this is first time it has opened it reads the UserDefaults and checks.

Example 2:  It says, "Hello [Name]", where Name is something you have entered.  If you have opened the app and there is no name, it should say "Hello World."  I need to check if you have entered a name already and act accordingly.  The name would be stored in NSUserDefaults.

Some help here?  I'd really appreciate it!

答:
Extend UserDefaults once to don't copy-paste this solution:

```<code>extension UserDefaults {

    func hasValue(forKey key: String) -> Bool {
        return nil != object(forKey: key)
    }
}

// Example
UserDefaults.standard.hasValue(forKey: "username")
</code>```

Body:
Extend UserDefaults once to don't copy-paste this solution:

extension UserDefaults {

    func hasValue(forKey key: String) -> Bool {
        return nil != object(forKey: key)
    }
}

// Example
UserDefaults.standard.hasValue(forKey: "username")


问:
Laravel default orderBy
Is there a clean way to enable certain models to be ordered by a property by default?
It could work by extending the laravel's QueryBuilder, but to do so, you'll have to rewire some of it's core features - bad practice.

reason

The main point of doing this is - one of my models get's heavily reused by many others and right now you have to resort the order over and over again. Even when using a closure for this - you still have to call it. It would be much better to be able to apply a default sorting, so everyone who uses this model, and does not provide custom sorting options, will receive records sorted by the default option. Using a repository is not an option here, because it get's eager loaded.

SOLUTION

Extending the base model:

```<code>protected $orderBy;
protected $orderDirection = 'ASC';

public function scopeOrdered($query)
{
    if ($this->orderBy)
    {
        return $query->orderBy($this->orderBy, $this->orderDirection);
    }

    return $query;
}

public function scopeGetOrdered($query)
{
    return $this->scopeOrdered($query)->get();
}
</code>```

In your model:

```<code>protected $orderBy = 'property';
protected $orderDirection = 'DESC';

// ordering eager loaded relation
public function anotherModel()
{
    return $this->belongsToMany('SomeModel', 'some_table')->ordered();
}
</code>```

In your controller:

```<code>MyModel::with('anotherModel')->getOrdered();
// or
MyModel::with('anotherModel')->ordered()->first();
</code>```

答:
An slightly improved answer given by Joshua Jabbour

you can use the code he offered in a Trait, and then add that trait to the models where you want them to be ordered.

```<code><?php

namespace App\Traits;

trait AppOrdered {
    protected $orderBy = 'created_at';
    protected $orderDirection = 'desc';

    public function newQuery($ordered = true)
    {
        $query = parent::newQuery();

        if (empty($ordered)) {
            return $query;
        }

        return $query->orderBy($this->orderBy, $this->orderDirection);
    }
}
</code>```

then in whichever model you want the data to be ordered you can use use :

```<code>class PostsModel extends Model {

    use AppOrdered;
    ....
</code>```

now everytime you request that model, data will be ordered, that's somehow more organized, but my answers is Jabbour's answer.

Title: Laravel default orderBy

Body:
Is there a clean way to enable certain models to be ordered by a property by default?
It could work by extending the laravel's QueryBuilder, but to do so, you'll have to rewire some of it's core features - bad practice.

reason

The main point of doing this is - one of my models get's heavily reused by many others and right now you have to resort the order over and over again. Even when using a closure for this - you still have to call it. It would be much better to be able to apply a default sorting, so everyone who uses this model, and does not provide custom sorting options, will receive records sorted by the default option. Using a repository is not an option here, because it get's eager loaded.

SOLUTION

Extending the base model:

protected $orderBy;
protected $orderDirection = 'ASC';

public function scopeOrdered($query)
{
    if ($this->orderBy)
    {
        return $query->orderBy($this->orderBy, $this->orderDirection);
    }

    return $query;
}

public function scopeGetOrdered($query)
{
    return $this->scopeOrdered($query)->get();
}

In your model:

protected $orderBy = 'property';
protected $orderDirection = 'DESC';

// ordering eager loaded relation
public function anotherModel()
{
    return $this->belongsToMany('SomeModel', 'some_table')->ordered();
}

In your controller:

MyModel::with('anotherModel')->getOrdered();
// or
MyModel::with('anotherModel')->ordered()->first();

Body:
An slightly improved answer given by Joshua Jabbour

you can use the code he offered in a Trait, and then add that trait to the models where you want them to be ordered.

<?php

namespace App\Traits;

trait AppOrdered {
    protected $orderBy = 'created_at';
    protected $orderDirection = 'desc';

    public function newQuery($ordered = true)
    {
        $query = parent::newQuery();

        if (empty($ordered)) {
            return $query;
        }

        return $query->orderBy($this->orderBy, $this->orderDirection);
    }
}

then in whichever model you want the data to be ordered you can use use :

class PostsModel extends Model {

    use AppOrdered;
    ....

now everytime you request that model, data will be ordered, that's somehow more organized, but my answers is Jabbour's answer.

ContentLicense: CC BY-SA 4.0


问:
How to keep the JMS Headers coming from Upstream applications?
I am using Spring integration JMS Outbound adapter to send message to IBM MQ and I found that some of JMS headers coming from the upstream application is missed out or defaulted. The upstream application is sending the below JMS headers,

JMSType:

JMSDeliveryMode:

JMSExpiration:

JMSPriority:

JMSMessageID:

JMSTimestamp:

JMSCorrelationID:
JMSDestination:

JMSReplyTo:

JMSRedelivered:

After going through Spring's DefaultJmsHeaderMapper conversion, the below Headers are defaulted/missed.

JMSPriority:

JMSDeliveryMode:

JMSExpiration:

JMSRedelivered:

JMSReplyTo:

I enabled explicit-qos flag in JMS Outbound adapter and I do see Priority. But Still have issues with other Headers.

答:
This is simplified version what is mapped by the DefaultJmsHeaderMapper on the inbound part:

```<code>public Map<String, Object> toHeaders(javax.jms.Message jmsMessage) {
    Map<String, Object> headers = new HashMap<String, Object>();
        headers.put(JmsHeaders.MESSAGE_ID, messageId);
        headers.put(JmsHeaders.DESTINATION, destination);
        headers.put(JmsHeaders.CORRELATION_ID, correlationId);
        headers.put(JmsHeaders.REPLY_TO, replyTo);
        headers.put(JmsHeaders.REDELIVERED, jmsMessage.getJMSRedelivered());
        headers.put(JmsHeaders.TYPE, type);
        headers.put(JmsHeaders.TIMESTAMP, jmsMessage.getJMSTimestamp());
        if (this.mapInboundPriority) {
            headers.put(IntegrationMessageHeaderAccessor.PRIORITY, jmsMessage.getJMSPriority());
        }
        Enumeration<?> jmsPropertyNames = jmsMessage.getPropertyNames();
            while (jmsPropertyNames.hasMoreElements()) {
                String propertyName = jmsPropertyNames.nextElement().toString();
                String headerName = this.toHeaderName(propertyName);
                    headers.put(headerName, jmsMessage.getObjectProperty(propertyName));
                }
            }
        }
    return headers;
}
</code>```

Would you mind to share logs how does the message look after on sending to the message channel for the JmsMessageDrivenEndpoint?

OTOH you always can extend/override the default and provide your own JmsHeaderMapper implementation.

Body:
This is simplified version what is mapped by the DefaultJmsHeaderMapper on the inbound part:

public Map<String, Object> toHeaders(javax.jms.Message jmsMessage) {
    Map<String, Object> headers = new HashMap<String, Object>();
        headers.put(JmsHeaders.MESSAGE_ID, messageId);
        headers.put(JmsHeaders.DESTINATION, destination);
        headers.put(JmsHeaders.CORRELATION_ID, correlationId);
        headers.put(JmsHeaders.REPLY_TO, replyTo);
        headers.put(JmsHeaders.REDELIVERED, jmsMessage.getJMSRedelivered());
        headers.put(JmsHeaders.TYPE, type);
        headers.put(JmsHeaders.TIMESTAMP, jmsMessage.getJMSTimestamp());
        if (this.mapInboundPriority) {
            headers.put(IntegrationMessageHeaderAccessor.PRIORITY, jmsMessage.getJMSPriority());
        }
        Enumeration<?> jmsPropertyNames = jmsMessage.getPropertyNames();
            while (jmsPropertyNames.hasMoreElements()) {
                String propertyName = jmsPropertyNames.nextElement().toString();
                String headerName = this.toHeaderName(propertyName);
                    headers.put(headerName, jmsMessage.getObjectProperty(propertyName));
                }
            }
        }
    return headers;
}

Would you mind to share logs how does the message look after on sending to the message channel for the JmsMessageDrivenEndpoint?

OTOH you always can extend/override the default and provide your own JmsHeaderMapper implementation.


问:
Express.js: res.render() does not send data when wrapped in promise chain
I recently started refactoring older callback-hell routes to use promises. (Note: the refactor is not complete so some of the following code is ugly)

Doing so broke my res.render() function.

I am using EJS for my render engine.

Most of my promise chains are built off of MongoDB / Mongoose queries.

The basic app structure is a complex survey / quiz that sorts users into different categories. It stores their info and renders a custom EJS page at the end. Here's how the final call works, basically:

```<code>         mongoose.model('Result')
             .findOne({quizId: req.query.id})
             .then(getPageData)
             .then(renderPage)
             .catch(errorHandler)
</code>```

Simple enough, in theory.

Relevant functions:

```<code>    let getPageData = (mongooseResult) => {

      let resultsPage;
      let analyticsData;

      if (mongooseResult.answers.section1.question1.answer != null && mongooseResult.answers.section1.question1.answer != undefined){
          let resultsPage = WP.getPage(wp_pages_data, 'slug', mongooseResult.coreFit);
          let analyticsData = {
            quizId: mongooseResult.quizId,
            coreFit: mongooseResult.coreFit,
            secondFit: mongooseResult.secondFit,
            degree: mongooseResult.answers.section1.question1.answer,
            year: mongooseResult.answers.section1.question2.answer,
            concentration: mongooseResult.answers.section1.question3.answer,
            views: mongooseResult.views,
          }

        mongooseResult.views++;
        mongooseResult.save();

        return [resultsPage, analyticsData, mongooseResult];
      } else {
        throw new Error('S1Q1 IS UNDEFINED');
      }
    };
    let renderPage = ([resultsPage, analyticsData, mongooseResult]) => {
      if (resultsPage != null && resultsPage != undefined){

        // WHY IS MY RENDER NOT WORKING???
        res.render('templates/' + mongooseResult.coreFit,  Object.assign({}, WP.get_WP_data(resultsPage), getPartials(mongooseResult.modules), analyticsData), (err, html) => {if (err) console.log(err); else res.send(html);});
      } else {
        throw new Error('GETTING PAGE DATA RETURNED UNDEFINED');
      }
    };
</code>```

Incoming requests are first routed to a /submit POST route - which manipulates some data, stores it all in the DB, then does res.redirect() to the /results?id=12345 GET route, which runs the logic above.

What's funky is that the render() actually fires; the callback ( (err, html) => {if (err) console.log(err); else res.send(html);} ) sends rendered HTML to IF YOU HIT THE ROUTE A SECOND TIME.

Completing the survey does NOT generate a response; but it DOES successfully store all our info in the DB and console.logs the ID to which the client request should redirect. Hitting the GET route with this generated ID / URL, literally by copy-pasting it, renders just fine.

Swapping the render for a simple res.send('wtf') works - an actual response is sent to the client. (in this case the string 'wtf' ... )

The response just doesn't send back data. I don't get it. Any ideas?

UPDATE:
Strangely enough, hitting the route manually vs the redirect from my earlier POST request produce different results with a simple res.send('wtf mate').

Hitting the GET route and passing in a previously existing ID to the req.query manually:

Hitting the GET route AFTER the res.redirect() call from the prior POST request:

This might be more an Express request type mismatch issue? Why would a res.redirect('/results?id=someString') call mutate the URL vs sending back a string / HTML?

答:
Based on your update, it sounds like your res.send() call is being interpreted strangely on the client side. POST request should not affect the URL bar unless you've specifically told it to - have you checked where the client initially sends this request?

My guess - since you say that the routing code you posted above is being hit from res.redirect() on a prior POST route - is that there is client-side logic expecting a response object to be a URL string, and hitting the GET route for the first time via your redirect carries over this response object. So that the client is attempting to insert a massive string of HTML into the URL bar.

In this case, hitting the GET route manually, like you said, would simply render the HTML from res.render() by default - but your initial hit from the res.redirect() might not.

Body:
I recently started refactoring older callback-hell routes to use promises. (Note: the refactor is not complete so some of the following code is ugly)

Doing so broke my res.render() function.

I am using EJS for my render engine.

Most of my promise chains are built off of MongoDB / Mongoose queries.

The basic app structure is a complex survey / quiz that sorts users into different categories. It stores their info and renders a custom EJS page at the end. Here's how the final call works, basically:

         mongoose.model('Result')
             .findOne({quizId: req.query.id})
             .then(getPageData)
             .then(renderPage)
             .catch(errorHandler)

Simple enough, in theory.

Relevant functions:

    let getPageData = (mongooseResult) => {

      let resultsPage;
      let analyticsData;

      if (mongooseResult.answers.section1.question1.answer != null && mongooseResult.answers.section1.question1.answer != undefined){
          let resultsPage = WP.getPage(wp_pages_data, 'slug', mongooseResult.coreFit);
          let analyticsData = {
            quizId: mongooseResult.quizId,
            coreFit: mongooseResult.coreFit,
            secondFit: mongooseResult.secondFit,
            degree: mongooseResult.answers.section1.question1.answer,
            year: mongooseResult.answers.section1.question2.answer,
            concentration: mongooseResult.answers.section1.question3.answer,
            views: mongooseResult.views,
          }

        mongooseResult.views++;
        mongooseResult.save();

        return [resultsPage, analyticsData, mongooseResult];
      } else {
        throw new Error('S1Q1 IS UNDEFINED');
      }
    };
    let renderPage = ([resultsPage, analyticsData, mongooseResult]) => {
      if (resultsPage != null && resultsPage != undefined){

        // WHY IS MY RENDER NOT WORKING???
        res.render('templates/' + mongooseResult.coreFit,  Object.assign({}, WP.get_WP_data(resultsPage), getPartials(mongooseResult.modules), analyticsData), (err, html) => {if (err) console.log(err); else res.send(html);});
      } else {
        throw new Error('GETTING PAGE DATA RETURNED UNDEFINED');
      }
    };

Incoming requests are first routed to a /submit POST route - which manipulates some data, stores it all in the DB, then does res.redirect() to the /results?id=12345 GET route, which runs the logic above.

What's funky is that the render() actually fires; the callback ( (err, html) => {if (err) console.log(err); else res.send(html);} ) sends rendered HTML to IF YOU HIT THE ROUTE A SECOND TIME.

Completing the survey does NOT generate a response; but it DOES successfully store all our info in the DB and console.logs the ID to which the client request should redirect. Hitting the GET route with this generated ID / URL, literally by copy-pasting it, renders just fine.

Swapping the render for a simple res.send('wtf') works - an actual response is sent to the client. (in this case the string 'wtf' ... )

The response just doesn't send back data. I don't get it. Any ideas?

UPDATE:
Strangely enough, hitting the route manually vs the redirect from my earlier POST request produce different results with a simple res.send('wtf mate').

Hitting the GET route and passing in a previously existing ID to the req.query manually:

Hitting the GET route AFTER the res.redirect() call from the prior POST request:

This might be more an Express request type mismatch issue? Why would a res.redirect('/results?id=someString') call mutate the URL vs sending back a string / HTML?


问:
Inserting sumif into all the cells of a column
I would like to insert IF(A2<>"Sub-task",SUMIF(D:D,D2,I:I),"  ") in Cell J2 using vba.  I then want to copy this formula down to every row in column J until the last row of data in Column D</p>

答:
The following should work.  It assigns the formula you requested to all cells in column J, starting from row 2 and ending at the row containing the last used cell in column D.</p>

```<code>Sub Test
    With ActiveSheet
        .Range("J2:J" & .Cells(.Rows.Count, "D").End(xlUp).Row).Formula = _
              "=IF(A2<>""Sub-task"",SUMIF(D:D,D2,I:I),"" "")"
    End With
End Sub
</code>```

Body:
The following should work.  It assigns the formula you requested to all cells in column J, starting from row 2 and ending at the row containing the last used cell in column D.

Sub Test
    With ActiveSheet
        .Range("J2:J" & .Cells(.Rows.Count, "D").End(xlUp).Row).Formula = _
              "=IF(A2<>""Sub-task"",SUMIF(D:D,D2,I:I),"" "")"
    End With
End Sub


问:
Cant get SQL results to write to file Java
The title says it all. This is my ResultSet code:

```<code>try {
    while (rs.next()) {
        int ID  = rs.getInt("ID");
        String Name = rs.getString("Name");
        String CountryCode = rs.getString("CountryCode");
        String District = rs.getString("District");
        int Population = rs.getInt("Population");

        //Display values
        try {
            writeToFile(ID, Name, CountryCode, District, Population);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
</code>```

This is my writeToFile method:

```<code>public void writeToFile(int id, String name, String countryCode, String district, int population) throws IOException {
    FileWriter fw = new FileWriter("C:\\Users\\horry\\Desktop\\results.txt");
    fw.write(id + " " + name + " " + countryCode + " " + district + " " + population + "\n");
    try {
        fw.flush();
        fw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code>```

Ive tried the usual flush and close method but something is missing. Should the filewriter be declared elsewgere?

答:
You are opening a new FileWriter for each iteration of your ResultSet. By default a FileWriter writes at the beginning of the file. So you are continously overwritting what you have written in the file at the previous iteration.

Furthermore, I would advice to not create a new FileWriter at each iteration. I would open a FileWriter just one time and use the same one for all the ietrations.

Then, use a BufferedWriter instead of a pure FileWriter. It will be much faster.

Also, close the writer in a finally block, not within the try. Since Java 7, you can even use try-with-resources.

Finally, use br.newLine(); to write a new line instead of managing the "\n" yourself.

Please check the code below

```<code>File f = new File("C:\\Users\\horry\\Desktop\\results.txt");
try (BufferedWriter bw = new BufferedWriter(new FileWriter(f))) {
    while (rs.next()) {
        int id  = rs.getInt("ID");
        String name = rs.getString("Name");
        String countryCode = rs.getString("CountryCode");
        String district = rs.getString("District");
        int population = rs.getInt("Population");
        bw.write(id + " " + name + " " + countryCode + " " + district + " " + population);
        bw.newLine();
    }
}
</code>```

Body:
The title says it all. This is my ResultSet code:

try {
    while (rs.next()) {
        int ID  = rs.getInt("ID");
        String Name = rs.getString("Name");
        String CountryCode = rs.getString("CountryCode");
        String District = rs.getString("District");
        int Population = rs.getInt("Population");

        //Display values
        try {
            writeToFile(ID, Name, CountryCode, District, Population);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

This is my writeToFile method:

public void writeToFile(int id, String name, String countryCode, String district, int population) throws IOException {
    FileWriter fw = new FileWriter("C:\\Users\\horry\\Desktop\\results.txt");
    fw.write(id + " " + name + " " + countryCode + " " + district + " " + population + "\n");
    try {
        fw.flush();
        fw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Ive tried the usual flush and close method but something is missing. Should the filewriter be declared elsewgere?

Body:
You are opening a new FileWriter for each iteration of your ResultSet. By default a FileWriter writes at the beginning of the file. So you are continously overwritting what you have written in the file at the previous iteration.

Furthermore, I would advice to not create a new FileWriter at each iteration. I would open a FileWriter just one time and use the same one for all the ietrations.

Then, use a BufferedWriter instead of a pure FileWriter. It will be much faster.

Also, close the writer in a finally block, not within the try. Since Java 7, you can even use try-with-resources.

Finally, use br.newLine(); to write a new line instead of managing the "\n" yourself.

Please check the code below

File f = new File("C:\\Users\\horry\\Desktop\\results.txt");
try (BufferedWriter bw = new BufferedWriter(new FileWriter(f))) {
    while (rs.next()) {
        int id  = rs.getInt("ID");
        String name = rs.getString("Name");
        String countryCode = rs.getString("CountryCode");
        String district = rs.getString("District");
        int population = rs.getInt("Population");
        bw.write(id + " " + name + " " + countryCode + " " + district + " " + population);
        bw.newLine();
    }
}


问:
How to change the Region in identity pool ID?
I am working on a mobile app. In which i am using amazon s3 service. For that i make an Identity pool. But when it created it automatically set the region in identity pool id to US-EAST-2. Now the problem is when i use this code

```<code>CognitoCachingCredentialsProvider credentialsProvider = new
       CognitoCachingCredentialsProvider(
           getApplicationContext(),
           "us-east-2:*******", // Identity Pool ID
           Regions.US_EAST_2 // Region
);
</code>```

On line number 5 code Region.US-East-2 give error that it cannot resolved symbol US-East-2.
Please help me here.
Or tell me can i make an identity pool with the region i selected.

答:
Problem Solved:

Actually i was using an old version of amazon mobile sdk and US-East-2 is not included in it. When i use the latest version of amazon mobile sdk the problem solved.

Body:
I am working on a mobile app. In which i am using amazon s3 service. For that i make an Identity pool. But when it created it automatically set the region in identity pool id to US-EAST-2. Now the problem is when i use this code

CognitoCachingCredentialsProvider credentialsProvider = new
       CognitoCachingCredentialsProvider(
           getApplicationContext(),
           "us-east-2:*******", // Identity Pool ID
           Regions.US_EAST_2 // Region
);

On line number 5 code Region.US-East-2 give error that it cannot resolved symbol US-East-2.
Please help me here.
Or tell me can i make an identity pool with the region i selected.


问:
Problems with installing matplotlib in python 3.6
I'm trying to teach myself python, and I feel out of my depth.  To start, I am working on a mac which already comes with python 2.7 installed.

I installed python 3.6 recently and have been using it to teach myself the basics.  I'd like to eventually learn how to produce mathematical plots in python, and I know I will need the matplotlib package to do that.

Following some advice online, I was told that python3 already comes with pip installed, which is what I thought I should use to install matplotlib.  The advice said I should type the following into the mac terminal:

python3.6 -m pip install matplotlib

I typed this, and it seemed like the package was installing, but I ended up getting some sort of error code that said:

Command "python setup.py egg_info" failed with error code 1 in [folder].

I tried opening IDLE and typing "import matplotlib", but I got the error: "no module named matplotlib".  I also tried typing "import matplotlib.pyplot as plt", but I got the same error.

Based on further research and this youtube video, I've decided to just install miniconda in order to have access to the matplotlib package.

The problem is, I'm not sure if I should somehow be uninstalling whatever was installed when I ran the code above to install matplotlib.  I've actually run that line of code 3 or 4 times.  Should I remove anything before installing miniconda?  Also, I am running python 3.6, while miniconda is listed on the website as being for python 3.5.  Does this mean it won't work for my version of python?

答: I ended up downloading anaconda and using the python interpreter that comes with it, as anaconda comes with matplotlib and many other python packages of interest.</p>


问:
Trying to use an image saved in firebase with IBM Watson Image Recon
Hello I am saving my images to firebase and want to use them with Watson Image Recognition but firebase only gives me a download link and that doesn't seem to work with the Watson Api. Is there a way to get this to work our would there be a better way for me save my images on the web. Thanks for the help </p>

答:
Get the Firebase URL via the yourRef.downloadUrl() method:

https://firebase.google.com/docs/storage/ios/download-files

Then you can use this URL in the Watson API call using their SDK

```<code>import VisualRecognitionV3

let apiKey = "your-apikey-here"
let version = "YYYY-MM-DD" // use today's date for the most recent version
let visualRecognition = VisualRecognition(apiKey: apiKey, version: version)

let url = "your-image-url"
let failure = { (error: Error) in print(error) }
visualRecognition.classify(image: url, failure: failure) { classifiedImages in
    print(classifiedImages)
}
</code>```

Reference: https://github.com/watson-developer-cloud/swift-sdk#visual-recognition

Reference: https://github.com/firebase/firebase-ios-sdk

Guide: https://firebase.google.com/docs/ios/setup

Body:
Get the Firebase URL via the yourRef.downloadUrl() method:

https://firebase.google.com/docs/storage/ios/download-files

Then you can use this URL in the Watson API call using their SDK

import VisualRecognitionV3

let apiKey = "your-apikey-here"
let version = "YYYY-MM-DD" // use today's date for the most recent version
let visualRecognition = VisualRecognition(apiKey: apiKey, version: version)

let url = "your-image-url"
let failure = { (error: Error) in print(error) }
visualRecognition.classify(image: url, failure: failure) { classifiedImages in
    print(classifiedImages)
}

Reference: https://github.com/watson-developer-cloud/swift-sdk#visual-recognition

Reference: https://github.com/firebase/firebase-ios-sdk

Guide: https://firebase.google.com/docs/ios/setup


问:
Avoiding binding in Render while maintaining context from Parent Component
I currently have (TableHeader component) table headers being rendered with onClick handlers which, when fired, capture the value of the header and set state in the Parent component (Parent is a Table component, child is TableHeader).

I want to avoid binding the onClick function within TableHeader's render method while still maintaining access to the Parent component's context. Currently what I have:

```<code>render() {
  return (
  ...
    <tr>
      {columns.map(col => <th key={col} onClick={this.props.onClick.bind(null, col)} {...hoverHandlers}>{col}</th>)}
    </tr>
  )
}
</code>```

The function being passed to each th is just taking the value of the column and sorting accordingly.

In the parent component's constructor, that function is bound:

```<code>this.sortColumns = this.sortColumns.bind(this);
</code>```

Then passed:

```<code><TableHeader onClick={this.sortColumns} />
</code>```

答:
Change sortColumns() to take the col variable as a parameter. And then update render() to pass the variable.

```<code>render() {
  return (
   ...
   <tr>
     {columns.map(col => <th key={col}
        onClick={function() { this.props.onClick(col) } }
        {...hoverHandlers}>{col}</th>)}
   </tr>
   )
}
</code>```

Body:
I currently have (TableHeader component) table headers being rendered with onClick handlers which, when fired, capture the value of the header and set state in the Parent component (Parent is a Table component, child is TableHeader).

I want to avoid binding the onClick function within TableHeader's render method while still maintaining access to the Parent component's context. Currently what I have:

render() {
  return (
  ...

      {columns.map(col => {col}	)}

  )
}

The function being passed to each th is just taking the value of the column and sorting accordingly.

In the parent component's constructor, that function is bound:

this.sortColumns = this.sortColumns.bind(this);

Then passed:

<TableHeader onClick={this.sortColumns} />

Body:
Change sortColumns() to take the col variable as a parameter. And then update render() to pass the variable.

render() {
  return (
   ...
   <tr>
     {columns.map(col => <th key={col}
        onClick={function() { this.props.onClick(col) } }
        {...hoverHandlers}>{col}</th>)}
   </tr>
   )
}


问:
create an array with values located in the array in a key
After running it appears to fail at test: "should return an array containing all the elements greater than 10 in the array located at key". I don't see why.

var obj = {
   key:[1,20,30]
};

function getElementsGreaterThan10AtProperty(obj, key) {

   var arr = [];
   for (var prop in obj) {
     for (var i = 0; i < obj[prop].length; i++) {
       if (obj[prop][i] > 10) {
         arr.push(obj[prop][i]);
       }
     }
   }
   return arr;
}

getElementsGreaterThan10AtProperty(obj,'key')

 ```

答:
You are not using the key parameter passed to the function at all, and your for (var prop in obj) iteration is unnecessary, as now you are returning an array of all elements over 10 in all properties of obj, not just the one specified by key. You need to remove that loop and use key instead of prop:

function getElementsGreaterThan10AtProperty(obj, key) {
  var arr = [];
  for (var i = 0; i < obj[key].length; i++) {
    if (obj[key][i] > 10) {
      arr.push(obj[key][i]);
    }
  }
  return arr;
}
```


问:
IApplicationBuilder does not contain UseStaticFiles()
I tried different versions of StaticFiles.But it shows error because IApplicationBuilder does not contain UseStaticFiles().

```<code>"Microsoft.AspNetCore.StaticFiles": "1.1.1"
</code>```

I am using the exact code provided in the .net documentation by Microsoft. Here is what I have in Startup.cs. Note: app is an IApplicationBuilder

```<code>app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(
                    PathString.Combine(Directory.GetCurrentDiriectory(), @"Files")),
                RequestPath = new PathString("/Files")
            });
</code>```

To put it in context, I want to read the directories and files inside the "Files" folder.
Here is the line of code I am using to read the content of the folder but it always returns null. Note: "initialFilePath" is relative path to the folder "File".

```<code>var contents = _fileProvider.GetDirectoryContents(initalFilePath);
</code>```

Thanks

答:
Open your csproj files in notepad and make sure you have the following line.

```<code><PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.2" />
</code>```

If not, add it and reload the project and rebuild.

Body:
I tried different versions of StaticFiles.But it shows error because IApplicationBuilder does not contain UseStaticFiles().

"Microsoft.AspNetCore.StaticFiles": "1.1.1"

I am using the exact code provided in the .net documentation by Microsoft. Here is what I have in Startup.cs. Note: app is an IApplicationBuilder

app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(
                    PathString.Combine(Directory.GetCurrentDiriectory(), @"Files")),
                RequestPath = new PathString("/Files")
            });

To put it in context, I want to read the directories and files inside the "Files" folder.
Here is the line of code I am using to read the content of the folder but it always returns null. Note: "initialFilePath" is relative path to the folder "File".

var contents = _fileProvider.GetDirectoryContents(initalFilePath);

Thanks

Body:
Open your csproj files in notepad and make sure you have the following line.

<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.2" />

If not, add it and reload the project and rebuild.


问:
Write Json to server endpoint
I have an Ubuntu server instance running in Amazon EC2.

I want to write json to an endpoint in that url, for instance "http://myurl/myendpoint".

How do I create this endpoint and how do I write json to it with C#?

答:
Information you gave are too scarse. What exactly are you tryingt to achieve? Do you have a REST API deployed on that server? If not, then you probably want to create a REST Api. You can use it to create a mechanism that will be able to handle requests/responses.

https://learn.microsoft.com/en-us/aspnet/web-api/overview/older-versions/build-restful-apis-with-aspnet-web-api

Title: Write Json to server endpoint


问:
Reading integers from text file
I am trying to read integers from a text file but I failed.
(It fails to read even the first integer)

```<code>public void readFromFile(String filename) {
    File file = new File(filename);
    try {
        Scanner scanner = new Scanner(file);
        if (scanner.hasNextInt()) {
            int x = scanner.nextInt();
        }
        scanner.close();

    } catch (FileNotFoundException e) {
        System.out.println("File to load game was not found");
    }
}
</code>```

The error I get is: NoSuchElementException.
The file looks like this:

```<code>N,X1,Y1,X2,Y2,X3,Y3
</code>```

While n equals 3 in this example.

I call this method a in the main method like this:

```<code>readFromFile("file.txt");
</code>```

答: Scanneruses whitespace as the default delimiter. You can change that with useDelimiter See here: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

Title: Reading integers from text file

Body:
I am trying to read integers from a text file but I failed.
(It fails to read even the first integer)

public void readFromFile(String filename) {
    File file = new File(filename);
    try {
        Scanner scanner = new Scanner(file);
        if (scanner.hasNextInt()) {
            int x = scanner.nextInt();
        }
        scanner.close();

    } catch (FileNotFoundException e) {
        System.out.println("File to load game was not found");
    }
}

The error I get is: NoSuchElementException.
The file looks like this:

N,X1,Y1,X2,Y2,X3,Y3

While n equals 3 in this example.

I call this method a in the main method like this:

readFromFile("file.txt");


问:
Upload video using retrofit2
I am trying to upload a video from android device to server using Retrofit2 and end up getting error '400 Bad Request'. Below is the implementation. Could somebody help to fix the error?

```<code>public interface RetrofitService {
/**
 * Upload Videos to Server
 */
@Multipart
@POST("store/S3")
Call<ResponseBody> uploadToServer(@Query("key") String ServerAPI,
                                      @Query("mimetype") String videoMimeType,
                                      @Query("path") String path,
                                      @Query("container") String container,
                                      @Query("policy") String policy,
                                      @Query("signature") String signature,
                                      @Part MultipartBody.Part video,
                                      @Part("type") String videoType,
                                      @Part("name") String videoName );
</code>```

}

Client implemetation in helper.java

```<code>  private void uploadVideos(String videUri, String policy, String signature){
    String BASE_URL = "https://www.example.com/api/";
    String EXAMPLE_API_KEY = "xebfc";
    String mimeType = "video/mp4";
    String path = "mezzanine_videos/";
    String container = S3_BUCKET;

    // use the FileUtils to get the actual file by uri
    File videoFile = new File(videoUri);

    // create RequestBody instance from file
    RequestBody videoBody = RequestBody.create(MediaType.parse("video/*"), videoFile);

    // MultipartBody.Part is used to send the actual file
    MultipartBody.Part vFile = MultipartBody.Part.createFormData("video", videoFile.getName(), videoBody);

    String videoType = "video/mp4";
    String videoName = "video.mp4";

    final Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient)
            .build();

    RetrofitService service = retrofit.create(RetrofitService.class);
    Call<ResponseBody> call = service.uploadToServer( EXAMPLE_API_KEY, mimeType, path, container, policy, signature, vFile, videoType, videoName);
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            Log.d("Response", "Successful Response");
        }

        @Override
        public void onFailure(Call call, Throwable t) {
            Log.d("Response", "Failure Response");
        }
    }); }
</code>```

Server implementation works fine because I get a valid response by doing a curl post like below.

```<code>curl -X POST -F fileUpload=@animation.mov "https://www.example.com/api/store/S3?key= xebfc&mimetype=video%2Fmp4&path=mezzanine_videos/&container= S3_BUCKET&policy=ppppp&signature=ssss
</code>```

答:
After some debugging on MultipartBody.Part.createFormData, figured out that the name was not matching with my backend implementation. Below code fixed the issue.

```<code>    MultipartBody.Part vFile = MultipartBody.Part.createFormData("fileUpload", videoFile.getName(), fileBody);
</code>```

Rest of the code is same as mentioned above.

Title: Upload video using retrofit2

Body:
I am trying to upload a video from android device to server using Retrofit2 and end up getting error '400 Bad Request'. Below is the implementation. Could somebody help to fix the error?

public interface RetrofitService {
/**
 * Upload Videos to Server
 */
@Multipart
@POST("store/S3")
Call<ResponseBody> uploadToServer(@Query("key") String ServerAPI,
                                      @Query("mimetype") String videoMimeType,
                                      @Query("path") String path,
                                      @Query("container") String container,
                                      @Query("policy") String policy,
                                      @Query("signature") String signature,
                                      @Part MultipartBody.Part video,
                                      @Part("type") String videoType,
                                      @Part("name") String videoName );

}

Client implemetation in helper.java

  private void uploadVideos(String videUri, String policy, String signature){
    String BASE_URL = "https://www.example.com/api/";
    String EXAMPLE_API_KEY = "xebfc";
    String mimeType = "video/mp4";
    String path = "mezzanine_videos/";
    String container = S3_BUCKET;

    // use the FileUtils to get the actual file by uri
    File videoFile = new File(videoUri);

    // create RequestBody instance from file
    RequestBody videoBody = RequestBody.create(MediaType.parse("video/*"), videoFile);

    // MultipartBody.Part is used to send the actual file
    MultipartBody.Part vFile = MultipartBody.Part.createFormData("video", videoFile.getName(), videoBody);

    String videoType = "video/mp4";
    String videoName = "video.mp4";

    final Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient)
            .build();

    RetrofitService service = retrofit.create(RetrofitService.class);
    Call<ResponseBody> call = service.uploadToServer( EXAMPLE_API_KEY, mimeType, path, container, policy, signature, vFile, videoType, videoName);
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            Log.d("Response", "Successful Response");
        }

        @Override
        public void onFailure(Call call, Throwable t) {
            Log.d("Response", "Failure Response");
        }
    }); }

Server implementation works fine because I get a valid response by doing a curl post like below.

curl -X POST -F fileUpload=@animation.mov "https://www.example.com/api/store/S3?key= xebfc&mimetype=video%2Fmp4&path=mezzanine_videos/&container= S3_BUCKET&policy=ppppp&signature=ssss

Body:
After some debugging on MultipartBody.Part.createFormData, figured out that the name was not matching with my backend implementation. Below code fixed the issue.

    MultipartBody.Part vFile = MultipartBody.Part.createFormData("fileUpload", videoFile.getName(), fileBody);

Rest of the code is same as mentioned above.


问:
How to use a SSL in a request, swift 3
I'm trying to use a SSL (from OPENSSL), but I don't know how to put it on the request, neither on URLSession.

I have already put the App Transport Security Settings and the Exception Domains on the Info.plist.

The requests without HTTPS goes great.

Someone can help me with this?

答:
You can’t use OpenSSL together with NSURLSession, it uses the built-in SSL library provided by the system and has no extension points where you could get a third-party SSL implementation in. There is no reason to do that.

If you want to use the built-in SSL functionality you just use an HTTPS URL and the system does everything for you. Of course your server also has to support HTTPS.

Title: How to use a SSL in a request, swift 3