问:
Validation for digit only in an EditText
I am trying to make a simple functionality which the user inserts 2 numbers and a toast present the sum...
First, in order to do so, I would like to verify the user insert only digits. If not, I would like to set toast message (error) explains that only digits allow here. I use a boolean isdigit (EditText input) method.
However, I get an error -maybe because the for loop cannot accept null?</p>

```<code>public class MainActivity extends AppCompatActivity {
private EditText firstIntCB, secundIntCB;
private Button getProductCB;

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

    addDataToDisplay();
}

public void addDataToDisplay() {
   if (isdigit(firstIntCB)==true && isdigit(secundIntCB)==true){
        firstIntCB = (EditText)findViewById(R.id.firstNumber);
        secundIntCB = (EditText)findViewById(R.id.secundNumber);
        getProductCB =(Button)findViewById(R.id.GetProduct);

        getProductCB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Integer intFirst = Integer.parseInt(firstIntCB.getText().toString());
                Integer intSec = Integer.parseInt(secundIntCB.getText().toString());
                String product = Integer.toString((int)Math.pow(intFirst,intSec));
                Toast.makeText
                        (getApplicationContext(),String.valueOf(product), Toast.LENGTH_LONG).show();
            }
        });
    }
}

public boolean isdigit(EditText input) {
    String data=input.getText().toString().trim();
    for(int i=0;i<data.length();i++)
    {
        if (!Character.isDigit(data.charAt(i)))
            return false;

    }
    return true;
}
</code>```

答:
you are making a mistake..you should findViewById in your onCreate then do the other things.

the compiler try to resolve if condition but you not defined your edit text.

So:

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

    firstIntCB = (EditText)findViewById(R.id.firstNumber);
    secundIntCB = (EditText)findViewById(R.id.secundNumber);
    getProductCB =(Button)findViewById(R.id.GetProduct);

addDataToDisplay();
}
</code>```

then put android:inputType="number" in your edit text xml

i hope this work for you

Body:
I am trying to make a simple functionality which the user inserts 2 numbers and a toast present the sum...
First, in order to do so, I would like to verify the user insert only digits. If not, I would like to set toast message (error) explains that only digits allow here. I use a boolean isdigit (EditText input) method.
However, I get an error -maybe because the for loop cannot accept null?

public class MainActivity extends AppCompatActivity {
private EditText firstIntCB, secundIntCB;
private Button getProductCB;

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

    addDataToDisplay();
}

public void addDataToDisplay() {
   if (isdigit(firstIntCB)==true && isdigit(secundIntCB)==true){
        firstIntCB = (EditText)findViewById(R.id.firstNumber);
        secundIntCB = (EditText)findViewById(R.id.secundNumber);
        getProductCB =(Button)findViewById(R.id.GetProduct);

        getProductCB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Integer intFirst = Integer.parseInt(firstIntCB.getText().toString());
                Integer intSec = Integer.parseInt(secundIntCB.getText().toString());
                String product = Integer.toString((int)Math.pow(intFirst,intSec));
                Toast.makeText
                        (getApplicationContext(),String.valueOf(product), Toast.LENGTH_LONG).show();
            }
        });
    }
}

public boolean isdigit(EditText input) {
    String data=input.getText().toString().trim();
    for(int i=0;i<data.length();i++)
    {
        if (!Character.isDigit(data.charAt(i)))
            return false;

    }
    return true;
}

Body:
you are making a mistake..you should findViewById in your onCreate then do the other things.

the compiler try to resolve if condition but you not defined your edit text.

So:

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

    firstIntCB = (EditText)findViewById(R.id.firstNumber);
    secundIntCB = (EditText)findViewById(R.id.secundNumber);
    getProductCB =(Button)findViewById(R.id.GetProduct);

addDataToDisplay();
}

then put android:inputType="number" in your edit text xml

i hope this work for you


来源: stackexchange

问:
Animate SVG on scroll
I'm animating an SVG line based on my scroll position. It works but the FPS is really low and the animation itself is laggy. I pretty sure it's my native Javascript skills that are screwing things up, but I don't know how to solve it.

I made a quick and dirty JSbin replica of what I currently have on the actual website;

http://jsbin.com/vigaqoxiru/edit?html,css,js,output

```<code>window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || function(f){setTimeout(f, 1000/60)}

document.addEventListener('DOMContentLoaded', function() {
    Timeline();
});

function Timeline() {
    requestAnimationFrame(animateLine)

    function convertRange( value, r1, r2 ) {
         return ( value - r1[ 0 ] ) * ( r2[ 1 ] - r2[ 0 ] ) / ( r1[ 1 ] - r1[ 0 ] ) + r2[ 0 ];
    }

    function animateLine() {
        var offset = window.scrollY;
        var wheight = window.innerHeight;
        var timeline = document.querySelector(".Approach--steps");
        var theight = timeline.getBoundingClientRect().top - wheight;

        if (theight < 0) {
            var timelineMin = timeline.offsetHeight;
            var objectMin = timeline.offsetTop;
            var objectMax = timeline.offsetTop + timeline.offsetHeight;

            document.querySelector(".Approach--timeline svg").setAttribute("style", "transform: scaleY(" + Math.floor(convertRange( (offset + wheight), [objectMin, objectMax], [0, 1.0]) * 100) / 100 + ")");
        }
    }

    window.addEventListener('scroll', function(){
        requestAnimationFrame(animateLine)
    });
}
</code>```

As you can see it's jumpy it doesn't scroll at 60fps, altho I'm using the scale attribute, requestAnimationFrame and rounded values. Any idea what a better way of implementing this animation is? Preferably without jQuery. GSAP is okay since I'm already running it.

答:
Here's a gist of a working GSAP example.

You mentioned you plan on adding other elements to your SVG. I would recommend you read the GSAP/SVG docs here.

When animating with GSAP, I'd pretty much always recommend using an ID selector.

ContentLicense: CC BY-SA 3.0

Title: Animate SVG on scroll

Body:
I'm animating an SVG line based on my scroll position. It works but the FPS is really low and the animation itself is laggy. I pretty sure it's my native Javascript skills that are screwing things up, but I don't know how to solve it.

I made a quick and dirty JSbin replica of what I currently have on the actual website;

http://jsbin.com/vigaqoxiru/edit?html,css,js,output

window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || function(f){setTimeout(f, 1000/60)}

document.addEventListener('DOMContentLoaded', function() {
    Timeline();
});

function Timeline() {
    requestAnimationFrame(animateLine)

    function convertRange( value, r1, r2 ) {
         return ( value - r1[ 0 ] ) * ( r2[ 1 ] - r2[ 0 ] ) / ( r1[ 1 ] - r1[ 0 ] ) + r2[ 0 ];
    }

    function animateLine() {
        var offset = window.scrollY;
        var wheight = window.innerHeight;
        var timeline = document.querySelector(".Approach--steps");
        var theight = timeline.getBoundingClientRect().top - wheight;

        if (theight < 0) {
            var timelineMin = timeline.offsetHeight;
            var objectMin = timeline.offsetTop;
            var objectMax = timeline.offsetTop + timeline.offsetHeight;

            document.querySelector(".Approach--timeline svg").setAttribute("style", "transform: scaleY(" + Math.floor(convertRange( (offset + wheight), [objectMin, objectMax], [0, 1.0]) * 100) / 100 + ")");
        }
    }

    window.addEventListener('scroll', function(){
        requestAnimationFrame(animateLine)
    });
}

As you can see it's jumpy it doesn't scroll at 60fps, altho I'm using the scale attribute, requestAnimationFrame and rounded values. Any idea what a better way of implementing this animation is? Preferably without jQuery. GSAP is okay since I'm already running it.


问:
Am I using Javascript call-backs appropriately (object-oriented style)?
I have the following code example to use an object that receives the action from the callback.  Doesn't seem like this is a good design pattern.  Or is it?

When setTimeOut() fires on the function after 1 second, it uses the objInstance global variable (DOM scope) to access the ClassExample object instance.  Can someone recommend a better way to utilize callbacks within an object oriented design?

The whole idea is so I can use the callback to update data within my object instance (increment a variable for example).

```<code>function ClassExample{
    this.initiate = function() {
        setTimeOut(objInstance.afterTimeOut,1000); //using the objects global handle
    }

    this.afterTimeOut = function() {
        alert("Received!");
    }

}

var objInstance = new ClassExample(); //instance
objInstance.initiate();
</code>```

答:
```<code>function ClassExample{
    this.afterTimeOut = function() {
        alert("Received!");
    }; // Don't forget these

    setTimeOut(afterTimeOut, 1000); // Don't use () if you're passing the function as an argument
}

var objInstance = new ClassExample(); //instance
</code>```

That way you don't need the initiate() method.

If you really want the initiate() method, I'd do it like this:

```<code>function ClassExample{
    var self = this;

    self.afterTimeOut = function() {
        alert("Received!");
    };

    self.initiate = function() {
        setTimeOut(self.afterTimeOut, 1000);
    };

}

var objInstance = new ClassExample(); //instance
objInstance.initiate();
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have the following code example to use an object that receives the action from the callback.  Doesn't seem like this is a good design pattern.  Or is it?

When setTimeOut() fires on the function after 1 second, it uses the objInstance global variable (DOM scope) to access the ClassExample object instance.  Can someone recommend a better way to utilize callbacks within an object oriented design?

The whole idea is so I can use the callback to update data within my object instance (increment a variable for example).

function ClassExample{
    this.initiate = function() {
        setTimeOut(objInstance.afterTimeOut,1000); //using the objects global handle
    }

    this.afterTimeOut = function() {
        alert("Received!");
    }

}

var objInstance = new ClassExample(); //instance
objInstance.initiate();

Body:
function ClassExample{
    this.afterTimeOut = function() {
        alert("Received!");
    }; // Don't forget these

    setTimeOut(afterTimeOut, 1000); // Don't use () if you're passing the function as an argument
}

var objInstance = new ClassExample(); //instance

That way you don't need the initiate() method.

If you really want the initiate() method, I'd do it like this:

function ClassExample{
    var self = this;

    self.afterTimeOut = function() {
        alert("Received!");
    };

    self.initiate = function() {
        setTimeOut(self.afterTimeOut, 1000);
    };

}

var objInstance = new ClassExample(); //instance
objInstance.initiate();


问:
Get Where Condition From SQL Query in java
how can i get exact Condition From SQL Query like below :

```<code>select * from users where name = "ned stark" order by id ;
select * from users where name = "rob stark" group by id ;
</code>```

i want to get ' name = "ned stark" ' and ' name = "rob stark" ';
is there way to do this ?

答:
You can solve your problem using simply substring:</p>

```<code>String aa = "select * from test where a='aa' and b='bb' order by aa";
int startIndext = aa.indexOf("where") + 5;
int endIndex = aa.indexOf("group");
if(endIndex<0) endIndex = aa.indexOf("order");
if(endIndex<0) endIndex = aa.length();
String whereCondition = aa.substring(startIndext, endIndex);
System.out.println("whereCondition: " + whereCondition);
</code>```

Body:
how can i get exact Condition From SQL Query like below :

