问:
don`t succed in make one python file run another
I am trying to make one python file run another only if the user choose that option, and every time it runs the another file no matter what happened.

I have two options:

If the user chose option 1: the code needs to run SendMenu file.

If the user chose option 2: the code needs to run RecvimagesMenu file
but it doesn't work like I want, it opens the SendMenu file when I run the code.

Code:

```<code>import sys
from Tkinter import *
import Image, ImageTk
import SendMenu
import RecvimagesMenu

mGui = Tk()

def mhello():
    global v
    if(v.get() == 1): # if the user chose option 1
        mGui.destroy()
        SendMenu.run()
    if(v.get() == 2): # if the user chose option 2
        mGui.destroy()
        RecvimagesMenu.run()

    else: # if the user didn`t choose any option
        print "5"

def Action():
    global v
    print (v.get())

def close(): # close the window
    exit()

def menu():
    global v
    v = IntVar()

    menubar = Menu(mGui)  # menu

    filemenu = Menu(menubar, tearoff=0)  # menu works
    filemenu.add_command(label="Close", command=close)
    menubar.add_cascade(label="File", menu=filemenu)

    mGui.geometry('450x300+500+300')
    mGui.title('Nir`s ScreenShare')

    canvas = Canvas(mGui, width=500, height=150)
    canvas.pack(pady = 10)
    pilImage = Image.open("logo5.png")
    image = ImageTk.PhotoImage(pilImage)
    imagesprite = canvas.create_image(0, 0, image=image, anchor="nw")
    Radiobutton(mGui, text="Share My Screen             ", variable=v, value=1, command = Action).pack(anchor=CENTER)
    Radiobutton(mGui, text="Watch Another`s Screen", variable=v, value=2, command = Action).pack(anchor=CENTER, pady = 7.5)

    mbutton = Button(mGui, text='Start', command=mhello).pack()  # button\

    mGui.config(menu=menubar)  # menu helper

    mGui.mainloop()

