问:
Design pattern for self-referencing ordered tree of objects (C#/ASP.Net Core/EFCore)
First I apologise if I should have been able to find this myself through search... I'm rusty and learning a lot of new stuff so I'm not even sure if I'm using the right terms to describe what I want - don't kick the noob please :)

Question: Part 1 - Specific scenario
I am trying to build classes to produce a tree of "goal objects", where

a) order matters and needs to be retained,

b) each goal object in the tree may stand alone as a single object, or comprise a collection of subgoals (and those subgoals further subgoals etc - let's say to a depth of 5 levels),

c) ability to edit the tree efficiently is necessary (including changing the order or index of any goal object, adding / removing / reordering / moving  subgoals, pruning/adding branches to the tree).
I can certainly work out a way to do this, but I strongly suspect my way will be highly inefficient both in terms of memory / processing and in terms of quantity of code required to manage the editing etc.

My question therefor: Can anyone point me to a design pattern or tutorial that will show me an efficient way to do this - or something similar that I can adapt?
(I am currently working in C# & ASP.NET Core with EFCore pointing to SQLserver)

Part 2: Recommendations for a book / site that has an excellent set of fundamental design patterns suitable for C# would also be welcome.

Many thanks for any help you can offer.
Chris

答:
Sounds like you're not looking for a programming pattern, you are looking for a data structure.

Have a look at Red-Black Trees.

That is a (quasi-)balanced tree which preserves ordering of its nodes, and all operations are logarithmic (that is, efficient).


来源: stackexchange

问:
Gradle grouping dependencies
I was experimenting with my project's build.gradle. Currently my project consist of several modules, each of these module have common dependencies, such as android support or network library. I'm Experimenting with gradle dependencies.
I've declared a group of dependencies named lib_mandatory() in file lib-group.gradle, but when I tried to include it in my app's build.gradle the gradle sync failed.

```<code>Error:Could not find method lib_mandatory() for arguments [] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
</code>```

How can I fix this? or any hints about what this error means?

Update:
Here's the lib-group.gradle

```<code>def dependencyGroup(Closure closure) {
   closure.delegate = dependencies
   return closure
}
def lib_mandatory = dependencyGroup{
   implementation libraries.rxjava
   implementation libraries.rxandroid
}
</code>```

and here's the app's build.gradle

```<code>apply from: '../lib-group.gradle'
dependencies {
    lib_mandatory()
}
</code>```

答:
The approach that is used in that article is a bit different, the article used the function inside the lib-group.gradle and only applied (apply from ...) the lib-group.gradle in the app's build.gradle.

In your approach, you're trying to use the function in the app's build.gradle.

If you want your functions to be accessed from other files, you should use ext instead of def. You might want to read this:
Gradle def vs ext

ContentLicense: CC BY-SA 3.0

Title: Gradle grouping dependencies

Body:
I was experimenting with my project's build.gradle. Currently my project consist of several modules, each of these module have common dependencies, such as android support or network library. I'm Experimenting with gradle dependencies.
I've declared a group of dependencies named lib_mandatory() in file lib-group.gradle, but when I tried to include it in my app's build.gradle the gradle sync failed.

Error:Could not find method lib_mandatory() for arguments [] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

How can I fix this? or any hints about what this error means?

Update:
Here's the lib-group.gradle

def dependencyGroup(Closure closure) {
   closure.delegate = dependencies
   return closure
}
def lib_mandatory = dependencyGroup{
   implementation libraries.rxjava
   implementation libraries.rxandroid
}

and here's the app's build.gradle

apply from: '../lib-group.gradle'
dependencies {
    lib_mandatory()
}


问:
Unity Character Controller Script bug
I am using the Script from unity scripting reference :
http://docs.unity3d.com/ScriptReference/CharacterController.Move.html

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    public float speed = 6.0F;
    public float jumpSpeed = 8.0F;
    public float gravity = 20.0F;
    private Vector3 moveDirection = Vector3.zero;
    void Update() {
        CharacterController controller = GetComponent<CharacterController>();
        if (controller.isGrounded) {
            moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
            moveDirection = transform.TransformDirection(moveDirection);
            moveDirection *= speed;
            if (Input.GetButton("Jump"))
                moveDirection.y = jumpSpeed;

        }
        moveDirection.y -= gravity * Time.deltaTime;
        controller.Move(moveDirection * Time.deltaTime);
    }
}
```

But Problem is that , When I have built it its shows the following errors

Has there any solution ?

答:
This happens (also with Visual Studio) sometimes if you add a new  / move a Script inside of Unity.

The only solution I found until now is closing both Unity and the Editor, go to the Folder on your harddrive and remove the *.csproj and evtl. the *.sln files.

(In worst case you also can try to remove the Library folder it is also builded by Unity)

Then relunch Unity and the Editor. Now it should rebuild the project and parse correctly.

Title: Unity Character Controller Script bug

Body:
I am using the Script from unity scripting reference :
http://docs.unity3d.com/ScriptReference/CharacterController.Move.html

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    public float speed = 6.0F;
    public float jumpSpeed = 8.0F;
    public float gravity = 20.0F;
    private Vector3 moveDirection = Vector3.zero;
    void Update() {
        CharacterController controller = GetComponent<CharacterController>();
        if (controller.isGrounded) {
            moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
            moveDirection = transform.TransformDirection(moveDirection);
            moveDirection *= speed;
            if (Input.GetButton("Jump"))
                moveDirection.y = jumpSpeed;

        }
        moveDirection.y -= gravity * Time.deltaTime;
        controller.Move(moveDirection * Time.deltaTime);
    }
}

But Problem is that , When I have built it its shows the following errors

Has there any solution ?


问:
tkinter, button returns variable
I am trying to make a GUI text based adventure game in python. I want to be able to take text from a textinput box and store it as string variable.

I have 2 problems:

Making the python wait for the submit button to be pressed, before
processing the input and updating the game.

Getting the text variable out of the command, I would like to not
use global if possible.

Here is some of my code to better understand:

```<code>root = tk.Tk()
root.geometry('800x600+100+100')
root.title("my game")
textbox = tk.StringVar()
textboxentry = tk.Entry(root, textvariable=textbox, bd=5, width = "40",  font=("times", 20))
textboxentry.pack(in_=bgImageLabel, side = "bottom")
def getInput():
    textboxInput = textbox.get() #gets entry
    lengthEntry = len(textbox.get())
    textboxentry.delete(0,lengthEntry) #removes entry from widget
    return textboxInput # I would like this return to work

submit = tk.Button(root, text ="Submit", command = (textboxInput = getInput()))
##I want the command function to use command = getInput and store the return on getInput as textboxInput. This will update the wait_variable down below, and give the inputs(textboxInput) a string to work with.

submit.pack(in_=bgImageLabel, side = "bottom")

while game == True:
    root.update_idletasks()
    root.update()
    submit.wait_variable(textboxentry)
## I need it to wait before proceeding to this next line because i need the textboxInput from the entry widget.
    actionInput, extraInput, texts = inputs(textboxInput)
</code>```

Currently I can't figure a way to use command = (textboxInput = getInput), using lambda or anything else. I just want to store the return which comes off of the Entry as a string variable that can be used by the main function.
All help is appreciated!

答:
I think you should use inputs() inside getInputs() and then button doesn't have to return any variables - and then you can use root.mainloop() instead of while loop.

```<code>import tkinter as tk

# --- functions ---

def inputs(text):
    # do something with text
    print(text)

    # and return something
    return 'a', 'b', 'c'

def get_input():
    global action_input, extra_input, texts

    text = textbox.get()

    if text: # check if text is not empty
        textbox.set('') # remove text from entry
        #textbox_entry.delete(0, 'end') # remove text from entry
        action_input, extra_input, texts = inputs(text)

# --- main ---

root = tk.Tk()

textbox = tk.StringVar()

textbox_entry = tk.Entry(root, textvariable=textbox)
textbox_entry.pack()

submit = tk.Button(root, text="Submit", command=get_input)
submit.pack()

root.mainloop()
</code>```

BTW: you could better organize code

all functions before main part (root = tk.Tk())

PEP8 suggests to use lower_case_names for functions and variables (instead of CamelCaseNames)

global is not prefered method but I think it is better solution than yours.

If you don't need global then you can use classes with self.

```<code>import tkinter as tk

# --- classes ---

class Game:

    def __init__(self):
        self.root = tk.Tk()

        self.textbox = tk.StringVar()

        self.textbox_entry = tk.Entry(self.root, textvariable=self.textbox)
        self.textbox_entry.pack()

        self.submit = tk.Button(self.root, text="Submit", command=self.get_input)
        self.submit.pack()

    def run(self):
        self.root.mainloop()

    def inputs(self, text):
        # do something with text
        print(text)

        # and return something
        return 'a', 'b', 'c'

    def get_input(self):

        text = self.textbox.get()

        if text: # check if text is not empty
            self.textbox.set('') # remove text from entry
            #textbox_entry.delete(0, 'end') # remove text from entry
            self.action_input, self.extra_input, self.texts = self.inputs(text)

# --- functions ---

# empty

# --- main ---