select * from users where name = "ned stark" order by id ;
select * from users where name = "rob stark" group by id ;

i want to get ' name = "ned stark" ' and ' name = "rob stark" ';
is there way to do this ?

Body:
You can solve your problem using simply substring:

String aa = "select * from test where a='aa' and b='bb' order by aa";
int startIndext = aa.indexOf("where") + 5;
int endIndex = aa.indexOf("group");
if(endIndex<0) endIndex = aa.indexOf("order");
if(endIndex<0) endIndex = aa.length();
String whereCondition = aa.substring(startIndext, endIndex);
System.out.println("whereCondition: " + whereCondition);


问:
Why does changing a variable from a lambda not work?
I have been working on Tkinter and am finding trouble passing values between different frames, so I followed this tutorial here, using the "shared data" solution provided by Bryan Oakley and adding it to my own code.
Except I cannot set the value in the "shared data" dictionary as a command on a button.

A few comments in the code below outline the problem. If I just try to change the variable during the init of my choice page, it changes normally. But putting it in a lambda means that the dictionary variable won't change at all. And trying to use a def for the button command has its own complications.

```<code>import tkinter as tk
import tkinter.ttk as ttk

# from tkinter import messagebox

TITLE_FONT = ("Segoe UI Light", 22)
SUBTITLE_FONT = ("Segoe UI Light", 12)

window_size = [300, 200]

resistors = []
choice = "default"

class RegApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        tk.Tk.iconbitmap(self, default="test.ico")
        tk.Tk.wm_title(self, "Test")

        self.shared_data = {
            "choice": tk.StringVar(),
        }

        container = tk.Frame(self, width=window_size[0], height=window_size[1])
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}

        for F in panels:
            frame = F(container, self)

            self.frames[F] = frame

            frame.grid(row=0, column=0, sticky="NSEW")

        self.show_frame(WelcomePage)

    def show_frame(self, container):
        frame = self.frames[container]
        frame.tkraise()

class WelcomePage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        title_label = ttk.Label(self, text="Welcome", font=TITLE_FONT)
        subtitle_label = ttk.Label(self, text="Let's run some numbers.", font=SUBTITLE_FONT)
        start_button = ttk.Button(self, text="Begin", width=24, command=lambda: controller.show_frame(ChoicePage))
        title_label.pack(pady=(40, 5))
        subtitle_label.pack(pady=(0, 10))
        start_button.pack()

class ChoicePage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        self.controller.shared_data["choice"].set("test2")  # Here, the variable is set fine

        title_label = ttk.Label(self, text="Is your resistor network \nin series or parallel?", font=SUBTITLE_FONT,
                                justify=tk.CENTER)
        series_button = ttk.Button(self, text="Series", width=24,
                                   command=lambda: [self.controller.shared_data["choice"].set("series"), controller.show_frame(ValuePage)])
        # But when I use it in a lambda, the variable doesn't even seem to set at all. It switches to the next page and has the value ""
        parallel_button = ttk.Button(self, text="Parallel", width=24,
                                     command=lambda: controller.show_frame(ValuePage))

        title_label.pack()
        series_button.pack()
        parallel_button.pack()

        # TODO Make the user select between 'series' and 'parallel'

class ValuePage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        title_label = ttk.Label(self, text=self.controller.shared_data["choice"].get(), font=SUBTITLE_FONT,
                                justify=tk.CENTER)

        title_label.pack()

panels = [WelcomePage, ChoicePage, ValuePage]

app = RegApp()
app.resizable(False, False)
app.geometry('{}x{}'.format(window_size[0], window_size[1]))
app.mainloop()
</code>```

答:
well passing data between frames isn't too hard. there are 2 ways I like to do it.

Method 1:

setup a frame to be something like this....

```<code>class ThirdName(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        self.controller = controller
</code>```

now just say something like:

```<code>self.data = "this is some data"
</code>```

now when you're in another frame you can call it like this:

```<code>print(ThirdName.data)
>>> "this is some data"
</code>```

Second way is just to send it somewhere like this:

```<code>value_1 = 'Richard'
bobby_def(value_1, 42, 'this is some text')
</code>```

...

```<code>def bobby_def(name, number, text)
    print(text)

    or...
    return(name, number, text)
</code>```

Bobby will get the data :)

ok.... second point... moving between frames can be done with something like this:

```<code>self.button_to_go_to_home_page = tk.Button(self, text='Third\nPage', font=Roboto_Normal_Font,
                             command=lambda: self.controller.show_frame(ThirdName),
                             height=2, width=12, bd = 0, activeforeground=active_fg, activebackground=active_bg, highlightbackground=border_colour,
                             foreground=bg_text_colour, background=background_deselected)
self.button_to_go_to_home_page.place(x=20, y=280)
</code>```

**set up a frame with stuff like this:

```<code>class SecondName(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        self.controller = controller
</code>```

Yes, the self.controller method is one I use too and it's nice to have lots of your data together in one frame.

Body:
I have been working on Tkinter and am finding trouble passing values between different frames, so I followed this tutorial here, using the "shared data" solution provided by Bryan Oakley and adding it to my own code.
Except I cannot set the value in the "shared data" dictionary as a command on a button.

A few comments in the code below outline the problem. If I just try to change the variable during the init of my choice page, it changes normally. But putting it in a lambda means that the dictionary variable won't change at all. And trying to use a def for the button command has its own complications.

import tkinter as tk
import tkinter.ttk as ttk

# from tkinter import messagebox

TITLE_FONT = ("Segoe UI Light", 22)
SUBTITLE_FONT = ("Segoe UI Light", 12)

window_size = [300, 200]

resistors = []
choice = "default"

class RegApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        tk.Tk.iconbitmap(self, default="test.ico")
        tk.Tk.wm_title(self, "Test")

        self.shared_data = {
            "choice": tk.StringVar(),
        }

        container = tk.Frame(self, width=window_size[0], height=window_size[1])
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}

        for F in panels:
            frame = F(container, self)

            self.frames[F] = frame

            frame.grid(row=0, column=0, sticky="NSEW")

        self.show_frame(WelcomePage)

    def show_frame(self, container):
        frame = self.frames[container]
        frame.tkraise()

class WelcomePage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        title_label = ttk.Label(self, text="Welcome", font=TITLE_FONT)
        subtitle_label = ttk.Label(self, text="Let's run some numbers.", font=SUBTITLE_FONT)
        start_button = ttk.Button(self, text="Begin", width=24, command=lambda: controller.show_frame(ChoicePage))
        title_label.pack(pady=(40, 5))
        subtitle_label.pack(pady=(0, 10))
        start_button.pack()

class ChoicePage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        self.controller.shared_data["choice"].set("test2")  # Here, the variable is set fine

        title_label = ttk.Label(self, text="Is your resistor network \nin series or parallel?", font=SUBTITLE_FONT,
                                justify=tk.CENTER)
        series_button = ttk.Button(self, text="Series", width=24,
                                   command=lambda: [self.controller.shared_data["choice"].set("series"), controller.show_frame(ValuePage)])
        # But when I use it in a lambda, the variable doesn't even seem to set at all. It switches to the next page and has the value ""
        parallel_button = ttk.Button(self, text="Parallel", width=24,
                                     command=lambda: controller.show_frame(ValuePage))

        title_label.pack()
        series_button.pack()
        parallel_button.pack()

        # TODO Make the user select between 'series' and 'parallel'

class ValuePage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        title_label = ttk.Label(self, text=self.controller.shared_data["choice"].get(), font=SUBTITLE_FONT,
                                justify=tk.CENTER)

        title_label.pack()

panels = [WelcomePage, ChoicePage, ValuePage]

app = RegApp()
app.resizable(False, False)
app.geometry('{}x{}'.format(window_size[0], window_size[1]))
app.mainloop()

Body:
well passing data between frames isn't too hard. there are 2 ways I like to do it.

Method 1:

setup a frame to be something like this....

class ThirdName(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        self.controller = controller

now just say something like:

self.data = "this is some data"

now when you're in another frame you can call it like this:

print(ThirdName.data)
>>> "this is some data"

Second way is just to send it somewhere like this:

value_1 = 'Richard'
bobby_def(value_1, 42, 'this is some text')

...

def bobby_def(name, number, text)
    print(text)

    or...
    return(name, number, text)

Bobby will get the data :)

ok.... second point... moving between frames can be done with something like this:

self.button_to_go_to_home_page = tk.Button(self, text='Third\nPage', font=Roboto_Normal_Font,
                             command=lambda: self.controller.show_frame(ThirdName),
                             height=2, width=12, bd = 0, activeforeground=active_fg, activebackground=active_bg, highlightbackground=border_colour,
                             foreground=bg_text_colour, background=background_deselected)
self.button_to_go_to_home_page.place(x=20, y=280)

**set up a frame with stuff like this:

class SecondName(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        self.controller = controller

Yes, the self.controller method is one I use too and it's nice to have lots of your data together in one frame.


问:
Checking constructor parameter for null before calling base
I usually check constructor arguments for null values in the following manner:

```<code>public class SomeClass(SomeArgument someArgument)
{
     if(someArgument == null) throw new ArgumentNullException("someArgument");
}
</code>```

But say I have a class that inherits from another class:

```<code>public abstract class TheBase
{
    public TheBase(int id)
    {

    }
}

public class TheArgument
{
    public int TheId { get; set; }
}

public class TheInheritor : TheBase
{
    public TheInheritor(TheArgument theArgument) : base(theArgument.TheId)
    {

    }
}
</code>```

And someone now constructs an instance of TheInheritor like this:

```<code>var theVar = new TheInheritor(null);
</code>```

I can't think of a way that to check for null before base is being called (and throwing a NullReferenceException). Short of letting TheBase's constructor accept an instance of TheArgument I can't see how I could have this sanity-check. But what if TheArgument is related only to TheInheritor and there are a lot of other classes inheriting from TheBase?

Any recommendations on how to solve this?

答:
As of C# 6.0 you can use null-coalescing operator combined with the null-conditional operator like this:</p>

```<code>public TheInheritor(TheArgument theArgument)
    : base(theArgument?.TheId ?? throw new ArgumentNullException(nameof(theArgument)))
{

}
</code>```

Body:
I usually check constructor arguments for null values in the following manner:

public class SomeClass(SomeArgument someArgument)
{
     if(someArgument == null) throw new ArgumentNullException("someArgument");
}

But say I have a class that inherits from another class:

public abstract class TheBase
{
    public TheBase(int id)
    {

    }
}

public class TheArgument
{
    public int TheId { get; set; }
}

public class TheInheritor : TheBase
{
    public TheInheritor(TheArgument theArgument) : base(theArgument.TheId)
    {

    }
}

And someone now constructs an instance of TheInheritor like this:

var theVar = new TheInheritor(null);

I can't think of a way that to check for null before base is being called (and throwing a NullReferenceException). Short of letting TheBase's constructor accept an instance of TheArgument I can't see how I could have this sanity-check. But what if TheArgument is related only to TheInheritor and there are a lot of other classes inheriting from TheBase?

Any recommendations on how to solve this?

Body:
As of C# 6.0 you can use null-coalescing operator combined with the null-conditional operator like this:

public TheInheritor(TheArgument theArgument)
    : base(theArgument?.TheId ?? throw new ArgumentNullException(nameof(theArgument)))
{

}


问:
Git Bash: Not accepting my keyboard input
So, I have reproduced it. Running:
git ls-files|grep navbar.html|xargs vim

 in my Git Bash and exiting vim making my Git Bash not accept keyboard inputs anymore. However my other Git Bash windows working fine.

Any ideas how can I get arround this problem?

答:
This is a common vim usage error (see also https://unix.stackexchange.com/questions/77395/grep-l-xargs-vim-generates-a-warning-why). This command will do what you want:

git ls-files | grep navbar.html | xargs sh -c 'vim "$@" <$0' /dev/tty


问:
How to sort a list of objects by date when date is String?
I have the following Java POJO, Start date is a string:

POJO Object:

```<code>public class Schedule {

    private String id;

    private String startDate = "";

    //const and getters and setters
}
</code>```

I want to sort a list of these objects by the start date field:

Adding POJOS to list:

```<code>List<Schedule> schedules = new ArrayList<Schedule>();

Schedule s1 = new Schedule();
s1.setStartDate("2018-09-01T15:00:00+0000");

Schedule s2 = new Schedule();
s2.setStartDate("2018-09-15T15:00:00+0000");

schedules.add(s1);
schedules.add(s2);
</code>```

I have tried writing a comparator but it does not seem to work, is there a way of sorting strings by date (earliest first)?

Edit: I am currently using Java 7

答:
Basically you need to convert the timezones to dates as part of the sorting operation:</p>

```<code>schedules.sort((s1, s2) -> {
  ZonedDateTime d1 = DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse(s1.getStartDate(), ZonedDateTime::from);
  ZonedDateTime d2 = DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse(s2.getStartDate(), ZonedDateTime::from);

  return d1.compareTo(d2);
});
</code>```

Body:
I have the following Java POJO, Start date is a string:

POJO Object:

public class Schedule {

    private String id;

    private String startDate = "";

    //const and getters and setters
}

I want to sort a list of these objects by the start date field:

Adding POJOS to list:

List<Schedule> schedules = new ArrayList<Schedule>();

Schedule s1 = new Schedule();
s1.setStartDate("2018-09-01T15:00:00+0000");

Schedule s2 = new Schedule();
s2.setStartDate("2018-09-15T15:00:00+0000");

schedules.add(s1);
schedules.add(s2);

I have tried writing a comparator but it does not seem to work, is there a way of sorting strings by date (earliest first)?

Edit: I am currently using Java 7

Body:
Basically you need to convert the timezones to dates as part of the sorting operation:

schedules.sort((s1, s2) -> {
  ZonedDateTime d1 = DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse(s1.getStartDate(), ZonedDateTime::from);
  ZonedDateTime d2 = DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse(s2.getStartDate(), ZonedDateTime::from);

  return d1.compareTo(d2);
});


问:
std::string part into integer
I have a std::string: 01001, I want to get each number:

```<code>std::string foo = "01001";
for (int i=0; i < foo.size(); ++i)
{
   int res = atoi( foo[i] );  // fail
   int res = atoi( &foo[i] ); // ok, but res = 0 in any case
}
</code>```

How to do that?

答:
Each digit can be obtained by simply using subtraction:

```<code>int res = foo[i] - '0';
</code>```

atoi takes a null-terminated string, not an individual character.  The subtraction approach works because the ten decimal digits are guaranteed to be consecutive in the character set (obviously, if there is a chance that you'll have nondigit characters in the string, you'll want to do proper error handling).

Title: std::string part into integer

Body:
I have a std::string: 01001, I want to get each number:

std::string foo = "01001";
for (int i=0; i < foo.size(); ++i)
{
   int res = atoi( foo[i] );  // fail
   int res = atoi( &foo[i] ); // ok, but res = 0 in any case
}

How to do that?

Body:
Each digit can be obtained by simply using subtraction:

int res = foo[i] - '0';

atoi takes a null-terminated string, not an individual character.  The subtraction approach works because the ten decimal digits are guaranteed to be consecutive in the character set (obviously, if there is a chance that you'll have nondigit characters in the string, you'll want to do proper error handling).


问:
jQuery: how to unbind an event binded to document object?
I've a bad-programmed library which is doing this

```<code>$(document).on('click','#keep_first_only_button', function(){
</code>```

I wrote, after this, a piece of code to 'override' this bad behaviour

```<code>$("keep_first_only_button").unbind("click");
$("keep_first_only_button").on("click", selectKeepFirstOfAll);
</code>```

BUT this is not working, then document.click function handler is triggered again

I cannot unbind all click events from document, because disasters will happen in the page.

Which is the right way to proceed in this situation?

EDIT: Sorry for time loosing question, I didn't see the missing '#' in my selector. I'm really sorry !

答:
If you want remove event with out consider selector use </p>

<p>$(document).off("click","**");</p>

Body:
I've a bad-programmed library which is doing this

$(document).on('click','#keep_first_only_button', function(){

I wrote, after this, a piece of code to 'override' this bad behaviour

$("keep_first_only_button").unbind("click");
$("keep_first_only_button").on("click", selectKeepFirstOfAll);

BUT this is not working, then document.click function handler is triggered again

I cannot unbind all click events from document, because disasters will happen in the page.

Which is the right way to proceed in this situation?

EDIT: Sorry for time loosing question, I didn't see the missing '#' in my selector. I'm really sorry !

Body:
If you want remove event with out consider selector use

$(document).off("click","**");


问:
How to evaluate multiple expression in if--elif statement in python?
How to evaluate multiple expression in if--elif in below code snipet.

I am sure its basic syntax issue

```<code>n=5
if n%2 != 0:
    print ("weird")
elif n%2 == 0 && 2 < n && n <5:
    print "Not Weird"
elif n%2 == 0 && 6 < n && n < 20:
    print "Weird"
elif n%2 == 0 && n >20:
    print "NOt Weird"
</code>```

答:
Some points while writing if else:

1. Don't repeat code if a condition is repeating break it into nested if-else.
2. Use 2 < n < 5 rather than 2 < n and n < 5, write code in pythonic style.

3. use else for default cases, don't put unnecessary conditions.

4. You are using print in 2 different styles, use one.

```<code>n=5
if n%2 != 0:
    print("weird")
else:
    if 2 < n < 5:
        print("Not Weird")
    elif 6 < n < 20:
        print("Weird")
    else:
        print("NOt Weird")
</code>```

Body:
How to evaluate multiple expression in if--elif in below code snipet.

I am sure its basic syntax issue

n=5
if n%2 != 0:
    print ("weird")
elif n%2 == 0 && 2 < n && n <5:
    print "Not Weird"
elif n%2 == 0 && 6 < n && n < 20:
    print "Weird"
elif n%2 == 0 && n >20:
    print "NOt Weird"

Body:
Some points while writing if else:

1. Don't repeat code if a condition is repeating break it into nested if-else.
2. Use 2 < n < 5 rather than 2 < n and n < 5, write code in pythonic style.

3. use else for default cases, don't put unnecessary conditions.

4. You are using print in 2 different styles, use one.

n=5
if n%2 != 0:
    print("weird")
else:
    if 2 < n < 5:
        print("Not Weird")
    elif 6 < n < 20:
        print("Weird")
    else:
        print("NOt Weird")


问:
Cant pull or push dockerhub repo to or from my local machine - docker
I have a local project I want to push to docker hub. I have an account with docker hub and i created a repository for testing docker out. My local file with my project is called docker-test and it is a django application. My docker hub project is also named docker-test. I am running the following commands and I am getting the following errors... Can anyone help me...

This is the push

```<code>docker push omaryap/docker-test
The push refers to a repository [docker.io/omaryap/docker-test]
An image does not exist locally with the tag: omaryap/docker-test
</code>```

this is the pull

```<code>omars-mbp:docker-test omarjandali$ docker pull omaryap/docker-test
Using default tag: latest
Error response from daemon: manifest for omaryap/docker-test:latest not found
</code>```

This is the link to my docker hub repository:

```<code>https://hub.docker.com/r/omaryap/docker-test/
</code>```

答:
The error

docker push omaryap/docker-test
  The push refers to a repository [docker.io/omaryap/docker-test]
  An image does not exist locally with the tag: omaryap/docker-test

says that, there is no local image with that tag. So first you need to build the image and tag it locally, before pushing it to the hub.

And this error

omars-mbp:docker-test omarjandali$ docker pull omaryap/docker-test
  Using default tag: latest
  Error response from daemon: manifest for omaryap/docker-test:latest not found

is saying that there is no image in that repository.

Please build the image. I recommend you to start with creating a docker file for your application and then building it locally.

You can follow this link for step by step process
https://semaphoreci.com/community/tutorials/dockerizing-a-python-django-web-application

Body:
I have a local project I want to push to docker hub. I have an account with docker hub and i created a repository for testing docker out. My local file with my project is called docker-test and it is a django application. My docker hub project is also named docker-test. I am running the following commands and I am getting the following errors... Can anyone help me...

This is the push

docker push omaryap/docker-test
The push refers to a repository [docker.io/omaryap/docker-test]
An image does not exist locally with the tag: omaryap/docker-test

this is the pull

omars-mbp:docker-test omarjandali$ docker pull omaryap/docker-test
Using default tag: latest
Error response from daemon: manifest for omaryap/docker-test:latest not found

This is the link to my docker hub repository:

https://hub.docker.com/r/omaryap/docker-test/


问:
How to Merge multiple workbook in excel with Charts/Graphs
i have two different Excel files(workbook), one have 2 sheets and another have 3, through PHP code using PHP Excel library , i managed to combine all  these in one file and able to make one file with 5 sheets, all the data & table are fine , but there are no any pie charts & graphs( its blank).
How can i combine workbook along with charts & graphs.</p>

```<code>include ("PHPExcel.php");

$inputFileType1 = 'Excel2007';
$inputFileName1 = 'a.xlsx';
$inputFileType2 = 'Excel2007';
$inputFileName2 = 'b.xlsx';
$outputFileType = 'Excel2007';
$outputFileName = 'c.xlsx';

 // Load the first workbook (an xlsx file)
$objPHPExcelReader1 = PHPExcel_IOFactory::createReader($inputFileType1);
$objPHPExcelReader1->setIncludeCharts(TRUE);

$objPHPExcel1 = $objPHPExcelReader1->load($inputFileName1);

// Load the second workbook (an xls file)
$objPHPExcelReader2 = PHPExcel_IOFactory::createReader($inputFileType2);
$objPHPExcelReader2->setIncludeCharts(TRUE);
$objPHPExcel2 = $objPHPExcelReader2->load($inputFileName2);

// Merge the second workbook into the first
$objPHPExcel2->getActiveSheet()->setTitle('Unique worksheet name');
$objPHPExcel1->addExternalSheet($objPHPExcel2->getActiveSheet());

 // Save the merged workbook under a new name (could save under the original
 name)
// as an xls file
$objPHPExcelWriter = PHPExcel_IOFactory::createWriter($objPHPExcel1,$outputFileType);
$objPHPExcelWriter->save($outputFileName);
</code>```

答:
```<code>$inputFileType1 = 'Excel2007';
$inputFileName1 = 'inputData1.xlsx';
$inputFileType2 = 'Excel5';
$inputFileName2 = 'inputData2.xls';
$outputFileType = 'Excel5';
$outputFileName = 'outputData.xls';

// Load the first workbook (an xlsx file)
$objPHPExcelReader1 = PHPExcel_IOFactory::createReader($inputFileType1);
$objPHPExcel1 = $objPHPExcelReader1->load($inputFileName1);

// Load the second workbook (an xls file)
$objPHPExcelReader2 = PHPExcel_IOFactory::createReader($inputFileType2);
$objPHPExcel2 = $objPHPExcelReader2->load($inputFileName2);

// Merge the second workbook into the first
$objPHPExcel2->getActiveSheet()->setTitle('Unique worksheet name');
$objPHPExcel1->addExternalSheet($objPHPExcel2->getActiveSheet());

// Save the merged workbook under a new name (could save under the original name)
// as an xls file
$objPHPExcelWriter = PHPExcel_IOFactory::createWriter($objPHPExcel1,$outputFileType);
$objPHPExcelWriter->save($outputFileName);
</code>```

Body:
i have two different Excel files(workbook), one have 2 sheets and another have 3, through PHP code using PHP Excel library , i managed to combine all  these in one file and able to make one file with 5 sheets, all the data & table are fine , but there are no any pie charts & graphs( its blank).
How can i combine workbook along with charts & graphs.

include ("PHPExcel.php");

$inputFileType1 = 'Excel2007';
$inputFileName1 = 'a.xlsx';
$inputFileType2 = 'Excel2007';
$inputFileName2 = 'b.xlsx';
$outputFileType = 'Excel2007';
$outputFileName = 'c.xlsx';

 // Load the first workbook (an xlsx file)
$objPHPExcelReader1 = PHPExcel_IOFactory::createReader($inputFileType1);
$objPHPExcelReader1->setIncludeCharts(TRUE);

$objPHPExcel1 = $objPHPExcelReader1->load($inputFileName1);

// Load the second workbook (an xls file)
$objPHPExcelReader2 = PHPExcel_IOFactory::createReader($inputFileType2);
$objPHPExcelReader2->setIncludeCharts(TRUE);
$objPHPExcel2 = $objPHPExcelReader2->load($inputFileName2);

// Merge the second workbook into the first
$objPHPExcel2->getActiveSheet()->setTitle('Unique worksheet name');
$objPHPExcel1->addExternalSheet($objPHPExcel2->getActiveSheet());

 // Save the merged workbook under a new name (could save under the original
 name)
// as an xls file
$objPHPExcelWriter = PHPExcel_IOFactory::createWriter($objPHPExcel1,$outputFileType);
$objPHPExcelWriter->save($outputFileName);


问:
How to put month and year in database according to end of year
i have some checkboxes which created by For loop like this:

```<code>for ($i=1; $i <= $loan['loanreqmonth']; $i++)
{
    echo '<input name="loan['.$i.']" type="checkbox" value="'.$i.'">loan # '.$i.'</div>';
}
</code>```

and i process and import the selected checkboxes whith something like this:

```<code>foreach($_POST['loan'] as $loan)
{
    mysql_query("INSERT INTO `loanpays`(`loanid`,`type`,`num`,`codemelli`, `price`, `month`, `year`,`stamp`) VALUES ('$loan[ID]','loan','$loan','$_SESSION[codemelli]','$priceloan','$month','$year','$stamp')");
}
</code>```

i want to put month (1-12) and year(2017-2020) from current month and year for each selected checkbox.
for example the first checkbox month is (11) and year is(2017)
the next one is 12 / 2017
but the problem is the next one is 1 / 2018!

how can I solve this problem?

答:
If I understand the question correctly:

Look at modulo operator (%) it gives you a remainer after division by the specified number - lets say 2 % 12 = 2, 13 % 12 = 1 - this will allow you to loop through months 1 to 12 infinitely, you just need to take care of the 12 month because 12 % 12 will give you 0 where you need 12.

Too iterate the year, simply check whether the current loop month value is divisable by 12 (x % 12 == 0) and if so iterate the year at the end of loop, cause next month will be January of next year...

Body:
i have some checkboxes which created by For loop like this:

for ($i=1; $i <= $loan['loanreqmonth']; $i++)
{
    echo '<input name="loan['.$i.']" type="checkbox" value="'.$i.'">loan # '.$i.'
';
}

and i process and import the selected checkboxes whith something like this:

foreach($_POST['loan'] as $loan)
{
    mysql_query("INSERT INTO `loanpays`(`loanid`,`type`,`num`,`codemelli`, `price`, `month`, `year`,`stamp`) VALUES ('$loan[ID]','loan','$loan','$_SESSION[codemelli]','$priceloan','$month','$year','$stamp')");
}

i want to put month (1-12) and year(2017-2020) from current month and year for each selected checkbox.
for example the first checkbox month is (11) and year is(2017)
the next one is 12 / 2017
but the problem is the next one is 1 / 2018!

how can I solve this problem?


问:
Modifying the javascript array and pushing it into array is copying to every element in array
I am not able to understand why it is copying the modified value to every element in the javascript array. Can somebody please explain the concept why?

```<code>var obj = {x:12};

var arr =[];

for(var i=0;i<5;i++){
    obj["x"] = i;
    arr.push(obj);
    println("Inside -> " + JSON.stringify(arr));
}
println("Output -> " + JSON.stringify(arr));
</code>```

Output of the above code returns -

```<code>Inside -> [{"x":0}]
Inside -> [{"x":1},{"x":1}]
Inside -> [{"x":2},{"x":2},{"x":2}]
Inside -> [{"x":3},{"x":3},{"x":3},{"x":3}]
Inside -> [{"x":4},{"x":4},{"x":4},{"x":4},{"x":4}]

Output -> [{"x":4},{"x":4},{"x":4},{"x":4},{"x":4}]
</code>```

答:
You're pushing an reference of the original Object into the array.
By changing the value of an reference-object you do it for the original one too.

To prevent that you have to clone it.

```<code>const clone = Object.assign({}, obj)
</code>```

Example:

var obj = {
  x: 12
};

var arr = [];

for (var i = 0; i < 5; i++) {
  const clone = Object.assign({}, obj);
  clone["x"] = i;
  arr.push(clone);
  println("Inside -> " + JSON.stringify(arr));
}
println("Output -> " + JSON.stringify(arr));

function println(x) {
  console.log(x);
}```

Object.assign (MDN)

Body:
I am not able to understand why it is copying the modified value to every element in the javascript array. Can somebody please explain the concept why?

var obj = {x:12};

var arr =[];

for(var i=0;i<5;i++){
    obj["x"] = i;
    arr.push(obj);
    println("Inside -> " + JSON.stringify(arr));
}
println("Output -> " + JSON.stringify(arr));

Output of the above code returns -

Inside -> [{"x":0}]
Inside -> [{"x":1},{"x":1}]
Inside -> [{"x":2},{"x":2},{"x":2}]
Inside -> [{"x":3},{"x":3},{"x":3},{"x":3}]
Inside -> [{"x":4},{"x":4},{"x":4},{"x":4},{"x":4}]

Output -> [{"x":4},{"x":4},{"x":4},{"x":4},{"x":4}]

Body:
You're pushing an reference of the original Object into the array.
By changing the value of an reference-object you do it for the original one too.

To prevent that you have to clone it.

const clone = Object.assign({}, obj)

Example:

var obj = {
  x: 12
};

var arr = [];

for (var i = 0; i < 5; i++) {
  const clone = Object.assign({}, obj);
  clone["x"] = i;
  arr.push(clone);
  println("Inside -> " + JSON.stringify(arr));
}
println("Output -> " + JSON.stringify(arr));

function println(x) {
  console.log(x);
}

Object.assign (MDN)


答:
change your addDataToDisplay(); method like this</p>

```<code>public void addDataToDisplay() {
    firstIntCB = (EditText)findViewById(R.id.firstNumber);
    secundIntCB = (EditText)findViewById(R.id.secundNumber);
    getProductCB =(Button)findViewById(R.id.GetProduct);

        getProductCB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isdigit(firstIntCB)==true && isdigit(secundIntCB)==true) {
                    Integer intFirst = Integer.parseInt(firstIntCB.getText().toString());
                    Integer intSec = Integer.parseInt(secundIntCB.getText().toString());
                    String product = Integer.toString((int) Math.pow(intFirst, intSec));
                    Toast.makeText
                            (getApplicationContext(), String.valueOf(product), Toast.LENGTH_LONG).show();
                }else{
                    Toast.makeText(getApplicationContext(),"Enter values", Toast.LENGTH_LONG).show();
                }
            }
        });

}
</code>```

Title: Validation for digit only in an EditText

Body:
I am trying to make a simple functionality which the user inserts 2 numbers and a toast present the sum...
First, in order to do so, I would like to verify the user insert only digits. If not, I would like to set toast message (error) explains that only digits allow here. I use a boolean isdigit (EditText input) method.
However, I get an error -maybe because the for loop cannot accept null?

public class MainActivity extends AppCompatActivity {
private EditText firstIntCB, secundIntCB;
private Button getProductCB;

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

    addDataToDisplay();
}

public void addDataToDisplay() {
   if (isdigit(firstIntCB)==true && isdigit(secundIntCB)==true){
        firstIntCB = (EditText)findViewById(R.id.firstNumber);
        secundIntCB = (EditText)findViewById(R.id.secundNumber);
        getProductCB =(Button)findViewById(R.id.GetProduct);

        getProductCB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Integer intFirst = Integer.parseInt(firstIntCB.getText().toString());
                Integer intSec = Integer.parseInt(secundIntCB.getText().toString());
                String product = Integer.toString((int)Math.pow(intFirst,intSec));
                Toast.makeText
                        (getApplicationContext(),String.valueOf(product), Toast.LENGTH_LONG).show();
            }
        });
    }
}

public boolean isdigit(EditText input) {
    String data=input.getText().toString().trim();
    for(int i=0;i<data.length();i++)
    {
        if (!Character.isDigit(data.charAt(i)))
            return false;

    }
    return true;
}

Body:
change your addDataToDisplay(); method like this

public void addDataToDisplay() {
    firstIntCB = (EditText)findViewById(R.id.firstNumber);
    secundIntCB = (EditText)findViewById(R.id.secundNumber);
    getProductCB =(Button)findViewById(R.id.GetProduct);

        getProductCB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isdigit(firstIntCB)==true && isdigit(secundIntCB)==true) {
                    Integer intFirst = Integer.parseInt(firstIntCB.getText().toString());
                    Integer intSec = Integer.parseInt(secundIntCB.getText().toString());
                    String product = Integer.toString((int) Math.pow(intFirst, intSec));
                    Toast.makeText
                            (getApplicationContext(), String.valueOf(product), Toast.LENGTH_LONG).show();
                }else{
                    Toast.makeText(getApplicationContext(),"Enter values", Toast.LENGTH_LONG).show();
                }
            }
        });

}


问:
Remove a verb as a stopword
There are some words which are used sometimes as a verb and sometimes as other part of speech.

Example

A sentence with the meaning of the word as verb:

```<code>I blame myself for what happened
</code>```

And a sentence with the meaning of word as noun:

```<code>For what happened the blame is yours
</code>```

The word I want to detect is known to me, in the example above is "blame". I would like to detect and remove as stopwords only when it has meaning like a verb.

Is there any easy way to make it?

答:
You can do something like this in Python
 .

```<code>import ntlk
>>> text = word_tokenize("And now for something completely different")
>>> nltk.pos_tag(text)
[('And', 'CC'), ('now', 'RB'), ('for', 'IN'), ('something', 'NN'),
('completely', 'RB'), ('different', 'JJ')]
</code>```

And add youre filter to eliminate Verbs for instance .

Hope this is helpful !

Title: Remove a verb as a stopword

Body:
There are some words which are used sometimes as a verb and sometimes as other part of speech.

Example

A sentence with the meaning of the word as verb:

I blame myself for what happened

And a sentence with the meaning of word as noun:

For what happened the blame is yours

The word I want to detect is known to me, in the example above is "blame". I would like to detect and remove as stopwords only when it has meaning like a verb.

Is there any easy way to make it?

Body:
You can do something like this in Python
 .

import ntlk
>>> text = word_tokenize("And now for something completely different")
>>> nltk.pos_tag(text)
[('And', 'CC'), ('now', 'RB'), ('for', 'IN'), ('something', 'NN'),
('completely', 'RB'), ('different', 'JJ')]

And add youre filter to eliminate Verbs for instance .

Hope this is helpful !


答:
In your code you are pushing the same object to all indices in array. You can use Object.assign to copy an object and push a copy each to each index.

var obj = {x:12};

var arr =[];

for(var i=0;i<5;i++){
    let objCopy = Object.assign({}, obj);
    objCopy["x"] = i;
    arr.push(objCopy);
    console.log("Inside -> " + JSON.stringify(arr));
}
console.log("Output -> " + JSON.stringify(arr));```