menu()
</code>```

答:
The problem you have is when you import your python file into the other one, it runs all of the code. Since you have not given the code for those 2 I can make an educated guess. You are not putting the code in those files into functions

```<code>for example:
def printme( str ):
   print("str"
print"Hello world again"
</code>```

If this was in a RecvimagesMenu.py as soon as you import the code it would print "Hello world again" and then you call RecvimagesMenu.printme("hello world") it would print the "Hello world".

In your file you also have code not in functions which is being executed right away. Either remove this code or move it into functions and call them.

Body:
I am trying to make one python file run another only if the user choose that option, and every time it runs the another file no matter what happened.

I have two options:

If the user chose option 1: the code needs to run SendMenu file.

If the user chose option 2: the code needs to run RecvimagesMenu file
but it doesn't work like I want, it opens the SendMenu file when I run the code.

Code:

import sys
from Tkinter import *
import Image, ImageTk
import SendMenu
import RecvimagesMenu

mGui = Tk()

def mhello():
    global v
    if(v.get() == 1): # if the user chose option 1
        mGui.destroy()
        SendMenu.run()
    if(v.get() == 2): # if the user chose option 2
        mGui.destroy()
        RecvimagesMenu.run()

    else: # if the user didn`t choose any option
        print "5"

def Action():
    global v
    print (v.get())

def close(): # close the window
    exit()

def menu():
    global v
    v = IntVar()

    menubar = Menu(mGui)  # menu

    filemenu = Menu(menubar, tearoff=0)  # menu works
    filemenu.add_command(label="Close", command=close)
    menubar.add_cascade(label="File", menu=filemenu)

    mGui.geometry('450x300+500+300')
    mGui.title('Nir`s ScreenShare')

    canvas = Canvas(mGui, width=500, height=150)
    canvas.pack(pady = 10)
    pilImage = Image.open("logo5.png")
    image = ImageTk.PhotoImage(pilImage)
    imagesprite = canvas.create_image(0, 0, image=image, anchor="nw")
    Radiobutton(mGui, text="Share My Screen             ", variable=v, value=1, command = Action).pack(anchor=CENTER)
    Radiobutton(mGui, text="Watch Another`s Screen", variable=v, value=2, command = Action).pack(anchor=CENTER, pady = 7.5)

    mbutton = Button(mGui, text='Start', command=mhello).pack()  # button\

    mGui.config(menu=menubar)  # menu helper

    mGui.mainloop()

menu()

Body:
The problem you have is when you import your python file into the other one, it runs all of the code. Since you have not given the code for those 2 I can make an educated guess. You are not putting the code in those files into functions

for example:
def printme( str ):
   print("str"
print"Hello world again"

If this was in a RecvimagesMenu.py as soon as you import the code it would print "Hello world again" and then you call RecvimagesMenu.printme("hello world") it would print the "Hello world".

In your file you also have code not in functions which is being executed right away. Either remove this code or move it into functions and call them.


来源: stackexchange

问:
Laravel - Sum values between two dates
I need to sum values using Laravel db::table and get the result between two dates, example:

Date: 05/30/2016 Sold: 1
 Date: 05/31/2016 Sold: 2

So result should be Sold: 3

This is a search result given by a filter by date, i have done something like this with no results:

```<code>DB::table('sales')
 ->where('date',$date_from)
 ->where('date',$date_to)
 ->selectRaw('sum(price)')
 ->selectRaw('id')
 ->groupBy('id')
 ->get();
</code>```

答:
You should use whereBetween function, and I think you are using a wrong group by:

```<code>DB::table('sales')
        ->whereBetween('date', [$date_from, $date_to])
        ->groupBy('date')
        ->sum('price');
</code>```

And if the date column's type is a `DATETIME, you should use:

```<code>->groupBy(DB::raw("DATE(date)"))
</code>```

ContentLicense: CC BY-SA 3.0

Title: Laravel - Sum values between two dates

Body:
I need to sum values using Laravel db::table and get the result between two dates, example:

Date: 05/30/2016 Sold: 1
 Date: 05/31/2016 Sold: 2

So result should be Sold: 3

This is a search result given by a filter by date, i have done something like this with no results:

DB::table('sales')
 ->where('date',$date_from)
 ->where('date',$date_to)
 ->selectRaw('sum(price)')
 ->selectRaw('id')
 ->groupBy('id')
 ->get();

Body:
You should use whereBetween function, and I think you are using a wrong group by:

DB::table('sales')
        ->whereBetween('date', [$date_from, $date_to])
        ->groupBy('date')
        ->sum('price');

And if the date column's type is a `DATETIME, you should use:

->groupBy(DB::raw("DATE(date)"))


问:
How to install all the packages under JuliaStats?
I want to install all the packages under JuliaStats, but none of the followings is working:

```<code>julia> Pkg.add("JuliaStats")
ERROR: unknown package JuliaStats
 in macro expansion at ./pkg/entry.jl:53 [inlined]
 in (::Base.Pkg.Entry.##2#5{String,Base.Pkg.Types.VersionSet})() at ./task.jl:360
 in sync_end() at ./task.jl:311
 in macro expansion at ./task.jl:327 [inlined]
 in add(::String, ::Base.Pkg.Types.VersionSet) at ./pkg/entry.jl:51
 in (::Base.Pkg.Dir.##2#3{Array{Any,1},Base.Pkg.Entry.#add,Tuple{String}})() at ./pkg/dir.jl:31
 in cd(::Base.Pkg.Dir.##2#3{Array{Any,1},Base.Pkg.Entry.#add,Tuple{String}}, ::String) at ./file.jl:59
 in #cd#1(::Array{Any,1}, ::Function, ::Function, ::String, ::Vararg{Any,N}) at ./pkg/dir.jl:31
 in add(::String) at ./pkg/pkg.jl:100

julia> Pkg.add("julia-stats")
ERROR: unknown package julia-stats
 in macro expansion at ./pkg/entry.jl:53 [inlined]
 in (::Base.Pkg.Entry.##2#5{String,Base.Pkg.Types.VersionSet})() at ./task.jl:360
 in sync_end() at ./task.jl:311
 in macro expansion at ./task.jl:327 [inlined]
 in add(::String, ::Base.Pkg.Types.VersionSet) at ./pkg/entry.jl:51
 in (::Base.Pkg.Dir.##2#3{Array{Any,1},Base.Pkg.Entry.#add,Tuple{String}})() at ./pkg/dir.jl:31
 in cd(::Base.Pkg.Dir.##2#3{Array{Any,1},Base.Pkg.Entry.#add,Tuple{String}}, ::String) at ./file.jl:59
 in #cd#1(::Array{Any,1}, ::Function, ::Function, ::String, ::Vararg{Any,N}) at ./pkg/dir.jl:31
 in add(::String) at ./pkg/pkg.jl:100

julia> Pkg.add("juliastats")
ERROR: unknown package juliastats
 in macro expansion at ./pkg/entry.jl:53 [inlined]
 in (::Base.Pkg.Entry.##2#5{String,Base.Pkg.Types.VersionSet})() at ./task.jl:360
 in sync_end() at ./task.jl:311
 in macro expansion at ./task.jl:327 [inlined]
 in add(::String, ::Base.Pkg.Types.VersionSet) at ./pkg/entry.jl:51
 in (::Base.Pkg.Dir.##2#3{Array{Any,1},Base.Pkg.Entry.#add,Tuple{String}})() at ./pkg/dir.jl:31
 in cd(::Base.Pkg.Dir.##2#3{Array{Any,1},Base.Pkg.Entry.#add,Tuple{String}}, ::String) at ./file.jl:59
 in #cd#1(::Array{Any,1}, ::Function, ::Function, ::String, ::Vararg{Any,N}) at ./pkg/dir.jl:31
 in add(::String) at ./pkg/pkg.jl:100
</code>```

I was not able find any help regarding this issue on the homepage of JuliaStats. Any help?

答:
JuliaStats is not a library of packages.
It is an organization of people who together maintain collection of packages.

You don't want to install all of their packages.
Several of them are deprecated -- replaced by newer packages from the same org.

You want to install the package that you want, for your task.
The package manager will workout what other packages that one needs, and download them for your.

Eg you want to sample from a Trucated Gausian Distribution?
Then you'll want Distributions.jl.
Install that by running: Pkg.add("Distributions")

This will also install a number of other packages from Julia Stats: StatsFuns.jl, StatsBase.jl, and also from elsewhere Calculus.jl,  SpecialFunctions.jl.
Because these packages are required for Distributions.jl to run.

Body:
I want to install all the packages under JuliaStats, but none of the followings is working:

julia> Pkg.add("JuliaStats")
ERROR: unknown package JuliaStats
 in macro expansion at ./pkg/entry.jl:53 [inlined]
 in (::Base.Pkg.Entry.##2#5{String,Base.Pkg.Types.VersionSet})() at ./task.jl:360
 in sync_end() at ./task.jl:311
 in macro expansion at ./task.jl:327 [inlined]
 in add(::String, ::Base.Pkg.Types.VersionSet) at ./pkg/entry.jl:51
 in (::Base.Pkg.Dir.##2#3{Array{Any,1},Base.Pkg.Entry.#add,Tuple{String}})() at ./pkg/dir.jl:31
 in cd(::Base.Pkg.Dir.##2#3{Array{Any,1},Base.Pkg.Entry.#add,Tuple{String}}, ::String) at ./file.jl:59
 in #cd#1(::Array{Any,1}, ::Function, ::Function, ::String, ::Vararg{Any,N}) at ./pkg/dir.jl:31
 in add(::String) at ./pkg/pkg.jl:100

julia> Pkg.add("julia-stats")
ERROR: unknown package julia-stats
 in macro expansion at ./pkg/entry.jl:53 [inlined]
 in (::Base.Pkg.Entry.##2#5{String,Base.Pkg.Types.VersionSet})() at ./task.jl:360
 in sync_end() at ./task.jl:311
 in macro expansion at ./task.jl:327 [inlined]
 in add(::String, ::Base.Pkg.Types.VersionSet) at ./pkg/entry.jl:51
 in (::Base.Pkg.Dir.##2#3{Array{Any,1},Base.Pkg.Entry.#add,Tuple{String}})() at ./pkg/dir.jl:31
 in cd(::Base.Pkg.Dir.##2#3{Array{Any,1},Base.Pkg.Entry.#add,Tuple{String}}, ::String) at ./file.jl:59
 in #cd#1(::Array{Any,1}, ::Function, ::Function, ::String, ::Vararg{Any,N}) at ./pkg/dir.jl:31
 in add(::String) at ./pkg/pkg.jl:100

julia> Pkg.add("juliastats")
ERROR: unknown package juliastats
 in macro expansion at ./pkg/entry.jl:53 [inlined]
 in (::Base.Pkg.Entry.##2#5{String,Base.Pkg.Types.VersionSet})() at ./task.jl:360
 in sync_end() at ./task.jl:311
 in macro expansion at ./task.jl:327 [inlined]
 in add(::String, ::Base.Pkg.Types.VersionSet) at ./pkg/entry.jl:51
 in (::Base.Pkg.Dir.##2#3{Array{Any,1},Base.Pkg.Entry.#add,Tuple{String}})() at ./pkg/dir.jl:31
 in cd(::Base.Pkg.Dir.##2#3{Array{Any,1},Base.Pkg.Entry.#add,Tuple{String}}, ::String) at ./file.jl:59
 in #cd#1(::Array{Any,1}, ::Function, ::Function, ::String, ::Vararg{Any,N}) at ./pkg/dir.jl:31
 in add(::String) at ./pkg/pkg.jl:100

I was not able find any help regarding this issue on the homepage of JuliaStats. Any help?


问:
Wicket 6.22 Automatic redirection to external URL
I have a wicket (6.22) web application. I need to perform automatic redirection to an external URL. The scenario is described bellow:

The customers enter their data in a form

The server processes several actions and displays a result page

The result page should last 5 seconds and then automatically redirect customers to an external URL.
The result page contains a "back" link, so the customers may click on it to be redirected to the same external URL.

I did use "renderHead" function to add tag

<meta http-equiv="refresh" content="5; url=http://example.com">```

The issue is that I need to invalidate the session before the redirection. If I do so, the customers are redirected to my ExpiredSession page instead of the external URL.

Is their any clean solution to make it happend?

Thank you for your help

答:
Instead of using <meta http-equiv="refresh" content="5; url=http://example.com"> you can set up an Ajax behavior that will: 1) invalidate the session; 2) redirect to the external page

```<code> anyComponent.add(new AbstractAjaxTimerBehavior(Duration.seconds(5)) {
     @Override protected void onTimer(AjaxRequestTarget target) {
       getSession().invalidate();
       throw new RedirectToUrlException("https://external.page");
    }
 });
</code>```

Body:
I have a wicket (6.22) web application. I need to perform automatic redirection to an external URL. The scenario is described bellow:

The customers enter their data in a form

The server processes several actions and displays a result page

The result page should last 5 seconds and then automatically redirect customers to an external URL.
The result page contains a "back" link, so the customers may click on it to be redirected to the same external URL.

I did use "renderHead" function to add tag

<meta http-equiv="refresh" content="5; url=http://example.com">

The issue is that I need to invalidate the session before the redirection. If I do so, the customers are redirected to my ExpiredSession page instead of the external URL.

Is their any clean solution to make it happend?

Thank you for your help

Body:
Instead of using <meta http-equiv="refresh" content="5; url=http://example.com"> you can set up an Ajax behavior that will: 1) invalidate the session; 2) redirect to the external page

 anyComponent.add(new AbstractAjaxTimerBehavior(Duration.seconds(5)) {
     @Override protected void onTimer(AjaxRequestTarget target) {
       getSession().invalidate();
       throw new RedirectToUrlException("https://external.page");
    }
 });


问:
How can I write a piece of Java an code that checks if any character of a string is convertible to an integer between 0 and 9?
How can I write a piece of Java code that checks if a string is convertible to an integer, that is if any character of it is convertible to an integer between 0 and 9 ? I thought of something like this:

```<code>String s = "...";

for (int i = 0; i < s.length(); i++)

{

    int h = Integer.parseInt(s.substring(i, i + 1));
    if (h < 0 || h > 9)
        throw new IntegerFormatException();
}

catch (IntegerFormatException e)

{

    System.out.println("This is not an integer");

}
</code>```

where IntegerFormat Exception is something like

```<code>public class IntegerFormatException extends Exception

{

    public IntegerFormatException()
    {
        super ("This string isn't convertible to  an integer");
    }
    public IntegerFormatException(String message)
    {
        super (message);
    }

}
</code>```

But if I then try the code with, say, "8&35" as the string I don't get my message "This is not an integer", but I get and IDE automatic red ink message stating

Exception in thread "main" java.lang.NumberFormatException: For input string: "&"

```<code>at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.parseInt(Integer.java:615)
at project.pkg9.pkg2.Project92.main(Project92.java:60)
</code>```

Java Result: 1

Is my code wrong ? If yes, how can I fix it ? Many thanks in advance for all your answers.

答:
Integer.parseInt(s.substring(i, i + 1)); throw an exception by itself.

In particular, it throws the java.lang.NumberFormatException: which is not caught by your catch.

If you really need to use your exception (there is already one so why not to use that one?) use the following instead:

```<code>public static void main(String[] args) {
    String s = "1234/&&56";

    try{
        for (int i = 0; i < s.length(); i++)

        {

            char c = s.charAt(i);
            int h = c-'0';

            if (h < 0 || h > 9)
                throw new IntegerFormatException();
        }

    }catch(IntegerFormatException e)
    {

        System.out.println("This is not an integer");

    }
}
</code>```

Note that you should also include the check for the very first character (it could be the - sign) in the case you are trying to parse signed numbers.

Body:
How can I write a piece of Java code that checks if a string is convertible to an integer, that is if any character of it is convertible to an integer between 0 and 9 ? I thought of something like this:

String s = "...";

for (int i = 0; i < s.length(); i++)

{

    int h = Integer.parseInt(s.substring(i, i + 1));
    if (h < 0 || h > 9)
        throw new IntegerFormatException();
}

catch (IntegerFormatException e)

{

    System.out.println("This is not an integer");

}

where IntegerFormat Exception is something like

public class IntegerFormatException extends Exception

{

    public IntegerFormatException()
    {
        super ("This string isn't convertible to  an integer");
    }
    public IntegerFormatException(String message)
    {
        super (message);
    }

}

But if I then try the code with, say, "8&35" as the string I don't get my message "This is not an integer", but I get and IDE automatic red ink message stating

Exception in thread "main" java.lang.NumberFormatException: For input string: "&"

at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.parseInt(Integer.java:615)
at project.pkg9.pkg2.Project92.main(Project92.java:60)

Java Result: 1

Is my code wrong ? If yes, how can I fix it ? Many thanks in advance for all your answers.

Body:
Integer.parseInt(s.substring(i, i + 1)); throw an exception by itself.

In particular, it throws the java.lang.NumberFormatException: which is not caught by your catch.

If you really need to use your exception (there is already one so why not to use that one?) use the following instead:

public static void main(String[] args) {
    String s = "1234/&&56";

    try{
        for (int i = 0; i < s.length(); i++)

        {

            char c = s.charAt(i);
            int h = c-'0';

            if (h < 0 || h > 9)
                throw new IntegerFormatException();
        }

    }catch(IntegerFormatException e)
    {

        System.out.println("This is not an integer");

    }
}

Note that you should also include the check for the very first character (it could be the - sign) in the case you are trying to parse signed numbers.


问:
Program that tracks mouse coordinates and allows to draw lines in a window
The program should do the following:

Open a window. Get the Location of the mouse in the Window (x and y coordinates) and set these as the title of the window.

If you click and hold the left mouse button you should be able to draw a line.

The problem is when I run the program no. 1 works, but not no. 2. Upon resizing the Window the coordinates freeze, but I can draw lines.

Hope someone can help with this.

```<code>import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Point;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JPanel {

    private Point lastPoint;

    public Main() {
        addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                lastPoint = new Point(e.getX(), e.getY());
            }
        });
        addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseDragged(MouseEvent e) {
                Graphics g = getGraphics();
                g.drawLine(lastPoint.x, lastPoint.y, e.getX(), e.getY());
                lastPoint = new Point(e.getX(), e.getY());
                g.dispose();
            }
        });
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 600);
        frame.setResizable(true);
        frame.setVisible(true);
        frame.getContentPane().add(new Main(), BorderLayout.CENTER);
        frame.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseMoved(MouseEvent e) {
                int x = e.getX();
                int y = e.getY();
                String xstring = String.valueOf(x);
                String ystring = String.valueOf(y);
                frame.setTitle(xstring + ", " +  ystring);
        }
        });
        }

}
</code>```

答:
If you add the following to the MouseMotionAdapter you can see how your title is adapted while you drag the mouse.
Perhaps you can contionue from there.

```<code>public void mouseDragged(MouseEvent e) {
  int x = e.getX();
  int y = e.getY();
  String xstring = String.valueOf(x);
  String ystring = String.valueOf(y);
  frame.setTitle("dragged - " + xstring + ", " + ystring);
}
</code>```

Experimenting a little bit then led to this code:

```<code>public class Draw {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 600);
        frame.setResizable(true);
        frame.setVisible(true);
        JPanel myPanel = new MyPanel();
        frame.getContentPane().add(myPanel, BorderLayout.CENTER);
        myPanel.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseMoved(MouseEvent e) {
                int x = e.getX();
                int y = e.getY();
                String xstring = String.valueOf(x);
                String ystring = String.valueOf(y);
                frame.setTitle(xstring + ", " + ystring);
                ((MyPanel) myPanel).setLastPoint(e);
            }

            public void mouseDragged(MouseEvent e) {
                int x = e.getX();
                int y = e.getY();
                String xstring = String.valueOf(x);
                String ystring = String.valueOf(y);
                frame.setTitle("dragged - " + xstring + ", " + ystring);

                Graphics g = myPanel.getGraphics();
                Point lastPoint = ((MyPanel) myPanel).getLastPoint();
                g.drawLine(lastPoint.x, lastPoint.y, e.getX(), e.getY());
                ((MyPanel) myPanel).setLastPoint(new Point(e.getX(), e.getY()));
                g.dispose();
            }
        });
    }
}