app = Game()
app.run()
</code>```

Title: tkinter, button returns variable

Body:
I am trying to make a GUI text based adventure game in python. I want to be able to take text from a textinput box and store it as string variable.

I have 2 problems:

Making the python wait for the submit button to be pressed, before
processing the input and updating the game.

Getting the text variable out of the command, I would like to not
use global if possible.

Here is some of my code to better understand:

root = tk.Tk()
root.geometry('800x600+100+100')
root.title("my game")
textbox = tk.StringVar()
textboxentry = tk.Entry(root, textvariable=textbox, bd=5, width = "40",  font=("times", 20))
textboxentry.pack(in_=bgImageLabel, side = "bottom")
def getInput():
    textboxInput = textbox.get() #gets entry
    lengthEntry = len(textbox.get())
    textboxentry.delete(0,lengthEntry) #removes entry from widget
    return textboxInput # I would like this return to work

submit = tk.Button(root, text ="Submit", command = (textboxInput = getInput()))
##I want the command function to use command = getInput and store the return on getInput as textboxInput. This will update the wait_variable down below, and give the inputs(textboxInput) a string to work with.

submit.pack(in_=bgImageLabel, side = "bottom")

while game == True:
    root.update_idletasks()
    root.update()
    submit.wait_variable(textboxentry)
## I need it to wait before proceeding to this next line because i need the textboxInput from the entry widget.
    actionInput, extraInput, texts = inputs(textboxInput)

Currently I can't figure a way to use command = (textboxInput = getInput), using lambda or anything else. I just want to store the return which comes off of the Entry as a string variable that can be used by the main function.
All help is appreciated!

Body:
I think you should use inputs() inside getInputs() and then button doesn't have to return any variables - and then you can use root.mainloop() instead of while loop.

import tkinter as tk

# --- functions ---

def inputs(text):
    # do something with text
    print(text)

    # and return something
    return 'a', 'b', 'c'

def get_input():
    global action_input, extra_input, texts

    text = textbox.get()

    if text: # check if text is not empty
        textbox.set('') # remove text from entry
        #textbox_entry.delete(0, 'end') # remove text from entry
        action_input, extra_input, texts = inputs(text)

# --- main ---

root = tk.Tk()

textbox = tk.StringVar()

textbox_entry = tk.Entry(root, textvariable=textbox)
textbox_entry.pack()

submit = tk.Button(root, text="Submit", command=get_input)
submit.pack()

root.mainloop()

BTW: you could better organize code

all functions before main part (root = tk.Tk())

PEP8 suggests to use lower_case_names for functions and variables (instead of CamelCaseNames)

global is not prefered method but I think it is better solution than yours.

If you don't need global then you can use classes with self.

import tkinter as tk

# --- classes ---

class Game:

    def __init__(self):
        self.root = tk.Tk()

        self.textbox = tk.StringVar()

        self.textbox_entry = tk.Entry(self.root, textvariable=self.textbox)
        self.textbox_entry.pack()

        self.submit = tk.Button(self.root, text="Submit", command=self.get_input)
        self.submit.pack()

    def run(self):
        self.root.mainloop()

    def inputs(self, text):
        # do something with text
        print(text)

        # and return something
        return 'a', 'b', 'c'

    def get_input(self):

        text = self.textbox.get()

        if text: # check if text is not empty
            self.textbox.set('') # remove text from entry
            #textbox_entry.delete(0, 'end') # remove text from entry
            self.action_input, self.extra_input, self.texts = self.inputs(text)

# --- functions ---

# empty

# --- main ---

app = Game()
app.run()


问:
dequeueReusableCellWithIdentifier creates duplicate UITableviewcell

I am creating a page where I am using UITableView and UITableViewCell. The above shown photo is one UITableViewCell created programatically.

This UITableViewCell is getting created in cellForRowAtIndexPath where i am using tags for views and reusing views with tags whenever cellForRowAtIndexPath is called

------------------- Code for cell creation ---------------------------

```<code>NSString* reuseIdentifier = @"NameNCityCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];

    // Configure the cell...
    if (nil == cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
    }

    [self configureCell:cell withIndexPath: indexPath];
</code>```

In this UITableViewCell when we tap on city , A new controller is opened where I can select city which will reflect in the City Column in current viewcontroller.

Now The problem.

when I open the page with this cell, new cell is created but after tapping on the citycontroller and selecting city it comes to this previous controller and instead of using the same cell, it creates new . So its like one cell over another (Duplicates)

Now I again tap on citycontroller and select city, on selection when it comes to this VC and it uses the hidden view from the 2 views.

I need to know How should I do that so that two view are not created. I want to work with the same view.

Let me now if you need more details.

答:
```<code>    You are overwriting cell in a UItableview. Please use below simple 1 line of code.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

         YourtableViewCellName *cell = (YourtableViewCellName *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];

            cell.profilePic.image = [UIImage imageNamed:@"Image-1"]; //profilePic - image View
            cell.titleTV.text = @"Hi"; //Name
            cell.detailTV.text = @"How are you?"; //City
            return cell;
     }
