问:
How to use redirect at listview on django
I want to use redirect at listview on django.

If username is yusl, he connect to www.example.com/user/yusl, he can see his photo list, and if he connect to www.example.com/user/dksdl, it makes him to redirect www.example.com/user/yusl.

but there are error. error is

```<code>TypeError at /user/user/
context must be a dict rather than HttpResponseRedirect.
Request Method: GET
Request URL:    http://ec2-13-124-23-182.ap-northeast-2.compute.amazonaws.com/user/user/
Django Version: 1.11.1
Exception Type: TypeError
Exception Value:
context must be a dict rather than HttpResponseRedirect.
Exception Location: /home/ubuntu/my_env/lib/python3.5/site-packages/django/template/context.py in make_context, line 287
Python Executable:  /home/ubuntu/my_env/bin/python
Python Version: 3.5.2
Python Path:
['/home/ubuntu/project',
 '/home/ubuntu/my_env/lib/python35.zip',
 '/home/ubuntu/my_env/lib/python3.5',
 '/home/ubuntu/my_env/lib/python3.5/plat-x86_64-linux-gnu',
 '/home/ubuntu/my_env/lib/python3.5/lib-dynload',
 '/usr/lib/python3.5',
 '/usr/lib/python3.5/plat-x86_64-linux-gnu',
 '/home/ubuntu/my_env/lib/python3.5/site-packages']
Server time:    Sun, 4 Jun 2017 17:41:21 +0000
</code>```

this is my views.py

```<code>class PhotoListView(ListView):
    model = Photo

    def get_context_data(self, **kwargs):
        username = self.kwargs['username']
        User = get_user_model()
        user = get_object_or_404(User, username=username)

        if not user == self.request.user:
            return redirect('index')

        context = super(PhotoListView, self).get_context_data(**kwargs)
        context['photo_list'] = user.photo_set.order_by('-posted_on','-pk')
        return context
</code>```

this is urls.py

```<code>url(r'^user/(?P<username>[\w.@+-]+)/$', PhotoListView.as_view(), name='photo-list'),
</code>```

答:
You can't return a redirect from get_context_data, because as the name implies, that's for getting a template context.

Instead you need to do it from the method that actually creates and returns the response; in this case, the get method.

Also note, your code is unnecessarily complicated: all it needs to do is to check if the user has the required authorization to access the view, there is no need to query the database at all.

So:

```<code>class PhotoListView(ListView):
    model = Photo

    def get(self, *args, **kwargs):
        if not self.request.user.is_authenticated:
            return redirect('index')
        return super(PhotoListView, self).get(*args, **kwargs)
</code>```

Body:
I want to use redirect at listview on django.

If username is yusl, he connect to www.example.com/user/yusl, he can see his photo list, and if he connect to www.example.com/user/dksdl, it makes him to redirect www.example.com/user/yusl.

but there are error. error is

TypeError at /user/user/
context must be a dict rather than HttpResponseRedirect.
Request Method: GET
Request URL:    http://ec2-13-124-23-182.ap-northeast-2.compute.amazonaws.com/user/user/
Django Version: 1.11.1
Exception Type: TypeError
Exception Value:
context must be a dict rather than HttpResponseRedirect.
Exception Location: /home/ubuntu/my_env/lib/python3.5/site-packages/django/template/context.py in make_context, line 287
Python Executable:  /home/ubuntu/my_env/bin/python
Python Version: 3.5.2
Python Path:
['/home/ubuntu/project',
 '/home/ubuntu/my_env/lib/python35.zip',
 '/home/ubuntu/my_env/lib/python3.5',
 '/home/ubuntu/my_env/lib/python3.5/plat-x86_64-linux-gnu',
 '/home/ubuntu/my_env/lib/python3.5/lib-dynload',
 '/usr/lib/python3.5',
 '/usr/lib/python3.5/plat-x86_64-linux-gnu',
 '/home/ubuntu/my_env/lib/python3.5/site-packages']
Server time:    Sun, 4 Jun 2017 17:41:21 +0000

this is my views.py

class PhotoListView(ListView):
    model = Photo

    def get_context_data(self, **kwargs):
        username = self.kwargs['username']
        User = get_user_model()
        user = get_object_or_404(User, username=username)

        if not user == self.request.user:
            return redirect('index')

        context = super(PhotoListView, self).get_context_data(**kwargs)
        context['photo_list'] = user.photo_set.order_by('-posted_on','-pk')
        return context

this is urls.py

url(r'^user/(?P<username>[\w.@+-]+)/$', PhotoListView.as_view(), name='photo-list'),

Body:
You can't return a redirect from get_context_data, because as the name implies, that's for getting a template context.

Instead you need to do it from the method that actually creates and returns the response; in this case, the get method.

Also note, your code is unnecessarily complicated: all it needs to do is to check if the user has the required authorization to access the view, there is no need to query the database at all.

So:

class PhotoListView(ListView):
    model = Photo

    def get(self, *args, **kwargs):
        if not self.request.user.is_authenticated:
            return redirect('index')
        return super(PhotoListView, self).get(*args, **kwargs)


来源: stackexchange

问:
How can I insert 0 and 1 values in the sql as bit datatype
I created a table like
Create table t(name varchar(50),age int,sex bit)
This is the table when I insert values in the table...like
Insert into t values('rakesh',28,1)
It displays rakesh 28 true
I need to store 1or 0 values in the database which is having data type as bit...</p>

答:
In binary, a one equals TRUE and a zero equals FALSE. If you'd like to display 1 or 0 use something like this:</p>

```<code>int i = sex ? 1 : 0;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In binary, a one equals TRUE and a zero equals FALSE. If you'd like to display 1 or 0 use something like this:

int i = sex ? 1 : 0;

ContentLicense: CC BY-SA 4.0


问:
If Let vs Guard Let for UIImage in Swift 1.2
I am working my way through the iOS Apple Developer Tutorial, but am having a bit of an issue since my computer's version of Swift is 1.2 and Xcode is 6.4 instead of Swift 3.0.  I've been able to work along-side downgrading the code as need, but have hit an error in "guard let", which was introduced in Swift 2.0, below:

```<code>// The info dictionary may contain multiple representations of the image.
// You want to use the original.

guard let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {
    fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
}
</code>```

I converted it to the following:

```<code>if let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
     return selectedImage
} else {
     fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
}

//Set photoImageView to display the image.
photoImageView.image = selectedImage
</code>```

but I got the following error: "Use of unresolved identified 'selectedImage'"

Any help would be greatly appreciated!

EDIT: FULL CODE BELOW

```<code>import UIKit

class ViewController: UIViewController, UITextFieldDelegate,
UIImagePickerControllerDelegate, UINavigationControllerDelegate {

//MARK: Properties
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var mealNameLabel: UILabel!
@IBOutlet weak var photoImageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    //Handle the text field's user input through the delegate callbacks
    nameTextField.delegate = self
}

//MARK: UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
    //Hide the keyboard
    textField.resignFirstResponder()
    return true
}
func textFieldDidEndEditing(textField: UITextField) {
    //Set the lablel name as what the used typed
    mealNameLabel.text = textField.text
}

//MARK: UIImagePickerControllerDelegate
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
    //Dismiss the picker if the user canceled
    dismissViewControllerAnimated(true, completion:nil)
}
func imagePickerController(picker: UIImagePickerController,
    didFinishPickingMediaWithInfo info: [String : Any]) {
        //The info dictionary may contain multiple representations of the image. You want to use the original.
        if let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
            //Set photoImageView to display the image
            photoImageView.image = selectedImage
        } else {
            fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
        }

        //Set photoImageView to display the image
        //photoImageView.image = selectedImage

        //Dismiss the picker
        dismissViewControllerAnimated(true, completion: nil)
}

//MARK: Actions
@IBAction func selectImageFromPhotoLibrary(sender: UITapGestureRecognizer) {
    //Hide the keyboard
    nameTextField.resignFirstResponder()

    //UIImagePickerController is a view controller that lets a user pick media from their photo library.
    let imagePickerController = UIImagePickerController()

    //Only allow photos to be picked, not taken.
    imagePickerController.sourceType = .PhotoLibrary

    //Make sure ViewController is notified when the user picks and image.
    imagePickerController.delegate = self
    presentViewController(imagePickerController, animated: true, completion: nil)

}
@IBAction func setDefaultLabelText(_: UIButton) {
    mealNameLabel.text = "Default Text"
}
}
</code>```

答:
An if let optional binding statement creates a new variable that only exists inside the braces that follow:

```<code>if let foo = optionalFoo {
  //foo is only defined here
}