Title: Modifying the javascript array and pushing it into array is copying to every element in array


问:
Spring Data Couchbase example can't resolve Repository instance
Using Couchbase Enterprise Edition 5.0.0 build 2873 and Spring Data Couchbase 2.1.2, I am getting the error explained at the bottom of the question. Go forward if you just need the short story.

If you want a little more explanation, here it comes:

Imagine that the CrudRepository methods are fine to me. I mean, I don't need to add any more methods.

How the repository would look like? Would I declare an empty repository just like this?

```<code>@Repository
public interface PersonRepository extends CrudRepository<Person, String> {
// Empty
}
</code>```

Or would I use directly CrudRepositoy as my Base repository. I don't think so, because you need to pass Type and ID to the CrudRepository.

But the question is not that. Here comes the question:

How Spring knows how to instantiate PersonRepository, taking into account that there is no implementation of that base repository? Take a look to PersonService and PersonServiceImpl interface/implementation.

Interface:

```<code>@Service
public interface PersonService {
    Person findOne (String id);
    List<Person> findAll();
    //...
}
</code>```

Implementation:

```<code>public class PersonServiceImpl implements PersonService {

    // This is the variable for the repository
    @Autowired
    private PersonRepository personRepository;

    public Person findOne(String id){
        return personRepository(id);
    }

    public List<Person> findAll(){
        List<Hero> personList = new ArrayList<>();

        Iterator<Person> it = personRepository.iterator();

        while (it.hasNext()){
            personList.add(it.next());
        }

        return personList;
    }
//...
}
</code>```