class MyPanel extends JPanel {
    private Point lastPoint;

    public Point getLastPoint() {
        return lastPoint;
    }

    public void setLastPoint(Point point) {
        lastPoint = point;

    }

    public void setLastPoint(MouseEvent e) {
        lastPoint = new Point(e.getX(), e.getY());
    }
}
</code>```

Body:
The program should do the following:

Open a window. Get the Location of the mouse in the Window (x and y coordinates) and set these as the title of the window.

If you click and hold the left mouse button you should be able to draw a line.

The problem is when I run the program no. 1 works, but not no. 2. Upon resizing the Window the coordinates freeze, but I can draw lines.

Hope someone can help with this.

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Point;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JPanel {

    private Point lastPoint;

    public Main() {
        addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                lastPoint = new Point(e.getX(), e.getY());
            }
        });
        addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseDragged(MouseEvent e) {
                Graphics g = getGraphics();
                g.drawLine(lastPoint.x, lastPoint.y, e.getX(), e.getY());
                lastPoint = new Point(e.getX(), e.getY());
                g.dispose();
            }
        });
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 600);
        frame.setResizable(true);
        frame.setVisible(true);
        frame.getContentPane().add(new Main(), BorderLayout.CENTER);
        frame.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseMoved(MouseEvent e) {
                int x = e.getX();
                int y = e.getY();
                String xstring = String.valueOf(x);
                String ystring = String.valueOf(y);
                frame.setTitle(xstring + ", " +  ystring);
        }
        });
        }

}

Body:
If you add the following to the MouseMotionAdapter you can see how your title is adapted while you drag the mouse.
Perhaps you can contionue from there.

public void mouseDragged(MouseEvent e) {
  int x = e.getX();
  int y = e.getY();
  String xstring = String.valueOf(x);
  String ystring = String.valueOf(y);
  frame.setTitle("dragged - " + xstring + ", " + ystring);
}

Experimenting a little bit then led to this code:

public class Draw {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 600);
        frame.setResizable(true);
        frame.setVisible(true);
        JPanel myPanel = new MyPanel();
        frame.getContentPane().add(myPanel, BorderLayout.CENTER);
        myPanel.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseMoved(MouseEvent e) {
                int x = e.getX();
                int y = e.getY();
                String xstring = String.valueOf(x);
                String ystring = String.valueOf(y);
                frame.setTitle(xstring + ", " + ystring);
                ((MyPanel) myPanel).setLastPoint(e);
            }

            public void mouseDragged(MouseEvent e) {
                int x = e.getX();
                int y = e.getY();
                String xstring = String.valueOf(x);
                String ystring = String.valueOf(y);
                frame.setTitle("dragged - " + xstring + ", " + ystring);

                Graphics g = myPanel.getGraphics();
                Point lastPoint = ((MyPanel) myPanel).getLastPoint();
                g.drawLine(lastPoint.x, lastPoint.y, e.getX(), e.getY());
                ((MyPanel) myPanel).setLastPoint(new Point(e.getX(), e.getY()));
                g.dispose();
            }
        });
    }
}

class MyPanel extends JPanel {
    private Point lastPoint;

    public Point getLastPoint() {
        return lastPoint;
    }

    public void setLastPoint(Point point) {
        lastPoint = point;

    }

    public void setLastPoint(MouseEvent e) {
        lastPoint = new Point(e.getX(), e.getY());
    }
}


问:
How to extract session id from response in jmeter?
How can I extract the session id from response?</p>

```<code>{"game_url":"https://nogs-gl-stage.nyxmalta.com/game/?nogsgameid=110004&nogsoperatorid=421&sessionid=2007_a87178f4-a398-46f9-b156-a05da5040a37&nogscurrency=EUR&nogslang=en_us&nogsmode=real&accountid=7116&clienttype=html5&lobbyurl=https%3A%2F%2F%2Flobby%2Ffeatured-games",
 "non_regulated_game":"NON_REGULATED_GAME_MESSAGE"}
</code>```

答:
Example configuration would be:

Add Regular Expression Extractor as a child of the request which returns the above response

Configure it as follows:

Reference Name: anything meaningful, u.e. sessionid

Regular Expression: sessionid=(.+?)&

Template: $1$

Refer extracted value as ${sessionid} or ${__V(sessionid)} where required later on

You can also use "RegEx Tester" view of the View Results Tree listener to test your regular expressions without having to re-run the request:

References:

JMeter: Regular Expressions

Using RegEx (Regular Expression Extractor) With JMeter

Perl 5 Regex Cheat sheet

Body:
How can I extract the session id from response?

{"game_url":"https://nogs-gl-stage.nyxmalta.com/game/?nogsgameid=110004&nogsoperatorid=421&sessionid=2007_a87178f4-a398-46f9-b156-a05da5040a37&nogscurrency=EUR&nogslang=en_us&nogsmode=real&accountid=7116&clienttype=html5&lobbyurl=https%3A%2F%2F%2Flobby%2Ffeatured-games",
 "non_regulated_game":"NON_REGULATED_GAME_MESSAGE"}


问:
SQL CE 4.0 - Exception - Cannot drop the database, because you do not have permission or it is being accessed by some other process
HI,

I have followed through an example on the net of using SQLCE 4 with MVC 3, using NuGet.

Everything seems to working fine for most users, but everynow and again I get this error.
Cannot drop the database, because you do not have permission or it is being accessed by some other process.

I'm not actually able to reproduce as it doesnt happen often, I pulled this from my logs.

Anyone know how I can resolve this?

Thx

The code in the AppStart_SQLECEntityFramework.cs

```<code>public static class AppStart_SQLCEEntityFramework {
    public static void Start() {
        Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0", HostingEnvironment.MapPath("~/App_Data/"), "");

        Database.SetInitializer(new RecreateDatabaseIfModelChanges<OCCardMailout.Domain.OCCardContext>());
    }
}
</code>```

答: Are you using EF4 CodeFirst CTP ? There is a bug in SQLCE4 CTP2, that can cause CreateDatabaseOnlyIfNotExist to fail - see http://erikej.blogspot.com/2010/10/sql-server-compact-40-ctp2-released.html</p>

ContentLicense: CC BY-SA 2.5

Body:
HI,

I have followed through an example on the net of using SQLCE 4 with MVC 3, using NuGet.

Everything seems to working fine for most users, but everynow and again I get this error.
Cannot drop the database, because you do not have permission or it is being accessed by some other process.

I'm not actually able to reproduce as it doesnt happen often, I pulled this from my logs.

Anyone know how I can resolve this?

Thx

The code in the AppStart_SQLECEntityFramework.cs

public static class AppStart_SQLCEEntityFramework {
    public static void Start() {
        Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0", HostingEnvironment.MapPath("~/App_Data/"), "");

        Database.SetInitializer(new RecreateDatabaseIfModelChanges<OCCardMailout.Domain.OCCardContext>());
    }
}


问:
How to display the role of a user in FOSUserBundle
I would like to display the user role in Symfony with the FOSUserBundle.

```<code>public function showAction() {
    $model = new User();
    $role = $model->getRoles();
    $user = $this->getUser();
    if (!is_object($user) || !$user instanceof UserInterface) {
        throw new AccessDeniedException('This user does not have access to this section.');
    }

    return $this->render('@FOSUser/Profile/show.html.twig', array(
        'user' => $user,
        'role' => $role,
    ));
}
</code>```

This my code in my ProfileController put that I can not call in Twig. Here is my Twig file:

```<code><div class="fos_user_user_show">

<p><b>{{ 'Username'|trans }}</b>: {{ user.username }}</p>
<p><b>{{ 'Email'|trans }}</b>: {{ user.email }}</p>
<p><b>{{ 'Role'|trans }}</b>: {{ role.user }}</p>
</code>```

答:
try only with this:</p>

```<code><p><b>{{ 'Role'|trans }}</b>: {{ role }}</p>
</code>```

Body:
I would like to display the user role in Symfony with the FOSUserBundle.

public function showAction() {
    $model = new User();
    $role = $model->getRoles();
    $user = $this->getUser();
    if (!is_object($user) || !$user instanceof UserInterface) {
        throw new AccessDeniedException('This user does not have access to this section.');
    }

    return $this->render('@FOSUser/Profile/show.html.twig', array(
        'user' => $user,
        'role' => $role,
    ));
}

This my code in my ProfileController put that I can not call in Twig. Here is my Twig file:

{{ 'Username'|trans }}: {{ user.username }}

{{ 'Email'|trans }}: {{ user.email }}

{{ 'Role'|trans }}: {{ role.user }}

Body:
try only with this:

<p><b>{{ 'Role'|trans }}</b>: {{ role }}</p>


问:
Dealing with arbitrarily large inbound data in JavaScript
Here's a function to remove specified characters from a string:

function remove(str, chars) {
    var set = new Set(chars);
    return [...str].filter(i => !set.has(i)).join('');
}

console.log(remove('hello world', 'el') === 'ho word'); // true```

But... what if the inbound string is arbitrarily large and possibly continually extended?

Presumably we need a completely different strategy to deal with it in a piecemeal fashion?

Would such an implementation look like constructing a buffer object that is periodically updated as the data is inbound, and then having sampling logic to deal with the "delta", process it and pass it on?

And that this would have to be done asynchronously to avoid blocking everything else on the event loop?

Is this essentially what Node.js streams are?

答:
[...str] will convert string into array of 1-character strings, which will occupy additional memory. Then .filter() will produces another array of strings, which could be as big as previous one, depending on input data. End then, the resulting string.

If you concerned about possible memory and/or performance, you can implement this with regular cycle "for" and "charAt" function.

Body:
Here's a function to remove specified characters from a string:

function remove(str, chars) {
    var set = new Set(chars);
    return [...str].filter(i => !set.has(i)).join('');
}

console.log(remove('hello world', 'el') === 'ho word'); // true

But... what if the inbound string is arbitrarily large and possibly continually extended?

Presumably we need a completely different strategy to deal with it in a piecemeal fashion?