//foo has gone out of scope.
</code>```

guard let creates a new variable that exists from the code after through the end of the current scope:

```<code>func bar(optionalFoo: FooThing) {
  guard let foo = optionalFoo else {return}

  //foo exists from here until the end of the
  //current scope (the end of the func)
}
</code>```

Since Swift 1 doesn't have a guard statement, you need to move the code that's after the guard let to inside the braces of the if let:

It looks like @ReinierMelian beat me to it with his answer. See his answer for the correct form of your code in Swift 1.x.

Note that Swift 1.0 is badly out of date, and you are doing yourself a disservice working with it. You should upgrade to Xcode 8.3 and Swift 3.1. The change from Swift 1 to Swift 2 was significant, and from Swift 2 to Swift 3 was big. Swift 1 code won't compile in Xcode 8, and you may not be able to run it through an automatic conversion. (Xcode 8 will offer to run Swift 2.x through an automatic conversion to Swift 3, but I'm not sure if it will convert Swift 1 to Swift 3.

Body:
I am working my way through the iOS Apple Developer Tutorial, but am having a bit of an issue since my computer's version of Swift is 1.2 and Xcode is 6.4 instead of Swift 3.0.  I've been able to work along-side downgrading the code as need, but have hit an error in "guard let", which was introduced in Swift 2.0, below:

// The info dictionary may contain multiple representations of the image.
// You want to use the original.

guard let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {
    fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
}

I converted it to the following:

if let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
     return selectedImage
} else {
     fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
}

//Set photoImageView to display the image.
photoImageView.image = selectedImage

but I got the following error: "Use of unresolved identified 'selectedImage'"

Any help would be greatly appreciated!

EDIT: FULL CODE BELOW

import UIKit

class ViewController: UIViewController, UITextFieldDelegate,
UIImagePickerControllerDelegate, UINavigationControllerDelegate {

//MARK: Properties
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var mealNameLabel: UILabel!
@IBOutlet weak var photoImageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    //Handle the text field's user input through the delegate callbacks
    nameTextField.delegate = self
}

//MARK: UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
    //Hide the keyboard
    textField.resignFirstResponder()
    return true
}
func textFieldDidEndEditing(textField: UITextField) {
    //Set the lablel name as what the used typed
    mealNameLabel.text = textField.text
}

//MARK: UIImagePickerControllerDelegate
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
    //Dismiss the picker if the user canceled
    dismissViewControllerAnimated(true, completion:nil)
}
func imagePickerController(picker: UIImagePickerController,
    didFinishPickingMediaWithInfo info: [String : Any]) {
        //The info dictionary may contain multiple representations of the image. You want to use the original.
        if let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
            //Set photoImageView to display the image
            photoImageView.image = selectedImage
        } else {
            fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
        }

        //Set photoImageView to display the image
        //photoImageView.image = selectedImage

        //Dismiss the picker
        dismissViewControllerAnimated(true, completion: nil)
}

//MARK: Actions
@IBAction func selectImageFromPhotoLibrary(sender: UITapGestureRecognizer) {
    //Hide the keyboard
    nameTextField.resignFirstResponder()

    //UIImagePickerController is a view controller that lets a user pick media from their photo library.
    let imagePickerController = UIImagePickerController()

    //Only allow photos to be picked, not taken.
    imagePickerController.sourceType = .PhotoLibrary

    //Make sure ViewController is notified when the user picks and image.
    imagePickerController.delegate = self
    presentViewController(imagePickerController, animated: true, completion: nil)

}
@IBAction func setDefaultLabelText(_: UIButton) {
    mealNameLabel.text = "Default Text"
}
}

Body:
An if let optional binding statement creates a new variable that only exists inside the braces that follow:

if let foo = optionalFoo {
  //foo is only defined here
}

//foo has gone out of scope.

guard let creates a new variable that exists from the code after through the end of the current scope:

func bar(optionalFoo: FooThing) {
  guard let foo = optionalFoo else {return}

  //foo exists from here until the end of the
  //current scope (the end of the func)
}

Since Swift 1 doesn't have a guard statement, you need to move the code that's after the guard let to inside the braces of the if let:

It looks like @ReinierMelian beat me to it with his answer. See his answer for the correct form of your code in Swift 1.x.

Note that Swift 1.0 is badly out of date, and you are doing yourself a disservice working with it. You should upgrade to Xcode 8.3 and Swift 3.1. The change from Swift 1 to Swift 2 was significant, and from Swift 2 to Swift 3 was big. Swift 1 code won't compile in Xcode 8, and you may not be able to run it through an automatic conversion. (Xcode 8 will offer to run Swift 2.x through an automatic conversion to Swift 3, but I'm not sure if it will convert Swift 1 to Swift 3.


问:
Corner case in using lambdas expression in base constructor
In the Framework we are building we need the following pattern:

```<code>public class BaseRenderer
{
    Func<string> renderer;
    public BaseRenderer(Func<string> renderer)
    {
        this.renderer = renderer;
    }

    public string Render()
    {
        return renderer();
    }
}

public class NameRenderer : BaseRenderer
{
    public string Name{ get; set; }

     public NameRenderer ()
        : base(() =>this.Name)
     {}
}
</code>```

As you see, we create a lambda when calling the base constructor.

```<code>public class Program
{
    public static void Main()
    {
        Console.WriteLine(new NameRenderer(){Name = "Foo"}.Render());
    }
}
</code>```

Oddly, when trying to actually use the lambda it throws NullReferenceException (Console Application), or some kind of ExecutionEngineExceptionexception (Web app on IIS).

I think the reason is that this pointer is not ready before calling base constructor, so the lambda is unable to capture this.Name at this stage.

Shouldn't it throw an exception in "capture time" instead of "execution time"?
Is this behavior documented?

I can refactor the code in a different way, but I think it worths a comment.

答: wouldn't : base(()=>this) be legal? You can do  : this() so a reference to this seems to be fine, just not properties on it. The fact that : base(()=>this) is no longer legal just broke some partial function application I did during construction. Can be fixed by moving it into the body of the constructor, but there is an order difference: the base class can no longer be passed transparently a partial function application to itself (because the base class constructor gets called before the body of the subclass constructor).

ContentLicense: CC BY-SA 2.5

Body:
In the Framework we are building we need the following pattern:

public class BaseRenderer
{
    Func<string> renderer;
    public BaseRenderer(Func<string> renderer)
    {
        this.renderer = renderer;
    }

    public string Render()
    {
        return renderer();
    }
}

public class NameRenderer : BaseRenderer
{
    public string Name{ get; set; }

     public NameRenderer ()
        : base(() =>this.Name)
     {}
}

As you see, we create a lambda when calling the base constructor.

public class Program
{
    public static void Main()
    {
        Console.WriteLine(new NameRenderer(){Name = "Foo"}.Render());
    }
}

Oddly, when trying to actually use the lambda it throws NullReferenceException (Console Application), or some kind of ExecutionEngineExceptionexception (Web app on IIS).

I think the reason is that this pointer is not ready before calling base constructor, so the lambda is unable to capture this.Name at this stage.

Shouldn't it throw an exception in "capture time" instead of "execution time"?
Is this behavior documented?

I can refactor the code in a different way, but I think it worths a comment.


问:
Spring integration flow with two sources
I try to create a flow which get message from 2 sources (1 mqtt and one from a user service interaction) and it generate message to another mqtt.
In fact, i try to use this answer: How to crate Spring Integration Flow from two MessageProducerSpec?

And here is my result:

```<code>@Bean
public IntegrationFlow mqttInFlow() {
    return IntegrationFlows.from(mqttInbound())
            .channel("mainMessageChannel")
            .get();
}

@Bean
public IntegrationFlow mqttTestMessageFlow() {
    return IntegrationFlows.from(messageService.testInbound())
            .channel("mainMessageChannel")
            .get();
}

@Bean
public IntegrationFlow mainMessageFlow() {
    return IntegrationFlows.from("mainMessageChannel")
            .handle(eventServiceHandler())
            .split(operationSplitter())
            .handle(mqttOutbound())
            .get();
}
</code>```

But i have the following error:

```<code>java.lang.IllegalStateException: 'outputChannel' or 'outputChannelName' is required
    at org.springframework.util.Assert.state(Assert.java:70)
    at org.springframework.integration.endpoint.MessageProducerSupport.afterSingletonsInstantiated(MessageProducerSupport.java:136)
</code>```

答:
Well, you have to use it in those MessageProducerSupport definitions, not like channel("mainMessageChannel"):

```<code>@Bean
MessageProducerSupport mqttInbound() {
   ...
   adapter.setOutputChannelName("mainMessageChannel");
   ...
}

@Bean
MessageProducerSupport testInbound() {
   ...
   adapter.setOutputChannelName("mainMessageChannel");
   ...
}
</code>```

or... Just don't @Bean annotation on them and Java DSL will take care about their declaration!

Body:
I try to create a flow which get message from 2 sources (1 mqtt and one from a user service interaction) and it generate message to another mqtt.
In fact, i try to use this answer: How to crate Spring Integration Flow from two MessageProducerSpec?

And here is my result:

@Bean
public IntegrationFlow mqttInFlow() {
    return IntegrationFlows.from(mqttInbound())
            .channel("mainMessageChannel")
            .get();
}

@Bean
public IntegrationFlow mqttTestMessageFlow() {
    return IntegrationFlows.from(messageService.testInbound())
            .channel("mainMessageChannel")
            .get();
}

@Bean
public IntegrationFlow mainMessageFlow() {
    return IntegrationFlows.from("mainMessageChannel")
            .handle(eventServiceHandler())
            .split(operationSplitter())
            .handle(mqttOutbound())
            .get();
}

But i have the following error:

java.lang.IllegalStateException: 'outputChannel' or 'outputChannelName' is required
    at org.springframework.util.Assert.state(Assert.java:70)
    at org.springframework.integration.endpoint.MessageProducerSupport.afterSingletonsInstantiated(MessageProducerSupport.java:136)

Body:
Well, you have to use it in those MessageProducerSupport definitions, not like channel("mainMessageChannel"):

@Bean
MessageProducerSupport mqttInbound() {
   ...
   adapter.setOutputChannelName("mainMessageChannel");
   ...
}

@Bean
MessageProducerSupport testInbound() {
   ...
   adapter.setOutputChannelName("mainMessageChannel");
   ...
}

or... Just don't @Bean annotation on them and Java DSL will take care about their declaration!


问:
Return first word in sentence?
Heres the question I have to answer for school

For the purposes of this question, we will define a word as ending a sentence if that word is immediately followed by a period. For example, in the text “This is a sentence. The last sentence had four words.”, the ending words are ‘sentence’ and ‘words’. In a similar fashion, we will define the starting word of a sentence as any word that is preceded by the end of a sentence. The starting words from the previous example text would be “The”. You do not need to consider the first word of the text as a starting word. Write a program that has:

An endwords function that takes a single string argument. This functioin must return a list of all sentence ending words that appear in the given string. There should be no duplicate entries in the returned list and the periods should not be included in the ending words.

The code I have so far is:

```<code>def startwords(astring):
    mylist = astring.split()
    if mylist.endswith('.') == True:
        return my list
</code>```

but I don't know if I'm using the right approach. I need some help

答:
Several issues with your code. The following would be a simple approach. Create a list of bigrams and pick the second token of each bigram where the first token ends with a period:

```<code>def startwords(astring):
    mylist = astring.split()  # a list! Has no 'endswith' method
    bigrams = zip(mylist, mylist[1:])
    return [b[1] for b in bigrams if b[0].endswith('.')]
</code>```

zip and list comprehenion are two things worth reading up on.

Title: Return first word in sentence?

Body:
Heres the question I have to answer for school

For the purposes of this question, we will define a word as ending a sentence if that word is immediately followed by a period. For example, in the text “This is a sentence. The last sentence had four words.”, the ending words are ‘sentence’ and ‘words’. In a similar fashion, we will define the starting word of a sentence as any word that is preceded by the end of a sentence. The starting words from the previous example text would be “The”. You do not need to consider the first word of the text as a starting word. Write a program that has:

An endwords function that takes a single string argument. This functioin must return a list of all sentence ending words that appear in the given string. There should be no duplicate entries in the returned list and the periods should not be included in the ending words.

The code I have so far is:

def startwords(astring):
    mylist = astring.split()
    if mylist.endswith('.') == True:
        return my list

but I don't know if I'm using the right approach. I need some help

Body:
Several issues with your code. The following would be a simple approach. Create a list of bigrams and pick the second token of each bigram where the first token ends with a period:

def startwords(astring):
    mylist = astring.split()  # a list! Has no 'endswith' method
    bigrams = zip(mylist, mylist[1:])
    return [b[1] for b in bigrams if b[0].endswith('.')]

zip and list comprehenion are two things worth reading up on.


问:
Assigning values to a block in a numpy array
I am trying to change a block within a two-dimensional numpy array by inserting pasting another 2-dim array. The sample below gives me unexpected behavior:

```<code>import numpy as np
M=np.ones((4,4))
print(M)
S=[0,1]
print('to be set to zero: ',M[S,:][:,S])
M[S,:][:,S]=np.zeros((2,2))
print('after setting to zero: ',M)
</code>```

I would expect the upper left corner of M to become zeros. However I get

```<code>[[ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]]
to be set to zero:  [[ 1.  1.]
 [ 1.  1.]]