Is it really enough with declaring an empty PersonRepository extending from CrudRepository? No need to implement and say anything about each method of CrudRepository?. At least something to tell Spring about some constructor...

This doubt are all because I am getting this error when Spring tries to inject the personRepository variable:

```<code>Error creating bean with name 'personRepository': Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities).
</code>```

Apparently, it is asking to have some class defining at least the constructor of the implementation. How do I tell Spring to avoid those type ambiguities mentioned in the error?

答:
As for the repository you'll need to extend CouchbaseRepository if you're strictly working with Couchbase, by that your repository will expose lower level couchbase objects/functionality.

For example

```<code>public interface PersonRepository extends CouchbaseRepository<Person, String> {
}
</code>```

For your service, you don't need to define findOne() and findAll(), those are strictly the responsibility of the repository.

For example

```<code>public interface PersonService {
    void doOperationOnPerson(String personId);
}

@Service
public class PersonServiceImpl implements PersonService {
    @Autowired
    PersonRepository personRepo;

    @Override
    void doOperationOnPerson(String personId) {
    Person person = personRepo.findById(personId);
    //do operation
    }
}
</code>```

Note that the @Service annotation goes on the implementation. (It actually should work either way but I think having the annotation on the implementation is more proper)

If you need to define custom queries then it should be done inside the repository itself.

You also might need to define an empty constructor on your Person class if you have a non-default constructor.

I suggest you to read more about Spring Data.

Body:
Using Couchbase Enterprise Edition 5.0.0 build 2873 and Spring Data Couchbase 2.1.2, I am getting the error explained at the bottom of the question. Go forward if you just need the short story.

If you want a little more explanation, here it comes:

Imagine that the CrudRepository methods are fine to me. I mean, I don't need to add any more methods.

How the repository would look like? Would I declare an empty repository just like this?

@Repository
public interface PersonRepository extends CrudRepository<Person, String> {
// Empty
}

Or would I use directly CrudRepositoy as my Base repository. I don't think so, because you need to pass Type and ID to the CrudRepository.

But the question is not that. Here comes the question:

How Spring knows how to instantiate PersonRepository, taking into account that there is no implementation of that base repository? Take a look to PersonService and PersonServiceImpl interface/implementation.

Interface:

@Service
public interface PersonService {
    Person findOne (String id);
    List<Person> findAll();
    //...
}

Implementation:

public class PersonServiceImpl implements PersonService {

    // This is the variable for the repository
    @Autowired
    private PersonRepository personRepository;

    public Person findOne(String id){
        return personRepository(id);
    }

    public List<Person> findAll(){
        List<Hero> personList = new ArrayList<>();

        Iterator<Person> it = personRepository.iterator();

        while (it.hasNext()){
            personList.add(it.next());
        }

        return personList;
    }
//...
}

Is it really enough with declaring an empty PersonRepository extending from CrudRepository? No need to implement and say anything about each method of CrudRepository?. At least something to tell Spring about some constructor...

This doubt are all because I am getting this error when Spring tries to inject the personRepository variable:

Error creating bean with name 'personRepository': Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities).

Apparently, it is asking to have some class defining at least the constructor of the implementation. How do I tell Spring to avoid those type ambiguities mentioned in the error?

Body:
As for the repository you'll need to extend CouchbaseRepository if you're strictly working with Couchbase, by that your repository will expose lower level couchbase objects/functionality.

For example

public interface PersonRepository extends CouchbaseRepository<Person, String> {
}

For your service, you don't need to define findOne() and findAll(), those are strictly the responsibility of the repository.

For example

public interface PersonService {
    void doOperationOnPerson(String personId);
}

@Service
public class PersonServiceImpl implements PersonService {
    @Autowired
    PersonRepository personRepo;

    @Override
    void doOperationOnPerson(String personId) {
    Person person = personRepo.findById(personId);
    //do operation
    }
}

Note that the @Service annotation goes on the implementation. (It actually should work either way but I think having the annotation on the implementation is more proper)

If you need to define custom queries then it should be done inside the repository itself.

You also might need to define an empty constructor on your Person class if you have a non-default constructor.

I suggest you to read more about Spring Data.


答:
This is the easiest way I see:</p>

```<code>std::string foo = "01001";
for (int i=0; i < foo.size(); ++i)
{
   int res = foo[i] - '0';
}
</code>```

Title: std::string part into integer

Body:
I have a std::string: 01001, I want to get each number:

std::string foo = "01001";
for (int i=0; i < foo.size(); ++i)
{
   int res = atoi( foo[i] );  // fail
   int res = atoi( &foo[i] ); // ok, but res = 0 in any case
}

How to do that?

Body:
This is the easiest way I see:

std::string foo = "01001";
for (int i=0; i < foo.size(); ++i)
{
   int res = foo[i] - '0';
}


问:
Calculate all the subsets of a list in python using java approach
I'm working through some interview problems and one of the classic ones, which uses backtracking, is to calculate the powerset (all the subsets) of a list. I have the java solution for the problem:

```<code>    public List<List<Integer>> subsets(int[] nums) {
     List<List<Integer>> list = new ArrayList<>();
     Arrays.sort(nums);
     backtrack(list, new ArrayList<>(), nums, 0);
     return list;
    }

   private void backtrack(List<List<Integer>> list , List<Integer> {
     tempList, int [] nums, int start){
     list.add(new ArrayList<>(tempList));
     for(int i = start; i < nums.length; i++){
      tempList.add(nums[i]);
     backtrack(list, tempList, nums, i + 1);
     tempList.remove(tempList.size() - 1);
   }
 }
</code>```

I'm trying to do the same thing but using python instead:

```<code>class Solution:
  def subsets(self, nums):
   lista = []
   self.backtrack(lista, [], sorted(nums), 0)
   return lista
 def backtrack(self, lista, tempList, nums, start):
   lista.append(tempList)
   for i in range(start, len(nums)):
     tempList.append(nums[i])
     self.backtrack(lista, tempList, nums, i+1)
     tempList.pop()
</code>```

I printed the tempList and it seems to be working as expected. The problem I believe is that it lista.append(tempList) is not working as I expected. Is there some particularity in python that is yielding this different result? Thanks!

答:
This problem (powerset iterator) is addressed already in the standard documentation of itertools module:

```<code> def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
</code>```

To address the problem of the final paragraph:

tempList.append(n) appends the argument as a whole (since a list is heterogeneous in Python, able to contain all types). You might replace it by temPist.extend(n) instead, which moves the elements, as you seem to expect.