Would such an implementation look like constructing a buffer object that is periodically updated as the data is inbound, and then having sampling logic to deal with the "delta", process it and pass it on?

And that this would have to be done asynchronously to avoid blocking everything else on the event loop?

Is this essentially what Node.js streams are?


问:
Does Java automatically save an 'evaluate' statement in a predefined Java variable?
Say I perform a simple add/concatenation statement:

```<code>variable + newInput
</code>```

Without setting the calculated value to a new variable, as in:

```<code>variable = variable + newInput
</code>```

or

```<code>variable += newInput
</code>```

Does Java have some sort of specifier to be able to use the computed sum or concatenated string?

Apparently in Python it is automatically saved in the implicit global variable _ -which is implementable like

```<code>Print(_)
</code>```

Is there anything like this in Java?

答:
The point is: the + operator in Java simply takes two operands and returns a result (either numerical, or as string concatenation).

Without assigning this result to something (like returning it from a method; or as shown in your example) ... it is like: the operation never takes place.

This operation doesn't have any side effects on its operands; and there is no way of accessing this result.

Beyond that, there is no operator overloading in Java. So it is also not possible to do some black magic that somehow stores the result of operation as side effect. You could theoretically add an agent to the JVM, that intercepts at runtime to do something upon an add operation, but that is more like: "technically possible", but nothing you would do in practical reality.

Other JVM languages, like Scala for example might use it implicitly - the last expression in a method is always returned, even when leaving out the return statement (in scala).

Body:
Say I perform a simple add/concatenation statement:

variable + newInput

Without setting the calculated value to a new variable, as in:

variable = variable + newInput

or

variable += newInput

Does Java have some sort of specifier to be able to use the computed sum or concatenated string?

Apparently in Python it is automatically saved in the implicit global variable _ -which is implementable like

Print(_)

Is there anything like this in Java?


问:
Generic extension methods using where T : Interface
Does these 2 extension methods are the same or is there some danger in using 1 of the 2

```<code>public static T  GetSomthingFromListOf<T>(this List<T> list)where T: IMyInterface
{
    //do somthing that returns an item of T
}
</code>```

Versus

```<code>public static IMyInterface GetSomthingFromList(this List<IMyInterface> list)
{
    //do somthing that returns an item of IMyInterface
}
</code>```

答:
In addition to @Clint answer:

1) if you have instance of List<ConcreteType> - only generic extension method will be available

2) if you pass struct as a parameter to non-generic method which expects interface - boxing will occur

Body:
Does these 2 extension methods are the same or is there some danger in using 1 of the 2

public static T  GetSomthingFromListOf<T>(this List<T> list)where T: IMyInterface
{
    //do somthing that returns an item of T
}

Versus

public static IMyInterface GetSomthingFromList(this List<IMyInterface> list)
{
    //do somthing that returns an item of IMyInterface
}


问:
How to access contact list in react native app
I am developing a complete mobile CRM, as part of the development I need to access and modify contact list over the phone.

Which is the best plugin to use for this purpose?

答: Look at React Native Contacts, found here</p>


问:
Android relative layout with DP pixels misarranged whole layout for different screens
I am using Relative layout with dp (dentisy pixels). Which is ideal for all screen. But on android htc desire it looks fine but on other phones half of the screen is visible.

I am putting my xml file here for clearity .

With this xml in Htc desire everything look fine but on other phone say samsung small screen one buttons not shown. i.e. half of the screen visible. What i am doing wrong?

```<code> <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/chosenstore">

<TextView
    android:id="@+id/youhavechosen"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="20dp"
    android:layout_marginTop="20dp"
    android:textSize="20dp"
    android:textStyle="bold"
    android:textColor="#000000"
    android:text="You have chosen:" />
</code>```

```<code>    android:layout_below="@+id/youhavechosen"
    android:layout_marginLeft="84dp"
    android:layout_marginTop="22dp"
    android:textSize="15dp"
     android:textStyle="bold"
     android:textColor="#666666"
    android:text="The Money Shop" />

<TextView
    android:id="@+id/tvLocConfirmStreet"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textStyle="bold"
    android:layout_below="@+id/tvLocTheMoneyShop"
    android:layout_marginLeft="84dp"
    android:textColor="#666666"
    android:text="TextView" />

 <TextView
    android:id="@+id/tvLocConfirmTown"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
   android:layout_below="@+id/tvLocConfirmStreet"
   android:layout_alignLeft="@+id/tvLocConfirmStreet"
     android:textStyle="bold"
      android:textColor="#666666"
    android:text="TextView" />

 <TextView
     android:id="@+id/tvLocConfirmPostCode"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignLeft="@+id/tvLocConfirmTown"
     android:layout_below="@+id/tvLocConfirmTown"
      android:textStyle="bold"
      android:textColor="#666666"
     android:text="TextView" />

 <TextView
     android:id="@+id/tvLocConfirmTele"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignLeft="@+id/tvLocConfirmPostCode"
     android:layout_below="@+id/tvLocConfirmPostCode"
      android:textStyle="bold"
      android:textColor="#666666"
     android:text="TextView" />

 <TextView
     android:id="@+id/tvLocConfirmOpeningTime"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignLeft="@+id/tvLocConfirmTele"
     android:layout_below="@+id/tvLocConfirmTele"
     android:layout_marginTop="10dp"
     android:textSize="15dp"
     android:text="Opening Time:"
      android:textColor="#666666"
      android:textStyle="bold"
      />

 <TextView
     android:id="@+id/tvMon"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignLeft="@+id/tvLocConfirmOpeningTime"
     android:layout_below="@+id/tvLocConfirmOpeningTime"
     android:layout_marginTop="10dp"
      android:textStyle="bold"
      android:textColor="#666666"
     android:text="Mon:" />
 <TextView
     android:id="@+id/tvTue"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignLeft="@+id/tvMon"
     android:layout_below="@+id/tvMon"
      android:textStyle="bold"
       android:textColor="#666666"

     android:text="Tue:" />
 <TextView
     android:id="@+id/tvWed"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignLeft="@+id/tvLocConfirmOpeningTime"
     android:layout_below="@+id/tvTue"
      android:textStyle="bold"
       android:textColor="#666666"
     android:text="Wed:" />
 <TextView
     android:id="@+id/tvThur"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignLeft="@+id/tvLocConfirmOpeningTime"
     android:layout_below="@+id/tvWed"
      android:textStyle="bold"
      android:textColor="#666666"
     android:text="Thur:" />
 <TextView
     android:id="@+id/tvFri"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignLeft="@+id/tvLocConfirmOpeningTime"
     android:layout_below="@+id/tvThur"
      android:textStyle="bold"
       android:textColor="#666666"
     android:text="Fri:" />
 <TextView
     android:id="@+id/tvSat"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignLeft="@+id/tvLocConfirmOpeningTime"
     android:layout_below="@+id/tvFri"
      android:textStyle="bold"
       android:textColor="#666666"
     android:text="Sat:" />
 <TextView
     android:id="@+id/tvSun"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignLeft="@+id/tvLocConfirmOpeningTime"
     android:layout_below="@+id/tvSat"
      android:textStyle="bold"
    android:textColor="#666666"
     android:text="Sun:" />

 <TextView
     android:id="@+id/tvLocConfirmMon"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignBaseline="@+id/tvMon"
     android:layout_alignBottom="@+id/tvMon"
     android:layout_toRightOf="@+id/tvMon"
     android:text="TextView"
      android:textColor="#666666"
      android:textStyle="bold"
      />

 <TextView
     android:id="@+id/tvLocConfirmTue"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignTop="@+id/tvTue"
     android:layout_toRightOf="@+id/tvTue"
      android:textStyle="bold"
     android:textColor="#666666"
     android:text="TextView" />
   <TextView
     android:id="@+id/tvLocConfirmWed"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignTop="@+id/tvWed"
     android:layout_toRightOf="@+id/tvWed"
      android:textStyle="bold"
      android:textColor="#666666"
     android:text="TextView" />
     <TextView
     android:id="@+id/tvLocConfirmThur"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignTop="@+id/tvThur"
     android:layout_toRightOf="@+id/tvThur"
      android:textStyle="bold"
    android:textColor="#666666"
     android:text="TextView" />
       <TextView
     android:id="@+id/tvLocConfirmFri"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignTop="@+id/tvFri"
     android:layout_toRightOf="@+id/tvFri"
      android:textStyle="bold"
       android:textColor="#666666"
     android:text="TextView" />
         <TextView
     android:id="@+id/tvLocConfirmSat"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignTop="@+id/tvSat"
     android:layout_toRightOf="@+id/tvSat"
      android:textStyle="bold"
     android:textColor="#666666"
     android:text="TextView" />
           <TextView
     android:id="@+id/tvLocConfirmSun"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignTop="@+id/tvSun"
     android:layout_toRightOf="@+id/tvSun"
      android:textColor="#666666"
      android:textStyle="bold"
     android:text="TextView" />

           <Button
               android:id="@+id/collect"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_centerHorizontal="true"
               android:layout_below="@+id/tvLocConfirmSun"
               android:layout_marginTop="1dp"

               android:background="@drawable/collectherebutton"
               />
              <Button
               android:id="@+id/storeDetail"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_centerHorizontal="true"
               android:layout_below="@+id/collect"
               android:layout_marginTop="5dp"

               android:background="@drawable/storedetailbutton"
               />

              <ImageView
                  android:id="@+id/locConfirmImage"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:layout_marginLeft="20dp"

                  android:layout_alignTop="@+id/tvLocTheMoneyShop"
                  android:src="@drawable/locicon" />

              <Button
                  android:id="@+id/mapButton"
                  style="?android:attr/buttonStyleSmall"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:layout_alignBottom="@+id/tvLocConfirmTele"
                  android:layout_alignParentRight="true"
                  android:layout_marginRight="22dp"
                  android:text="Button" />
</code>```

答: Use a scroll view before first text view, and end just before your relative layout closing tag. This will sort it out.</p>

Body:
I am using Relative layout with dp (dentisy pixels). Which is ideal for all screen. But on android htc desire it looks fine but on other phones half of the screen is visible.

I am putting my xml file here for clearity .

With this xml in Htc desire everything look fine but on other phone say samsung small screen one buttons not shown. i.e. half of the screen visible. What i am doing wrong?

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/chosenstore">

<TextView
    android:id="@+id/youhavechosen"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="20dp"
    android:layout_marginTop="20dp"
    android:textSize="20dp"
    android:textStyle="bold"
    android:textColor="#000000"
    android:text="You have chosen:" />

    android:layout_below="@+id/youhavechosen"
    android:layout_marginLeft="84dp"
    android:layout_marginTop="22dp"
    android:textSize="15dp"
     android:textStyle="bold"
     android:textColor="#666666"
    android:text="The Money Shop" />