after setting to zero:  [[ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]]
</code>```

It seems that I can extract the upper left block but not write to it. I get the expected behavior if I replace the line

```<code>M[S,:][:,S]=np.zeros((2,2))
</code>```

with

```<code>M[0:2,:][:,0:2]=np.zeros((2,2))
</code>```

What am I doing wrong?
Thank you

Body:
I am trying to change a block within a two-dimensional numpy array by inserting pasting another 2-dim array. The sample below gives me unexpected behavior:

import numpy as np
M=np.ones((4,4))
print(M)
S=[0,1]
print('to be set to zero: ',M[S,:][:,S])
M[S,:][:,S]=np.zeros((2,2))
print('after setting to zero: ',M)

I would expect the upper left corner of M to become zeros. However I get

[[ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]]
to be set to zero:  [[ 1.  1.]
 [ 1.  1.]]
after setting to zero:  [[ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]]

It seems that I can extract the upper left block but not write to it. I get the expected behavior if I replace the line

M[S,:][:,S]=np.zeros((2,2))

with

M[0:2,:][:,0:2]=np.zeros((2,2))

What am I doing wrong?
Thank you

Body:
You can use numpy advanced indexing ix_

M[np.ix_(S,S)]=0

M
Out[622]:
array([[ 0.,  0.,  1.,  1.],
       [ 0.,  0.,  1.,  1.],
       [ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.]])


问:
How to share a deep link on social networks in react native
as the title says, I'd like to know if there's a way to share URL deep link in a social network (eg: twitter, facebook, whatsaap, etc). I'm using this library react-native-share but since it isn't a web URL but a URL from an App (The URL is something like: myapp://app/1 (the last part is the parameter that I have to send)) the message doesn't appear as a hyperlink but just as a simple string, like a normal message in the social network. I tried making the text a link with the .link function from javascript, but that only works on web browsers, I'd like to know if there's another way to accomplish this or if you have any idea of how to convert the message into a clickable link. I just want the others apps to recognize it as a link and let it open on the web browser, that way It'll open the app I'm developing.</p>

答:
You need to add this intent filter in your AndroidManifest.xml first.

```<code><activity
    [...]

    <intent-filter android:label="filter_react_native">
      <action android:name="android.intent.action.VIEW" />
      <category android:name="android.intent.category.DEFAULT" />
      <category android:name="android.intent.category.BROWSABLE" />
      <data android:scheme="http"
            android:host="www.your-domain.com"
            android:pathPrefix="/new/9/read" />
      <data android:scheme="appname"
            android:host="yourhost" />
    </intent-filter>
</code>```

Then you can use the Linking API that react-native provides to handle your deep links.

ex:

```<code>componentDidMount() {
  Linking.getInitialURL().then((url) => {
    if (url) {
      console.log('Initial url is: ' + url);
    }
  }).catch(err => console.error('An error occurred', err));
}
</code>```

Body:
You need to add this intent filter in your AndroidManifest.xml first.

<activity
    [...]

    <intent-filter android:label="filter_react_native">
      <action android:name="android.intent.action.VIEW" />
      <category android:name="android.intent.category.DEFAULT" />
      <category android:name="android.intent.category.BROWSABLE" />
      <data android:scheme="http"
            android:host="www.your-domain.com"
            android:pathPrefix="/new/9/read" />
      <data android:scheme="appname"
            android:host="yourhost" />
    </intent-filter>

Then you can use the Linking API that react-native provides to handle your deep links.

ex:

componentDidMount() {
  Linking.getInitialURL().then((url) => {
    if (url) {
      console.log('Initial url is: ' + url);
    }
  }).catch(err => console.error('An error occurred', err));
}


问:
Axios is not defined
I am using axios for building a simple weather app with React.js. I just completed the code but there is a problem. When I launch that app, it's not working at all and I see a reference error that says axios is not defined.

Here is my webpack.config.js file:

```<code>module.exports = {
    entry: './public/app/app.jsx',
    output: {
        path: __dirname,
        filename: './public/js/bundle.js'
    },
    externals: ['axios'],
    resolve: {
        root: __dirname,
        alias: {
            OpenWeatherMap: 'public/components/OpenWeatherMap.jsx',
            Main: 'public/components/Main.jsx',
            Nav: 'public/components/Nav.jsx',
            Weather: 'public/components/Weather.jsx',
            WeatherForm: 'public/components/WeatherForm.jsx',
            WeatherMessage: 'public/components/WeatherMessage.jsx',
            About: 'public/components/About.jsx'
        },
        extensions: ['', '.js', '.jsx']
    },
    module: {
        loaders: [{
            loader: 'babel-loader',
            query: {
                presets: ['react','es2015', 'stage-0']
            },
            test: /\.jsx?$/,
            exclude: /(node_modules|bower_components)/
        },{
            loader: 'json-loader',
            test: /\.json?$/
        }]
    }
};
</code>```

and package.json file:

```<code>{
  "name": "weather",
  "version": "1.0.0",
  "description": "Simple Weather App",
  "main": "ext.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Milad Fattahi",
  "license": "ISC",
  "dependencies": {
    "axios": "^0.16.1",
    "express": "^4.15.3",
    "json": "^9.0.6",
    "json-loader": "^0.5.4",
    "react": "^15.5.4",
    "react-dom": "^15.5.4",
    "react-router": "^4.1.1",
    "react-router-dom": "^4.1.1"
  },
  "devDependencies": {
    "babel-core": "^6.5.1",
    "babel-loader": "^6.2.2",
    "babel-preset-es2015": "^6.5.0",
    "babel-preset-react": "^6.5.0",
    "babel-preset-stage-0": "^6.24.1",
    "webpack": "^1.12.13"
  }
}
</code>```

答:
I know this might seem obvious but make sure there is a reference at the top of your file to the correct axios or install it
https://www.npmjs.com/package/axios</p>

```<code><script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</code>```

Title: Axios is not defined

Body:
I am using axios for building a simple weather app with React.js. I just completed the code but there is a problem. When I launch that app, it's not working at all and I see a reference error that says axios is not defined.

Here is my webpack.config.js file:

module.exports = {
    entry: './public/app/app.jsx',
    output: {
        path: __dirname,
        filename: './public/js/bundle.js'
    },
    externals: ['axios'],
    resolve: {
        root: __dirname,
        alias: {
            OpenWeatherMap: 'public/components/OpenWeatherMap.jsx',
            Main: 'public/components/Main.jsx',
            Nav: 'public/components/Nav.jsx',
            Weather: 'public/components/Weather.jsx',
            WeatherForm: 'public/components/WeatherForm.jsx',
            WeatherMessage: 'public/components/WeatherMessage.jsx',
            About: 'public/components/About.jsx'
        },
        extensions: ['', '.js', '.jsx']
    },
    module: {
        loaders: [{
            loader: 'babel-loader',
            query: {
                presets: ['react','es2015', 'stage-0']
            },
            test: /\.jsx?$/,
            exclude: /(node_modules|bower_components)/
        },{
            loader: 'json-loader',
            test: /\.json?$/
        }]
    }
};

and package.json file:

{
  "name": "weather",
  "version": "1.0.0",
  "description": "Simple Weather App",
  "main": "ext.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Milad Fattahi",
  "license": "ISC",
  "dependencies": {
    "axios": "^0.16.1",
    "express": "^4.15.3",
    "json": "^9.0.6",
    "json-loader": "^0.5.4",
    "react": "^15.5.4",
    "react-dom": "^15.5.4",
    "react-router": "^4.1.1",
    "react-router-dom": "^4.1.1"
  },
  "devDependencies": {
    "babel-core": "^6.5.1",
    "babel-loader": "^6.2.2",
    "babel-preset-es2015": "^6.5.0",
    "babel-preset-react": "^6.5.0",
    "babel-preset-stage-0": "^6.24.1",
    "webpack": "^1.12.13"
  }
}

Body:
I know this might seem obvious but make sure there is a reference at the top of your file to the correct axios or install it
https://www.npmjs.com/package/axios

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>


问:
How can I let Arduino GSM shield respond only to authorized numbers?
I am working on a project where I send '1' to my Arduino GSM Shield to switch on the LED connected to pin 13 and I switch it off by sending '0', but I would like to modify the code in order for the GSM Shield to respond only to the number specified. Here is my code, in my case I used an example phone number. Currently when I send a message from adminNumber the LED does not switch on nor off.

// include the GSM library
#include <GSM.h>

// PIN Number for the SIM
#define PINNUMBER ""

// initialize the library instances
GSM gsmAccess;
GSM_SMS sms;

// Array to hold the number a SMS is retreived from

char senderNumber[20];
char adminNumber[20]="+123456789234";

void setup()
{

  // initialize digital pin 13 as an output.
  pinMode(13, OUTPUT);

  // initialize serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  Serial.println("SMS Messages Receiver");

  // connection state
  boolean notConnected = true;

  // Start GSM connection
  while (notConnected)
  {
    if (gsmAccess.begin(PINNUMBER) == GSM_READY)
      notConnected = false;
    else
    {
      Serial.println("Not connected");
      delay(1000);
    }
  }

  Serial.println("GSM initialized");
  Serial.println("Waiting for messages");
}

void loop()
{
  char c;

  sms.remoteNumber(senderNumber, 20);
  sms.remoteNumber(adminNumber, 20);

    // If there are any SMSs available()
  if (sms.available())
  {
    Serial.println("Message received from:");

     // Get remote number
    sms.remoteNumber(senderNumber, 20);
    Serial.println(senderNumber);

       // Any number besides admin number will not change the state of the pin
    while(adminNumber == senderNumber){
        // Any messages starting with 1 will set pin 13 to HIGH
if (sms.peek() == '1'){
      digitalWrite(13, HIGH);
     sms.flush();
    }
        // Any messages starting with 0 will set pin 13 to LOW
else if(sms.peek() == '0'){
      digitalWrite(13, LOW);

        sms.flush()
}
    }

    // Read message bytes and print them
    while (c = sms.read())
      Serial.print(c);

    Serial.println("\nEND OF MESSAGE");

    // Delete message from modem memory
    sms.flush();
    Serial.println("MESSAGE DELETED");
  }

  delay(1000);

}
```