</code>```

Body:
I am creating a page where I am using UITableView and UITableViewCell. The above shown photo is one UITableViewCell created programatically.

This UITableViewCell is getting created in cellForRowAtIndexPath where i am using tags for views and reusing views with tags whenever cellForRowAtIndexPath is called

------------------- Code for cell creation ---------------------------

NSString* reuseIdentifier = @"NameNCityCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];

    // Configure the cell...
    if (nil == cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
    }

    [self configureCell:cell withIndexPath: indexPath];

In this UITableViewCell when we tap on city , A new controller is opened where I can select city which will reflect in the City Column in current viewcontroller.

Now The problem.

when I open the page with this cell, new cell is created but after tapping on the citycontroller and selecting city it comes to this previous controller and instead of using the same cell, it creates new . So its like one cell over another (Duplicates)

Now I again tap on citycontroller and select city, on selection when it comes to this VC and it uses the hidden view from the 2 views.

I need to know How should I do that so that two view are not created. I want to work with the same view.

Let me now if you need more details.


问:
Cassandra driver exception "All host(s) tried for query failed" occurs every few hours without explanation
I have an issue with my Cassandra cluster (4 node cluster). Cassandra version is 2.2.9 and driver version is 3.0.3.

After a couple of hours (~ 3 hours) I see the following issues in the driver log:

OutOfDirectMemoryError (Occurs sporadic and most of the time without impact)

No protocol version matching integer version

Unknown response opcode

Heartbeat query timed out

All host(s) tried for query failed --> Can't query Cassandra anymore

The Cassandra cluster is healthy and when I restart the app everything works again for a couple of hours.

Log snippet:

```<code>First Time                       Count  Message
2017-11-11 19:03:03 +0100            51  [/??.???.??.??:????] preparing to open ? new connections, total = ???
2017-11-11 19:03:03 +0100            49  [/??.???.??.??:????] Connection[/??.???.??.??:????-???, inFlight=?, closed=false] Transport initialized, connection ready
2017-11-11 19:03:03 +0100            24  [/??.???.??.??:????] Connection[/??.???.??.??:????-???, inFlight=?, closed=true] closed, remaining = ???
2017-11-11 19:03:29 +0100             1  Defuncting Connection[/??.???.??.??:????-???, inFlight=???, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: io.netty.util.internal.OutOfDirectMemoryError: failed to allocate ??????? byte(s) of direct memory (used: ???????, max: ????????))
2017-11-11 19:03:29 +0100            14  [/??.???.??.??:????] Connection[/??.???.??.??:????-???, inFlight=???, closed=false] failed, remaining = ???
2017-11-11 19:03:29 +0100             7  [/??.???.??.??:????] Connection[/??.???.??.??:????-???, inFlight=??, closed=false] failed, remaining = ???
2017-11-11 19:03:29 +0100             1  Defuncting Connection[/??.???.??.??:????-???, inFlight=??, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: java.lang.IllegalArgumentException: No protocol version matching integer version ?)
2017-11-11 19:03:29 +0100             5  Defuncting Connection[/??.???.??.??:????-???, inFlight=??, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: com.datastax.driver.core.exceptions.DriverInternalError: Unknown response opcode ??)
2017-11-11 19:03:29 +0100             4  Defuncting Connection[/??.???.??.??:????-???, inFlight=???, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: com.datastax.driver.core.exceptions.DriverInternalError: Unknown response opcode ?)
2017-11-11 19:03:29 +0100             3  Defuncting Connection[/??.???.??.??:????-???, inFlight=???, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: com.datastax.driver.core.exceptions.DriverInternalError: Unknown response opcode -???)
2017-11-11 19:03:30 +0100             3  Defuncting Connection[/??.???.??.??:????-???, inFlight=???, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: com.datastax.driver.core.exceptions.DriverInternalError: Unknown response opcode ??)
2017-11-11 19:03:30 +0100             2  Defuncting Connection[/??.???.??.??:????-???, inFlight=?, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: com.datastax.driver.core.exceptions.DriverInternalError: Unknown response opcode ??)
2017-11-11 19:03:30 +0100           401  [/??.???.??.??:????] Connection[/??.???.??.??:????-???, inFlight=?, closed=false] failed, remaining = ???
2017-11-11 19:03:33 +0100             1  Defuncting Connection[/??.???.??.??:????-???, inFlight=???, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: com.datastax.driver.core.exceptions.DriverInternalError: Unknown response opcode ???)
2017-11-11 19:03:41 +0100           722  Defuncting Connection[/??.???.??.??:????-???, inFlight=?, closed=false] because: [/??.???.??.??:????] Heartbeat query timed out
2017-11-11 19:03:41 +0100             8  [/??.???.??.??:????] Connection[/??.???.??.??:????-?, inFlight=?, closed=false] failed, remaining = ???
2017-11-11 19:03:41 +0100            11  Defuncting Connection[/??.???.??.??:????-?, inFlight=?, closed=false] because: [/??.???.??.??:????] Heartbeat query timed out
2017-11-11 19:03:41 +0100            67  [/??.???.??.??:????] Connection[/??.???.??.??:????-??, inFlight=?, closed=false] failed, remaining = ???
2017-11-11 19:03:41 +0100           115  Defuncting Connection[/??.???.??.??:????-??, inFlight=?, closed=false] because: [/??.???.??.??:????] Heartbeat query timed out
2017-11-11 19:03:44 +0100             2  Defuncting Connection[/??.???.??.??:????-???, inFlight=??, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: com.datastax.driver.core.exceptions.DriverInternalError: Unknown response opcode ?)
2017-11-11 19:03:51 +0100             2  Defuncting Connection[/??.???.??.??:????-???, inFlight=???, closed=false] because: [/??.???.??.??:????] Heartbeat query timed out
2017-11-11 19:03:51 +0100           265  Failed to post timeseries data Error Returned -
2017-11-11 19:03:57 +0100             3  Defuncting Connection[/??.???.??.??:????-???, inFlight=??, closed=false] because: [/??.???.??.??:????] Heartbeat query timed out
2017-11-11 19:04:01 +0100            39  Defuncting Connection[/??.???.??.??:????-???, inFlight=?, closed=false] because: [/??.???.??.??:????] Operation timed out
2017-11-11 19:04:01 +0100            12  Error processing jobs: execution of statement failed:All host(s) tried for query failed (tried: /??.???.??.??:???? (com.datastax.driver.core.exceptions.DriverException: Timeout while trying to acquire available connection (you may want to increase the driver number of per-host connections)), /??.???.??.??:???? (com.datastax.driver.core.exceptions.DriverException: Timeout while trying to acquire available connection (you may want to increase the driver number of per-host connections)), /??.???.??.??:???? (com.datastax.driver.core.exceptions.DriverException: Timeout while trying to acquire available connection (you may want to increase the driver number of per-host connections)), /??.???.??.??:???? [only showing errors of first ? hosts, use getErrors() for more details])
</code>```

Does somebody have an idea what could be the root cause?

答:
```<code>Defuncting Connection[/??.???.??.??:????-???, inFlight=???, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: io.netty.util.internal.OutOfDirectMemoryError: failed to allocate ??????? byte(s) of direct memory (used: ???????, max: ????????))
</code>```

You have some memory issues. You can't expect the driver to work properly as long as these issues exists. You also say that your application stops working after a couple of hours. To me it sounds like you have memory leaks in your application.

Body:
I have an issue with my Cassandra cluster (4 node cluster). Cassandra version is 2.2.9 and driver version is 3.0.3.

After a couple of hours (~ 3 hours) I see the following issues in the driver log:

OutOfDirectMemoryError (Occurs sporadic and most of the time without impact)

No protocol version matching integer version

Unknown response opcode

Heartbeat query timed out

All host(s) tried for query failed --> Can't query Cassandra anymore

The Cassandra cluster is healthy and when I restart the app everything works again for a couple of hours.

Log snippet:

First Time                       Count  Message
2017-11-11 19:03:03 +0100            51  [/??.???.??.??:????] preparing to open ? new connections, total = ???
2017-11-11 19:03:03 +0100            49  [/??.???.??.??:????] Connection[/??.???.??.??:????-???, inFlight=?, closed=false] Transport initialized, connection ready
2017-11-11 19:03:03 +0100            24  [/??.???.??.??:????] Connection[/??.???.??.??:????-???, inFlight=?, closed=true] closed, remaining = ???
2017-11-11 19:03:29 +0100             1  Defuncting Connection[/??.???.??.??:????-???, inFlight=???, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: io.netty.util.internal.OutOfDirectMemoryError: failed to allocate ??????? byte(s) of direct memory (used: ???????, max: ????????))
2017-11-11 19:03:29 +0100            14  [/??.???.??.??:????] Connection[/??.???.??.??:????-???, inFlight=???, closed=false] failed, remaining = ???
2017-11-11 19:03:29 +0100             7  [/??.???.??.??:????] Connection[/??.???.??.??:????-???, inFlight=??, closed=false] failed, remaining = ???
2017-11-11 19:03:29 +0100             1  Defuncting Connection[/??.???.??.??:????-???, inFlight=??, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: java.lang.IllegalArgumentException: No protocol version matching integer version ?)
2017-11-11 19:03:29 +0100             5  Defuncting Connection[/??.???.??.??:????-???, inFlight=??, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: com.datastax.driver.core.exceptions.DriverInternalError: Unknown response opcode ??)
2017-11-11 19:03:29 +0100             4  Defuncting Connection[/??.???.??.??:????-???, inFlight=???, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: com.datastax.driver.core.exceptions.DriverInternalError: Unknown response opcode ?)
2017-11-11 19:03:29 +0100             3  Defuncting Connection[/??.???.??.??:????-???, inFlight=???, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: com.datastax.driver.core.exceptions.DriverInternalError: Unknown response opcode -???)
2017-11-11 19:03:30 +0100             3  Defuncting Connection[/??.???.??.??:????-???, inFlight=???, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: com.datastax.driver.core.exceptions.DriverInternalError: Unknown response opcode ??)
2017-11-11 19:03:30 +0100             2  Defuncting Connection[/??.???.??.??:????-???, inFlight=?, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: com.datastax.driver.core.exceptions.DriverInternalError: Unknown response opcode ??)
2017-11-11 19:03:30 +0100           401  [/??.???.??.??:????] Connection[/??.???.??.??:????-???, inFlight=?, closed=false] failed, remaining = ???
2017-11-11 19:03:33 +0100             1  Defuncting Connection[/??.???.??.??:????-???, inFlight=???, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: com.datastax.driver.core.exceptions.DriverInternalError: Unknown response opcode ???)
2017-11-11 19:03:41 +0100           722  Defuncting Connection[/??.???.??.??:????-???, inFlight=?, closed=false] because: [/??.???.??.??:????] Heartbeat query timed out
2017-11-11 19:03:41 +0100             8  [/??.???.??.??:????] Connection[/??.???.??.??:????-?, inFlight=?, closed=false] failed, remaining = ???
2017-11-11 19:03:41 +0100            11  Defuncting Connection[/??.???.??.??:????-?, inFlight=?, closed=false] because: [/??.???.??.??:????] Heartbeat query timed out
2017-11-11 19:03:41 +0100            67  [/??.???.??.??:????] Connection[/??.???.??.??:????-??, inFlight=?, closed=false] failed, remaining = ???
2017-11-11 19:03:41 +0100           115  Defuncting Connection[/??.???.??.??:????-??, inFlight=?, closed=false] because: [/??.???.??.??:????] Heartbeat query timed out
2017-11-11 19:03:44 +0100             2  Defuncting Connection[/??.???.??.??:????-???, inFlight=??, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: com.datastax.driver.core.exceptions.DriverInternalError: Unknown response opcode ?)
2017-11-11 19:03:51 +0100             2  Defuncting Connection[/??.???.??.??:????-???, inFlight=???, closed=false] because: [/??.???.??.??:????] Heartbeat query timed out
2017-11-11 19:03:51 +0100           265  Failed to post timeseries data Error Returned -
2017-11-11 19:03:57 +0100             3  Defuncting Connection[/??.???.??.??:????-???, inFlight=??, closed=false] because: [/??.???.??.??:????] Heartbeat query timed out
2017-11-11 19:04:01 +0100            39  Defuncting Connection[/??.???.??.??:????-???, inFlight=?, closed=false] because: [/??.???.??.??:????] Operation timed out
2017-11-11 19:04:01 +0100            12  Error processing jobs: execution of statement failed:All host(s) tried for query failed (tried: /??.???.??.??:???? (com.datastax.driver.core.exceptions.DriverException: Timeout while trying to acquire available connection (you may want to increase the driver number of per-host connections)), /??.???.??.??:???? (com.datastax.driver.core.exceptions.DriverException: Timeout while trying to acquire available connection (you may want to increase the driver number of per-host connections)), /??.???.??.??:???? (com.datastax.driver.core.exceptions.DriverException: Timeout while trying to acquire available connection (you may want to increase the driver number of per-host connections)), /??.???.??.??:???? [only showing errors of first ? hosts, use getErrors() for more details])

Does somebody have an idea what could be the root cause?

Body:
Defuncting Connection[/??.???.??.??:????-???, inFlight=???, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: io.netty.util.internal.OutOfDirectMemoryError: failed to allocate ??????? byte(s) of direct memory (used: ???????, max: ????????))

You have some memory issues. You can't expect the driver to work properly as long as these issues exists. You also say that your application stops working after a couple of hours. To me it sounds like you have memory leaks in your application.


问:
How to encrypt or decrypt with Rijndael and a block-size of 256 bits?
For certain reasons I need to implement Rijndael de/compression with a blocksize of 256 bits instead of AES which uses a block size of 128 bits (reason: data is encrypted in PHP using Rijndael...).

How can I change the block-size for a cipher?

If i just get a cipher with "RIJNDAEL/CFB/PKCS5Padding" and try to initialize a IV with 256 bits I get an exception, because the block-size is only 128 bits.

答:
Note that PHP mcrypt uses Zero Byte padding so new ZeroBytePadding() should be used instead of new PKCS7Padding().

Bellow a full implementation using CBC and RIJNDAEL 256.

import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.RijndaelEngine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.paddings.ZeroBytePadding;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.bouncycastle.util.encoders.Base64;

public static String encryptWithAesCBC(String plaintext, String key, String iv)
{
    try {
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new RijndaelEngine(256)), new ZeroBytePadding());
        CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key.getBytes()), iv.getBytes());
        cipher.init(true, ivAndKey);
        return new String(Base64.encode(cipherData(cipher, plaintext.getBytes())));
    } catch (InvalidCipherTextException e) {
        throw new RuntimeException(e);
    }
}

public static String decryptWithAesCBC(String encrypted, String key, String iv)
{
    try {
        byte[] ciphertext = Base64.decode(encrypted);
        PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(new RijndaelEngine(256)), new ZeroBytePadding());

        CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key.getBytes()), iv.getBytes());
        aes.init(false, ivAndKey);
        return new String(cipherData(aes, ciphertext));
    } catch (InvalidCipherTextException e) {
        throw new RuntimeException(e);
    }
}

private static byte[] cipherData(PaddedBufferedBlockCipher cipher, byte[] data) throws InvalidCipherTextException
{
    int minSize = cipher.getOutputSize(data.length);
    byte[] outBuf = new byte[minSize];
    int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0);
    int length2 = cipher.doFinal(outBuf, length1);
    int actualLength = length1 + length2;
    byte[] cipherArray = new byte[actualLength];
    for (int x = 0; x < actualLength; x++) {
        cipherArray[x] = outBuf[x];
    }
    return cipherArray;
}

 private String md5(String string)
 {
    try {
        java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
        byte[] array = md.digest(string.getBytes());
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < array.length; ++i) {
            sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString();
    } catch (java.security.NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}
```

<p>When using CFB, <code>PaddedBufferedBlockCipher</code> should be replace by the following:</p>

<pre class="lang-java prettyprint-override"><code>PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CFBBlockCipher(new RijndaelEngine(256),8), new ZeroBytePadding());
// PHP mcrypt uses a blocksize of 8 bit for CFB
</code>```

Usage:

String salt = "fbhweui3497";
String key = md5(salt);
String iv = md5(md5(salt));

String encrypted = encryptWithAesCBC("text to encript", key, iv);

String decrypted = decryptWithAesCBC(encrypted, key, iv);
```

Body:
Note that PHP mcrypt uses Zero Byte padding so new ZeroBytePadding() should be used instead of new PKCS7Padding().

Bellow a full implementation using CBC and RIJNDAEL 256.

import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.RijndaelEngine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.paddings.ZeroBytePadding;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.bouncycastle.util.encoders.Base64;

public static String encryptWithAesCBC(String plaintext, String key, String iv)
{
    try {
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new RijndaelEngine(256)), new ZeroBytePadding());
        CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key.getBytes()), iv.getBytes());
        cipher.init(true, ivAndKey);
        return new String(Base64.encode(cipherData(cipher, plaintext.getBytes())));
    } catch (InvalidCipherTextException e) {
        throw new RuntimeException(e);
    }
}

public static String decryptWithAesCBC(String encrypted, String key, String iv)
{
    try {
        byte[] ciphertext = Base64.decode(encrypted);
        PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(new RijndaelEngine(256)), new ZeroBytePadding());

        CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key.getBytes()), iv.getBytes());
        aes.init(false, ivAndKey);
        return new String(cipherData(aes, ciphertext));
    } catch (InvalidCipherTextException e) {
        throw new RuntimeException(e);
    }
}