<TextView
    android:id="@+id/tvLocConfirmStreet"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textStyle="bold"
    android:layout_below="@+id/tvLocTheMoneyShop"
    android:layout_marginLeft="84dp"
    android:textColor="#666666"
    android:text="TextView" />

 <TextView
    android:id="@+id/tvLocConfirmTown"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
   android:layout_below="@+id/tvLocConfirmStreet"
   android:layout_alignLeft="@+id/tvLocConfirmStreet"
     android:textStyle="bold"
      android:textColor="#666666"
    android:text="TextView" />

 <TextView
     android:id="@+id/tvLocConfirmPostCode"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignLeft="@+id/tvLocConfirmTown"
     android:layout_below="@+id/tvLocConfirmTown"
      android:textStyle="bold"
      android:textColor="#666666"
     android:text="TextView" />

 <TextView
     android:id="@+id/tvLocConfirmTele"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignLeft="@+id/tvLocConfirmPostCode"
     android:layout_below="@+id/tvLocConfirmPostCode"
      android:textStyle="bold"
      android:textColor="#666666"
     android:text="TextView" />

 <TextView
     android:id="@+id/tvLocConfirmOpeningTime"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignLeft="@+id/tvLocConfirmTele"
     android:layout_below="@+id/tvLocConfirmTele"
     android:layout_marginTop="10dp"
     android:textSize="15dp"
     android:text="Opening Time:"
      android:textColor="#666666"
      android:textStyle="bold"
      />

 <TextView
     android:id="@+id/tvMon"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignLeft="@+id/tvLocConfirmOpeningTime"
     android:layout_below="@+id/tvLocConfirmOpeningTime"
     android:layout_marginTop="10dp"
      android:textStyle="bold"
      android:textColor="#666666"
     android:text="Mon:" />
 <TextView
     android:id="@+id/tvTue"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignLeft="@+id/tvMon"
     android:layout_below="@+id/tvMon"
      android:textStyle="bold"
       android:textColor="#666666"

     android:text="Tue:" />
 <TextView
     android:id="@+id/tvWed"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignLeft="@+id/tvLocConfirmOpeningTime"
     android:layout_below="@+id/tvTue"
      android:textStyle="bold"
       android:textColor="#666666"
     android:text="Wed:" />
 <TextView
     android:id="@+id/tvThur"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignLeft="@+id/tvLocConfirmOpeningTime"
     android:layout_below="@+id/tvWed"
      android:textStyle="bold"
      android:textColor="#666666"
     android:text="Thur:" />
 <TextView
     android:id="@+id/tvFri"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignLeft="@+id/tvLocConfirmOpeningTime"
     android:layout_below="@+id/tvThur"
      android:textStyle="bold"
       android:textColor="#666666"
     android:text="Fri:" />
 <TextView
     android:id="@+id/tvSat"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignLeft="@+id/tvLocConfirmOpeningTime"
     android:layout_below="@+id/tvFri"
      android:textStyle="bold"
       android:textColor="#666666"
     android:text="Sat:" />
 <TextView
     android:id="@+id/tvSun"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignLeft="@+id/tvLocConfirmOpeningTime"
     android:layout_below="@+id/tvSat"
      android:textStyle="bold"
    android:textColor="#666666"
     android:text="Sun:" />

 <TextView
     android:id="@+id/tvLocConfirmMon"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignBaseline="@+id/tvMon"
     android:layout_alignBottom="@+id/tvMon"
     android:layout_toRightOf="@+id/tvMon"
     android:text="TextView"
      android:textColor="#666666"
      android:textStyle="bold"
      />

 <TextView
     android:id="@+id/tvLocConfirmTue"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignTop="@+id/tvTue"
     android:layout_toRightOf="@+id/tvTue"
      android:textStyle="bold"
     android:textColor="#666666"
     android:text="TextView" />
   <TextView
     android:id="@+id/tvLocConfirmWed"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignTop="@+id/tvWed"
     android:layout_toRightOf="@+id/tvWed"
      android:textStyle="bold"
      android:textColor="#666666"
     android:text="TextView" />
     <TextView
     android:id="@+id/tvLocConfirmThur"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignTop="@+id/tvThur"
     android:layout_toRightOf="@+id/tvThur"
      android:textStyle="bold"
    android:textColor="#666666"
     android:text="TextView" />
       <TextView
     android:id="@+id/tvLocConfirmFri"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignTop="@+id/tvFri"
     android:layout_toRightOf="@+id/tvFri"
      android:textStyle="bold"
       android:textColor="#666666"
     android:text="TextView" />
         <TextView
     android:id="@+id/tvLocConfirmSat"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignTop="@+id/tvSat"
     android:layout_toRightOf="@+id/tvSat"
      android:textStyle="bold"
     android:textColor="#666666"
     android:text="TextView" />
           <TextView
     android:id="@+id/tvLocConfirmSun"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignTop="@+id/tvSun"
     android:layout_toRightOf="@+id/tvSun"
      android:textColor="#666666"
      android:textStyle="bold"
     android:text="TextView" />

           <Button
               android:id="@+id/collect"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_centerHorizontal="true"
               android:layout_below="@+id/tvLocConfirmSun"
               android:layout_marginTop="1dp"

               android:background="@drawable/collectherebutton"
               />
              <Button
               android:id="@+id/storeDetail"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_centerHorizontal="true"
               android:layout_below="@+id/collect"
               android:layout_marginTop="5dp"

               android:background="@drawable/storedetailbutton"
               />

              <ImageView
                  android:id="@+id/locConfirmImage"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:layout_marginLeft="20dp"

                  android:layout_alignTop="@+id/tvLocTheMoneyShop"
                  android:src="@drawable/locicon" />

              <Button
                  android:id="@+id/mapButton"
                  style="?android:attr/buttonStyleSmall"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:layout_alignBottom="@+id/tvLocConfirmTele"
                  android:layout_alignParentRight="true"
                  android:layout_marginRight="22dp"
                  android:text="Button" />


问:
SQL : Error converting data type nvarchar to float
I want to convert nvarchar data to float type.

In my case I have SalesValue column and I used this command

```<code>UPDATE Overseas
SET SalesValue = CONVERT(FLOAT, REPLACE([SalesValue],',','') )
</code>```

My table has values like

```<code>201.01
40.50
215.12
550
304.201
</code>```

But I get an error

SQL : Error converting data type nvarchar to float.

How can I solve this problem ?

答:
This will get you closer than ISNUMERIC()

```<code>declare @table table (SalesValue varchar(16))
insert into @table
values
('1e4'),
('$'),
('134.55'),
('66,9897'),
('14')

select
    SalesValue
    ,case
        when SalesValue NOT LIKE '%[^0-9,.]%'
        then convert(decimal(16,4),replace(SalesValue,',','.'))
    end
from
    @table
</code>```

Body:
I want to convert nvarchar data to float type.

In my case I have SalesValue column and I used this command

UPDATE Overseas
SET SalesValue = CONVERT(FLOAT, REPLACE([SalesValue],',','') )

My table has values like

201.01
40.50
215.12
550
304.201

But I get an error

SQL : Error converting data type nvarchar to float.

How can I solve this problem ?

Body:
This will get you closer than ISNUMERIC()

declare @table table (SalesValue varchar(16))
insert into @table
values
('1e4'),
('$'),
('134.55'),
('66,9897'),
('14')

select
    SalesValue
    ,case
        when SalesValue NOT LIKE '%[^0-9,.]%'
        then convert(decimal(16,4),replace(SalesValue,',','.'))
    end
from
    @table


问:
Global method for all Controller classes ASP.NET MVC
I have a lot of different controllers and each of them contains a lot of ActionResult methods which returns different views.

In my program you set a variable before you start using it. I store the variable in a Session.

For now, most of my Controllers, have methods with the same if-sentence.
Example:

```<code>        if (Session["myVariable"] == null)
        {
            return RedirectToAction("/../Cons/SetVariable");
        }
</code>```

What i would like to is not to write this logic in all my controllers methods. Perhaps there is a way i could extend a new controller with the logic or something similar?

I hope somebody understands my problem and can help.

答:
You can use MVC/WebAPI's filter attributes to execute the check and use context to perform the actions

```<code>public class VariableCheckerValidationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext
    filterContext)
    {
        if(filterContext.HttpContext.Session["myVariable"] == null)
        {
            filterContext.Result = new RedirectToRouteResult("/../Cons/SetVariable", filterContext.RouteData.Values);
        }
    }
}
</code>```

Then register the action filter as a global filter, and it will automatically apply to every single action in your application.

In WebApiConfig (in case of WebAPI project), in typically the Register method, add:

```<code>config.Filters.Add(new VariableCheckerValidationAttribute());
</code>```

Or, instead, apply at controller or action levels as needed.

If you do decide to go the global application, and you have an action that doesn't need it, then you would need to create an attribute to 'exception' out of the policy, and update the above attribute code to test for presence of the 'exception' attribute and then not apply the check in that case.

Body:
I have a lot of different controllers and each of them contains a lot of ActionResult methods which returns different views.

In my program you set a variable before you start using it. I store the variable in a Session.

For now, most of my Controllers, have methods with the same if-sentence.
Example:

        if (Session["myVariable"] == null)
        {
            return RedirectToAction("/../Cons/SetVariable");
        }

What i would like to is not to write this logic in all my controllers methods. Perhaps there is a way i could extend a new controller with the logic or something similar?

I hope somebody understands my problem and can help.

Body:
You can use MVC/WebAPI's filter attributes to execute the check and use context to perform the actions

public class VariableCheckerValidationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext
    filterContext)
    {
        if(filterContext.HttpContext.Session["myVariable"] == null)
        {
            filterContext.Result = new RedirectToRouteResult("/../Cons/SetVariable", filterContext.RouteData.Values);
        }
    }
}

Then register the action filter as a global filter, and it will automatically apply to every single action in your application.

In WebApiConfig (in case of WebAPI project), in typically the Register method, add:

config.Filters.Add(new VariableCheckerValidationAttribute());

Or, instead, apply at controller or action levels as needed.

If you do decide to go the global application, and you have an action that doesn't need it, then you would need to create an attribute to 'exception' out of the policy, and update the above attribute code to test for presence of the 'exception' attribute and then not apply the check in that case.


问:
Need Help regarding backup css
I need your help.

My website css has been crashed due to suddenly power supply off and next while I saw css, CSS was cleaned totally.
Anyone suggest me How can I get them again?

Thanks in advance.

答:
Try Google webcache for your website. It has usually the content. You may be able to get it from there. If your site is mysite.com, then type this in Google:

```<code>cache:www.mysite.com
</code>```

And see the results.

Title: Need Help regarding backup css