答:
Array comparison can be donne like Kurz7 does https://cboard.cprogramming.com/c-programming/41972-how-do-i-compare-two-arrays.html

// include the GSM library
#include <GSM.h>
#include <string.h>

// PIN Number for the SIM
#define PINNUMBER "xxxx"

// initialize the library instances
GSM gsmAccess;
GSM_SMS sms;

// Array to hold the number a SMS is retreived from
char senderNumber[20];
char adminNumber[20]="+xxxxxxxxxxx";

void setup()
{

// initialize digital pin 13 as an output.
pinMode(13, OUTPUT);

// initialize serial communications and wait for port to open:
Serial.begin(9600);
Serial.println("SMS Messages Receiver");

// connection state
boolean notConnected = true;

// Start GSM connection
while (notConnected)
{
 if (gsmAccess.begin(PINNUMBER) == GSM_READY)
 notConnected = false;
 else
{
 Serial.println("Not connected");
 delay(1000);
 }
 }

Serial.println("GSM initialized");
Serial.println("Waiting for messages");
}

void loop()
{
char c;

// If there are any SMSs available()
if (sms.available())

{
Serial.println("Message received from:");
sms.remoteNumber(senderNumber,20); // Get remote number
Serial.println(senderNumber);

// Any number besides admin number will not change the state of the pin

if (strcmp( adminNumber, senderNumber ) == 0 )
{

// Any messages starting with 1 will set pin 13 to HIGH

if (sms.peek() == '1') {digitalWrite(13, HIGH);

}
// Any messages starting with 0 will set pin 13 to LOW
else if(sms.peek() == '0') {digitalWrite(13, LOW);

}

// Read message bytes and print them
while (c = sms.read())
Serial.print(c);

Serial.println("\nEND OF MESSAGE");

// Delete message from modem memory
sms.flush();
Serial.println("MESSAGE DELETED");
}

delay(1000);

}}
```


问:
Drawable to byte[]
I have an image from the web in an ImageView. It is very small (a favicon) and I'd like to store it in my SQLite database.
I can get a Drawable from mImageView.getDrawable() but then I don't know what to do next. I don't fully understand the Drawable class in Android.

I know I can get a byte array from a Bitmap like:

```<code>Bitmap defaultIcon = BitmapFactory.decodeStream(in);

ByteArrayOutputStream stream = new ByteArrayOutputStream();
defaultIcon.compress(Bitmap.CompressFormat.JPEG, 100, stream);

byte[] bitmapdata = stream.toByteArray();
</code>```

But how do I get a byte array from a Drawable?

答:
```<code>Drawable d; // the drawable (Captain Obvious, to the rescue!!!)
Bitmap bitmap = ((BitmapDrawable)d).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bitmapdata = stream.toByteArray();
</code>```

Title: Drawable to byte[]

Body:
I have an image from the web in an ImageView. It is very small (a favicon) and I'd like to store it in my SQLite database.
I can get a Drawable from mImageView.getDrawable() but then I don't know what to do next. I don't fully understand the Drawable class in Android.

I know I can get a byte array from a Bitmap like:

Bitmap defaultIcon = BitmapFactory.decodeStream(in);

ByteArrayOutputStream stream = new ByteArrayOutputStream();
defaultIcon.compress(Bitmap.CompressFormat.JPEG, 100, stream);

byte[] bitmapdata = stream.toByteArray();

But how do I get a byte array from a Drawable?


问:
In Xcode, is there a way to set up a table which is not for UI but like an 'engine' for processing data
I'm wondering if there is some sort of way to set up something similar to a spreadsheet in Xcode. I'm trying to create a 'tapping game' or a 'clicker game' and storing so many variables in regular coding would be really tough.

Having this 'table' would enable me to keep track of multipliers and upgrade levels instead of clogging my coding with it.

Preferably, I could then just tell my code what to pull and what to look for off of the table. The table would be an 'engine' of sorts and it would not be UI. The table would do all of the work behind scenes, then show it through UI based on labels and buttons.

答:
Yes, you can.

Create a shared or singleton instance and retain all the data in instances of it.
(or) create a custom data structure and overide set or get methods to autoprocess the exiting data everytime you add or delete data element

Ex: If you want to maintain an array thats is always sorted. MySortedArray is the custom structure that inherits NSMutableArray and maintain a protected NSMutableArray instance. Overide addObject method to ensure sorting it whenever a new object is added.


问:
Detecting contact of a SKSpritenode with many SKSpritenodes Swift
I need to detect contact in my project, but I have 9 squares that i want to detect contact with. Is there a way to detect contact without creating 9 different physics bodies or something like an array of physics bodies. Also, every time the circle touches a square, that square will turn color. I want to do this with something like an array like this:

```<code>for i in 1...9{
if firstBody.categoryBitMask == PhysicsCategory.square[i] && secondBody.categoryBitMask == PhysicsCategory.circle || firstBody.categoryBitMask ==
PhysicsCategory.circle && secondBody.categoryBitMask == PhysicsCategory.square[i] {

    squares[i].node.color = squares[i].targetColor
    //this is my array of structs containing the skspritenodes
    squares[i].colorBlendFactor = 1.0

}
}
</code>```

I have tried making 9 physics bodies but i got a lot of errors. This is what I have done so far.

```<code>import SpriteKit

var squares = Array<square>()
var positions = Array<CGPoint>()
var squareUnit = CGFloat()
var rows = Array<CGFloat>()
var columbs = Array<CGFloat>()
var circle = SKSpriteNode()
var physics = Array<UInt32>()

struct PhysicsCategory{

static let circle : UInt32 = 0x1 << 0
static let square1 : UInt32 = 0x1 << 1
static let square2 : UInt32 = 0x1 << 2
static let square3 : UInt32 = 0x1 << 3
static let square4 : UInt32 = 0x1 << 4
static let square5 : UInt32 = 0x1 << 5
static let square6 : UInt32 = 0x1 << 6
static let square7 : UInt32 = 0x1 << 7
static let square8 : UInt32 = 0x1 << 8
static let square9 : UInt32 = 0x1 << 9

}

struct square{

var startColor = UIColor()
var middleColor = UIColor()
var targetColor = UIColor()
var has3Colors = Bool()
var permanent = Bool()
var node = SKSpriteNode(imageNamed:"Square")
var currentState = Int()

}

class GameScene: SKScene, SKPhysicsContactDelegate {

override func didMove(to view: SKView) {

        createScene()

       }

    func createScene(){
    self.physicsWorld.contactDelegate = self
    self.anchorPoint = CGPoint(x: 0, y: 0)
    createSquares()
    createCircles()

}

func createCircles(){

    circle = SKSpriteNode(imageNamed: "Circle")
    circle.size.width = squares[1].node.size.width * 0.9
    circle.size.height = squares[1].node.size.height * 0.9
    circle.position = squares[4].node.position
    circle.color = UIColor.blue
    circle.colorBlendFactor = 1.0
    circle.zPosition = 10
    circle.physicsBody = SKPhysicsBody(circleOfRadius: circle.frame.width / 2)
    circle.physicsBody?.categoryBitMask = PhysicsCategory.circle
    circle.physicsBody?.affectedByGravity = false
    circle.physicsBody?.isDynamic = false
    circle.physicsBody?.contactTestBitMask = PhysicsCategory.square1
    circle.physicsBody?.contactTestBitMask = PhysicsCategory.square2
    circle.physicsBody?.contactTestBitMask = PhysicsCategory.square3
    circle.physicsBody?.contactTestBitMask = PhysicsCategory.square4
    circle.physicsBody?.contactTestBitMask = PhysicsCategory.square5
    circle.physicsBody?.contactTestBitMask = PhysicsCategory.square6
    circle.physicsBody?.contactTestBitMask = PhysicsCategory.square7
    circle.physicsBody?.contactTestBitMask = PhysicsCategory.square8
    circle.physicsBody?.contactTestBitMask = PhysicsCategory.square9

        self.addChild(circle)

}

func didBegin(_ contact: SKPhysicsContact) {

    let firstBody = contact.bodyA
    let secondBody = contact.bodyB

       }

func createSquares(){
    for i in 1...9{

       // squares[i].currentState = 1

    }
    squareUnit = self.frame.width / 4

    columbs = [squareUnit / 4 + squareUnit/2, self.frame.width/2,self.frame.width - squareUnit / 4 - squareUnit / 2]
    rows = [squareUnit / 4 + squareUnit/2, self.frame.width/2,self.frame.width - squareUnit / 4 - squareUnit / 2]
    for row in rows{
        for columb in columbs{

          positions.append(CGPoint(x: columb, y: row))

        }

    }

    squares = (0...8).map { _ in square() }

    for i in (0...8){

        squares[i].node.position = positions[i]
        squares[i].node.physicsBody = SKPhysicsBody(rectangleOf: squares[i].node.size )
        squares[i].node.physicsBody?.affectedByGravity = false
        squares[i].node.physicsBody?.isDynamic = false

    }
    for square in squares {

        square.node.size = CGSize(width: squareUnit, height: squareUnit)
        square.node.color = UIColor.white
    }

    squares.forEach { self.addChild($0.node) }

}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

    for touch in touches {

        let location = touch.location(in: self)

        circle.run(SKAction.move(to: CGPoint(x: location.x, y: location.y), duration: 0.2))

    }

}

override func update(_ currentTime: TimeInterval) {
    // Called before each frame is rendered
}
}
</code>```

答:
I figured it out i just create 9 physics bodies and then add them all to an array of UInt32 and assign them each to each node.</p>

```<code>var physics = Array<UInt32>()

struct PhysicsCategory{

    static let square1 : UInt32 = 0x1 << 1
    static let square2 : UInt32 = 0x1 << 2
    static let square3 : UInt32 = 0x1 << 3
    static let square4 : UInt32 = 0x1 << 4
    static let square5 : UInt32 = 0x1 << 5
    static let square6 : UInt32 = 0x1 << 6
    static let square7 : UInt32 = 0x1 << 7
    static let square8 : UInt32 = 0x1 << 8
    static let square9 : UInt32 = 0x1 << 9
}