private static byte[] cipherData(PaddedBufferedBlockCipher cipher, byte[] data) throws InvalidCipherTextException
{
    int minSize = cipher.getOutputSize(data.length);
    byte[] outBuf = new byte[minSize];
    int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0);
    int length2 = cipher.doFinal(outBuf, length1);
    int actualLength = length1 + length2;
    byte[] cipherArray = new byte[actualLength];
    for (int x = 0; x < actualLength; x++) {
        cipherArray[x] = outBuf[x];
    }
    return cipherArray;
}

 private String md5(String string)
 {
    try {
        java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
        byte[] array = md.digest(string.getBytes());
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < array.length; ++i) {
            sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString();
    } catch (java.security.NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}

When using CFB, PaddedBufferedBlockCipher should be replace by the following:

PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CFBBlockCipher(new RijndaelEngine(256),8), new ZeroBytePadding());
// PHP mcrypt uses a blocksize of 8 bit for CFB

Usage:

String salt = "fbhweui3497";
String key = md5(salt);
String iv = md5(md5(salt));

String encrypted = encryptWithAesCBC("text to encript", key, iv);

String decrypted = decryptWithAesCBC(encrypted, key, iv);


问:
WPF Add KeyBinding events with umlaut characters in XAML
Can anyone tell me why keybinding events do not work with umlaut characters like this?

Trying in xaml

```<code><Grid.InputBindings>
    <KeyBinding Key="Ü" ... />
</Grid.InputBindings>
</code>```

Will throw error:

Cannot convert string value 'Ü' to type System.Windows.Input.Key

答: Because KeyBinding.Key is enumeration, you can see all possible values here. Since your umlaut character is not part of that enumeraton - you cannot use it.

Body:
Can anyone tell me why keybinding events do not work with umlaut characters like this?

Trying in xaml

<Grid.InputBindings>
    <KeyBinding Key="Ü" ... />
</Grid.InputBindings>

Will throw error:

Cannot convert string value 'Ü' to type System.Windows.Input.Key


问:
XSLT for oddly formatted XML File
I am trying to create an XSLT file to output HTML for the following oddly structured XML:

```<code>   <?xml version="1.0" encoding="UTF-8"?>
<java version="1.8.0_66" class="java.beans.XMLDecoder">
    <object class="java.util.HashMap">
        <void method="put">
            <string>Field_01</string>
            <long>1005079534</long>
        </void>
        <void method="put">
            <string>Field_02</string>
            <int>1328</int>
        </void>
        <void method="put">
            <string>Field_03</string>
            <string>10050741652</string>
        </void>
        <void method="put">
            <string>properties</string>
            <object class="java.util.Properties">
                <void method="put">
                    <string>Property_01</string>
                    <object class="java.util.HashMap">
                        <void method="put">
                            <string>Attribute_01</string>
                            <array class="java.lang.Object" length="2">
                                <void index="0">
                                    <string>Data_01</string>
                                </void>
                                <void index="1">
                                    <boolean>Data_02</boolean>
                                </void>
                            </array>
                        </void>
                        <void method="put">
                            <string>Attribute_02</string>
                            <array class="java.lang.Object" length="2">
                                <void index="0">
                                    <string>Data_01</string>
                                </void>
                                <void index="1">
                                    <boolean>Data_02</boolean>
                                </void>
                            </array>
                        </void>
                    </object>
                </void>
            </object>
        </void>
    </object>
</java>
</code>```

I want it formatted to something like:

```<code><html>
    <body>
        <h2>Field_01: </h2> <p>1005079534
        <h2>Field_02: </h2> 1328
        <h2>Field_03: </h2> 10050741652
        <h2>Properties</h2>
        <h3>Property_01:</h3>
        <h3>Attribute_01</h3>
        <ul>
            <li>Data_01</li>
            <li>Data_02</li>
        </ul>
        <h3>Attribute_02</h3>
        <ul>
            <li>Data_01</li>
            <li>Data_02</li>
        </ul>
    </body>
</html>
</code>```

I know that XSTL uses the XML tags to create the html file. Is it possible to use XSTL to use the content of the tags in place of tag names to display html instead of name of the tags?

答:
Is it possible to use XSLT to use the content of the tags in place of tag names to display html instead of name of the tags?

Yes of course. For example

```<code><xsl:element name="{child::string}">
</code>```

constructs an element in the result tree whose name is taken from the content of the child element named "string" in the source tree.

Title: XSLT for oddly formatted XML File

Body:
I am trying to create an XSLT file to output HTML for the following oddly structured XML:

   <?xml version="1.0" encoding="UTF-8"?>
<java version="1.8.0_66" class="java.beans.XMLDecoder">
    <object class="java.util.HashMap">
        <void method="put">
            <string>Field_01</string>
            <long>1005079534</long>
        </void>
        <void method="put">
            <string>Field_02</string>
            <int>1328</int>
        </void>
        <void method="put">
            <string>Field_03</string>
            <string>10050741652</string>
        </void>
        <void method="put">
            <string>properties</string>
            <object class="java.util.Properties">
                <void method="put">
                    <string>Property_01</string>
                    <object class="java.util.HashMap">
                        <void method="put">
                            <string>Attribute_01</string>
                            <array class="java.lang.Object" length="2">
                                <void index="0">
                                    <string>Data_01</string>
                                </void>
                                <void index="1">
                                    <boolean>Data_02</boolean>
                                </void>
                            </array>
                        </void>
                        <void method="put">
                            <string>Attribute_02</string>
                            <array class="java.lang.Object" length="2">
                                <void index="0">
                                    <string>Data_01</string>
                                </void>
                                <void index="1">
                                    <boolean>Data_02</boolean>
                                </void>
                            </array>
                        </void>
                    </object>
                </void>
            </object>
        </void>
    </object>
</java>

I want it formatted to something like:

Field_01:

1005079534

Field_02:
 1328

Field_03:
 10050741652

Properties

Property_01:

Attribute_01

Data_01

Data_02

Attribute_02

Data_01

Data_02

I know that XSTL uses the XML tags to create the html file. Is it possible to use XSTL to use the content of the tags in place of tag names to display html instead of name of the tags?

Body:
Is it possible to use XSLT to use the content of the tags in place of tag names to display html instead of name of the tags?

Yes of course. For example

<xsl:element name="{child::string}">

constructs an element in the result tree whose name is taken from the content of the child element named "string" in the source tree.


问:
Full screen is not working on iPhone 5s with Ionic 3 on iOS 11
We have a problem to enable full screen on iPhone 5s with iOS11.

We are developing this app with Ionic 3.15 and Cordova 7.0.1

Greetings!

答:
I was experiencing the same thing. Check out this answer. It got me to my solution.

I had just updated to xcode 9.1 and IOS 11.11, and since the update, I was having these issues.

Solution: Go to project settings (first item in file manager) > General > App icons and launch images (roughly halfway down).

For me the 3rd dropdown "Launch Screen file" was empty. I selected CDVLauncherScreen.storyboard, and that fixed it.

ContentLicense: CC BY-SA 4.0


问:
Why {a: '1'}.toString() fails and var obj= {a: '1'}; obj.toString() does not
I was wondering whether execution of these two has any difference to the JS interpreter.
is this because we can not create and call method on object simultaneously.?
Any help on this?</p>

答:
Because JavaScript will interpret your curly brace as a block, not an object. Try with:</p>

```<code>({}).toString()
</code>```

Body:
Because JavaScript will interpret your curly brace as a block, not an object. Try with:

({}).toString()


Title: Python Partition By

Body:
I have the below dataframe df:

| Staff_ID | Join_Date | Time_Stamp |
|----------|-----------|------------|
| 1        | 3/29/2016 | 4/23/2016  |
| 1        | 3/29/2016 | 3/29/2016  |
| 1        | 3/29/2016 | 6/21/2016  |
| 2        | 5/15/2016 | 4/1/2016   |
| 2        | 5/15/2016 | 5/25/2016  |
| 3        | 7/24/2016 | 6/21/2016  |
| 3        | 7/24/2016 | 6/10/2016  |
| 3        | 7/24/2016 | 4/21/2016  |

I want to get the Min and Max "Time_Stamp Date" partition by "Staff_ID" such that the resultant dataframe is as follows:

| Staff_ID | Join_Date | Time_Stamp | Min_Time_Stamp | Max_Time_Stamp |
|----------|-----------|------------|----------------|----------------|
| 1        | 3/29/2016 | 4/23/2016  | 3/29/2016      | 6/21/2016      |
| 1        | 3/29/2016 | 3/29/2016  | 3/29/2016      | 6/21/2016      |
| 1        | 3/29/2016 | 6/21/2016  | 3/29/2016      | 6/21/2016      |
| 2        | 5/15/2016 | 4/1/2016   | 4/1/2016       | 5/25/2016      |
| 2        | 5/15/2016 | 5/25/2016  | 4/1/2016       | 5/25/2016      |
| 3        | 7/24/2016 | 6/21/2016  | 4/21/2016      | 6/21/2016      |
| 3        | 7/24/2016 | 6/10/2016  | 4/21/2016      | 6/21/2016      |
| 3        | 7/24/2016 | 4/21/2016  | 4/21/2016      | 6/21/2016      |

How can I do this in Python ?

Body:
You can use groupby and then merge the results:

group = df.groupby("Staff_ID", as_index=False)["Time_Stamp"]
df = pd.merge(df, group.min(), on=["Staff_ID"])
df = df.rename(columns = {"Time_Stamp_x" : "Time_Stamp", "Time_Stamp_y": "Min_Time_Stamp"})
df = pd.merge(df, group.max(), on=["Staff_ID"])
df = df.rename(columns = {"Time_Stamp_x" : "Time_Stamp", "Time_Stamp_y" : "Max_Time_Stamp"})

Result:

   Join_Date  Staff_ID Time_Stamp Min_Time_Stamp Max_Time_Stamp
0  3/29/2016         1  4/23/2016      3/29/2016      6/21/2016
1  3/29/2016         1  3/29/2016      3/29/2016      6/21/2016
2  3/29/2016         1  6/21/2016      3/29/2016      6/21/2016
3  5/15/2016         2   4/1/2016       4/1/2016      5/25/2016
4  5/15/2016         2  5/25/2016       4/1/2016      5/25/2016
5  7/24/2016         3  6/21/2016      4/21/2016      6/21/2016
6  7/24/2016         3  6/10/2016      4/21/2016      6/21/2016
7  7/24/2016         3  4/21/2016      4/21/2016      6/21/2016