Body:
Try Google webcache for your website. It has usually the content. You may be able to get it from there. If your site is mysite.com, then type this in Google:

cache:www.mysite.com

And see the results.


问:
Strings and List of Strings in Mustache - Java
is there a simple way to output Strings and List of Strings with Mustache in a HTML-File?

I started to make a HashMap with all the information:

```<code>hashMap1.put("time", a.getTime().toString());
</code>```

And so on. But i also want to write a List<String> into the html file. How can I do that properly?

答:
I wasn't aware, that Mustache can handle Object directly. I solved my problem with the following implementation:</p>

```<code>HashMap<String, Object> hashMap1 = new HashMap<>();
</code>```

Body:
is there a simple way to output Strings and List of Strings with Mustache in a HTML-File?

I started to make a HashMap with all the information:

hashMap1.put("time", a.getTime().toString());

And so on. But i also want to write a List<String> into the html file. How can I do that properly?

Body:
I wasn't aware, that Mustache can handle Object directly. I solved my problem with the following implementation:

HashMap<String, Object> hashMap1 = new HashMap<>();


问:
Python regex re.findall
I am using Python2.7 and I encounter the following problem, I have the string:

```<code>s = 'No of tests:  23'
</code>```

I am using the following the regex:

```<code>re.findall('No of tests: \d+',s)
</code>```

And apparently the regex return an empty list. Any idea why?

答:
Your string contains 2 spaces before the number.

It is a good idea to use \s* to match any zero or more whitespace characters when the input string is user-defined and spaces may come in different number. To make sure there is 1 or more spaces, use \s+.

Thus, it is advisable to use

```<code>r'No\s+of\s+tests:\s*\d+'
</code>```