override func didMove(to view: SKView) {

    physics.append(PhysicsCategory.square1)
    physics.append(PhysicsCategory.square2)
    physics.append(PhysicsCategory.square3)
    physics.append(PhysicsCategory.square4)
    physics.append(PhysicsCategory.square5)
    physics.append(PhysicsCategory.square6)
    physics.append(PhysicsCategory.square7)
    physics.append(PhysicsCategory.square8)
    physics.append(PhysicsCategory.square9)

   for i in (0...8){

        squares[i].node.physicsBody = SKPhysicsBody(rectangleOf: squares[i].node.size )
        squares[i].node.physicsBody?.categoryBitMask = physics[i]
        squares[i].node.physicsBody?.affectedByGravity = false
        squares[i].node.physicsBody?.isDynamic = false
        squares[i].node.physicsBody?.contactTestBitMask = PhysicsCategory.Circle
        squares[i].node.physicsBody?.collisionBitMask = 0

    }

}
</code>```

Body:
I need to detect contact in my project, but I have 9 squares that i want to detect contact with. Is there a way to detect contact without creating 9 different physics bodies or something like an array of physics bodies. Also, every time the circle touches a square, that square will turn color. I want to do this with something like an array like this:

for i in 1...9{
if firstBody.categoryBitMask == PhysicsCategory.square[i] && secondBody.categoryBitMask == PhysicsCategory.circle || firstBody.categoryBitMask ==
PhysicsCategory.circle && secondBody.categoryBitMask == PhysicsCategory.square[i] {

    squares[i].node.color = squares[i].targetColor
    //this is my array of structs containing the skspritenodes
    squares[i].colorBlendFactor = 1.0

}
}

I have tried making 9 physics bodies but i got a lot of errors. This is what I have done so far.

import SpriteKit

var squares = Array<square>()
var positions = Array<CGPoint>()
var squareUnit = CGFloat()
var rows = Array<CGFloat>()
var columbs = Array<CGFloat>()
var circle = SKSpriteNode()
var physics = Array<UInt32>()

struct PhysicsCategory{

static let circle : UInt32 = 0x1 << 0
static let square1 : UInt32 = 0x1 << 1
static let square2 : UInt32 = 0x1 << 2
static let square3 : UInt32 = 0x1 << 3
static let square4 : UInt32 = 0x1 << 4
static let square5 : UInt32 = 0x1 << 5
static let square6 : UInt32 = 0x1 << 6
static let square7 : UInt32 = 0x1 << 7
static let square8 : UInt32 = 0x1 << 8
static let square9 : UInt32 = 0x1 << 9

}

struct square{

var startColor = UIColor()
var middleColor = UIColor()
var targetColor = UIColor()
var has3Colors = Bool()
var permanent = Bool()
var node = SKSpriteNode(imageNamed:"Square")
var currentState = Int()

}

class GameScene: SKScene, SKPhysicsContactDelegate {

override func didMove(to view: SKView) {

        createScene()

       }

    func createScene(){
    self.physicsWorld.contactDelegate = self
    self.anchorPoint = CGPoint(x: 0, y: 0)
    createSquares()
    createCircles()

}

func createCircles(){

    circle = SKSpriteNode(imageNamed: "Circle")
    circle.size.width = squares[1].node.size.width * 0.9
    circle.size.height = squares[1].node.size.height * 0.9
    circle.position = squares[4].node.position
    circle.color = UIColor.blue
    circle.colorBlendFactor = 1.0
    circle.zPosition = 10
    circle.physicsBody = SKPhysicsBody(circleOfRadius: circle.frame.width / 2)
    circle.physicsBody?.categoryBitMask = PhysicsCategory.circle
    circle.physicsBody?.affectedByGravity = false
    circle.physicsBody?.isDynamic = false
    circle.physicsBody?.contactTestBitMask = PhysicsCategory.square1
    circle.physicsBody?.contactTestBitMask = PhysicsCategory.square2
    circle.physicsBody?.contactTestBitMask = PhysicsCategory.square3
    circle.physicsBody?.contactTestBitMask = PhysicsCategory.square4
    circle.physicsBody?.contactTestBitMask = PhysicsCategory.square5
    circle.physicsBody?.contactTestBitMask = PhysicsCategory.square6
    circle.physicsBody?.contactTestBitMask = PhysicsCategory.square7
    circle.physicsBody?.contactTestBitMask = PhysicsCategory.square8
    circle.physicsBody?.contactTestBitMask = PhysicsCategory.square9

        self.addChild(circle)

}

func didBegin(_ contact: SKPhysicsContact) {

    let firstBody = contact.bodyA
    let secondBody = contact.bodyB

       }

func createSquares(){
    for i in 1...9{

       // squares[i].currentState = 1

    }
    squareUnit = self.frame.width / 4

    columbs = [squareUnit / 4 + squareUnit/2, self.frame.width/2,self.frame.width - squareUnit / 4 - squareUnit / 2]
    rows = [squareUnit / 4 + squareUnit/2, self.frame.width/2,self.frame.width - squareUnit / 4 - squareUnit / 2]
    for row in rows{
        for columb in columbs{

          positions.append(CGPoint(x: columb, y: row))

        }

    }

    squares = (0...8).map { _ in square() }

    for i in (0...8){

        squares[i].node.position = positions[i]
        squares[i].node.physicsBody = SKPhysicsBody(rectangleOf: squares[i].node.size )
        squares[i].node.physicsBody?.affectedByGravity = false
        squares[i].node.physicsBody?.isDynamic = false

    }
    for square in squares {

        square.node.size = CGSize(width: squareUnit, height: squareUnit)
        square.node.color = UIColor.white
    }

    squares.forEach { self.addChild($0.node) }

}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

    for touch in touches {

        let location = touch.location(in: self)

        circle.run(SKAction.move(to: CGPoint(x: location.x, y: location.y), duration: 0.2))

    }

}

override func update(_ currentTime: TimeInterval) {
    // Called before each frame is rendered
}
}

Body:
I figured it out i just create 9 physics bodies and then add them all to an array of UInt32 and assign them each to each node.

var physics = Array<UInt32>()

struct PhysicsCategory{

    static let square1 : UInt32 = 0x1 << 1
    static let square2 : UInt32 = 0x1 << 2
    static let square3 : UInt32 = 0x1 << 3
    static let square4 : UInt32 = 0x1 << 4
    static let square5 : UInt32 = 0x1 << 5
    static let square6 : UInt32 = 0x1 << 6
    static let square7 : UInt32 = 0x1 << 7
    static let square8 : UInt32 = 0x1 << 8
    static let square9 : UInt32 = 0x1 << 9
}

override func didMove(to view: SKView) {

    physics.append(PhysicsCategory.square1)
    physics.append(PhysicsCategory.square2)
    physics.append(PhysicsCategory.square3)
    physics.append(PhysicsCategory.square4)
    physics.append(PhysicsCategory.square5)
    physics.append(PhysicsCategory.square6)
    physics.append(PhysicsCategory.square7)
    physics.append(PhysicsCategory.square8)
    physics.append(PhysicsCategory.square9)

   for i in (0...8){

        squares[i].node.physicsBody = SKPhysicsBody(rectangleOf: squares[i].node.size )
        squares[i].node.physicsBody?.categoryBitMask = physics[i]
        squares[i].node.physicsBody?.affectedByGravity = false
        squares[i].node.physicsBody?.isDynamic = false
        squares[i].node.physicsBody?.contactTestBitMask = PhysicsCategory.Circle
        squares[i].node.physicsBody?.collisionBitMask = 0

    }

}


问:
Meteor execute functions synchronously
I have code where I crop an image before save it to collection, but code executes asynchronously. Insert to collection executes before image will be cropped.

```<code>Meteor.methods({
    'createWorkout': function(workoutFormContent, fileObj) {
        // crop image to width:height = 3:2 aspect ratio
        var workoutImage = gm(fileObj.path);
        workoutImage.size(function(error, size) {
            if (error) console.log(error);
            height = size.height;
            width = size.height * 1.5;
            workoutImage
                .gravity("Center")
                .crop(width, height)
                .write(fileObj.path, function(error) {
                    if (error) console.log(error)
                });
        });

        // add image to form content and insert to collection
        workoutFormContent.workoutImage = fileObj;
        Workouts.insert(workoutFormContent, function(error) {
            if (error) {
                console.log(error);
            }
        });
    },
});
</code>```

How I can run this code synchronously to be able insert already cropped image?

答:
Write to collection only after image is cropped:

```<code>import { Meteor } from 'meteor/meteor';
import gm from 'gm';
const bound = Meteor.bindEnvironment((callback) => {callback();});
Meteor.methods({
  createWorkout(workoutFormContent, fileObj) {
    // crop image to width:height = 3:2 aspect ratio
    const workoutImage = gm(fileObj.path);
    workoutImage.size((error, size) => {
      bound(() => {
        if (error) {
          console.log(error);
          return;
        }

        const height = size.height;
        const width = size.height * 1.5;
        workoutImage.gravity('Center').crop(width, height).write(fileObj.path, (writeError) => {
          bound(() => {
            if (writeError) {
              console.log(writeError);
              return;
            }
            // add image to form content and insert to collection
            workoutFormContent.workoutImage = fileObj;
            Workouts.insert(workoutFormContent, (insertError) => {
              if (insertError) {
                console.log(insertError);
              }
            });
          });
        });
      });
    });
  }
});
</code>```

Or use Fibers/Future lib, which can be used to block event loop.

Title: Meteor execute functions synchronously

Body:
I have code where I crop an image before save it to collection, but code executes asynchronously. Insert to collection executes before image will be cropped.

Meteor.methods({
    'createWorkout': function(workoutFormContent, fileObj) {
        // crop image to width:height = 3:2 aspect ratio
        var workoutImage = gm(fileObj.path);
        workoutImage.size(function(error, size) {
            if (error) console.log(error);
            height = size.height;
            width = size.height * 1.5;
            workoutImage
                .gravity("Center")
                .crop(width, height)
                .write(fileObj.path, function(error) {
                    if (error) console.log(error)
                });
        });

        // add image to form content and insert to collection
        workoutFormContent.workoutImage = fileObj;
        Workouts.insert(workoutFormContent, function(error) {
            if (error) {
                console.log(error);
            }
        });
    },
});

How I can run this code synchronously to be able insert already cropped image?

Body:
Write to collection only after image is cropped:

import { Meteor } from 'meteor/meteor';
import gm from 'gm';
const bound = Meteor.bindEnvironment((callback) => {callback();});
Meteor.methods({
  createWorkout(workoutFormContent, fileObj) {
    // crop image to width:height = 3:2 aspect ratio
    const workoutImage = gm(fileObj.path);
    workoutImage.size((error, size) => {
      bound(() => {
        if (error) {
          console.log(error);
          return;
        }

        const height = size.height;
        const width = size.height * 1.5;
        workoutImage.gravity('Center').crop(width, height).write(fileObj.path, (writeError) => {
          bound(() => {
            if (writeError) {
              console.log(writeError);
              return;
            }
            // add image to form content and insert to collection
            workoutFormContent.workoutImage = fileObj;
            Workouts.insert(workoutFormContent, (insertError) => {
              if (insertError) {
                console.log(insertError);
              }
            });
          });
        });
      });
    });
  }
});

Or use Fibers/Future lib, which can be used to block event loop.


问:
How can I set up two navigation properties of the same type in Entity Framework
With code first EF4 (using CTP5) I can add a single navigation property along with the foreign key and it will respect the naming and only add the foreign key to the table a single time. If I then go and add a second property of the same type, it breaks it down into 4 columns on the table instead of just two.

Sample code:

With this model, I get a single property added to the AdapterFrameCapability table for PressType named PressTypeID.

```<code>public class AdapterFrameCapability
{
    [Key]
    public int AdapterFrameCapabilityID { get; set; }

    [Required]
    public int PressTypeID { get; set; }

    public virtual PressType PressType { get; set; }
}
</code>```

This is the setup I want to model, but it results in 4 columns being created in the table, one each for FromPressTypeID, FromPressTypeFromPressTypeID, ToPressTypeID and ToPressTypePressTypeID. Ideally I'd just like a column for FromPressTypeID and ToPressTypeID. What am I doing wrong here?

```<code>public class AdapterFrameCapability
{
    [Key]
    public int AdapterFrameCapabilityID { get; set; }

    [Required]
    public int FromPressTypeID { get; set; }

    [Display(Name = "From Press Type")]
    public virtual PressType FromPressType { get; set; }

    [Required]
    public int ToPressTypeID { get; set; }

    [Display(Name = "To Press Type")]
    public virtual PressType ToPressType { get; set; }
}
</code>```

答:
It's one of those scenarios that you need to drop down fluent API to get the desired schema:

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<AdapterFrameCapability>()
                .HasRequired(afc => afc.FromPressType)
                .WithMany()
                .HasForeignKey(afc => afc.FromPressTypeID)
                .WillCascadeOnDelete(true);

    modelBuilder.Entity<AdapterFrameCapability>()
                .HasRequired(afc => afc.ToPressType)
                .WithMany()
                .HasForeignKey(afc => afc.ToPressTypeID)
                .WillCascadeOnDelete(false);
}
</code>```