问:
broadcast receiver not received in IntentService
I am building a service to be able to catch intent from FirebaseMessagingService.

The first version I made use to do it at app level in the main activity but I do not want to handle it at this level anymore. I have created an intent service as below:

```<code>package com.seb.sebastien.appservices;

import android.app.IntentService;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.Context;
import android.content.IntentFilter;
import android.telephony.TelephonyManager;
import android.util.Log;

public class appsControlIntentService extends IntentService {
    public static final String REQUEST_MSG = "request";
    public static final String RESPONSE_MSG = "response";
    public static final String TAG = "appsControlIntentService";
    private String type_sim;

    public appsControlIntentService() {
        super("appsControlIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        boolean request = intent.getBooleanExtra(REQUEST_MSG, false);

        if(request == true) {
            sendResponse("Enable");
            handleAction(getCarrier());
            registerAllReceivers();
        }
        else if (request == false) {
            sendResponse("Disable");
            unRegisterAllReceivers();
            disableAction();
        }
        else
            Log.e(TAG, "Error msg");

    }
    ...

    /* Firebase and SIM */
    private BroadcastReceiver serviceBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "Broadcast received");
            if (intent.getExtras().getString(appFirebaseMessagingService.FIREBASE).equals(appFirebaseMessagingService.FIREBASE))
                type_sim = intent.getExtras().getString(appFirebaseMessagingService.SIM_TYPE);
            else if(intent.getExtras().getString(SimNotificationService.EXTRA_SIM_STATE) != null)
                Log.d(TAG, "Get something from Sim");
            else
                type_sim = null;

            if(type_sim != null){
                handleAction(type_sim);
            }
        }
    };

    private void registerAllReceivers(){
        Log.d(TAG, "Broadcast receiver register");
        registerReceiver(serviceBroadcastReceiver, new IntentFilter(appFirebaseMessagingService.INTENT_FILTER));
    }

    private void unRegisterAllReceivers() {
        if (serviceBroadcastReceiver != null) {
            unregisterReceiver(serviceBroadcastReceiver);
            serviceBroadcastReceiver = null;
        }
    }

    @Override
    public void onDestroy() {
        unRegisterAllReceivers();
        super.onDestroy();
    }

}
</code>```

this intent service register a broadcast receiver to be able to receive the firebase broadcast as shown below:

```<code>package com.seb.sebastien.appservices;

public class appFirebaseMessagingService extends FirebaseMessagingService {

    public static final String TAG = "appFirebaseMessagingService";
    public static final String INTENT_FILTER = "INTENT_FILTER";
    public static final String FIREBASE = "firebase";
    public static final String SIM_TYPE = "simtype";

    public appFirebaseMessagingService() {
    }

   /* @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    } */

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        String sim = null;

        Log.d(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            sim = remoteMessage.getNotification().getBody();
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

        Intent intent = new Intent(INTENT_FILTER);
        intent.putExtra(FIREBASE, FIREBASE);
        intent.putExtra(SIM_TYPE, sim );

        sendBroadcast(intent);

    }
}
</code>```

when debugging, I saw that we went until the sendBroadcast but nothing seems received in the "appControlIntentService" class event if I have registered the receiver.

Any idea why the broadcast is not received in the intentservice ?

答:
First off, not sure where you actually created an instance of your appsControlIntentService.

Second, IntentService gets stopped when onHandleIntent finishes. It is meant to do a short task and finish. So basically even if you created one to listen to the broadcast, it would only do so for a very limited time until its onDestroy was called.

About BroadcastReceiver solutions for listening to your custom intent:

1) make a service that runs in the background (not IntentService, regular Service), and have it register a BroadcastListener. This service you can create when your activity first wakes, and probably in the Boot BroadcastReceiver. Decide if you want it to be a foreground or background service. background services are more likely to be killed by the OS due to memory issues. but foreground services require that you show an icon in the status bar.

2) just put the BroadcastReceiver in the manifest. This way the OS will even wake the app to handle the broadcast when it arrives. Even if the app is not currently running.
have a look at "Manifest-declared receivers" in: https://developer.android.com/guide/components/broadcasts.html.

to disable this receiver, have a look at: Android - how to unregister a receiver created in the manifest?. or, you could save in the shared preferences whether you want it to do something with the event or not, or better yet, don't send the intent from the FirebaseMessagingService if it is disabled in the first place.

Body:
I am building a service to be able to catch intent from FirebaseMessagingService.

The first version I made use to do it at app level in the main activity but I do not want to handle it at this level anymore. I have created an intent service as below:

package com.seb.sebastien.appservices;

import android.app.IntentService;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.Context;
import android.content.IntentFilter;
import android.telephony.TelephonyManager;
import android.util.Log;

public class appsControlIntentService extends IntentService {
    public static final String REQUEST_MSG = "request";
    public static final String RESPONSE_MSG = "response";
    public static final String TAG = "appsControlIntentService";
    private String type_sim;

    public appsControlIntentService() {
        super("appsControlIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        boolean request = intent.getBooleanExtra(REQUEST_MSG, false);

        if(request == true) {
            sendResponse("Enable");
            handleAction(getCarrier());
            registerAllReceivers();
        }
        else if (request == false) {
            sendResponse("Disable");
            unRegisterAllReceivers();
            disableAction();
        }
        else
            Log.e(TAG, "Error msg");

    }
    ...

    /* Firebase and SIM */
    private BroadcastReceiver serviceBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "Broadcast received");
            if (intent.getExtras().getString(appFirebaseMessagingService.FIREBASE).equals(appFirebaseMessagingService.FIREBASE))
                type_sim = intent.getExtras().getString(appFirebaseMessagingService.SIM_TYPE);
            else if(intent.getExtras().getString(SimNotificationService.EXTRA_SIM_STATE) != null)
                Log.d(TAG, "Get something from Sim");
            else
                type_sim = null;

            if(type_sim != null){
                handleAction(type_sim);
            }
        }
    };

    private void registerAllReceivers(){
        Log.d(TAG, "Broadcast receiver register");
        registerReceiver(serviceBroadcastReceiver, new IntentFilter(appFirebaseMessagingService.INTENT_FILTER));
    }

    private void unRegisterAllReceivers() {
        if (serviceBroadcastReceiver != null) {
            unregisterReceiver(serviceBroadcastReceiver);
            serviceBroadcastReceiver = null;
        }
    }

    @Override
    public void onDestroy() {
        unRegisterAllReceivers();
        super.onDestroy();
    }

}

this intent service register a broadcast receiver to be able to receive the firebase broadcast as shown below:

package com.seb.sebastien.appservices;

public class appFirebaseMessagingService extends FirebaseMessagingService {

    public static final String TAG = "appFirebaseMessagingService";
    public static final String INTENT_FILTER = "INTENT_FILTER";
    public static final String FIREBASE = "firebase";
    public static final String SIM_TYPE = "simtype";

    public appFirebaseMessagingService() {
    }

   /* @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    } */

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        String sim = null;

        Log.d(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            sim = remoteMessage.getNotification().getBody();
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

        Intent intent = new Intent(INTENT_FILTER);
        intent.putExtra(FIREBASE, FIREBASE);
        intent.putExtra(SIM_TYPE, sim );

        sendBroadcast(intent);

    }
}

when debugging, I saw that we went until the sendBroadcast but nothing seems received in the "appControlIntentService" class event if I have registered the receiver.

Any idea why the broadcast is not received in the intentservice ?


问:
Add columns dynamically and Later Parse values in the respective columns
I have an SP which accepts the Inputtable as parameter, My Inputtable is as shown in the code

```<code>`create table inputTable ( id int,ItemQty varchar(100))
insert into inputTable(id, ItemQty) values(1,'a,b,c')
insert into inputTable(id, ItemQty) values(2,'x,y')
insert into inputTable(id, ItemQty) values(3,'l,m,n,o,p')
insert into inputTable(id, ItemQty) values(4,'a,b')
insert into inputTable(id, ItemQty) values(5,'m')`
</code>```

and SP i have written is like below

```<code>`ALTER PROCEDURE [dbo].[Column_Dynamics] (@tablename varchar(50))

AS
BEGIN

-----
declare @maxcount as int
set @maxcount='select MAX(len(ITEMQTY) - len(replace(ITEMQTY, '','', '''')) +1) from '+@tablename

exec('select MAX(len(ITEMQTY) - len(replace(ITEMQTY, '','', '''')) +1) from '+@tablename)
print @maxcount
exec @maxcount
print @maxcount

declare @var varchar(100)
IF EXISTS(SELECT * FROM   sys.columns WHERE  object_id = Object_id(@tablename))
set @var='alter table '+ @tablename +' ADD column QTY1'
exec(@var)
select * from @tablename
select max(len(ItemQty))-max(len(replace(ItemQty, ',', ''))-1) from inputtable

END`
</code>```

My table is :

step 1 ) I want to add the columns dynamically to inputtable like QTY1,QTY2,QTY3,QTY4,QTY5 because maximum count of ItemQty column is 5, by considering comma as delimiter as shown in figure1