Note that raw string literals are best when defining regex patterns in Python (you won't get any problems due to escaping special characters, not the case here though).

Title: Python regex re.findall

Body:
I am using Python2.7 and I encounter the following problem, I have the string:

s = 'No of tests:  23'

I am using the following the regex:

re.findall('No of tests: \d+',s)

And apparently the regex return an empty list. Any idea why?

Body:
Your string contains 2 spaces before the number.

It is a good idea to use \s* to match any zero or more whitespace characters when the input string is user-defined and spaces may come in different number. To make sure there is 1 or more spaces, use \s+.

Thus, it is advisable to use

r'No\s+of\s+tests:\s*\d+'

Note that raw string literals are best when defining regex patterns in Python (you won't get any problems due to escaping special characters, not the case here though).


问:
Facebook Pixel ReferenceError: Set is not defined (<IE11)
We're trying to implement Facebook Pixel on a website and it's working in all browsers except in Internet Explorer 11 or below. The exact error what we're getting is: Facebook Pixel Error: ReferenceError: Set is not defined.

We were not able to find any info whatsoever with regards to this error.

答:
I've seen this too. I don't think IE11 and below support Set as its a relatively new ES6 feature but I'm unsure as why Pixel code is trying to use it in these environments.

Possibly related, are you loading Facebook Pixel via GTM?

```<code> function p() {
            var s = []
              , t = b.querySelectorAll('[itemscope]')
              , u = new Set();
            for (var v = t.length - 1; v >= 0; v--) {
                var w = t[v]
                  , x = w.querySelectorAll('[itemprop]')
                  , y = w.getAttribute('itemtype');
</code>```

Update:
After reporting this bug to Facebook it has now been resolved.

This should now be resolved. Thanks for flagging this, and thanks for your patience while we addressed the issue. Please ensure you are not caching an older version of the file.

Thanks,

Ram

Body:
I've seen this too. I don't think IE11 and below support Set as its a relatively new ES6 feature but I'm unsure as why Pixel code is trying to use it in these environments.

Possibly related, are you loading Facebook Pixel via GTM?

 function p() {
            var s = []
              , t = b.querySelectorAll('[itemscope]')
              , u = new Set();
            for (var v = t.length - 1; v >= 0; v--) {
                var w = t[v]
                  , x = w.querySelectorAll('[itemprop]')
                  , y = w.getAttribute('itemtype');

Update:
After reporting this bug to Facebook it has now been resolved.

This should now be resolved. Thanks for flagging this, and thanks for your patience while we addressed the issue. Please ensure you are not caching an older version of the file.

Thanks,

Ram


问:
How to make a class with nested objects Parcelable
I'd like to make class A Parcelable.

```<code>public class A {
    public String str;
    public ArrayList<B> list;
}
</code>```

This is what I've come up with so far. However it crashes with a NullPointerException. The problem are these two statements: dest.writeList(list); & in.readList(list, this.getClass().getClassLoader());.
I can't figure out what to do from here :(

Class A

```<code>public class A implements Parcelable {
    public String str;
    public ArrayList<B> list;

    @Override
    public int describeContents() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(str);
        dest.writeList(list);
    }

    private A(Parcel in) {
        str = in.readString();
        in.readList(list, this.getClass().getClassLoader());
    }

    public static final Parcelable.Creator<A> CREATOR
            = new Parcelable.Creator<A>() {
        public A createFromParcel(Parcel in) {
            return new A(in);
        }

        public A[] newArray(int size) {
            return new A[size];
        }
    };
}
</code>```

Class B

```<code>public class B implements Parcelable {
    public String str;

    @Override
    public int describeContents() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(str);
    }

    private B(Parcel in) {
        str = in.readString();
    }

    public static final Parcelable.Creator<B> CREATOR
            = new Parcelable.Creator<B>() {
        public B createFromParcel(Parcel in) {
            return new B(in);
        }

        public B[] newArray(int size) {
            return new B[size];
        }
    };
}
</code>```

Thank you for your time.

答: Just press ALT+ENTER and replace Parcelable it will implement all the necessary implementation</p>

Body:
I'd like to make class A Parcelable.

public class A {
    public String str;
    public ArrayList list;
}

This is what I've come up with so far. However it crashes with a NullPointerException. The problem are these two statements: dest.writeList(list); & in.readList(list, this.getClass().getClassLoader());.
I can't figure out what to do from here :(

Class A

public class A implements Parcelable {
    public String str;
    public ArrayList list;

    @Override
    public int describeContents() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(str);
        dest.writeList(list);
    }

    private A(Parcel in) {
        str = in.readString();
        in.readList(list, this.getClass().getClassLoader());
    }

    public static final Parcelable.Creator CREATOR
            = new Parcelable.Creator() {
        public A createFromParcel(Parcel in) {
            return new A(in);
        }

        public A[] newArray(int size) {
            return new A[size];
        }
    };
}

Class B

public class B implements Parcelable {
    public String str;

    @Override
    public int describeContents() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(str);
    }

    private B(Parcel in) {
        str = in.readString();
    }

    public static final Parcelable.Creator CREATOR
            = new Parcelable.Creator() {
        public B createFromParcel(Parcel in) {
            return new B(in);
        }

        public B[] newArray(int size) {
            return new B[size];
        }
    };
}

Thank you for your time.


问:
Better way to structure/new keyword
Some time ago I came across the following construct which I have rarely seen since, though I use it relatively frequently.  I use it typically when checking on a whole list of conditions are true and it prevents large levels of indentation.  Essentially it uses a for loop to provide a kind of structured goto.  My question is firstly whether there is better way to structure this, secondly whether people like it and thirdly whether a new keyword in java/c++ etc. such as unit { } which would only cause breaks to exit to the end of the unit would be useful and clearer.

ps I realise that it is on slip away from an infinite loop, but I think my paranoia about that has meant its never happened.

Edit: I have added some setup code for the further conditions to try to illuminate problems with chained if then elses

```<code>boolean valid = false;

// this loop never loops
for (;;)
{
    if (!condition1)
        break;

    condition2.setup();

    if (!condition2)
        break;

    condition3.setup();

    if (!condition3)
        break;

    valid = true;
    break;
}

if (valid) dosomething();
</code>```

EDIT:

I have just discovered that in fact there is a way to structure this in java without misusing loops etc. and wondered whether this would similarily be frowned on, though I guess I have missed the boat on this one.

The restructured code looks like this.

```<code>boolean valid = false;

breakout:
{
    if (!condition1)
        break breakout;

    condition2.setup();

    if (!condition2)
        break breakout;

    condition3.setup();

    if (!condition3)
        break breakout;

    valid = true;
}

if (valid) dosomething();
</code>```

Now that removes the misuse of the for loop which caused a lot of the complaints, and is actually a solution I think is quite neat and is what I was looking to find originally.
I am guessing that this structure is probably not well known since no one mentioned it, people object to this as strongly?

答:
The loop is counter-intuitive and would be questioned at code review: "Why do you need a loop if you always break on the first iteration?"

Why not use this?

```<code>boolean valid = true;

if (!condition1)
    valid = false;

else if (!condition2)
    valid = false;

else if (!condition3)
    valid = false;

if (valid) dosomething();
</code>```

Title: Better way to structure/new keyword

Body:
Some time ago I came across the following construct which I have rarely seen since, though I use it relatively frequently.  I use it typically when checking on a whole list of conditions are true and it prevents large levels of indentation.  Essentially it uses a for loop to provide a kind of structured goto.  My question is firstly whether there is better way to structure this, secondly whether people like it and thirdly whether a new keyword in java/c++ etc. such as unit { } which would only cause breaks to exit to the end of the unit would be useful and clearer.

ps I realise that it is on slip away from an infinite loop, but I think my paranoia about that has meant its never happened.

Edit: I have added some setup code for the further conditions to try to illuminate problems with chained if then elses

boolean valid = false;

// this loop never loops
for (;;)
{
    if (!condition1)
        break;

    condition2.setup();

    if (!condition2)
        break;

    condition3.setup();

    if (!condition3)
        break;

    valid = true;
    break;
}

if (valid) dosomething();

EDIT:

I have just discovered that in fact there is a way to structure this in java without misusing loops etc. and wondered whether this would similarily be frowned on, though I guess I have missed the boat on this one.

The restructured code looks like this.

boolean valid = false;

breakout:
{
    if (!condition1)
        break breakout;

    condition2.setup();

    if (!condition2)
        break breakout;

    condition3.setup();

    if (!condition3)
        break breakout;

    valid = true;
}

if (valid) dosomething();

Now that removes the misuse of the for loop which caused a lot of the complaints, and is actually a solution I think is quite neat and is what I was looking to find originally.
I am guessing that this structure is probably not well known since no one mentioned it, people object to this as strongly?

Body:
The loop is counter-intuitive and would be questioned at code review: "Why do you need a loop if you always break on the first iteration?"

Why not use this?

boolean valid = true;

if (!condition1)
    valid = false;

else if (!condition2)
    valid = false;

else if (!condition3)
    valid = false;

if (valid) dosomething();


问:
R - Using glmnet with purrr/tidyr
I am following code from this R Bloggers link in order to run models on groups within my data using tidyr and purrr. However, I would like to use glmnet rather than just lm on my nested data. Unlike lm, glmnet/cv.glmnet takes a model.matrix as the x argument and I need to abstract the formula fed to that model.matrix and that is what is holding me up.

So this works:

```<code>library(purrr)
library(tidyr)
library(dplyr)
library(glmnet)

mod_test <- mtcars %>%
  nest(-vs) %>%
  mutate(cv_mod = map(data, ~ cv.glmnet(
    x = model.matrix(data = ., .$mpg ~ .$cyl * .$hp)[,-1],
    y = .$mpg
  )))
mod_test
> mod_test
# A tibble: 2 x 3
     vs               data          cv_mod
  <dbl>             <list>          <list>
1     0 <tibble [18 x 10]> <S3: cv.glmnet>
2     1 <tibble [14 x 10]> <S3: cv.glmnet>
</code>```

But when I try to create the formula for the model.matrix separately, it does not.

```<code>mod_form <- as.formula(".$mpg ~ .$cyl * .$hp")

mod_test2 <- mtcars %>%
  nest(-vs) %>%
  mutate(cv_mod = map(data, ~ cv.glmnet(
    x = model.matrix(data = ., mod_form)[,-1],
    y = .$mpg
  )))
Error in mutate_impl(.data, dots) : object '.' not found
</code>```

答:
First part, why Error in mutate_impl(.data, dots) : object '.' not found? The folowing is my reasoning:

see manual of as.formula:

Formulas created with as.formula will use the env argument for their
  environment.

When you create mod_test: according to as.formula(object, env = parent.frame()), it will be <environment: R_GlobalEnv>.

Next,

A formula object has an associated environment, and this environment
  (rather than the parent environment) is used by model.frame to
  evaluate variables that are not found in the supplied data argument.

So, model.matrix will look for columns like .$mpg in data. Apprently, those columns are called like mpg not .$mpg. Then it will looks for .$mpg in env associated with the formula: R_GlobalEnv. There is no object called . in global env. Therefore error was reported.

(correct me if some of this part is wrong.)

Second, solution, try:

```<code>mod_form <- mpg ~ cyl * hp
# or
mod_form <- as.formula('mpg ~ cyl * hp')
</code>```

Title: R - Using glmnet with purrr/tidyr

Body:
I am following code from this R Bloggers link in order to run models on groups within my data using tidyr and purrr. However, I would like to use glmnet rather than just lm on my nested data. Unlike lm, glmnet/cv.glmnet takes a model.matrix as the x argument and I need to abstract the formula fed to that model.matrix and that is what is holding me up.

So this works:

library(purrr)
library(tidyr)
library(dplyr)
library(glmnet)

mod_test <- mtcars %>%
  nest(-vs) %>%
  mutate(cv_mod = map(data, ~ cv.glmnet(
    x = model.matrix(data = ., .$mpg ~ .$cyl * .$hp)[,-1],
    y = .$mpg
  )))
mod_test
> mod_test
# A tibble: 2 x 3
     vs               data          cv_mod
  <dbl>             <list>          <list>
1     0 <tibble [18 x 10]> <S3: cv.glmnet>
2     1 <tibble [14 x 10]> <S3: cv.glmnet>

But when I try to create the formula for the model.matrix separately, it does not.

mod_form <- as.formula(".$mpg ~ .$cyl * .$hp")

mod_test2 <- mtcars %>%
  nest(-vs) %>%
  mutate(cv_mod = map(data, ~ cv.glmnet(
    x = model.matrix(data = ., mod_form)[,-1],
    y = .$mpg
  )))
Error in mutate_impl(.data, dots) : object '.' not found

Body:
First part, why Error in mutate_impl(.data, dots) : object '.' not found? The folowing is my reasoning:

see manual of as.formula:

Formulas created with as.formula will use the env argument for their
  environment.

When you create mod_test: according to as.formula(object, env = parent.frame()), it will be <environment: R_GlobalEnv>.

Next,

A formula object has an associated environment, and this environment
  (rather than the parent environment) is used by model.frame to
  evaluate variables that are not found in the supplied data argument.

So, model.matrix will look for columns like .$mpg in data. Apprently, those columns are called like mpg not .$mpg. Then it will looks for .$mpg in env associated with the formula: R_GlobalEnv. There is no object called . in global env. Therefore error was reported.

(correct me if some of this part is wrong.)

Second, solution, try:

mod_form <- mpg ~ cyl * hp
# or
mod_form <- as.formula('mpg ~ cyl * hp')


问:
Can't install gensim with Ubuntu16.04 and anaconda
I am trying, unsuccefully, to install a python package (gensim).

```<code>System details:
I am using Python 3.6.0 :: Anaconda custom (64-bit) with Ubuntu16.04LTS.
</code>```

First I followed the directions from here (including updating before trying to install), I entered

```<code>easy_install --upgrade gensim
</code>```

and got the following error massage:

```<code>Searching for gensim
Reading https://pypi.python.org/simple/gensim/
Download error on https://pypi.python.org/simple/gensim/: unknown urltype: https -- Some packages may not be found!
Couldn't find index page for 'gensim' (maybe misspelled?)
Scanning index of all packages (this may take a while)
Reading https://pypi.python.org/simple/
Download error on https://pypi.python.org/simple/: unknown url type:https -- Some packages may not be found!
No local packages or working download links found for gensim
error: Could not find suitable distribution for
Requirement.parse('gensim')
</code>```

When I tried to install using anaconda,

```<code>conda install -c anaconda gensim=1.0.1
</code>```

as described here, I got

```<code>Fetching package metadata ...
CondaHTTPError: HTTP None None for url
<https://conda.anaconda.org/anaconda/linux-64/repodata.json>
Elapsed: None

An HTTP error occurred when trying to retrieve this URL.
HTTP errors are often intermittent, and a simple retry will get you on your way.
SSLError(SSLError("Can't connect to HTTPS URL because the SSL module is not available.",),)
</code>```

When I tried to install directly from git

```<code>pip install https://github.com/RaRe-Technologies/gensim.git
</code>```

I got a similar error

```<code>SSLError("Can't connect to HTTPS URL because the SSLpip._vendor.requests.packages.urllib3.exceptions.SSLError:
Can't connect to HTTPS URL because the SSL module is not available.
</code>```

I tried to work my way around this by using

```<code>PYTHONUSERBASE=/home/usr/anaconda3 pip3 install --user --upgrade gensim
</code>```

which was able to install the gensim package, but under a newly created folder /home/usr/anaconda3/python3.5 even though my default python is python3.6

Conclusion(?):

From this I understood that probably my Python was not compiled with SSL support, and if I fix this I may be able to win this long battle. BUT I don't understand how I can fix this D_:

PLUS, I don't understand why it insists on being installed under python3.5 when the manual says the package is also compatible with python3.6.

答:
First you need to install openssl:

sudo apt install openssl

And, then if you installed python from source you have to:

```<code>./configure
make
sudo checkinstall
</code>```

Body:
I am trying, unsuccefully, to install a python package (gensim).

System details:
I am using Python 3.6.0 :: Anaconda custom (64-bit) with Ubuntu16.04LTS.

First I followed the directions from here (including updating before trying to install), I entered

easy_install --upgrade gensim

and got the following error massage:

Searching for gensim
Reading https://pypi.python.org/simple/gensim/
Download error on https://pypi.python.org/simple/gensim/: unknown urltype: https -- Some packages may not be found!
Couldn't find index page for 'gensim' (maybe misspelled?)
Scanning index of all packages (this may take a while)
Reading https://pypi.python.org/simple/
Download error on https://pypi.python.org/simple/: unknown url type:https -- Some packages may not be found!
No local packages or working download links found for gensim
error: Could not find suitable distribution for
Requirement.parse('gensim')

When I tried to install using anaconda,

conda install -c anaconda gensim=1.0.1

as described here, I got

Fetching package metadata ...
CondaHTTPError: HTTP None None for url
<https://conda.anaconda.org/anaconda/linux-64/repodata.json>
Elapsed: None

An HTTP error occurred when trying to retrieve this URL.
HTTP errors are often intermittent, and a simple retry will get you on your way.
SSLError(SSLError("Can't connect to HTTPS URL because the SSL module is not available.",),)

When I tried to install directly from git

pip install https://github.com/RaRe-Technologies/gensim.git

I got a similar error

SSLError("Can't connect to HTTPS URL because the SSLpip._vendor.requests.packages.urllib3.exceptions.SSLError:
Can't connect to HTTPS URL because the SSL module is not available.

I tried to work my way around this by using

PYTHONUSERBASE=/home/usr/anaconda3 pip3 install --user --upgrade gensim

which was able to install the gensim package, but under a newly created folder /home/usr/anaconda3/python3.5 even though my default python is python3.6

Conclusion(?):

From this I understood that probably my Python was not compiled with SSL support, and if I fix this I may be able to win this long battle. BUT I don't understand how I can fix this D_:

PLUS, I don't understand why it insists on being installed under python3.5 when the manual says the package is also compatible with python3.6.

Body:
First you need to install openssl:

sudo apt install openssl

And, then if you installed python from source you have to:

./configure
make
sudo checkinstall


问:
How to terminate the function when it takes too many time in Scala?
Recently, I am learning the Scala language. Today I come out a question, that is,
how to terminate a function when it takes too many time.

For example:

```<code>object HelloWorld {
  def main(args: Array[String]) {
    println("Hello, World")
    // How to terminate the sum() function
    // when the time that it takes greater than 2 second?
    val t0 = System.nanoTime : Double
    val total: BigInt = sum(1000000000)
    val t1 = System.nanoTime : Double
    println("Elapsed time " + (t1 - t0) / 1000000.0 + " msecs")

    println(total)

  }

  //Given that sum() is written by others and I cannot change it.
  def sum(k: Int): BigInt = {
    var total: BigInt = 0
    for (i <- 1 to k) {
      total += i
    }
    total
  }
}
</code>```

The above scala code takes about 70s.

答:
Use Future(s) !

```<code>val resultFuture : Future[ReturnType] = Future.apply {
 longComputation
}

val resultMaybeCut = Await.result(resultFuture, DurationOfChoice)
</code>```

For the record, Await.result(awaitable: Awaitable[T], atMost: Duration) :

throws InterruptedException     if the current thread is interrupted while waiting

throws TimeoutException         if after waiting for the specified time awaitable is still not ready

throws IllegalArgumentException if atMost is Duration.Undefined

Warning (thanks @markusthoemmes):

Doing this doesn't interrupt the underlying future computation, it just let you easily timeout on it ! (which may or may not be a problem).
If I'm to believe Kill or timeout a Future in Scala 2.10 there's no super simple way to actually stop the underlying computation, so you may want to refer to the other solutions posted here !

Body:
Recently, I am learning the Scala language. Today I come out a question, that is,
how to terminate a function when it takes too many time.

For example:

object HelloWorld {
  def main(args: Array[String]) {
    println("Hello, World")
    // How to terminate the sum() function
    // when the time that it takes greater than 2 second?
    val t0 = System.nanoTime : Double
    val total: BigInt = sum(1000000000)
    val t1 = System.nanoTime : Double
    println("Elapsed time " + (t1 - t0) / 1000000.0 + " msecs")

    println(total)

  }

  //Given that sum() is written by others and I cannot change it.
  def sum(k: Int): BigInt = {
    var total: BigInt = 0
    for (i <- 1 to k) {
      total += i
    }
    total
  }
}

The above scala code takes about 70s.

Body:
Use Future(s) !

val resultFuture : Future[ReturnType] = Future.apply {
 longComputation
}

val resultMaybeCut = Await.result(resultFuture, DurationOfChoice)

For the record, Await.result(awaitable: Awaitable[T], atMost: Duration) :

throws InterruptedException     if the current thread is interrupted while waiting

throws TimeoutException         if after waiting for the specified time awaitable is still not ready

throws IllegalArgumentException if atMost is Duration.Undefined

Warning (thanks @markusthoemmes):

Doing this doesn't interrupt the underlying future computation, it just let you easily timeout on it ! (which may or may not be a problem).
If I'm to believe Kill or timeout a Future in Scala 2.10 there's no super simple way to actually stop the underlying computation, so you may want to refer to the other solutions posted here !


问:
Why are the input boxes completely overflowing their bounding divs?
I intend to line up 4 input text boxes housed in 4 equal sized columns in one row of the form. Making use of Bootstrap's grid column classes, I assigned  col--3 for medium and large screen sizes to those four input divs.
Likewise for small and extra small sizes, I assigned them col--12  so that the inputs occupy their own whole row. Then my guide wanted those input boxes sizes reduced. I added offset class to the four input and reduced their column span to 6 columns. These were centered appropriately.

However, this change screwed up my small screen layout. Now there are only two inputs in each row, while the other two in the next row.

/* button modification*/

#button-wrapper {
  width: 40%;
  min-width: 200px;
  margin: 0 auto;
}

#ebook-download-button {
  margin: auto 0.5em;
}

.inner {
  margin: 0 auto 0 auto;
  width: 150px;
  padding: 0;
  /* center the block element*/
}

img {
  min-width: 100%;
}

input {
  height: 60%;
  margin: 0px;
}

/* square boxes*/

.square-elem {
  border-radius: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<body>

  <form id="registration-form" class="">
    <!--<div class="col-md-12 col-sm-12">-->
    <div class="row">
      <div class="col-lg-3 col-md-3 col-sm-6 col-sm-offset-3 col-xs-6 col-xs-offset-3 ">
        <div class="form-group">
          <input type="input" class="form-control square-elem" id="first-name" placeholder="First Name">
        </div>
      </div>

      <div class="col-lg-3 col-md-3 col-sm-6 col-sm-offset-3 col-xs-6 col-xs-offset-3">
        <div class="form-group">
          <input type="input" class="form-control square-elem" id="last-name" placeholder="Last Name">
        </div>
      </div>

      <div class="col-lg-3 col-md-3 col-sm-6 col-sm-offset-3 col-xs-6 col-xs-offset-3">
        <div class="form-group">
          <input type="input" class="form-control square-elem" id="company" placeholder="Company">
        </div>
      </div>

      <div class="col-lg-3 col-md-3 col-sm-6 col-sm-offset-3 col-xs-6 col-xs-offset-3">
        <div class="form-group">
          <input type="input" class="form-control square-elem" id="email" placeholder="Email">
        </div>
      </div>
    </div>
    <div class="row">
      <div id="button-wrapper" style="">
        <div id="ebook-download-button" class="col-md-12 col-sm-12 col-xs-12 text-center">
           DOWNLOAD EBOOK
        </div>
      </div>
    </div>
    <!-- </div>
  -->
  </form>

</body></code>```

Here's the JSFiddle(Drag the frame) too. It seems the inputs(in each form group div) have completely positioned outside their bounding div box.The intended output should be the four inputs lined side by side in one row.
What can possibly be the issue here?

答:
you have classes col-sm-offset-3 and col-xs-offset-3  these classes 'push' the columns with a number of 3 columns. so the inputs have margin-left equal to 3 column widths

see more here > http://getbootstrap.com/css/#grid-offsetting

remove those classes and everything will work ok

see here fiddle
or snippet below

/*Main box*/
div #ebook-registration-box
{
  border: 2px solid #d3d3d3;
  padding: 10px;
  margin: 10px auto;
}

/* button modification*/
#button-wrapper
{
  width: 40%;
  min-width: 200px;
  margin: 0 auto;

}

#ebook-download-button
{
  margin: auto 0.5em;
}

 .inner
{
  margin: 0 auto 0 auto;
  width: 150px;

  padding: 0 ;

  /* center the block element*/
}

/* fixed height for responsive images
   (does not work)*/
img
{

  min-width: 100%;
}

input
{

  height: 60%;
  margin: 0px;
}

/* square boxes*/
.square-elem
{
  border-radius: 0px;
}
/* */```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<div id="ebook-registration-box" class="row">
  <div class="col-md-12" >

  <div id="registration-header" class="row">
     <div class="col-md-12">
        <p class="text-center">
           Register to download the device launch guide
        </p>
     </div>
  </div>
   <!-- 4 form elements-->

 <form id="registration-form" class="" >
   <!--<div class="col-md-12 col-sm-12">-->
     <div class="row">
        <div class="col-lg-3 col-md-3 col-sm-6  col-xs-6 ">
   <div class="form-group">
   <input type="input" class="form-control square-elem" id="first-name" placeholder="First Name">
            </div>
        </div>

         <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 ">
           <div class="form-group">
            <input type="input" class="form-control square-elem" id="last-name" placeholder="Last Name">
     </div>
         </div>

         <div class="col-lg-3 col-md-3 col-sm-6  col-xs-6 ">
           <div class="form-group">
   <input type="input" class="form-control square-elem" id="company" placeholder="Company">
     </div>
         </div>

        <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6">

           <div class="form-group">
      <input type="input" class="form-control square-elem" id="email" placeholder="Email">
           </div>
        </div>
      </div>

       <!-- Download Button                   -->
     <div class="row">
        <div id="button-wrapper"  style="">
         <div id="ebook-download-button" class="col-md-12 col-sm-12 col-xs-12 text-center">
           DOWNLOAD EBOOK
         </div>
        </div>
      </div>  <!-- </div>-->

  </form>
    </div>
 </div></code>```

Body:
I intend to line up 4 input text boxes housed in 4 equal sized columns in one row of the form. Making use of Bootstrap's grid column classes, I assigned  col--3 for medium and large screen sizes to those four input divs.
Likewise for small and extra small sizes, I assigned them col--12  so that the inputs occupy their own whole row. Then my guide wanted those input boxes sizes reduced. I added offset class to the four input and reduced their column span to 6 columns. These were centered appropriately.

However, this change screwed up my small screen layout. Now there are only two inputs in each row, while the other two in the next row.

/* button modification*/

#button-wrapper {
  width: 40%;
  min-width: 200px;
  margin: 0 auto;
}

#ebook-download-button {
  margin: auto 0.5em;
}

.inner {
  margin: 0 auto 0 auto;
  width: 150px;
  padding: 0;
  /* center the block element*/
}

img {
  min-width: 100%;
}

input {
  height: 60%;
  margin: 0px;
}

/* square boxes*/

.square-elem {
  border-radius: 0px;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

  <form id="registration-form" class="">

          <input type="input" class="form-control square-elem" id="first-name" placeholder="First Name">

          <input type="input" class="form-control square-elem" id="last-name" placeholder="Last Name">

          <input type="input" class="form-control square-elem" id="company" placeholder="Company">

          <input type="input" class="form-control square-elem" id="email" placeholder="Email">

           DOWNLOAD EBOOK

  </form>

Here's the JSFiddle(Drag the frame) too. It seems the inputs(in each form group div) have completely positioned outside their bounding div box.The intended output should be the four inputs lined side by side in one row.
What can possibly be the issue here?

Body:
you have classes col-sm-offset-3 and col-xs-offset-3  these classes 'push' the columns with a number of 3 columns. so the inputs have margin-left equal to 3 column widths

see more here > http://getbootstrap.com/css/#grid-offsetting

remove those classes and everything will work ok

see here fiddle
or snippet below

/*Main box*/
div #ebook-registration-box
{
  border: 2px solid #d3d3d3;
  padding: 10px;
  margin: 10px auto;
}

/* button modification*/
#button-wrapper
{
  width: 40%;
  min-width: 200px;
  margin: 0 auto;

}

#ebook-download-button
{
  margin: auto 0.5em;
}

 .inner
{
  margin: 0 auto 0 auto;
  width: 150px;

  padding: 0 ;

  /* center the block element*/
}

/* fixed height for responsive images
   (does not work)*/
img
{

  min-width: 100%;
}

input
{

  height: 60%;
  margin: 0px;
}

/* square boxes*/
.square-elem
{
  border-radius: 0px;
}
/* */

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<div id="ebook-registration-box" class="row">
  <div class="col-md-12" >

  <div id="registration-header" class="row">
     <div class="col-md-12">
        <p class="text-center">
           Register to download the device launch guide
        </p>
     </div>
  </div>
   <!-- 4 form elements-->

 <form id="registration-form" class="" >
   <!--<div class="col-md-12 col-sm-12">-->
     <div class="row">
        <div class="col-lg-3 col-md-3 col-sm-6  col-xs-6 ">
   <div class="form-group">
   <input type="input" class="form-control square-elem" id="first-name" placeholder="First Name">
            </div>
        </div>

         <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 ">
           <div class="form-group">
            <input type="input" class="form-control square-elem" id="last-name" placeholder="Last Name">
     </div>
         </div>

         <div class="col-lg-3 col-md-3 col-sm-6  col-xs-6 ">
           <div class="form-group">
   <input type="input" class="form-control square-elem" id="company" placeholder="Company">
     </div>
         </div>

        <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6">

           <div class="form-group">
      <input type="input" class="form-control square-elem" id="email" placeholder="Email">
           </div>
        </div>
      </div>

       <!-- Download Button                   -->
     <div class="row">
        <div id="button-wrapper"  style="">
         <div id="ebook-download-button" class="col-md-12 col-sm-12 col-xs-12 text-center">
          <a href="#" role="button" class="btn btn-danger btn-download form-control square-elem"  value=""> DOWNLOAD EBOOK </a>
         </div>
        </div>
      </div>  <!-- </div>-->

  </form>
    </div>
 </div>