Switching cascade delete off on one of the associations is intentional because otherwise SQL Server would throw out the following error:

Introducing FOREIGN KEY constraint 'AdapterFrameCapability_ToPressType' on table 'AdapterFrameCapabilities' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
  Could not create constraint.

So we need to switch it off on one of the associations like the way I did in the code.

Body:
With code first EF4 (using CTP5) I can add a single navigation property along with the foreign key and it will respect the naming and only add the foreign key to the table a single time. If I then go and add a second property of the same type, it breaks it down into 4 columns on the table instead of just two.

Sample code:

With this model, I get a single property added to the AdapterFrameCapability table for PressType named PressTypeID.

public class AdapterFrameCapability
{
    [Key]
    public int AdapterFrameCapabilityID { get; set; }

    [Required]
    public int PressTypeID { get; set; }

    public virtual PressType PressType { get; set; }
}

This is the setup I want to model, but it results in 4 columns being created in the table, one each for FromPressTypeID, FromPressTypeFromPressTypeID, ToPressTypeID and ToPressTypePressTypeID. Ideally I'd just like a column for FromPressTypeID and ToPressTypeID. What am I doing wrong here?

public class AdapterFrameCapability
{
    [Key]
    public int AdapterFrameCapabilityID { get; set; }

    [Required]
    public int FromPressTypeID { get; set; }

    [Display(Name = "From Press Type")]
    public virtual PressType FromPressType { get; set; }

    [Required]
    public int ToPressTypeID { get; set; }

    [Display(Name = "To Press Type")]
    public virtual PressType ToPressType { get; set; }
}

Body:
It's one of those scenarios that you need to drop down fluent API to get the desired schema:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<AdapterFrameCapability>()
                .HasRequired(afc => afc.FromPressType)
                .WithMany()
                .HasForeignKey(afc => afc.FromPressTypeID)
                .WillCascadeOnDelete(true);

    modelBuilder.Entity<AdapterFrameCapability>()
                .HasRequired(afc => afc.ToPressType)
                .WithMany()
                .HasForeignKey(afc => afc.ToPressTypeID)
                .WillCascadeOnDelete(false);
}

Switching cascade delete off on one of the associations is intentional because otherwise SQL Server would throw out the following error:

Introducing FOREIGN KEY constraint 'AdapterFrameCapability_ToPressType' on table 'AdapterFrameCapabilities' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
  Could not create constraint.

So we need to switch it off on one of the associations like the way I did in the code.


问:
How to get details from angularFire Database and set it into a template
I am trying to get a user details from a angularFire2 database. Therefore instead of using the FirebaseListObservable, I am using FirebaseObjectObservable since I am expecting just a user from the path.

This is the path and the colums through which I am deriving the user data

```<code>  path: /projects/users/
  columns: userID,username

  data
     userID:"001",
     username:"Icomin"
</code>```

And this the home.ts

```<code>   import { Component } from '@angular/core';
   import { NavController,AlertController,ActionSheetController } from 'ionic-angular';
   import{AngularFireDatabase,FirebaseListObservable,FirebaseObjectObservable} from 'angularfire2/database';
  import {Observable} from 'rxjs/Observable';

@Component({
   selector: 'my-child-component',
   template: `<h1>Welcome {{ (projects | async)}}</h1>` // The template
})
export class HomePage{

projects: FirebaseObjectObservable <any>;

 constructor(af:AngularFireDatabase) {

      this.projects = af.object(`/projects/users`);
  }
</code>```

I implement the template below, however the returnsWelcome [object object]

The template implementation

```<code> template: `<h1>Welcome {{ (projects | async)}}</h1>`
</code>```

How do I get the user details from the above path and set it into the template

答:
As you mention , you get Welcome [object object] from projects variable. It's mean that you receive a list from this call af.object('/projects/users') .

I dont really know what exactly you want to do with that list but you few options:

1 - show all users in list :

```<code>template: ' <h1 *ngFor="let proj of projects | async">{{ proj.username }}</h1>
</code>```

this will display all user's names , one by one.

2 - show specific user:

(you need to choose the filter criteria: userID or username)

```<code>export class HomePage{
  project: FirebaseObjectObservable <any>;
  constructor(af:AngularFireDatabase) {
    this.project = af.list(`/projects/users`,{
      query: {
          orderByChild: 'userID',      //or orderByChild: 'username',
          equalTo: <someUserID>        // equalTo: <someUsername>
      }
    });
  }
}
</code>```

and then the template to display the current username:

    template:
{{ project.username }}

Hope it fits what you wanted.

Body:
I am trying to get a user details from a angularFire2 database. Therefore instead of using the FirebaseListObservable, I am using FirebaseObjectObservable since I am expecting just a user from the path.

This is the path and the colums through which I am deriving the user data

  path: /projects/users/
  columns: userID,username

  data
     userID:"001",
     username:"Icomin"

And this the home.ts

   import { Component } from '@angular/core';
   import { NavController,AlertController,ActionSheetController } from 'ionic-angular';
   import{AngularFireDatabase,FirebaseListObservable,FirebaseObjectObservable} from 'angularfire2/database';
  import {Observable} from 'rxjs/Observable';

@Component({
   selector: 'my-child-component',
   template: `<h1>Welcome {{ (projects | async)}}</h1>` // The template
})
export class HomePage{

projects: FirebaseObjectObservable <any>;

 constructor(af:AngularFireDatabase) {

      this.projects = af.object(`/projects/users`);
  }

I implement the template below, however the returnsWelcome [object object]

The template implementation

 template: `<h1>Welcome {{ (projects | async)}}</h1>`

How do I get the user details from the above path and set it into the template

Body:
As you mention , you get Welcome [object object] from projects variable. It's mean that you receive a list from this call af.object('/projects/users') .

I dont really know what exactly you want to do with that list but you few options:

1 - show all users in list :

template: ' <h1 *ngFor="let proj of projects | async">{{ proj.username }}</h1>

this will display all user's names , one by one.

2 - show specific user:

(you need to choose the filter criteria: userID or username)

export class HomePage{
  project: FirebaseObjectObservable <any>;
  constructor(af:AngularFireDatabase) {
    this.project = af.list(`/projects/users`,{
      query: {
          orderByChild: 'userID',      //or orderByChild: 'username',
          equalTo: <someUserID>        // equalTo: <someUsername>
      }
    });
  }
}

and then the template to display the current username:

    template:  <h1>{{ project.username }}</h1>

Hope it fits what you wanted.


问:
BottomNavigationView Back button not working properly

When is press back button my fragment is changing to home page, but bottom icon is not changing. I posted my all code here. If i select more then two navigation button from bottom navigation view items then when i press back button it'll redirect to last selected button item.

But now what happening is that suppose i'm on the last item say 'Notification' [as you can see in screenshot], now when i press back button it'll directly take me to 'Home' button, but what i want is that it should take me first to 'Search' button item and then to 'Home' not directly to 'home'.

How can i achieve this??

Here is the layout:

```<code> <?xml version="1.0" encoding="utf-8"?>
            <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                xmlns:design="http://schemas.android.com/apk/res-auto"
                android:id="@+id/activity_main"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                tools:context="com.segunfamisa.sample.bottomnav.MainActivity">

                <FrameLayout
                    android:id="@+id/container"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="1"
                    android:background="#f1f1f1">

                </FrameLayout>

                <android.support.design.widget.BottomNavigationView
                    android:id="@+id/navigation"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="start"
                    design:menu="@menu/bottom_nav_items" />
            </LinearLayout>
</code>```

Here is the activity:

```<code>    public class MainActivity extends AppCompatActivity {
    private static final String SELECTED_ITEM = "arg_selected_item";

    private BottomNavigationView mBottomNav;
    private int mSelectedItem;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mBottomNav = (BottomNavigationView) findViewById(R.id.navigation);
        mBottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                selectFragment(item);
                return true;
            }
        });

        MenuItem selectedItem;
        if (savedInstanceState != null) {
            mSelectedItem = savedInstanceState.getInt(SELECTED_ITEM, 0);
            selectedItem = mBottomNav.getMenu().findItem(mSelectedItem);
        } else
        {
            selectedItem = mBottomNav.getMenu().getItem(0);
        }

        selectFragment(selectedItem);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt(SELECTED_ITEM, mSelectedItem);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onBackPressed() {
        MenuItem homeItem = mBottomNav.getMenu().getItem(0);

        if (mSelectedItem != homeItem.getItemId()) {
            // select home item
           // homeItem.setCheckable(true);

            Log.d("backpressids","****  "+mSelectedItem);
            selectFragment(homeItem);

        } else {

            super.onBackPressed();

        }
    }

    private void selectFragment(MenuItem item) {
        Fragment frag = null;
        item.setCheckable(true);
        // init corresponding fragment
        switch (item.getItemId()) {
            case R.id.menu_home:

                TabFragmentOne fragmentone = new TabFragmentOne();
                FragmentTransaction ft =  getSupportFragmentManager().beginTransaction();
                ft.replace(R.id.container, fragmentone);
                ft.commit();

                break;
            case R.id.menu_notifications:

                TabFragmentThree fragmentone_Three = new TabFragmentThree();
                FragmentTransaction ft_three =  getSupportFragmentManager().beginTransaction();
                ft_three.replace(R.id.container, fragmentone_Three);
                ft_three.commit();

                break;
            case R.id.menu_search:

                TabFragmentTwo tabFragmentTwo = new TabFragmentTwo();
                FragmentTransaction ft_two =  getSupportFragmentManager().beginTransaction();
                ft_two.replace(R.id.container,tabFragmentTwo);
                ft_two.commit();

                break;
        }

        // update selected item
        mSelectedItem = item.getItemId();

        updateToolbarText(item.getTitle());

        if (frag != null) {
            TabFragmentOne fragmentone = new TabFragmentOne();
            FragmentTransaction ft =  getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.container, fragmentone);
            ft.commit();
        }
    }

    private void updateToolbarText(CharSequence text) {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle(text);
        }
    }

}
</code>```

please help me any one.....

答:
You can use BottomNavigationView.setSelectedItemId(ITEM_ID) to select desired MenuItem:

In onBackPressed(), use mBottomNav.setSelectedItemId(R.id.menu_home) or mBottomNav.setSelectedItemId(homeItem.getItemId()).

Update onBackPressed() method as below:

```<code>@Override
public void onBackPressed() {
    MenuItem homeItem = mBottomNav.getMenu().getItem(0);

    if (mSelectedItem != homeItem.getItemId()) {

        selectFragment(homeItem);

        // Select home item
        mBottomNav.setSelectedItemId(homeItem.getItemId());
    } else {
        super.onBackPressed();
    }
}
</code>```

Hope this will help~

Body:
When is press back button my fragment is changing to home page, but bottom icon is not changing. I posted my all code here. If i select more then two navigation button from bottom navigation view items then when i press back button it'll redirect to last selected button item.

But now what happening is that suppose i'm on the last item say 'Notification' [as you can see in screenshot], now when i press back button it'll directly take me to 'Home' button, but what i want is that it should take me first to 'Search' button item and then to 'Home' not directly to 'home'.

How can i achieve this??

Here is the layout:

 <?xml version="1.0" encoding="utf-8"?>
            <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                xmlns:design="http://schemas.android.com/apk/res-auto"
                android:id="@+id/activity_main"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                tools:context="com.segunfamisa.sample.bottomnav.MainActivity">

                <FrameLayout
                    android:id="@+id/container"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="1"
                    android:background="#f1f1f1">

                </FrameLayout>

                <android.support.design.widget.BottomNavigationView
                    android:id="@+id/navigation"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="start"
                    design:menu="@menu/bottom_nav_items" />
            </LinearLayout>

Here is the activity:

    public class MainActivity extends AppCompatActivity {
    private static final String SELECTED_ITEM = "arg_selected_item";

    private BottomNavigationView mBottomNav;
    private int mSelectedItem;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mBottomNav = (BottomNavigationView) findViewById(R.id.navigation);
        mBottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                selectFragment(item);
                return true;
            }
        });

        MenuItem selectedItem;
        if (savedInstanceState != null) {
            mSelectedItem = savedInstanceState.getInt(SELECTED_ITEM, 0);
            selectedItem = mBottomNav.getMenu().findItem(mSelectedItem);
        } else
        {
            selectedItem = mBottomNav.getMenu().getItem(0);
        }

        selectFragment(selectedItem);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt(SELECTED_ITEM, mSelectedItem);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onBackPressed() {
        MenuItem homeItem = mBottomNav.getMenu().getItem(0);

        if (mSelectedItem != homeItem.getItemId()) {
            // select home item
           // homeItem.setCheckable(true);

            Log.d("backpressids","****  "+mSelectedItem);
            selectFragment(homeItem);

        } else {

            super.onBackPressed();

        }
    }

    private void selectFragment(MenuItem item) {
        Fragment frag = null;
        item.setCheckable(true);
        // init corresponding fragment
        switch (item.getItemId()) {
            case R.id.menu_home:

                TabFragmentOne fragmentone = new TabFragmentOne();
                FragmentTransaction ft =  getSupportFragmentManager().beginTransaction();
                ft.replace(R.id.container, fragmentone);
                ft.commit();

                break;
            case R.id.menu_notifications:

                TabFragmentThree fragmentone_Three = new TabFragmentThree();
                FragmentTransaction ft_three =  getSupportFragmentManager().beginTransaction();
                ft_three.replace(R.id.container, fragmentone_Three);
                ft_three.commit();

                break;
            case R.id.menu_search:

                TabFragmentTwo tabFragmentTwo = new TabFragmentTwo();
                FragmentTransaction ft_two =  getSupportFragmentManager().beginTransaction();
                ft_two.replace(R.id.container,tabFragmentTwo);
                ft_two.commit();

                break;
        }

        // update selected item
        mSelectedItem = item.getItemId();

        updateToolbarText(item.getTitle());

        if (frag != null) {
            TabFragmentOne fragmentone = new TabFragmentOne();
            FragmentTransaction ft =  getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.container, fragmentone);
            ft.commit();
        }
    }

    private void updateToolbarText(CharSequence text) {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle(text);
        }
    }

}

please help me any one.....

Body:
You can use BottomNavigationView.setSelectedItemId(ITEM_ID) to select desired MenuItem:

In onBackPressed(), use mBottomNav.setSelectedItemId(R.id.menu_home) or mBottomNav.setSelectedItemId(homeItem.getItemId()).

Update onBackPressed() method as below:

@Override
public void onBackPressed() {
    MenuItem homeItem = mBottomNav.getMenu().getItem(0);

    if (mSelectedItem != homeItem.getItemId()) {

        selectFragment(homeItem);

        // Select home item
        mBottomNav.setSelectedItemId(homeItem.getItemId());
    } else {
        super.onBackPressed();
    }
}

Hope this will help~


问:
Map-ing over ConduitM?
How can I implement the following in Conduit?

Given a conduit whose input is of type a and output is of type b, output a new conduit that returns a type of c, i.e. rather than b.

g :: Monad m => ConduitM a b m () -> (b -> c) -> ConduitM a c m ()

答:
Looking at the docs, this is just mapOutput, right?

https://www.stackage.org/haddock/lts-8.13/conduit-1.2.10/Data-Conduit.html#t:mapOutput

Title: Map-ing over ConduitM?


问:
How do I disable the GNOME desktop screen lock?
How do I stop my GNOME desktop from locking the screen after a few minutes of idle time?

I already tried the official manual at Red Hat and tried to use gconf-editor and gconftool-2 to set /apps/panel/global/disable_log_out and
/apps/panel/global/disable_lock_screen. No luck.

答:
On newer distributions of Linux, like Red Hat and CentOS 7, which run GNOME 3.x you'll want to disable this via the gsettings utility rather than gconftool-2. The default is 5 minutes before the system is considered idle. Setting the value to 0 disables this.

```<code>gsettings set org.gnome.desktop.session idle-delay 0
</code>```

This setting can also be made in the GUI dconf-editor from a logged in session of the user in question.

From the standard System Tools → Settings application, there is also a "Blank Screen" option in the power settings which may provide the same behavior as the gsettings command given previously. In my testing, setting the "Screen Lock" to "Off" in the privacy settings DID NOT disable the screen blanking after 5 minutes.

On a final note, you cannot run that gsettings command from a remote SSH session without getting errors. See the last reference link below.

It was quite a research effort to get this disabled on my virtual machine!

References:

https://superuser.com/questions/727120/make-gnome-screen-lock-after-1-hour-not-15-minutes

https://askubuntu.com/questions/22313/what-is-dconf-what-is-its-function-and-how-do-i-use-it

https://superuser.com/questions/444896/gnome-settings-gsettings-vs-gconftool-2

https://askubuntu.com/questions/323776/gsettings-not-working-over-ssh

Body:
On newer distributions of Linux, like Red Hat and CentOS 7, which run GNOME 3.x you'll want to disable this via the gsettings utility rather than gconftool-2. The default is 5 minutes before the system is considered idle. Setting the value to 0 disables this.

gsettings set org.gnome.desktop.session idle-delay 0

This setting can also be made in the GUI dconf-editor from a logged in session of the user in question.

From the standard System Tools → Settings application, there is also a "Blank Screen" option in the power settings which may provide the same behavior as the gsettings command given previously. In my testing, setting the "Screen Lock" to "Off" in the privacy settings DID NOT disable the screen blanking after 5 minutes.

On a final note, you cannot run that gsettings command from a remote SSH session without getting errors. See the last reference link below.

It was quite a research effort to get this disabled on my virtual machine!

References:

https://superuser.com/questions/727120/make-gnome-screen-lock-after-1-hour-not-15-minutes

https://askubuntu.com/questions/22313/what-is-dconf-what-is-its-function-and-how-do-i-use-it

https://superuser.com/questions/444896/gnome-settings-gsettings-vs-gconftool-2

https://askubuntu.com/questions/323776/gsettings-not-working-over-ssh


问:
Mathematical representation of a multidimensional array
This might me a ridiculous question.
I created mathematical model using Python and I know that I started this from the end, but I need write mathematical equations for the documentation.
The equation has multidimensional array in it.
So my question is how to present multidimensional array in mathematical way?</p>

答:
If the number of dimensions in your array is one, you can represent it as a vector, or perhaps a tuple. But this almost certainly is not what you mean by "multidimensional."

If the number of dimensions is two, you can use a matrix.

If the number of dimensions is greater than two, you can use a tensor. Here is a Wikipedia link explaining a little how tensors and multidimensional arrays are related. A search will give you many more such pages. Tensors include vectors and matrices, so this is the most general solution, though vectors and matrices are much more well known.


问:
How do I compare password and confirm password?
I am getting error in

```<code>final EditText etregpassword = (EditText)findViewById(R.id.etregpassword);
</code>```

I would like help with the comparison of password and confirm password and to display the error in password mismatch.