**step 2) ** Parse values in the respective columns(by considering the delimiter comma (,).as shown in figure2

Later SP: I got till here, But Not getting the second step, that is update Parse values in the respective columns.

```<code>ALTER PROCEDURE dynamic_tbl (@tablename varchar(50))

AS
BEGIN

DECLARE @ColumnCount int
DECLARE @rowcount TABLE (Value int);
INSERT INTO @rowcount
EXEC('select MAX(len(ITEMQTY) - len(replace(ITEMQTY, '','', '''')) +1) from '+@tablename);
SELECT @ColumnCount = Value FROM @rowcount;

    Declare @ColumnName nvarchar(10)='qty_'
    Declare @count int =0
    IF(@ColumnCount>0)
    BEGIN
        IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND  TABLE_NAME = 'dyn_tbl'))
        BEGIN
        DROP TABLE dyn_tbl
        END

        select * into dyn_tbl from inputtable
        SET @count=@count +1;
        WHile(@ColumnCount>=@count)
        BEGIN
            SET @ColumnName='qty_'+CONVERT(varchar(2),@count)
            EXEC ('ALTER TABLE dyn_tbl ADD ['+@ColumnName +'] varchar(20)')

            declare @myvar as varchar(max)

            set @myvar='update '+@tablename+' set '+@ColumnName +' =itemQty'

--exec dynamic_tbl 'dyn_tbl'

--select * from dyn_tbl

            --CAST('<A>'+REPLACE(ITEMQTY, ',', '</A><A>')+'</A>' AS XML)
            print @myvar

            exec(@myvar)

            SET @count=@count +1;
        END
    END

----
END
</code>```

答:
However, if you have maximum Qty's are known which are in comma separated format then you could use xml node method to separate them into columns.QTY1...QTY5

```<code>SELECT DISTINCT ID, ITEMQTY,
       a.value('/A[1]', 'VARCHAR(MAX)') as QTY1,
       a.value('/A[2]', 'VARCHAR(MAX)') as QTY2,
       a.value('/A[3]', 'VARCHAR(MAX)') as QTY3,
       a.value('/A[4]', 'VARCHAR(MAX)') as QTY4,
       a.value('/A[5]', 'VARCHAR(MAX)') as QTY5
FROM
(
    SELECT ID, ITEMQTY,
           CAST('<A>'+REPLACE(ITEMQTY, ',', '</A><A>')+'</A>' AS XML) AS ITEMQTY1
    FROM inputTable
) A
CROSS APPLY ITEMQTY1.nodes('/A') AS split(a);
</code>```

Result :

```<code>ID  ITEMQTY   QTY1  QTY2    QTY3    QTY4    QTY5
1   a,b,c     a     b       c       NULL    NULL
2   x,y       x     y       NULL    NULL    NULL
3   l,m,n,o,p l     m       n       o       p
4   a,b       a     b       NULL    NULL    NULL
5   m         m    NULL     NULL    NULL    NULL
</code>```

Later, you could replace null by using coalesce() or isnull() function with ''

Body:
I have an SP which accepts the Inputtable as parameter, My Inputtable is as shown in the code

`create table inputTable ( id int,ItemQty varchar(100))
insert into inputTable(id, ItemQty) values(1,'a,b,c')
insert into inputTable(id, ItemQty) values(2,'x,y')
insert into inputTable(id, ItemQty) values(3,'l,m,n,o,p')
insert into inputTable(id, ItemQty) values(4,'a,b')
insert into inputTable(id, ItemQty) values(5,'m')`

and SP i have written is like below

`ALTER PROCEDURE [dbo].[Column_Dynamics] (@tablename varchar(50))

AS
BEGIN

-----
declare @maxcount as int
set @maxcount='select MAX(len(ITEMQTY) - len(replace(ITEMQTY, '','', '''')) +1) from '+@tablename

exec('select MAX(len(ITEMQTY) - len(replace(ITEMQTY, '','', '''')) +1) from '+@tablename)
print @maxcount
exec @maxcount
print @maxcount

declare @var varchar(100)
IF EXISTS(SELECT * FROM   sys.columns WHERE  object_id = Object_id(@tablename))
set @var='alter table '+ @tablename +' ADD column QTY1'
exec(@var)
select * from @tablename
select max(len(ItemQty))-max(len(replace(ItemQty, ',', ''))-1) from inputtable

END`

My table is :

step 1 ) I want to add the columns dynamically to inputtable like QTY1,QTY2,QTY3,QTY4,QTY5 because maximum count of ItemQty column is 5, by considering comma as delimiter as shown in figure1