Body:
I'm working through some interview problems and one of the classic ones, which uses backtracking, is to calculate the powerset (all the subsets) of a list. I have the java solution for the problem:

    public List<List<Integer>> subsets(int[] nums) {
     List<List<Integer>> list = new ArrayList<>();
     Arrays.sort(nums);
     backtrack(list, new ArrayList<>(), nums, 0);
     return list;
    }

   private void backtrack(List<List<Integer>> list , List<Integer> {
     tempList, int [] nums, int start){
     list.add(new ArrayList<>(tempList));
     for(int i = start; i < nums.length; i++){
      tempList.add(nums[i]);
     backtrack(list, tempList, nums, i + 1);
     tempList.remove(tempList.size() - 1);
   }
 }

I'm trying to do the same thing but using python instead:

class Solution:
  def subsets(self, nums):
   lista = []
   self.backtrack(lista, [], sorted(nums), 0)
   return lista
 def backtrack(self, lista, tempList, nums, start):
   lista.append(tempList)
   for i in range(start, len(nums)):
     tempList.append(nums[i])
     self.backtrack(lista, tempList, nums, i+1)
     tempList.pop()

I printed the tempList and it seems to be working as expected. The problem I believe is that it lista.append(tempList) is not working as I expected. Is there some particularity in python that is yielding this different result? Thanks!

Body:
This problem (powerset iterator) is addressed already in the standard documentation of itertools module:

 def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

To address the problem of the final paragraph:

tempList.append(n) appends the argument as a whole (since a list is heterogeneous in Python, able to contain all types). You might replace it by temPist.extend(n) instead, which moves the elements, as you seem to expect.


问:
Python slicing - Skips certain number of rows
I currently have 500 rows of data. I want to use the first fifty rows, then skip 50 rows and so on. How do I go on about doing this?</p>

Body:
eg :

import numpy as np
x = np.array(range(0,500)) // assign numpy array of 500
b = np.array(([True] * 50 + [False] * 50) * 5)
print(x[b])

output:

[  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17
  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35
  36  37  38  39  40  41  42  43  44  45  46  47  48  49 100 101 102 103
 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
 140 141 142 143 144 145 146 147 148 149 200 201 202 203 204 205 206 207
 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
 244 245 246 247 248 249 300 301 302 303 304 305 306 307 308 309 310 311
 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
 348 349 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449]


问:
ScriptDom + DeleteStatement
I want to insert "DeleteStatement" after any "DeclareTableVariableStatement"
but I don't know how!
it's my sample code.</p>

```<code>public override void Visit(StatementList node)
{
    foreach (DeclareTableVariableStatement declareTableVariableStatement in node.Statements.Where(a => a is DeclareTableVariableStatement).ToList())
    {
        BeginEndBlockStatement deleteBeginEndBlockStatement = new BeginEndBlockStatement()
        {
            StatementList = new StatementList()
        };

        DeleteStatement deleteStatement = new DeleteStatement()
        {
           DeleteSpecification=new DeleteSpecification()
           {
                Target= ???
           }
        };
        deleteBeginEndBlockStatement.StatementList.Statements.Add(deleteStatement);
        node.Statements.Insert(node.Statements.IndexOf(declareTableVariableStatement) + 1, deleteBeginEndBlockStatement);
    }
    base.Visit(node);
}
</code>```

答:
I found the solution !</p>

```<code>public override void Visit(StatementList node)
{
    foreach (DeclareTableVariableStatement declareTableVariableStatement in node.Statements.Where(a => a is DeclareTableVariableStatement).ToList())
    {
        BeginEndBlockStatement deleteBeginEndBlockStatement = new BeginEndBlockStatement()
        {
            StatementList = new StatementList()
        };

        DeleteStatement deleteStatement = new DeleteStatement()
        {
            DeleteSpecification = new DeleteSpecification()
            {
                Target = new VariableTableReference()
                {
                    Variable = new VariableReference()
                    {
                        Name = declareTableVariableStatement.Body.VariableName.Value
                    }
                }
            }
        };

        deleteBeginEndBlockStatement.StatementList.Statements.Add(deleteStatement);
        node.Statements.Insert(node.Statements.IndexOf(declareTableVariableStatement) + 1, deleteBeginEndBlockStatement);
    }
    base.Visit(node);
}
</code>```

Title: ScriptDom + DeleteStatement

Body:
I want to insert "DeleteStatement" after any "DeclareTableVariableStatement"
but I don't know how!
it's my sample code.

public override void Visit(StatementList node)
{
    foreach (DeclareTableVariableStatement declareTableVariableStatement in node.Statements.Where(a => a is DeclareTableVariableStatement).ToList())
    {
        BeginEndBlockStatement deleteBeginEndBlockStatement = new BeginEndBlockStatement()
        {
            StatementList = new StatementList()
        };

        DeleteStatement deleteStatement = new DeleteStatement()
        {
           DeleteSpecification=new DeleteSpecification()
           {
                Target= ???
           }
        };
        deleteBeginEndBlockStatement.StatementList.Statements.Add(deleteStatement);
        node.Statements.Insert(node.Statements.IndexOf(declareTableVariableStatement) + 1, deleteBeginEndBlockStatement);
    }
    base.Visit(node);
}

Body:
I found the solution !

public override void Visit(StatementList node)
{
    foreach (DeclareTableVariableStatement declareTableVariableStatement in node.Statements.Where(a => a is DeclareTableVariableStatement).ToList())
    {
        BeginEndBlockStatement deleteBeginEndBlockStatement = new BeginEndBlockStatement()
        {
            StatementList = new StatementList()
        };

        DeleteStatement deleteStatement = new DeleteStatement()
        {
            DeleteSpecification = new DeleteSpecification()
            {
                Target = new VariableTableReference()
                {
                    Variable = new VariableReference()
                    {
                        Name = declareTableVariableStatement.Body.VariableName.Value
                    }
                }
            }
        };

        deleteBeginEndBlockStatement.StatementList.Statements.Add(deleteStatement);
        node.Statements.Insert(node.Statements.IndexOf(declareTableVariableStatement) + 1, deleteBeginEndBlockStatement);
    }
    base.Visit(node);
}


问:
MySQL select AND statement
I have a MySQL database like that:

```
Id | Name
1  | term1
1  | term2
1  | term3
2  | term4
2  | term5
2  | term6
```

I want to select ID that contains term1 AND term3.

Or, for example, term4 AND term5 AND term6.

How can I do that?
Any help would be greatly appreciated, thanks.

答:
```<code> SELECT Id, Count(Distinct Name)
 FROM Table
 WHERE Name in ('term1','term3')
 Group By Id
 HAVING Count(Distinct Name) > 1
</code>```

I think it's what you want. If you want 3 terms you change the Having ...>2

Title: MySQL select AND statement

Body:
I have a MySQL database like that:

Id | Name
1  | term1
1  | term2
1  | term3
2  | term4
2  | term5
2  | term6

I want to select ID that contains term1 AND term3.

Or, for example, term4 AND term5 AND term6.

How can I do that?
Any help would be greatly appreciated, thanks.

Body:
 SELECT Id, Count(Distinct Name)
 FROM Table
 WHERE Name in ('term1','term3')
 Group By Id
 HAVING Count(Distinct Name) > 1

I think it's what you want. If you want 3 terms you change the Having ...>2


问:
under which scenario AVAudioSessionRouteChangeReasonRouteConfigurationChange can be called
I have been investigating AVAudioSessionRouteChangeReason notification.
One of them is

```<code>AVAudioSessionRouteChangeReasonRouteConfigurationChange
</code>```

According to Apple document:
AVAudioSessionRouteChangeReasonRouteConfigurationChange

The set of input and output ports has not changed, but their configuration has—for example, a port’s selected data source has changed.

It is not very clear that under which scenario AVAudioSessionRouteChangeReasonRouteConfigurationChange can be called. If someone could make an example what a port's selected data source has changed meaning?

Thanks

答:
I'm looking for the 'Doc' answer as well, but I can also provide some example. After phone call ended I received AVAudioSessionInterruptionTypeEnded notification and just after it this one:

```<code>{
AVAudioSessionRouteChangePreviousRouteKey = "<AVAudioSessionRouteDescription: 0x1c001e380, \ninputs = (null); \noutputs = (\n    \"<AVAudioSessionPortDescription: 0x1c001e4d0, type = Speaker; name = G\\U0142o\\U015bnik; UID = Speaker; selectedDataSource = (null)>\"\n)>";
AVAudioSessionRouteChangeReasonKey = 8;
}
</code>```

and new Route was:

```<code><AVAudioSessionRouteDescription: 0x1c401de70,
inputs = (
    "<AVAudioSessionPortDescription: 0x1c401dac0, type = MicrophoneBuiltIn; name = iPhone Mikrofon; UID = Built-In Microphone; selectedDataSource = Bottom>"
);
outputs = (
    "<AVAudioSessionPortDescription: 0x1c401df10, type = Speaker; name = G\U0142o\U015bnik; UID = Speaker; selectedDataSource = (null)>"
)>
</code>```

So it looks like selected data source for microphone changed from null to bottom.

Body:
I have been investigating AVAudioSessionRouteChangeReason notification.
One of them is

AVAudioSessionRouteChangeReasonRouteConfigurationChange

According to Apple document:
AVAudioSessionRouteChangeReasonRouteConfigurationChange

The set of input and output ports has not changed, but their configuration has—for example, a port’s selected data source has changed.

It is not very clear that under which scenario AVAudioSessionRouteChangeReasonRouteConfigurationChange can be called. If someone could make an example what a port's selected data source has changed meaning?

Thanks

Body:
I'm looking for the 'Doc' answer as well, but I can also provide some example. After phone call ended I received AVAudioSessionInterruptionTypeEnded notification and just after it this one:

{
AVAudioSessionRouteChangePreviousRouteKey = "<AVAudioSessionRouteDescription: 0x1c001e380, \ninputs = (null); \noutputs = (\n    \"<AVAudioSessionPortDescription: 0x1c001e4d0, type = Speaker; name = G\\U0142o\\U015bnik; UID = Speaker; selectedDataSource = (null)>\"\n)>";
AVAudioSessionRouteChangeReasonKey = 8;
}

and new Route was:

<AVAudioSessionRouteDescription: 0x1c401de70,
inputs = (
    "<AVAudioSessionPortDescription: 0x1c401dac0, type = MicrophoneBuiltIn; name = iPhone Mikrofon; UID = Built-In Microphone; selectedDataSource = Bottom>"
);
outputs = (
    "<AVAudioSessionPortDescription: 0x1c401df10, type = Speaker; name = G\U0142o\U015bnik; UID = Speaker; selectedDataSource = (null)>"
)>

So it looks like selected data source for microphone changed from null to bottom.


问:
Which acceptance testing frameworks are better for backend development?
By backend I mean software systems that consume data, process files or communicate using machine interfaces (REST, SOAP, CORBA, etc...). No fancy web or UI testing is necessary. I have in mind Cucumber and Robotframework but I don't know how well suited they are in the task at hand.</p>

答: I have used Cucumber to test a batch application written in perl and plsql, an informatica transformation, and am currently using it to test a telephony ivr/queueing system.  Ruby provided the gems I needed to drive the system and it was very easy for the testers to learn the language/syntax. </p>


问:
digits after decimal point
how to get digits after decimal point from float number in objective c</p>

答:
this code works

```<code>CGFloat x = 2.43;
// CGFloat x = 3.145;
// CGFloat x = 2.0003;
// CGFloat x = 1.0;
// CGFloat x = 3.1415926535;

NSLog(@"%f -> %@", x, @([self numberOfFractionDigits:x]));

- (NSString *)numberOfFractionDigits:(CGFloat)number {
    CGFloat fractionalPart = number - (NSInteger)number;
    NSMutableString *r = [NSMutableString stringWithString:@""];
    while (fractionalPart) {
        [r appendFormat:@"%@", @((NSUInteger)(fractionalPart * 10 + .5))];
        number *= 10;
        fractionalPart = number - (NSInteger)number;
    }
    return r;
}
</code>```

output:

2.430000 -> 43

3.145000 -> 145

2.000300 -> 0003

1.000000 ->

3.141593 -> 1415926535 // for x = 3.1415926535;

Title: digits after decimal point

Body:
this code works

CGFloat x = 2.43;
// CGFloat x = 3.145;
// CGFloat x = 2.0003;
// CGFloat x = 1.0;
// CGFloat x = 3.1415926535;

NSLog(@"%f -> %@", x, @([self numberOfFractionDigits:x]));

- (NSString *)numberOfFractionDigits:(CGFloat)number {
    CGFloat fractionalPart = number - (NSInteger)number;
    NSMutableString *r = [NSMutableString stringWithString:@""];
    while (fractionalPart) {
        [r appendFormat:@"%@", @((NSUInteger)(fractionalPart * 10 + .5))];
        number *= 10;
        fractionalPart = number - (NSInteger)number;
    }
    return r;
}

output:

2.430000 -> 43

3.145000 -> 145

2.000300 -> 0003

1.000000 ->

3.141593 -> 1415926535 // for x = 3.1415926535;


问:
How to make click reveal in css/js?
Just want to know how to make click reveal when I click a button the word
"Phone" will change to "+971235051"

```<code><button type="button" class="btn btn-primary">Phone</button>
<span>+971235051</span>
</code>```

Any hint for this?I found a toggle, But can't find for click reveal.

Thankyou

答: <button type="button" id="btn" onclick="document.getElementById('btn').innerHTML = '+971235051'" class="btn btn-primary">Phone</button>```

Title: How to make click reveal in css/js?

Body:
Just want to know how to make click reveal when I click a button the word
"Phone" will change to "+971235051"

<button type="button" class="btn btn-primary">Phone</button>
+971235051

Any hint for this?I found a toggle, But can't find for click reveal.

Thankyou


问:
Alternative to using static factory (as cannot have abstract static methods)
I'm trying to build a functional package parser. I have a base class Datagram, now I was naively imagining I'd have it defined like this:

(Note on edit, this class is not abstract!)

```<code>public class Datagram
{
    public abstract static Datagram CreateFromDatagram(Datagram datagram);
}
</code>```

And then for specfic datagrams, say Ethernet and Tcp as an exampe:

```<code>public class EthernetDatagram : Datagram, IPayloadDatagram
{
    public override static Datagram CreateFromDatagram(Datagram datagram)
    {
        return new EthernetDatagram();
    }

    public Datagram Payload { get; }
}

public class TcpDatagram : Datagram, IPayloadDatagram
{
    public overrides static Datagram CreateFromDatagram(Datagram datagram)
    {
        return new TcpDatagram();
    }

    public Datagram Payload { get; }
}
</code>```

The reason for this (impossible) abstract static method is I want to have an extension method which allows me to "chain" all these packets together:

```<code>public static class DatagramExtensions
{
    public static T As<T>(this IPayloadDatagram datagram) where T : Datagram
    {
        return (T)T.CreateFromDatagram(datagram.Payload);
    }
}
</code>```

So, all I'd need to do to have a completely new datagram type ANewDatagram is have it define it's factory method CreateFromDatagram, and I'll be able to then merrily use my functional extension:

```<code>SomeDatagram.As<EthernetDatagram>().As<TcpDatagram>().As<ANewDatagram>()...
</code>```

and it'll all be extensible.

Given this isn't going to work as I can't inherit abstract classes, what would be a good alternative to instantiating a generic class like this?

I could use reflection, but then that's hiding it from the user. When I try create ANewDatagram I have to remember that I'm reflecting a CreateFromDatagram method later on.

I am currently using reflection to get the constructor - but there's no way for me to enforce there's a specific constructor that takes the payload. If someone creates a new Datagram there's no guarantee they add the right constructor, I'd have to inform them this in comments, which will very likely be missed, and the point of failure is at run-time at the latest possible point.

Is there a better alternative, architecturally, or with some form of interface/inheritence that could get around this issue?

(If anyone wants to see the full source code I'm working with, I'm trying to add these extensions to the packet interpretation library as part of https://github.com/PcapDotNet/Pcap.Net, with as little modification as possible)

答:
... but there's no way for me to enforce there's a specific
  constructor that takes the payload.

You could enforce it by declaring appropriate constructor in your base abstract class.

I also propose several modifications to your code. Since all of your derived classes are supposed to have the same Payload property, declare it in base Datagram class. Also consider declaring Datagram class as implementing IPayloadDatagram interface. It will make unnecessary to mark each derived class as implementing this interface.

Here is sample code that hopefully does what you need:

```<code>public interface IPayloadDatagram
{
    Datagram Payload { get; }
}

public abstract class Datagram : IPayloadDatagram
{
    public Datagram Payload { get; }

    protected Datagram(Datagram datagram)
    {
        Payload = datagram;
    }
}

public class EthernetDatagram : Datagram
{
    public EthernetDatagram(Datagram datagram) : base(datagram)
    {
    }
}

public static class DatagramExtensions
{
    public static T As<T>(this IPayloadDatagram datagram) where T : Datagram
    {
        return (T)Activator.CreateInstance(typeof(T), datagram.Payload);
    }
}
</code>```

Body:
I'm trying to build a functional package parser. I have a base class Datagram, now I was naively imagining I'd have it defined like this:

(Note on edit, this class is not abstract!)

public class Datagram
{
    public abstract static Datagram CreateFromDatagram(Datagram datagram);
}

And then for specfic datagrams, say Ethernet and Tcp as an exampe:

public class EthernetDatagram : Datagram, IPayloadDatagram
{
    public override static Datagram CreateFromDatagram(Datagram datagram)
    {
        return new EthernetDatagram();
    }

    public Datagram Payload { get; }
}

public class TcpDatagram : Datagram, IPayloadDatagram
{
    public overrides static Datagram CreateFromDatagram(Datagram datagram)
    {
        return new TcpDatagram();
    }

    public Datagram Payload { get; }
}

The reason for this (impossible) abstract static method is I want to have an extension method which allows me to "chain" all these packets together:

public static class DatagramExtensions
{
    public static T As<T>(this IPayloadDatagram datagram) where T : Datagram
    {
        return (T)T.CreateFromDatagram(datagram.Payload);
    }
}

So, all I'd need to do to have a completely new datagram type ANewDatagram is have it define it's factory method CreateFromDatagram, and I'll be able to then merrily use my functional extension:

SomeDatagram.As<EthernetDatagram>().As<TcpDatagram>().As<ANewDatagram>()...

and it'll all be extensible.

Given this isn't going to work as I can't inherit abstract classes, what would be a good alternative to instantiating a generic class like this?

I could use reflection, but then that's hiding it from the user. When I try create ANewDatagram I have to remember that I'm reflecting a CreateFromDatagram method later on.

I am currently using reflection to get the constructor - but there's no way for me to enforce there's a specific constructor that takes the payload. If someone creates a new Datagram there's no guarantee they add the right constructor, I'd have to inform them this in comments, which will very likely be missed, and the point of failure is at run-time at the latest possible point.

Is there a better alternative, architecturally, or with some form of interface/inheritence that could get around this issue?

(If anyone wants to see the full source code I'm working with, I'm trying to add these extensions to the packet interpretation library as part of https://github.com/PcapDotNet/Pcap.Net, with as little modification as possible)

Body:
... but there's no way for me to enforce there's a specific
  constructor that takes the payload.

You could enforce it by declaring appropriate constructor in your base abstract class.

I also propose several modifications to your code. Since all of your derived classes are supposed to have the same Payload property, declare it in base Datagram class. Also consider declaring Datagram class as implementing IPayloadDatagram interface. It will make unnecessary to mark each derived class as implementing this interface.

Here is sample code that hopefully does what you need:

public interface IPayloadDatagram
{
    Datagram Payload { get; }
}

public abstract class Datagram : IPayloadDatagram
{
    public Datagram Payload { get; }

    protected Datagram(Datagram datagram)
    {
        Payload = datagram;
    }
}

public class EthernetDatagram : Datagram
{
    public EthernetDatagram(Datagram datagram) : base(datagram)
    {
    }
}

public static class DatagramExtensions
{
    public static T As<T>(this IPayloadDatagram datagram) where T : Datagram
    {
        return (T)Activator.CreateInstance(typeof(T), datagram.Payload);
    }
}


问:
Chrome Doesn't Accept jQuery Symbol ($)
Not a problem as such but during development I noticed that Chrome doesn't accept the '$' symbol often used instead of 'jQuery'. But runs fine when 'jQuery' is used.

Noticed this with using Chromes developer tools and thought it was odd, anyone any ideas why?

答:
$ is a shorthand for jquery. Now, if some other libraries also uses $ along with jQuery, there occurs collisions in the usage of $.

It can be resolved by the following the below:

```<code><script src="mylibrary.js" ></script>
<script src="jquery.js"></script>
<script>
    jQuery.noConflict();
</script>
</code>```

Now after the first library jQuery takes full control over $, then the jQuery.noConflict() freesup the usage of $.
But now in your custom js whenever you want to make use of a jQuery method you can't use jQuery, you must use $.

Title: Chrome Doesn't Accept jQuery Symbol ($)

Body:
$ is a shorthand for jquery. Now, if some other libraries also uses $ along with jQuery, there occurs collisions in the usage of $.

It can be resolved by the following the below:

<script src="mylibrary.js" ></script>
<script src="jquery.js"></script>
<script>
    jQuery.noConflict();
</script>

Now after the first library jQuery takes full control over $, then the jQuery.noConflict() freesup the usage of $.
But now in your custom js whenever you want to make use of a jQuery method you can't use jQuery, you must use $.


问:
select2 results from server not displaying
I'm using Select2 4.0.3 trying to get the json returned from my server to appear as options in my drop down, but the results are simply not appearing when I open the drop down or search in the field.

```<code><body>
    <select class="select2-student form-control">
    </select>
</body>

<script>
    $(document).ready(function () {
        $(".select2-student").select2({
            ajax: {
                url: "/MyUrl",
                data: function (params) {
                    return {
                        text: params.term
                    };
                },
                processResults: function (data, params) {
                    return {
                        results: data
                    };
                }
            }
        });
    });
</script>
</code>```

I'm getting the response back as expected from the server when I enter matching text:

```<code>[{"Text":"My Student","Id":3}]
</code>```

And I'm getting "No results found" in the drop down when I input a string that doesn't match the server-side criteria (i.e. doesn't match what's in the "text" field), but when results ARE returned there's not even a drop down appearing with anything in it - and I'm not getting any errors either in my browser.

I've tried a number of variations on this code all day and have yet to get anything to work.  Advice?

答:
I know this is quite an old question, but a nicer way to do it would be to do something like this:

```<code>            processResults: function(data) {
                return {
                    results: jQuery.map(data, function(item) {
                        return {
                            id: item.key,
                            text: item.value
                        }
                    })
                };
            },
</code>```

That way you can just return a standard collection of mapped objects, without worrying about any casing.

Body:
I'm using Select2 4.0.3 trying to get the json returned from my server to appear as options in my drop down, but the results are simply not appearing when I open the drop down or search in the field.

    <select class="select2-student form-control">
    </select>

I'm getting the response back as expected from the server when I enter matching text:

[{"Text":"My Student","Id":3}]

And I'm getting "No results found" in the drop down when I input a string that doesn't match the server-side criteria (i.e. doesn't match what's in the "text" field), but when results ARE returned there's not even a drop down appearing with anything in it - and I'm not getting any errors either in my browser.

I've tried a number of variations on this code all day and have yet to get anything to work.  Advice?

Body:
I know this is quite an old question, but a nicer way to do it would be to do something like this:

            processResults: function(data) {
                return {
                    results: jQuery.map(data, function(item) {
                        return {
                            id: item.key,
                            text: item.value
                        }
                    })
                };
            },

That way you can just return a standard collection of mapped objects, without worrying about any casing.


问:
How to use result of CROSS APPLY in Full-Text search
I want to use the result of CROSS APPLY in full-text search (FREETEXT or CONTAINS) like this:

```<code>   SELECT  p.Id ,
            p.Name ,
            p.ShortDescription ,
            p.DisplayOrder ,
            cat.Name AS CategoryName
    FROM    dbo.Product AS p
            CROSS APPLY ( SELECT TOP 1
                                    c.Name ,
                                    c.Description ,
                                    c.Id
                          FROM      dbo.Product_Category_Mapping AS m
                                    LEFT JOIN dbo.Category AS c ON m.CategoryId = c.Id
                          WHERE     m.ProductId = p.Id
                                    AND c.Published = 1
                                    AND c.Deleted = 0
                        ) AS cat
    WHERE   p.Published = 1
            AND p.Deleted = 0
            AND ( CONTAINS ( p.NAME, @search )
                  OR CONTAINS ( p.FullDescription, @search )
                  OR CONTAINS ( cat.NAME, @search )
                );
</code>```

My problem is ==>  OR CONTAINS ( cat.Name, @search ).
The error returned by SQL Server is:

Cannot use a CONTAINS or FREETEXT predicate on column 'Name' because
  it is not full-text indexed.

It seems the result of CROSS APPLY is a table and this table is not full-text indexed. How can I apply the full-text index search condition to the result of the CROSS APPLY above?

答:
Try something like this:

```<code>SELECT  p.Id ,
            p.Name ,
            p.ShortDescription ,
            p.DisplayOrder ,
            cat.Name AS CategoryName
    FROM    dbo.Product AS p
            CROSS APPLY ( SELECT TOP 1
                                    c.Name ,
                                    c.Description ,
                                    c.Id
                          FROM      dbo.Product_Category_Mapping AS m
                                    LEFT JOIN dbo.Category AS c ON m.CategoryId = c.Id
                          WHERE     m.ProductId = p.Id
                                    AND c.Published = 1
                                    AND c.Deleted = 0
                        ) AS cat
    LEFT JOIN dbo.Category cat2 ON cat2.Id = cat.Id
    WHERE   p.Published = 1
            AND p.Deleted = 0
            AND ( CONTAINS ( p.NAME, @search )
                  OR CONTAINS ( p.FullDescription, @search )
                  OR CONTAINS ( cat2.NAME, @search )
                );
</code>```

Note, I have re-joined dbo.Category on main level and have changed CONTAINS predicate to reference cat2.NAME instead of cat.Name. cat is the CROSS JOIN alias which indeed is not under full text-index, but the main dbo.Category table aliased under cat2 IS under full-text index, so you can use its column NAME with CONTAINS.

Also, I think it would be better if you re-write your query and move the CONTAINS checks inside the CROSS JOIN like this:

```<code>SELECT  p.Id ,
            p.Name ,
            p.ShortDescription ,
            p.DisplayOrder ,
            cat.Name AS CategoryName
    FROM    dbo.Product AS p
            CROSS APPLY (
                SELECT TOP 1
                    c.Name ,
                    c.Description ,
                    c.Id,
                    (CASE WHEN CONTAINS(cat.NAME, @search) THEN 1 ELSE 0 END) as IsCategoryMatching
                FROM      dbo.Product_Category_Mapping AS m
                LEFT JOIN dbo.Category AS c ON m.CategoryId = c.Id
                WHERE m.ProductId = p.Id
                      AND c.Published = 1
                      AND c.Deleted = 0
            ) AS cat
    WHERE   p.Published = 1
            AND p.Deleted = 0
            AND ( CONTAINS ( p.NAME, @search )
                  OR CONTAINS ( p.FullDescription, @search )
                  OR cat.IsCategoryMatching=1
                );
</code>```

HTH

Body:
I want to use the result of CROSS APPLY in full-text search (FREETEXT or CONTAINS) like this:

   SELECT  p.Id ,
            p.Name ,
            p.ShortDescription ,
            p.DisplayOrder ,
            cat.Name AS CategoryName
    FROM    dbo.Product AS p
            CROSS APPLY ( SELECT TOP 1
                                    c.Name ,
                                    c.Description ,
                                    c.Id
                          FROM      dbo.Product_Category_Mapping AS m
                                    LEFT JOIN dbo.Category AS c ON m.CategoryId = c.Id
                          WHERE     m.ProductId = p.Id
                                    AND c.Published = 1
                                    AND c.Deleted = 0
                        ) AS cat
    WHERE   p.Published = 1
            AND p.Deleted = 0
            AND ( CONTAINS ( p.NAME, @search )
                  OR CONTAINS ( p.FullDescription, @search )
                  OR CONTAINS ( cat.NAME, @search )
                );

My problem is ==>  OR CONTAINS ( cat.Name, @search ).
The error returned by SQL Server is:

Cannot use a CONTAINS or FREETEXT predicate on column 'Name' because
  it is not full-text indexed.

It seems the result of CROSS APPLY is a table and this table is not full-text indexed. How can I apply the full-text index search condition to the result of the CROSS APPLY above?

Body:
Try something like this:

SELECT  p.Id ,
            p.Name ,
            p.ShortDescription ,
            p.DisplayOrder ,
            cat.Name AS CategoryName
    FROM    dbo.Product AS p
            CROSS APPLY ( SELECT TOP 1
                                    c.Name ,
                                    c.Description ,
                                    c.Id
                          FROM      dbo.Product_Category_Mapping AS m
                                    LEFT JOIN dbo.Category AS c ON m.CategoryId = c.Id
                          WHERE     m.ProductId = p.Id
                                    AND c.Published = 1
                                    AND c.Deleted = 0
                        ) AS cat
    LEFT JOIN dbo.Category cat2 ON cat2.Id = cat.Id
    WHERE   p.Published = 1
            AND p.Deleted = 0
            AND ( CONTAINS ( p.NAME, @search )
                  OR CONTAINS ( p.FullDescription, @search )
                  OR CONTAINS ( cat2.NAME, @search )
                );

Note, I have re-joined dbo.Category on main level and have changed CONTAINS predicate to reference cat2.NAME instead of cat.Name. cat is the CROSS JOIN alias which indeed is not under full text-index, but the main dbo.Category table aliased under cat2 IS under full-text index, so you can use its column NAME with CONTAINS.

Also, I think it would be better if you re-write your query and move the CONTAINS checks inside the CROSS JOIN like this:

SELECT  p.Id ,
            p.Name ,
            p.ShortDescription ,
            p.DisplayOrder ,
            cat.Name AS CategoryName
    FROM    dbo.Product AS p
            CROSS APPLY (
                SELECT TOP 1
                    c.Name ,
                    c.Description ,
                    c.Id,
                    (CASE WHEN CONTAINS(cat.NAME, @search) THEN 1 ELSE 0 END) as IsCategoryMatching
                FROM      dbo.Product_Category_Mapping AS m
                LEFT JOIN dbo.Category AS c ON m.CategoryId = c.Id
                WHERE m.ProductId = p.Id
                      AND c.Published = 1
                      AND c.Deleted = 0
            ) AS cat
    WHERE   p.Published = 1
            AND p.Deleted = 0
            AND ( CONTAINS ( p.NAME, @search )
                  OR CONTAINS ( p.FullDescription, @search )
                  OR cat.IsCategoryMatching=1
                );

HTH


问:
How can I verify if one list is a subset of another?
I need to verify if a list is a subset of another - a boolean return is all I seek.

Is testing equality on the smaller list after an intersection the fastest way to do this? Performance is of utmost importance given the number of datasets that need to be compared.

Adding further facts based on discussions:

Will either of the lists be the same for many tests?  It does as one of them is a static lookup table.

Does it need to be a list? It does not - the static lookup table can be anything that performs best. The dynamic one is a dict from which we extract the keys to perform a static lookup on.

What would be the optimal solution given the scenario?

答:
Set theory is inappropriate for lists since duplicates will result in wrong answers using set theory.

For example:

```<code>a = [1, 3, 3, 3, 5]
b = [1, 3, 3, 4, 5]
set(b) > set(a)
</code>```

has no meaning. Yes, it gives a false answer but this is not correct since set theory is just comparing: 1,3,5 versus 1,3,4,5. You must include all duplicates.

Instead you must count each occurrence of each item and do a greater than equal to check. This is not very expensive, because it is not using O(N^2) operations and does not require quick sort.

```<code>#!/usr/bin/env python

from collections import Counter

def containedInFirst(a, b):
  a_count = Counter(a)
  b_count = Counter(b)
  for key in b_count:
    if a_count.has_key(key) == False:
      return False
    if b_count[key] > a_count[key]:
      return False
  return True

a = [1, 3, 3, 3, 5]
b = [1, 3, 3, 4, 5]
print "b in a: ", containedInFirst(a, b)

a = [1, 3, 3, 3, 4, 4, 5]
b = [1, 3, 3, 4, 5]
print "b in a: ", containedInFirst(a, b)
</code>```

Then running this you get:

```<code>$ python contained.py
b in a:  False
b in a:  True
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Set theory is inappropriate for lists since duplicates will result in wrong answers using set theory.

For example:

a = [1, 3, 3, 3, 5]
b = [1, 3, 3, 4, 5]
set(b) > set(a)

has no meaning. Yes, it gives a false answer but this is not correct since set theory is just comparing: 1,3,5 versus 1,3,4,5. You must include all duplicates.

Instead you must count each occurrence of each item and do a greater than equal to check. This is not very expensive, because it is not using O(N^2) operations and does not require quick sort.

#!/usr/bin/env python

from collections import Counter

def containedInFirst(a, b):
  a_count = Counter(a)
  b_count = Counter(b)
  for key in b_count:
    if a_count.has_key(key) == False:
      return False
    if b_count[key] > a_count[key]:
      return False
  return True

a = [1, 3, 3, 3, 5]
b = [1, 3, 3, 4, 5]
print "b in a: ", containedInFirst(a, b)

a = [1, 3, 3, 3, 4, 4, 5]
b = [1, 3, 3, 4, 5]
print "b in a: ", containedInFirst(a, b)

Then running this you get:

$ python contained.py
b in a:  False
b in a:  True