```<code>public class RegisterActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);

    final EditText etregname = (EditText)findViewById(R.id.etregname);
    final EditText etregemailid = (EditText)findViewById(R.id.etregemailid);
    final EditText etregpassword = (EditText)findViewById(R.id.etregpassword);
    final EditText etconfirmregpassword = (EditText)findViewById(R.id.etconfirmregpassword);
    final Button regbutton = (Button) findViewById(R.id.regbutton);

    regbutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            final String User_name = etregname.getText().toString();
            final String Email_id = etregemailid.getText().toString();
            final String Password = etregpassword.getText().toString();
            final String Confirm_password = etconfirmregpassword.getText().toString();

            Response.Listener<String> responseListner = new Response.Listener<String>(){

                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        boolean SUCCESS = jsonObject.getBoolean("success");

                        if(SUCCESS){
                            Intent intent = new Intent(RegisterActivity.this,LoginActivity.class);
                            RegisterActivity.this.startActivity(intent);
                        }

                        else{
                            AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
                            builder.setMessage("Register Failed")
                                .setNegativeButton("Retry",null)
                                    .create()
                                     .show();

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            };

            RegisterRequest registerRequest = new RegisterRequest(User_name,Email_id,Password,Confirm_password,responseListner);
            RequestQueue queue= Volley.newRequestQueue(RegisterActivity.this);
            queue.add(registerRequest);
        }

    });

}

}
</code>```

答:
Just compare those values:</p>

```<code>final String password = etregpassword.getText().toString();
final String confirmPassword = etconfirmregpassword.getText().toString();
if (!TextUtils.isEmpty(password) && !TextUtils.isEmpty(confirmPassword))
    {
        if(password.equals(confirmPassword))
        {
            //are equal
        }
        else {
            //are different
        }
    }
</code>```

Body:
I am getting error in

final EditText etregpassword = (EditText)findViewById(R.id.etregpassword);

I would like help with the comparison of password and confirm password and to display the error in password mismatch.

public class RegisterActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);

    final EditText etregname = (EditText)findViewById(R.id.etregname);
    final EditText etregemailid = (EditText)findViewById(R.id.etregemailid);
    final EditText etregpassword = (EditText)findViewById(R.id.etregpassword);
    final EditText etconfirmregpassword = (EditText)findViewById(R.id.etconfirmregpassword);
    final Button regbutton = (Button) findViewById(R.id.regbutton);

    regbutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            final String User_name = etregname.getText().toString();
            final String Email_id = etregemailid.getText().toString();
            final String Password = etregpassword.getText().toString();
            final String Confirm_password = etconfirmregpassword.getText().toString();

            Response.Listener<String> responseListner = new Response.Listener<String>(){

                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        boolean SUCCESS = jsonObject.getBoolean("success");

                        if(SUCCESS){
                            Intent intent = new Intent(RegisterActivity.this,LoginActivity.class);
                            RegisterActivity.this.startActivity(intent);
                        }

                        else{
                            AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
                            builder.setMessage("Register Failed")
                                .setNegativeButton("Retry",null)
                                    .create()
                                     .show();

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            };

            RegisterRequest registerRequest = new RegisterRequest(User_name,Email_id,Password,Confirm_password,responseListner);
            RequestQueue queue= Volley.newRequestQueue(RegisterActivity.this);
            queue.add(registerRequest);
        }

    });

}

}

Body:
Just compare those values:

final String password = etregpassword.getText().toString();
final String confirmPassword = etconfirmregpassword.getText().toString();
if (!TextUtils.isEmpty(password) && !TextUtils.isEmpty(confirmPassword))
    {
        if(password.equals(confirmPassword))
        {
            //are equal
        }
        else {
            //are different
        }
    }


问:
Computer simulation of the brain
I've been hunting on the net periodically for several months for an answer to this with no joy. Grateful if anyone can shed any light..

I'm interested in work that's been done on simulating the human brain. I could of course mean many things by that. Here's what I do mean, followed by what I don't mean:

I AM interested in simulations of how we think and feel. I'm not talking about down to the level of neurons, but more simulation of the larger modules that are involved. For example one might simulate the 'anger' module as a service that measures the degree one has been disrespected (in some system of representation) and outputs an appropriate measure of anger (again in some system of representation).

I am NOT interested in projects like the Blue Brain etc, where accurate models of neuron clusters are being built. I'm interested in models operating at much higher levels of abstraction, on the level of emotional modules, cognitive reasoning systems etc.

I'm also NOT interested in AI projects that take as their inspiration or paradigm human mechanisms, like Belief-Desire-Intention systems, but which are not actually trying to replicate human behavior. Interesting though these systems are, I'm not interested in making effective systems, but effectively modelling human thought and emotion.

I've been searching far and wide, but all I've found are papers from the 60s like this one:
 Computer Simulation of Human Interaction in Small Groups

It almost appears to me as if psychologists were excited by simulating brains when computers were first available, but now don't do it at all?

Can anyone point me in the direction of more recent research/efforts, if there have been any?

答:
you should take a look into neural networks if you haven't already.

http://en.wikipedia.org/wiki/Neural_network

Title: Computer simulation of the brain


问:
Viewport meta tag not working in iPhone and Android
I am using the following html code

```<code><!DOCTYPE HTML>
  <html>
    <head>
     <title>test</title>
      <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
      <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
    </head>
    <body>
    test
    </body>
  </html>
</code>```

My intention is to prevent user from zooming in or out. The above code isn't working in iPhone and Android. Any solution ?

EDIT: It appears in iPhone settings, if Zoom is selected as On under Settings>Accessibility>Zoom, then this will override meta tag. Source

Not sure why it is happening in android.

答: Some time you need to add -webkit-flex:1 to containers (if flexbox in use ofcourse). That is helped me with my viewport problem.</p>

Body:
I am using the following html code

<!DOCTYPE HTML>

     <title>test</title>
      <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
      <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>

    test

My intention is to prevent user from zooming in or out. The above code isn't working in iPhone and Android. Any solution ?

EDIT: It appears in iPhone settings, if Zoom is selected as On under Settings>Accessibility>Zoom, then this will override meta tag. Source

Not sure why it is happening in android.


问:
Return first word in sentence?
Heres the question I have to answer for school

For the purposes of this question, we will define a word as ending a sentence if that word is immediately followed by a period. For example, in the text “This is a sentence. The last sentence had four words.”, the ending words are ‘sentence’ and ‘words’. In a similar fashion, we will define the starting word of a sentence as any word that is preceded by the end of a sentence. The starting words from the previous example text would be “The”. You do not need to consider the first word of the text as a starting word. Write a program that has:

An endwords function that takes a single string argument. This functioin must return a list of all sentence ending words that appear in the given string. There should be no duplicate entries in the returned list and the periods should not be included in the ending words.

The code I have so far is:

```<code>def startwords(astring):
    mylist = astring.split()
    if mylist.endswith('.') == True:
        return my list
</code>```

but I don't know if I'm using the right approach. I need some help

答:
```<code>mylist = astring.split()
if mylist.endswith('.')
</code>```

that cannot work, one of the reasons being that mylist is a list, and doesn't have endswith as a method.

Another answer fixed your approach so let me propose a regular expression solution:

```<code>import re

print(re.findall(r"\.\s*(\w+)","This is a sentence. The last sentence had four words."))
</code>```

match all words following a dot and optional spaces

result: ['The']

Title: Return first word in sentence?

Body:
Heres the question I have to answer for school

For the purposes of this question, we will define a word as ending a sentence if that word is immediately followed by a period. For example, in the text “This is a sentence. The last sentence had four words.”, the ending words are ‘sentence’ and ‘words’. In a similar fashion, we will define the starting word of a sentence as any word that is preceded by the end of a sentence. The starting words from the previous example text would be “The”. You do not need to consider the first word of the text as a starting word. Write a program that has:

An endwords function that takes a single string argument. This functioin must return a list of all sentence ending words that appear in the given string. There should be no duplicate entries in the returned list and the periods should not be included in the ending words.

The code I have so far is:

def startwords(astring):
    mylist = astring.split()
    if mylist.endswith('.') == True:
        return my list

but I don't know if I'm using the right approach. I need some help

Body:
mylist = astring.split()
if mylist.endswith('.')

that cannot work, one of the reasons being that mylist is a list, and doesn't have endswith as a method.

Another answer fixed your approach so let me propose a regular expression solution:

import re

print(re.findall(r"\.\s*(\w+)","This is a sentence. The last sentence had four words."))

match all words following a dot and optional spaces

result: ['The']


问:
Stripping JSON encoding of PHP array
I have a MySQL query done using PHP, result is presented as array.

```<code>$stmt = $mysqli->prepare("SELECT word FROM words ORDER BY RAND() LIMIT 5");
    $stmt->bind_result($words);

$stmt->execute();
$result = array();

while ($stmt->fetch()) {
    $w = new StdClass();
    $w->word = $words;
    array_push($result, $w);
}
$stmt->close();
</code>```

Then, i'm passing the array to javascript using JSON:

```<code>'words' : <?php echo json_encode($result); ?>,
</code>```

But the output is:

```<code>[{"word":"Watermelon"},{"word":"Orange"},{"word":"Melon"},{"word":"Cucumber"},{"word":"Apple"}]
</code>```

Is there any way to "strip" the "word" and make it look like that?

```<code>["Watermelon", "Orange", "Melon", "Cucumber", "Apple"]
</code>```

Thank you in advance.

答:
If you don't need array of objects ($ws) further in your code, you can simplify your code to:

```<code>$stmt = $mysqli->prepare("SELECT word FROM words ORDER BY RAND() LIMIT 5");
$stmt->bind_result($words);

$stmt->execute();
$result = array();

while ($stmt->fetch()) {
    array_push($result, $words);
}
$stmt->close();
</code>```

Title: Stripping JSON encoding of PHP array

Body:
I have a MySQL query done using PHP, result is presented as array.

$stmt = $mysqli->prepare("SELECT word FROM words ORDER BY RAND() LIMIT 5");
    $stmt->bind_result($words);

$stmt->execute();
$result = array();

while ($stmt->fetch()) {
    $w = new StdClass();
    $w->word = $words;
    array_push($result, $w);
}
$stmt->close();

Then, i'm passing the array to javascript using JSON:

'words' : <?php echo json_encode($result); ?>,

But the output is:

[{"word":"Watermelon"},{"word":"Orange"},{"word":"Melon"},{"word":"Cucumber"},{"word":"Apple"}]

Is there any way to "strip" the "word" and make it look like that?

["Watermelon", "Orange", "Melon", "Cucumber", "Apple"]

Thank you in advance.

Body:
If you don't need array of objects ($ws) further in your code, you can simplify your code to:

$stmt = $mysqli->prepare("SELECT word FROM words ORDER BY RAND() LIMIT 5");
$stmt->bind_result($words);

$stmt->execute();
$result = array();

while ($stmt->fetch()) {
    array_push($result, $words);
}
$stmt->close();