**step 2) ** Parse values in the respective columns(by considering the delimiter comma (,).as shown in figure2

Later SP: I got till here, But Not getting the second step, that is update Parse values in the respective columns.

ALTER PROCEDURE dynamic_tbl (@tablename varchar(50))

AS
BEGIN

DECLARE @ColumnCount int
DECLARE @rowcount TABLE (Value int);
INSERT INTO @rowcount
EXEC('select MAX(len(ITEMQTY) - len(replace(ITEMQTY, '','', '''')) +1) from '+@tablename);
SELECT @ColumnCount = Value FROM @rowcount;

    Declare @ColumnName nvarchar(10)='qty_'
    Declare @count int =0
    IF(@ColumnCount>0)
    BEGIN
        IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND  TABLE_NAME = 'dyn_tbl'))
        BEGIN
        DROP TABLE dyn_tbl
        END

        select * into dyn_tbl from inputtable
        SET @count=@count +1;
        WHile(@ColumnCount>=@count)
        BEGIN
            SET @ColumnName='qty_'+CONVERT(varchar(2),@count)
            EXEC ('ALTER TABLE dyn_tbl ADD ['+@ColumnName +'] varchar(20)')

            declare @myvar as varchar(max)

            set @myvar='update '+@tablename+' set '+@ColumnName +' =itemQty'

--exec dynamic_tbl 'dyn_tbl'

--select * from dyn_tbl

            --CAST(''+REPLACE(ITEMQTY, ',', '')+'' AS XML)
            print @myvar

            exec(@myvar)

            SET @count=@count +1;
        END
    END

----
END

Body:
However, if you have maximum Qty's are known which are in comma separated format then you could use xml node method to separate them into columns.QTY1...QTY5

SELECT DISTINCT ID, ITEMQTY,
       a.value('/A[1]', 'VARCHAR(MAX)') as QTY1,
       a.value('/A[2]', 'VARCHAR(MAX)') as QTY2,
       a.value('/A[3]', 'VARCHAR(MAX)') as QTY3,
       a.value('/A[4]', 'VARCHAR(MAX)') as QTY4,
       a.value('/A[5]', 'VARCHAR(MAX)') as QTY5
FROM
(
    SELECT ID, ITEMQTY,
           CAST('<A>'+REPLACE(ITEMQTY, ',', '</A><A>')+'</A>' AS XML) AS ITEMQTY1
    FROM inputTable
) A
CROSS APPLY ITEMQTY1.nodes('/A') AS split(a);

Result :

ID  ITEMQTY   QTY1  QTY2    QTY3    QTY4    QTY5
1   a,b,c     a     b       c       NULL    NULL
2   x,y       x     y       NULL    NULL    NULL
3   l,m,n,o,p l     m       n       o       p
4   a,b       a     b       NULL    NULL    NULL
5   m         m    NULL     NULL    NULL    NULL

Later, you could replace null by using coalesce() or isnull() function with ''


问:
if statements for c++
My program so far, my question is do i have to include the if statements after each cout/cin code or is there a way to generalize it? : </p>

```<code>#include <iostream>
using namespace std;

int main ()
{
   double watts, hours_per_day, watt_hours, dollars_per_wh, result;

   dollars_per_wh= .00008;

   cout << " How many Watts for the Air conditioner? ";
   cin >> watts;
   cout << " How many hours/day do you run the Air Conditioner? ";
   cin >> hours_per_day;

   if (watts< 0)
   {
      cout << "Error- negative watts detected " << endl;
      return 1;
   }

   if (hours_per_day< 0)
   {
      cout << "Error - negative hours/day detected " << endl;
      return 1;
   }

   cout << "How many Watts for the Television? " ;
   cin >> watts;
   cout << "How many hours/day do you run the Television? " ;
   cin >> hours_per_day;

   if (watts< 0)
   {
      cout << "Error- negative watts detected " << endl;
      return 1;
   }

   if (hours_per_day< 0)
   {
      cout << "Error - negative hours/day detected " << endl;
      return 1;
   }

   cout << "How many Watts for the Washer? " ;
   cin >> watts;
   cout << "How many hours/day do you run the Washer? " ;
   cin >> hours_per_day;

   if (watts< 0)
   {
      cout << "Error- negative watts detected " << endl;
      return 1;
   }

   if (hours_per_day< 0)
   {
      cout << "Error - negative hours/day detected " << endl;
      return 1;
   }

  return 0 ;
}
</code>```

答:
Yes, you can pull them out into a separate function:

```<code>void cinNonNegative(double &x)
{
  cin >> x;

  if (x< 0)
   {
      cout << "Error- negative value detected " << endl;
      exit(1);
   }
}

int main()
{
  ...
  cout << " How many Watts for the Air conditioner? ";
  cinNonNegative(watts);
  cout << " How many hours/day do you run the Air Conditioner? ";
  cinNonNegative(hours_per_day);
  ...
}
</code>```

And if you want to be more specific about the error message (e.g. "negative watts" instead of "negative value") you can add another parameter to cinNonNegative for the name of the variable (e.g. "watts").

ContentLicense: CC BY-SA 2.5

Title: if statements for c++

Body:
My program so far, my question is do i have to include the if statements after each cout/cin code or is there a way to generalize it? :

#include <iostream>
using namespace std;

int main ()
{
   double watts, hours_per_day, watt_hours, dollars_per_wh, result;

   dollars_per_wh= .00008;

   cout << " How many Watts for the Air conditioner? ";
   cin >> watts;
   cout << " How many hours/day do you run the Air Conditioner? ";
   cin >> hours_per_day;

   if (watts< 0)
   {
      cout << "Error- negative watts detected " << endl;
      return 1;
   }

   if (hours_per_day< 0)
   {
      cout << "Error - negative hours/day detected " << endl;
      return 1;
   }

   cout << "How many Watts for the Television? " ;
   cin >> watts;
   cout << "How many hours/day do you run the Television? " ;
   cin >> hours_per_day;

   if (watts< 0)
   {
      cout << "Error- negative watts detected " << endl;
      return 1;
   }

   if (hours_per_day< 0)
   {
      cout << "Error - negative hours/day detected " << endl;
      return 1;
   }

   cout << "How many Watts for the Washer? " ;
   cin >> watts;
   cout << "How many hours/day do you run the Washer? " ;
   cin >> hours_per_day;

   if (watts< 0)
   {
      cout << "Error- negative watts detected " << endl;
      return 1;
   }

   if (hours_per_day< 0)
   {
      cout << "Error - negative hours/day detected " << endl;
      return 1;
   }

  return 0 ;
}

Body:
Yes, you can pull them out into a separate function:

void cinNonNegative(double &x)
{
  cin >> x;

  if (x< 0)
   {
      cout << "Error- negative value detected " << endl;
      exit(1);
   }
}

int main()
{
  ...
  cout << " How many Watts for the Air conditioner? ";
  cinNonNegative(watts);
  cout << " How many hours/day do you run the Air Conditioner? ";
  cinNonNegative(hours_per_day);
  ...
}

And if you want to be more specific about the error message (e.g. "negative watts" instead of "negative value") you can add another parameter to cinNonNegative for the name of the variable (e.g. "watts").


问:
Slow query log logs queries that are fast during testing
My slow query log is full of queries with following query time and rows examined:

```<code># Query_time: 26.370100  Lock_time: 0.000213  Rows_sent: 0  Rows_examined: 30976475
</code>```

If I copy and paste the exact query from the log into phpmyadmin and run it, result comes instantly, even trying EXPLAIN upon that query reveals no flaws in indexes or bad structure.

As far as I can tell, for some reason a small fraction of queries fail to use indexes and trying to reproduce that event is next to impossible during testing.

How should I prevent these occasional slow queries which in vast majority of cases work as intended?

--- EDIT #1 ---

My create tables are:

```<code>CREATE TABLE msgs (
  id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  sender text NOT NULL,
  receiver text NOT NULL,
  cont blob NOT NULL,
  img text NOT NULL,
  orient text NOT NULL,
  d_t datetime NOT NULL,
  convo text NOT NULL,
  u_code text NOT NULL,
  viewed datetime NOT NULL,
  stat int(11) NOT NULL,
  device text NOT NULL,
  addr text NOT NULL,
  PRIMARY KEY (id),
  KEY msg_u_code (`u_code`(24)),
  KEY receiver (`receiver`(24)),
  KEY sender (`sender`(24)),
  KEY img (`img`(28)),
  KEY convo (`convo`(49))
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

CREATE TABLE usrs (
  id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  usr_name text NOT NULL,
  img text NOT NULL,
  orient text NOT NULL,
  `password` text NOT NULL,
  u_code text NOT NULL,
  d_t datetime NOT NULL,
  stat int(11) NOT NULL,
  device text NOT NULL,
  addr text NOT NULL,
  PRIMARY KEY (id),
  KEY img (`img`(28)),
  KEY usr_code (`u_code`(24))
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
</code>```

And my slow query log entry is:

```<code> # Time: 171115  6:26:37
 # User@Host: xxx[xxx] @ localhost []
 # Thread_id: 25524888  Schema: xxx  QC_hit: No
 # Query_time: 32.423430  Lock_time: 0.000425  Rows_sent: 1  Rows_examined: 30998008
 # Rows_affected: 0
 use xxx;
 SET timestamp=1510723597;
 select msg_cont, msg_u_code, msg_d_t, msg_viewed, usr_u_code, usr_name from
        (select
            msgs.id as msg_id,
            msgs.cont as msg_cont,
            msgs.u_code as msg_u_code,
            msgs.d_t as msg_d_t,
            msgs.viewed as msg_viewed,
            usrs.u_code as usr_u_code,
            usrs.usr_name as usr_name
            from msgs
            left join usrs on msgs.sender = usrs.u_code
    where  msgs.convo = 'aaaaaaaaaabfbaghdgcigfid_aaaaaaaaaabeiaccjfhjfach'
      and  (msgs.sender = 'aaaaaaaaaabfbaghdgcigfid'
              or  msgs.receiver = 'aaaaaaaaaabfbaghdgcigfid'
           )
      and  msgs.stat = '1'
      and  usrs.stat = '1'
      and  usrs.u_code not in('aaaaaaaaaabfaagfbgggiejh',
                              'aaaaaaaaaabfabgbjdfjigbd',
                ...... !!!!![here go 400 more usr_u_codes]!!!!!
                          )
      and  msgs.id > 30997997
        ) a order by msg_id asc;
</code>```

Caution, this query shall contain on average 400 elements in the not in function.

--- EDIT #2 ---

答:
While I am unable to explain why MySQL occasionally decided not to use index on a very obvious and very common query, the solution was to simply force the index.

In my particular case:

```<code>select msg_cont, msg_u_code, msg_d_t, msg_viewed, usr_u_code, usr_name from
        (select
            msgs.id as msg_id,
            msgs.cont as msg_cont,
            msgs.u_code as msg_u_code,
            msgs.d_t as msg_d_t,
            msgs.viewed as msg_viewed,
            usrs.u_code as usr_u_code,
            usrs.usr_name as usr_name
            from msgs FORCE INDEX (convo)
            left join usrs FORCE INDEX (u_code) on msgs.sender = usrs.u_code
    where  msgs.convo = 'aaaaaaaaaabfbaghdgcigfid_aaaaaaaaaabeiaccjfhjfach'
      and  (msgs.sender = 'aaaaaaaaaabfbaghdgcigfid'
              or  msgs.receiver = 'aaaaaaaaaabfbaghdgcigfid'
           )
      and  msgs.stat = '1'
      and  usrs.stat = '1'
      and  usrs.u_code not in('aaaaaaaaaabfaagfbgggiejh',
                              'aaaaaaaaaabfabgbjdfjigbd',
                ...... !!!!![here go 400 more usr_u_codes]!!!!!
                          )
      and  msgs.id > 30997997
        ) a order by msg_id asc;
</code>```

Slow query log proved this solution to be effective as no new slow entries emerge.

Body:
My slow query log is full of queries with following query time and rows examined:

# Query_time: 26.370100  Lock_time: 0.000213  Rows_sent: 0  Rows_examined: 30976475

If I copy and paste the exact query from the log into phpmyadmin and run it, result comes instantly, even trying EXPLAIN upon that query reveals no flaws in indexes or bad structure.

As far as I can tell, for some reason a small fraction of queries fail to use indexes and trying to reproduce that event is next to impossible during testing.

How should I prevent these occasional slow queries which in vast majority of cases work as intended?

--- EDIT #1 ---

My create tables are:

CREATE TABLE msgs (
  id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  sender text NOT NULL,
  receiver text NOT NULL,
  cont blob NOT NULL,
  img text NOT NULL,
  orient text NOT NULL,
  d_t datetime NOT NULL,
  convo text NOT NULL,
  u_code text NOT NULL,
  viewed datetime NOT NULL,
  stat int(11) NOT NULL,
  device text NOT NULL,
  addr text NOT NULL,
  PRIMARY KEY (id),
  KEY msg_u_code (`u_code`(24)),
  KEY receiver (`receiver`(24)),
  KEY sender (`sender`(24)),
  KEY img (`img`(28)),
  KEY convo (`convo`(49))
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

CREATE TABLE usrs (
  id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  usr_name text NOT NULL,
  img text NOT NULL,
  orient text NOT NULL,
  `password` text NOT NULL,
  u_code text NOT NULL,
  d_t datetime NOT NULL,
  stat int(11) NOT NULL,
  device text NOT NULL,
  addr text NOT NULL,
  PRIMARY KEY (id),
  KEY img (`img`(28)),
  KEY usr_code (`u_code`(24))
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

And my slow query log entry is:

 # Time: 171115  6:26:37
 # User@Host: xxx[xxx] @ localhost []
 # Thread_id: 25524888  Schema: xxx  QC_hit: No
 # Query_time: 32.423430  Lock_time: 0.000425  Rows_sent: 1  Rows_examined: 30998008
 # Rows_affected: 0
 use xxx;
 SET timestamp=1510723597;
 select msg_cont, msg_u_code, msg_d_t, msg_viewed, usr_u_code, usr_name from
        (select
            msgs.id as msg_id,
            msgs.cont as msg_cont,
            msgs.u_code as msg_u_code,
            msgs.d_t as msg_d_t,
            msgs.viewed as msg_viewed,
            usrs.u_code as usr_u_code,
            usrs.usr_name as usr_name
            from msgs
            left join usrs on msgs.sender = usrs.u_code
    where  msgs.convo = 'aaaaaaaaaabfbaghdgcigfid_aaaaaaaaaabeiaccjfhjfach'
      and  (msgs.sender = 'aaaaaaaaaabfbaghdgcigfid'
              or  msgs.receiver = 'aaaaaaaaaabfbaghdgcigfid'
           )
      and  msgs.stat = '1'
      and  usrs.stat = '1'
      and  usrs.u_code not in('aaaaaaaaaabfaagfbgggiejh',
                              'aaaaaaaaaabfabgbjdfjigbd',
                ...... !!!!![here go 400 more usr_u_codes]!!!!!
                          )
      and  msgs.id > 30997997
        ) a order by msg_id asc;

Caution, this query shall contain on average 400 elements in the not in function.

--- EDIT #2 ---

Body:
While I am unable to explain why MySQL occasionally decided not to use index on a very obvious and very common query, the solution was to simply force the index.

In my particular case:

select msg_cont, msg_u_code, msg_d_t, msg_viewed, usr_u_code, usr_name from
        (select
            msgs.id as msg_id,
            msgs.cont as msg_cont,
            msgs.u_code as msg_u_code,
            msgs.d_t as msg_d_t,
            msgs.viewed as msg_viewed,
            usrs.u_code as usr_u_code,
            usrs.usr_name as usr_name
            from msgs FORCE INDEX (convo)
            left join usrs FORCE INDEX (u_code) on msgs.sender = usrs.u_code
    where  msgs.convo = 'aaaaaaaaaabfbaghdgcigfid_aaaaaaaaaabeiaccjfhjfach'
      and  (msgs.sender = 'aaaaaaaaaabfbaghdgcigfid'
              or  msgs.receiver = 'aaaaaaaaaabfbaghdgcigfid'
           )
      and  msgs.stat = '1'
      and  usrs.stat = '1'
      and  usrs.u_code not in('aaaaaaaaaabfaagfbgggiejh',
                              'aaaaaaaaaabfabgbjdfjigbd',
                ...... !!!!![here go 400 more usr_u_codes]!!!!!
                          )
      and  msgs.id > 30997997
        ) a order by msg_id asc;

Slow query log proved this solution to be effective as no new slow entries emerge.


问:
How to find the source css code when dev tools does not specify a file name?
I am making a website in wordpress and I'm using a paid template. The template comes with a bootstrap grid. The issue I have is editing some css code, because I can't find the source of the css codes.

As you can see on the screenshot, the media queries are located at grid-responsive.css. The code I want to edit is the css above it. I want to remove the padding-right: 30px !important; from .mpce-prvt-4661-5a018ae17a157:not(.mpce-dsbl-padding-right) and same for the left side.

But I can't find the css file and on the right side it doesn't tell me which file the source is. I searched in all the css files I have and couldn't find it. Someone having an idea how to locate it?

答:
CSS references that do not show a source in the inspector are usually generated from sources that are not CSS.

The most common source for this is JavaScript.

The easiest solution would be to simply open the entire project in something like Visual Studio and search the whole project for the css string.


问:
react native flexbox stretch issue
In react native i want to achieve this effect

of course all buttons should have same width and height.
For that i use flex box. How can i do it with flexbox ?
I try:

const styles = StyleSheet.create({
  mainView: {
     flex: 1,
     flexDirection: 'column',
     alignItems: 'stretch'
  },
  rows: {
      flex: 1,
      flexDirection: 'row',
  },
  buttons: {
      flex: 1,
  }
});

export default class Home extends Component {
render() {
    return (
      <View style={styles.mainView}>
        <View style={styles.rows}>
          <View style={styles.buttons}><Button title="aaa"/></View>
          <View style={styles.buttons}><Button title="aaa"/></View>
        </View>
        <View style={styles.rows}>
          <View style={styles.buttons}><Button title="aaa"/></View>
          <View style={styles.buttons}><Button title="aaa"/></View>
        </View>
        <View style={styles.rows}>
          <View style={styles.buttons}><Button title="aaa"/></View>
          <View style={styles.buttons}><Button title="aaa"/></View>
        </View>
      </View>
    );
}
```

}

but that gave me:

Please help

答: If you set background colors to all your styles, you will see that your layout is working, except that you cannot change the height of Button in React Native. Use a TouchableOpacity or a TouchableHighlight instead of Button, and the "button" will fill the whole view instead of sticking to the top.

Title: react native flexbox stretch issue

Body:
In react native i want to achieve this effect

of course all buttons should have same width and height.
For that i use flex box. How can i do it with flexbox ?
I try:

const styles = StyleSheet.create({
  mainView: {
     flex: 1,
     flexDirection: 'column',
     alignItems: 'stretch'
  },
  rows: {
      flex: 1,
      flexDirection: 'row',
  },
  buttons: {
      flex: 1,
  }
});

export default class Home extends Component {
render() {
    return (
      <View style={styles.mainView}>
        <View style={styles.rows}>
          <View style={styles.buttons}><Button title="aaa"/></View>
          <View style={styles.buttons}><Button title="aaa"/></View>
        </View>
        <View style={styles.rows}>
          <View style={styles.buttons}><Button title="aaa"/></View>
          <View style={styles.buttons}><Button title="aaa"/></View>
        </View>
        <View style={styles.rows}>
          <View style={styles.buttons}><Button title="aaa"/></View>
          <View style={styles.buttons}><Button title="aaa"/></View>
        </View>
      </View>
    );
}

}

but that gave me:

Please help


问:
How can I vectorize an IF block using ARM Neon intrinsics?
I want to process a large array of floating-point numbers on the ARM processor,
using Neon technology to calculate them four at a time.  Everything's fine for operations like add and multiply, but what do I do if my calculation goes into an IF block?  Example:

```<code>// In the non-vectorized original code, A is an array of many floating-point
// numbers, which are calculated one at a time.  Now they're packed
// into a vector and processed four at a time

...calculate A...

if (A > 10.f)
{
    A = A+5.f;
}
else
{
    A = A+10.f;
}
</code>```

Now, which IF branch do I execute?  What if some of the values in the vector being processed are greater than 10 and some are less?  Is it even possible to vectorize code like this?

答:
In general with SIMD branching logic you use a compare mask and then select alternate results accordingly. I'll give pseudo code for your example and you can convert this to intrinsics or asm as needed:</p>

```<code>v5 = vector(5)              // set up some constant vectors
v10 = vector(10)
vMask = compare_gt(vA, v10) // generate mask for vector compare A > 10
va = add(vA, v10)           // vA = vA + 10 (all elements, unconditionally)
vtemp = and(v5, vMask)      // generate temp vector of 5 and 0 values based on mask
va = sub(vA, vTemp)         // subtract 5 from elements which are <= 10
</code>```

Body:
I want to process a large array of floating-point numbers on the ARM processor,
using Neon technology to calculate them four at a time.  Everything's fine for operations like add and multiply, but what do I do if my calculation goes into an IF block?  Example:

// In the non-vectorized original code, A is an array of many floating-point
// numbers, which are calculated one at a time.  Now they're packed
// into a vector and processed four at a time

...calculate A...

if (A > 10.f)
{
    A = A+5.f;
}
else
{
    A = A+10.f;
}

Now, which IF branch do I execute?  What if some of the values in the vector being processed are greater than 10 and some are less?  Is it even possible to vectorize code like this?

Body:
In general with SIMD branching logic you use a compare mask and then select alternate results accordingly. I'll give pseudo code for your example and you can convert this to intrinsics or asm as needed:

v5 = vector(5)              // set up some constant vectors
v10 = vector(10)
vMask = compare_gt(vA, v10) // generate mask for vector compare A > 10
va = add(vA, v10)           // vA = vA + 10 (all elements, unconditionally)
vtemp = and(v5, vMask)      // generate temp vector of 5 and 0 values based on mask
va = sub(vA, vTemp)         // subtract 5 from elements which are <= 10


问:
Resources ids not updating in Android Studio 3.0
I recently updated to Android Studio 3.0 and noticed that when I for example add any android:id, or create new drawable, or basically any resource, Android Studio does not update it in project until I build application. Every resource I create in xml, in class is marked as red and standard "Cannot resolve symbol ..." is shown. But surprisingly if you try to go to declaration, it correctly goes to the resource. Is there any option for this not to happen?
It's very irritating.

Edit:

It's still occuring sometimes, but I just got used to it. If someone fixed it I will be thankful for your answer.

答:
I resolved this problem in this way:

Navigate to Android Studio Settings - Build,Execution,Deployment - Gradle

Choose "Use local gradle distribution" and "Offline work", click "Apply"

At last you'll find it's ok, and at this time you can also choose back to "use  default gradle wrapper", it's normal


问:
TypeError: 'int' object is ubsubscriptable in python
I am writing a program that looks to see if in a word with three consecutive double letters, like bookkeeping.

When I try to run the program, I get the error, TypeError: 'int' object is ubsubscriptable.  Any reason why?

```<code>def find_word(string):

    count = 0
    for eachLetter in range(len(string)):
        if eachLetter[count] == eachLetter[count + 1] and eachLetter[count+ 2] == eachLetter[count + 3] and eachLetter[count+ 4] == eachLetter[count + 5]:
            print string
        else:
            count = count + 1

def main():

  try:
  fin = open('words.txt') #open the file
  except:
  print("No file")

  for eachLine in fin:
 string = eachLine
 find_word(string)

if __name__== '__main__':
  main()
</code>```

答:
```<code>fin = open('words.txt')
string = fin.readline()

def find_word(string):
    for string in fin:
        count = 0
        for count in range(len(string)-5):
              if string[count] == string[count + 1] and string[count+ 2] == string[count + 3] and string[count+ 4] == string[count + 5]:
                 print(string)

def main(fin):

    for string in fin:

        return find_word(string)

main(fin)
</code>```

Body:
I am writing a program that looks to see if in a word with three consecutive double letters, like bookkeeping.

When I try to run the program, I get the error, TypeError: 'int' object is ubsubscriptable.  Any reason why?

def find_word(string):

    count = 0
    for eachLetter in range(len(string)):
        if eachLetter[count] == eachLetter[count + 1] and eachLetter[count+ 2] == eachLetter[count + 3] and eachLetter[count+ 4] == eachLetter[count + 5]:
            print string
        else:
            count = count + 1

def main():

  try:
  fin = open('words.txt') #open the file
  except:
  print("No file")

  for eachLine in fin:
 string = eachLine
 find_word(string)

if __name__== '__main__':
  main()


问:
How to remove the word ‘api’ from Azure functions url
When you create an Http triggered API, Azure function hosts it on

```<code>https://[function-app-name].azurewebsites.net/api/[Route-configured-in-application]
</code>```

Is there any way of getting rid of the term api from the URL and make it look like:

```<code>https://[function-app-name].azurewebsites.net/[Route-configured-in-application]
</code>```

答:
You could also leverage the power of Azure Function Proxies for this, which might be better if you want to be explicit about which methods or routes you want to access.

Just create a proxy.json file and add the following piece of JSON to it.

```<code>{
  "$schema": "http://json.schemastore.org/proxies",
  "proxies": {
    "myazurefunctionproxy": {
      "matchCondition": {
        "methods": ["GET"],
        "route": "/{slug}"
      },
      "backendUri": "https://%WEBSITE_HOSTNAME%/api/{slug}"
    },
  }
}
</code>```

This sample will redirect all GET-requests to a route with /api/ prefixed.

Body:
When you create an Http triggered API, Azure function hosts it on

https://[function-app-name].azurewebsites.net/api/[Route-configured-in-application]

Is there any way of getting rid of the term api from the URL and make it look like:

https://[function-app-name].azurewebsites.net/[Route-configured-in-application]

Body:
You could also leverage the power of Azure Function Proxies for this, which might be better if you want to be explicit about which methods or routes you want to access.

Just create a proxy.json file and add the following piece of JSON to it.

{
  "$schema": "http://json.schemastore.org/proxies",
  "proxies": {
    "myazurefunctionproxy": {
      "matchCondition": {
        "methods": ["GET"],
        "route": "/{slug}"
      },
      "backendUri": "https://%WEBSITE_HOSTNAME%/api/{slug}"
    },
  }
}

This sample will redirect all GET-requests to a route with /api/ prefixed.


问:
Java exceptions wrapping: bad practice?
Coming from a PHP world where there's only one way to write exceptions handling.. I found the wrapping of exceptions in Java a bit "ugly":

```<code>public void exampleOneException(String input) throws MyBusinessException {
    try {
        // do something
    } catch (NumberFormatException e) {
        throw new MyBusinessException("Error...", e);
    }
}
</code>```

I prefer to use this style instead:

```<code>public void exampleTwoException() {
    try {
        // do something
    } catch (MyBusinessException e) {
        log.error("Error...: " + e);
    } catch (NumberFormatException e) {
        log.error("Error...: " + e);
    }
}
</code>```

Is there any difference or best practices on those approaches on handling exceptions?

答:
These are both valid approaches for two different scenarios.

In the first scenario, the method can't do anything intelligent about the exception, but it has to "report" it upwards. That way the caller can catch the exception and decide what to do with it (e.g. cancel the flow, pop a message up to the user, log it, etc.)

In the second scenario, you catch the exception and log it, effectively hiding the failure from the caller. This type of handling may be useful if the caller doesn't really care if the operation succeeded or not.

Title: Java exceptions wrapping: bad practice?

Body:
Coming from a PHP world where there's only one way to write exceptions handling.. I found the wrapping of exceptions in Java a bit "ugly":

public void exampleOneException(String input) throws MyBusinessException {
    try {
        // do something
    } catch (NumberFormatException e) {
        throw new MyBusinessException("Error...", e);
    }
}

I prefer to use this style instead:

public void exampleTwoException() {
    try {
        // do something
    } catch (MyBusinessException e) {
        log.error("Error...: " + e);
    } catch (NumberFormatException e) {
        log.error("Error...: " + e);
    }
}

Is there any difference or best practices on those approaches on handling exceptions?