问:
Managing column width tkinter
I have reviewed the documentation on rowconfugre and columnconfigure, and I just do not quite understand how to get it working properly. With the following code, how can I get the 'src_entry' Entry box directly against the 'src' Checkbutton, regardless of what other widget is in column 1? Essentially, I need the size of the column to form to the width of whatever widget is in that space on the grid.

Thanks,

```<code>from tkinter import *

class Example(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent, background="white")
        self.parent = parent
        self.parent.title("TCPDUMP Creator")
        self.centerWindow()
        self.pack(fill=BOTH, expand=1)

        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)
        fileMenu = Menu(menubar)
        fileMenu.add_command(label="Exit", command=self.quit)
        menubar.add_cascade(label="File", menu=fileMenu)
        self.columnconfigure(2, weight=5)

        int_lbl = Label(self, text="Interface")
        int_lbl.grid(row=1, column=0, sticky=W+E)
        self.int_entry = Entry(self, width=15)
        self.int_entry.grid(row=1, column=1)

        self.anyInt = BooleanVar()
        Checkbutton(self, text="Any", variable = self.anyInt).grid(row=1, column=2)

        int_lbl = Label(self, text="")
        int_lbl.grid(row=2, column=0, columnspan=99, sticky=W+E)

        self.notSrc = BooleanVar()
        Checkbutton(self, text = "Not--", variable = self.notSrc).grid(row=3, column=0, sticky=W+E)

        self.srcIP = BooleanVar()
        Checkbutton(self, text="Src", variable = self.srcIP).grid(row=3, column=1)

        src_entry = Entry(self, width=15)
        src_entry.grid(row=3, column=2)

        self.AndOr = StringVar()
        self.AndOr.set(None)

        Radiobutton(self, text = "And", variable = self.AndOr, value = "And").grid(row=3, column=3, pady=5, padx=2, sticky=E)
        Radiobutton(self, text = "Or", variable = self.AndOr, value = "Or").grid(row=3, column=4, pady=5, padx=10, sticky=W)

        self.notDst = BooleanVar()
        Checkbutton(self, text = "Not--", variable = self.notDst).grid(row=3, column=5, sticky=W+E)

        self.dstIP = BooleanVar()
        Checkbutton(self, text="Dst", variable = self.dstIP).grid(row=3,column=6, sticky=E, padx=0)

        dst_entry = Entry(self, width=15)
        dst_entry.grid(row=3, column=7)

        int_lbl = Label(self, text="")
        int_lbl.grid(row=4, column=0, columnspan=99, sticky=W+E)

        self.srcordst = StringVar()
        self.srcordst.set(None)

        Radiobutton(self, text = "And", variable = self.srcordst, value = "And").grid(row=4, column=1, pady=5, padx=2, sticky=E)
        Radiobutton(self, text = "Or", variable = self.srcordst, value = "Or").grid(row=4, column=2, pady=5, padx=10, sticky=W)

    def centerWindow(self):
        w = 600
        h = 300
        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()
        x = (sw - w)/2
        y = (sh - h)/2.7
        self.parent.geometry("%dx%d+%d+%d" % (w, h, x, y))

def main():
    root = Tk()
    app = Example(root)
    root.mainloop()

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

答:
The best way to do layouts is to break your UI into sections, and then layout each section independently.The reason you're having difficulty is that you're trying to force everything into a single grid, but you don't have items that naturally fit into a grid. You can make it work by using lots of invisible columns and clever use of columnspan, but there are easier ways.

In this specific case, pack and a few intermediate frames is a better solution in my opinion.

From what I see, your UI is made up of four areas:

A row that has an entry for int_entry and a checkbutton

A row that has several checkboxes and radiobuttons, along with an entry

A row with an 'And' and 'Or' radiobutton

A big blank area

The way I would do it is create four frames, one for each area:

```<code>frame1 = Frame(self, ...)
frame2 = Frame(self, ...)
frame3 = Frame(self, ...)
frame4 = Frame(self, ...)
</code>```

You can then use pack to stack those frames horizontally. All of them fill their area in the horizontal direction, and the last frame takes up all of the rest of the data.

```<code>frame1.pack(side="top", fill="x")
frame2.pack(side="top", fill="x")
frame3.pack(side="top", fill="x")
frame4.pack(side="top", fill="both", expand=True)
</code>```

Now, you can add widgets to each frame with little concern for how they affect the rest of the display.

For example, the "Interface" label, the entry and the "Any" checkbutton can go in frame1. pack makes for a sensible choice since you want these aligned to the left of the area (I assume...).

```<code>int_lbl = Label(frame1, text="Interface")
self.int_entry = Entry(frame1, width=15)
any_cb = Checkbutton(frame1, text="Any", ...)

int_lbl.pack(side="left")
self.int_entry.pack(side="left")
any_cb.pack(side="left")
</code>```

Do the same for the other frames. Within each frame you can choose to use pack or grid, as long as you consistently use pack or grid for every widget within the frame. pack is a very natural choice when you want all of your widgets aligned in one direction in the parent widget.

Title: Managing column width tkinter

Body:
I have reviewed the documentation on rowconfugre and columnconfigure, and I just do not quite understand how to get it working properly. With the following code, how can I get the 'src_entry' Entry box directly against the 'src' Checkbutton, regardless of what other widget is in column 1? Essentially, I need the size of the column to form to the width of whatever widget is in that space on the grid.

Thanks,

from tkinter import *

class Example(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent, background="white")
        self.parent = parent
        self.parent.title("TCPDUMP Creator")
        self.centerWindow()
        self.pack(fill=BOTH, expand=1)

        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)
        fileMenu = Menu(menubar)
        fileMenu.add_command(label="Exit", command=self.quit)
        menubar.add_cascade(label="File", menu=fileMenu)
        self.columnconfigure(2, weight=5)

        int_lbl = Label(self, text="Interface")
        int_lbl.grid(row=1, column=0, sticky=W+E)
        self.int_entry = Entry(self, width=15)
        self.int_entry.grid(row=1, column=1)

        self.anyInt = BooleanVar()
        Checkbutton(self, text="Any", variable = self.anyInt).grid(row=1, column=2)

        int_lbl = Label(self, text="")
        int_lbl.grid(row=2, column=0, columnspan=99, sticky=W+E)

        self.notSrc = BooleanVar()
        Checkbutton(self, text = "Not--", variable = self.notSrc).grid(row=3, column=0, sticky=W+E)

        self.srcIP = BooleanVar()
        Checkbutton(self, text="Src", variable = self.srcIP).grid(row=3, column=1)

        src_entry = Entry(self, width=15)
        src_entry.grid(row=3, column=2)

        self.AndOr = StringVar()
        self.AndOr.set(None)

        Radiobutton(self, text = "And", variable = self.AndOr, value = "And").grid(row=3, column=3, pady=5, padx=2, sticky=E)
        Radiobutton(self, text = "Or", variable = self.AndOr, value = "Or").grid(row=3, column=4, pady=5, padx=10, sticky=W)

        self.notDst = BooleanVar()
        Checkbutton(self, text = "Not--", variable = self.notDst).grid(row=3, column=5, sticky=W+E)

        self.dstIP = BooleanVar()
        Checkbutton(self, text="Dst", variable = self.dstIP).grid(row=3,column=6, sticky=E, padx=0)

        dst_entry = Entry(self, width=15)
        dst_entry.grid(row=3, column=7)

        int_lbl = Label(self, text="")
        int_lbl.grid(row=4, column=0, columnspan=99, sticky=W+E)

        self.srcordst = StringVar()
        self.srcordst.set(None)

        Radiobutton(self, text = "And", variable = self.srcordst, value = "And").grid(row=4, column=1, pady=5, padx=2, sticky=E)
        Radiobutton(self, text = "Or", variable = self.srcordst, value = "Or").grid(row=4, column=2, pady=5, padx=10, sticky=W)

    def centerWindow(self):
        w = 600
        h = 300
        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()
        x = (sw - w)/2
        y = (sh - h)/2.7
        self.parent.geometry("%dx%d+%d+%d" % (w, h, x, y))

def main():
    root = Tk()
    app = Example(root)
    root.mainloop()

if __name__ == '__main__':
    main()

Body:
The best way to do layouts is to break your UI into sections, and then layout each section independently.The reason you're having difficulty is that you're trying to force everything into a single grid, but you don't have items that naturally fit into a grid. You can make it work by using lots of invisible columns and clever use of columnspan, but there are easier ways.

In this specific case, pack and a few intermediate frames is a better solution in my opinion.

From what I see, your UI is made up of four areas:

A row that has an entry for int_entry and a checkbutton

A row that has several checkboxes and radiobuttons, along with an entry

A row with an 'And' and 'Or' radiobutton

A big blank area

The way I would do it is create four frames, one for each area:

frame1 = Frame(self, ...)
frame2 = Frame(self, ...)
frame3 = Frame(self, ...)
frame4 = Frame(self, ...)

You can then use pack to stack those frames horizontally. All of them fill their area in the horizontal direction, and the last frame takes up all of the rest of the data.

frame1.pack(side="top", fill="x")
frame2.pack(side="top", fill="x")
frame3.pack(side="top", fill="x")
frame4.pack(side="top", fill="both", expand=True)

Now, you can add widgets to each frame with little concern for how they affect the rest of the display.

For example, the "Interface" label, the entry and the "Any" checkbutton can go in frame1. pack makes for a sensible choice since you want these aligned to the left of the area (I assume...).

int_lbl = Label(frame1, text="Interface")
self.int_entry = Entry(frame1, width=15)
any_cb = Checkbutton(frame1, text="Any", ...)

int_lbl.pack(side="left")
self.int_entry.pack(side="left")
any_cb.pack(side="left")

Do the same for the other frames. Within each frame you can choose to use pack or grid, as long as you consistently use pack or grid for every widget within the frame. pack is a very natural choice when you want all of your widgets aligned in one direction in the parent widget.


来源: stackexchange

问:
What is the correct sql for Update a row in a table?
I am able to Insert data into MySQL using C# fine. However, it doesn't like my Update sql below. key is an autoincrement Primary Key.

This is the code i am using. What is the correct Update sql and the corresponding C# statement to execute it?

```<code>public int UpdatetData(int key, System.DateTime ts, string user)
    {
                string sql = @"update parameters (DateTime, User)
                              values (@timestamp, @user) where Key = @key";

                try
                {
                    using (MySqlCommand cmd = new MySqlCommand(sql, connection))
                    {
                        cmd.Parameters.AddWithValue("@key", key);
                        cmd.Parameters.AddWithValue("@timestamp", ts);
                        cmd.Parameters.AddWithValue("@user", user);
                        ...
                        return cmd.ExecuteNonQuery();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    return -1;
                }
        }
</code>```

答:
The correct syntax is:

```<code>update parameters (DateTime, User)
    set DateTime = @timestamp,
        User = @user
where Key = @key;
</code>```

Your syntax is a bit reminiscent of an insert.

You should be careful with your column names.  Some are keywords in SQL and might be reserved (depending on your database).  You would need to escape them, using backtick, double quotes, or square braces, depending on your database.

ContentLicense: CC BY-SA 3.0

Body:
I am able to Insert data into MySQL using C# fine. However, it doesn't like my Update sql below. key is an autoincrement Primary Key.

This is the code i am using. What is the correct Update sql and the corresponding C# statement to execute it?

public int UpdatetData(int key, System.DateTime ts, string user)
    {
                string sql = @"update parameters (DateTime, User)
                              values (@timestamp, @user) where Key = @key";

                try
                {
                    using (MySqlCommand cmd = new MySqlCommand(sql, connection))
                    {
                        cmd.Parameters.AddWithValue("@key", key);
                        cmd.Parameters.AddWithValue("@timestamp", ts);
                        cmd.Parameters.AddWithValue("@user", user);
                        ...
                        return cmd.ExecuteNonQuery();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    return -1;
                }
        }

Body:
The correct syntax is:

update parameters (DateTime, User)
    set DateTime = @timestamp,
        User = @user
where Key = @key;

Your syntax is a bit reminiscent of an insert.

You should be careful with your column names.  Some are keywords in SQL and might be reserved (depending on your database).  You would need to escape them, using backtick, double quotes, or square braces, depending on your database.


问:
Read float number from Postgres without rounding
this might seem a very naive question but I am having a hard time to figure this out. I have a float value 37.50378 in my PostgreSQL database. When I am trying to fetch this value in my Nodejs application it gives me 37.5038. I want to fetch the exact number without rounding off the decimal digits. How do I do that?
The data type of the column in Postgres is Real.

EDIT

I am using Knex schema builder and using float(column, precision, scale) to create a column(to store above-said value). I have tried different numbers for precision and scale just in case that's causing the above-said behavior. But every time I tried to fetch the value 37.50378, all I get back is 37.5038.

Thanks.

答:
This is because of the real 4-byte precision. See PostgreSQL Numeric Types.

It's got nothing to do with Node.js or its PostgreSQL driver.


问:
Update single service
I'm new in service fabric and cannot catch an idea how to update single micro-service in an application.
I have a number of repositories (one per micro-service) and need to update/deploy each micro-service separatly.

How can I make it? Where should I keep Application project? Can you please suggest solution structure.

P.S. I use standalone (on-premises) service fabric installation.

答:
Short answer is you cannot update a single microservice, SF has a different architecture. It's composed of Applications which themselves consist of Services. You an only update Application as a whole by raising version number in application manifest and services. Application version always goes up whereas service versions can either change or not (that affects upgrade process).

In your case you have two options:

Wrap each microservice in a separate SF application and deploy them separately. This will sort of simulate completely independent services and that's how most microservices are developed. It's a pain to version them independently and manage dependencies. Official documentation explains more on how to write manifests https://learn.microsoft.com/en-us/azure/service-fabric/service-fabric-application-model

Another option is go in line with SF design - create a single application manifest and manifest per service, each versioned properly. Deploy that as a single application and rip the benefits of transactional SF upgrades and all the niceties. I strongly suspect your microservices are plain windows executables? In that case you can describe them as guest executables https://learn.microsoft.com/en-us/azure/service-fabric/service-fabric-deploy-existing-app

Title: Update single service


问:
Grunt + Protractor + CucumberJs
I'm trying to use Grunt for my Protractor+Cucumber tests, I was using grunt-protractor-runner plugin, but I realized that it was not running my After steps, therefore my test fails.

Which plugin do you recommend? I was trying to use grunt-protractor-cucumber and I can't make it work!

Can you please assist?

答:
We use protractor cucumber framework and it's been great.

With it you can do things like:

```<code>this.After({tags: ['@myCustomScenarioTag']}, function() {
    //do stuff after a specific scenario has run
});
</code>```

Title: Grunt + Protractor + CucumberJs

Body:
We use protractor cucumber framework and it's been great.

With it you can do things like:

this.After({tags: ['@myCustomScenarioTag']}, function() {
    //do stuff after a specific scenario has run
});


问:
MPMoviePlayer sample doesn't work
I wish I could have found this solution when I googled every possible combination of these words.

Did you, like me, think you could download Apple's Movieplayer sample, click Build and Run and see a movie of an airplane?  And nothing happens, right?

Here is the solution:
Using MPMoviePlayerViewController in SDK 3.2 for iPad

答: Because the MoviePlayer demo is very old (2009-05-03) and because Apple is too lazy to update their code to support new approach on iOS 3.2/4.0.</p>

Title: MPMoviePlayer sample doesn't work

ContentLicense: CC BY-SA 2.5


答:
You may use this syntax, your syntax was a mix of an insert and an update statements.</p>

```<code>string sql = @"update `parameters`
              set `DateTime` = @timestamp ,
                  `User` = @user
              where `Key` = @key";
</code>```

Title: What is the correct sql for Update a row in a table?

Body:
You may use this syntax, your syntax was a mix of an insert and an update statements.

string sql = @"update `parameters`
              set `DateTime` = @timestamp ,
                  `User` = @user
              where `Key` = @key";


问:
Android EditText click, keyboard scroll to different view
I have an EditText. When I click on it, the input keyboard shows up with the EditText directly above it. I want the keyboard to show up a little bit further down at another View, as if the keyboard is focusing on that. Is there a way to handle this?

My use case is I have two EditTexts and a Button in vertical LinearLayout. I want it so that when I click on either of the EditTexts, the keyboard will popup and still show all three Views.

答:
Best practice, you won't want that, i.e showing all views while the keyboard is showing. This will force android to squeeze the views when there isn't enough space.
Best option is try adding paddingBottom to your EditText an example being android:paddingBottom="15dp" This should align the keyboard 15 pixels below your EditText.
You could also use ScrollView as suggested above which allows android to auto handle vertical scrolling for you.


问:
Creating Files Echo Success or Fail
I can't figure our where to properly add If (!){} else{} in my code when I create a new file. I want it to append to a .log file "Log Created" when true and "Log failed" when false. Am I approaching this wrong?

```<code>$foo = c:\path\to\folder
$bar_bar = <variable>

New-Item -path "$foo" -name "$bar_bar-test_archive.log" -type "file" -value "`n`r$(get-date -f yyyy-MM-dd.HH:mm:ss) : Process started.`n"
</code>```

SIDENOTE: I have to name my file "$bar_bar-test_archive.log" but I would prefer to name it "$bar_bar_test_archive.log", however because of the underscore in the variable name adding and underscore between the variable and constant messes it up. Is there a way to do this?

Thanks.

答:
SIDENOTE: I have to name my file "$bar_bar-test_archive.log" but I
  would prefer to name it "$bar_bar_test_archive.log", however because
  of the underscore in the variable name adding and underscore between
  the variable and constant messes it up. Is there a way to do this?

You can resolve that either of these ways:

```<code>-name "$bar_bar`_test_archive.log"

-name "$($bar_bar)_test_archive.log"
</code>```

As for logging if it works vs if it doesn't the correct way is with a try/catch construct which is a way to capture errors. For example,

```<code>$LogFile = 'C:\PSTest\log.log'

try
{
    Some-Action
}
catch
{
    'Failed to run Some-Action' | Out-File $LogFile -Append
}
</code>```

Inside the catch you would also generally add a Break or Continue for something like this:

```<code>$LogFile = 'C:\PSTest\log.log'

try
{
    Some-Action
}
catch
{
    'Failed to run Some-Action' | Out-File $LogFile -Append
    break # Exit Script
}

'Successfully ran Some-Action' | Out-File $LogFile -Append  # The script will only get here if there's no error as an error will trigger the break.
</code>```

You end up with something like this:

```<code>$foo = 'c:\PSTest'
$bar_bar = 'Test'
$LogFile = 'C:\PSTest\log.log'

try
{
    New-Item -path "$foo" -name "$bar_bar`_test_archive.log" -type "file" -value "`n`r$(get-date -f yyyy-MM-dd.HH:mm:ss) : Process started.`n" -ErrorAction Stop
}
catch
{
    "$(Get-Date -Format G) - Log Failed" | Out-File $LogFile -Append
    break
}

"$(Get-Date -Format G) - Log Succeeded" | Out-File $LogFile -Append
</code>```

Some additional notes:

Use more descriptive variable names than "Foo" and "Bar." It makes the code more readable and the longer your scripts get the easier it is to forget what a variable contains when named poorly.

You are/were missing quotes around the values for your variables. As strings use ''

You'll notice I added -ErrorAction Stop to the New-Item command; that allows the catch to function properly.

Title: Creating Files Echo Success or Fail

Body:
I can't figure our where to properly add If (!){} else{} in my code when I create a new file. I want it to append to a .log file "Log Created" when true and "Log failed" when false. Am I approaching this wrong?

$foo = c:\path\to\folder
$bar_bar = <variable>

New-Item -path "$foo" -name "$bar_bar-test_archive.log" -type "file" -value "`n`r$(get-date -f yyyy-MM-dd.HH:mm:ss) : Process started.`n"

SIDENOTE: I have to name my file "$bar_bar-test_archive.log" but I would prefer to name it "$bar_bar_test_archive.log", however because of the underscore in the variable name adding and underscore between the variable and constant messes it up. Is there a way to do this?

Thanks.

Body:
SIDENOTE: I have to name my file "$bar_bar-test_archive.log" but I
  would prefer to name it "$bar_bar_test_archive.log", however because
  of the underscore in the variable name adding and underscore between
  the variable and constant messes it up. Is there a way to do this?

You can resolve that either of these ways:

-name "$bar_bar`_test_archive.log"

-name "$($bar_bar)_test_archive.log"

As for logging if it works vs if it doesn't the correct way is with a try/catch construct which is a way to capture errors. For example,

$LogFile = 'C:\PSTest\log.log'

try
{
    Some-Action
}
catch
{
    'Failed to run Some-Action' | Out-File $LogFile -Append
}

Inside the catch you would also generally add a Break or Continue for something like this:

$LogFile = 'C:\PSTest\log.log'

try
{
    Some-Action
}
catch
{
    'Failed to run Some-Action' | Out-File $LogFile -Append
    break # Exit Script
}

'Successfully ran Some-Action' | Out-File $LogFile -Append  # The script will only get here if there's no error as an error will trigger the break.

You end up with something like this:

$foo = 'c:\PSTest'
$bar_bar = 'Test'
$LogFile = 'C:\PSTest\log.log'

try
{
    New-Item -path "$foo" -name "$bar_bar`_test_archive.log" -type "file" -value "`n`r$(get-date -f yyyy-MM-dd.HH:mm:ss) : Process started.`n" -ErrorAction Stop
}
catch
{
    "$(Get-Date -Format G) - Log Failed" | Out-File $LogFile -Append
    break
}

"$(Get-Date -Format G) - Log Succeeded" | Out-File $LogFile -Append

Some additional notes:

Use more descriptive variable names than "Foo" and "Bar." It makes the code more readable and the longer your scripts get the easier it is to forget what a variable contains when named poorly.

You are/were missing quotes around the values for your variables. As strings use ''

You'll notice I added -ErrorAction Stop to the New-Item command; that allows the catch to function properly.


答:
If you didn't want to use a try/catch like omniomi is using, which would likely be more appropriate, you could use Test-Path:

```<code>$foo = c:\path\to\folder
$bar_bar = <variable>

New-Item -path "$foo" -name "$bar_bar-test_archive.log" -type "file" -value "`n`r$(get-date -f yyyy-MM-dd.HH:mm:ss) : Process started.`n"
If (!(Test-Path $foo)){} else{}
</code>```

Answer to SideNote:
You could use $() to evaluate inside the quotes like this: "$($bar)_bar_test_archive.log"

Title: Creating Files Echo Success or Fail

Body:
If you didn't want to use a try/catch like omniomi is using, which would likely be more appropriate, you could use Test-Path:

$foo = c:\path\to\folder
$bar_bar = <variable>

New-Item -path "$foo" -name "$bar_bar-test_archive.log" -type "file" -value "`n`r$(get-date -f yyyy-MM-dd.HH:mm:ss) : Process started.`n"
If (!(Test-Path $foo)){} else{}

Answer to SideNote:
You could use $() to evaluate inside the quotes like this: "$($bar)_bar_test_archive.log"


问:
Best way to restrict access by IP address?
For an ASP.NET C# application, we will need to restrict access based on IP address. What is the best way to accomplish this?</p>

答:
Here is an article from Microsoft on how to do this.

Setting Folder Security by IP Address or Domain Name

Apache uses the Allow and Deny directives to determine the sites that can access a particular Web site or folder. However, Apache provides discretionary access control; you must either deny all sites and provide a specific list of sites or IP addresses that can access a folder or allow all sites and deny only those sites that you do not want to have access. For example, if you use the following directive, all client computers are denied access unless they are recognized as part of the domain.com domain:

Deny from all

Allow from .domain.com

IIS works the same way. All clients are specifically denied or granted access, except for those that are listed.

Define Access Control for Specific Folder or Site

Log on to the Web server computer as an administrator.

Click Start, point to Settings, and then click Control Panel.

Double-click Administrative Tools, and then double click Internet Services Manager.

If you want to limit access for the whole site, select the Web site from the list of different served sites in the left pane.

If you want to limit access only for a specific folder, click the folder you want to control.

Right-click the Web site or folder, and then click Properties.

Click the Directory Security panel.

If you want to limit access to a specific set of sites but deny access to all other sites, click Denied Access.

If you want to grant access to all clients by default but exclude a specific list of clients, click Granted Access.

To update the list of hosts or domains in the Except list, click Add.

To add a single computer to the list, click Single computer, type the IP address in the appropriate box, and then click OK.

To add a range of computers in a specific address range, click Group of computers, type the IP address for the network in the appropriate box, type the subnet mask for the network range you want to configure, and then click OK.

To add computers by their identified domain name, click Domain name, and then type the domain name in the appropriate box.

Click Properties, type the domain name, and then click OK.

Click OK, and then click OK.

NOTE: If you use domain name restrictions, the server has to perform a reverse DNS lookup for each request to check the host's registered domain name. Microsoft recommends that you use an IP address or network range whenever you can.

OwnerDisplayName: Keb

LastEditorDisplayName: Keb

OwnerDisplayName: Tom Anderson


问:
Type parameter in play-json read/write macro
I have a parametrized case class CaseClass[T](name: String, t: T) for which I would like to have serialization/deserialization using play-json (2.5).

Of course, I cannot have this if I do not have the equivalent for the type T, so I define

```<code>object CaseClass {
  implicit def reads[T: Reads] = Json.reads[CaseClass[T]]
}
</code>```

But I get the following compiler error:

```<code>overloaded method value apply with alternatives:
   [B](f: B => (String, T))(implicit fu: play.api.libs.functional.ContravariantFunctor[play.api.libs.json.Reads])play.api.libs.json.Reads[B] <and>
   [B](f: (String, T) => B)(implicit fu: play.api.libs.functional.Functor[play.api.libs.json.Reads])play.api.libs.json.Reads[B]
   cannot be applied to ((String, Nothing) => CaseClass[Nothing])
</code>```

If I try to do the same with the Json.writes macro, I get the error

```<code>type mismatch;
   found   : CaseClass[Nothing] => (String, Nothing)
   required: CaseClass[T] => (String, T)
</code>```

What is most surprising, is that neither error occur when I use the Json.format macro.

I know I have different solutions to by-pass this problem (using Json.format, writing my (de)serializer by hand, ...), but I'm rather curious about why this can occur here.

答:
It's either a limitation in the Json.reads macro, type inference, or both. Type inference has a little bit to do with it at least, because you can see that something is being inferred as Nothing in the error message.

If you use the compiler flag -Ymacro-debug-lite, you can see the macro generated AST.

```<code>implicit def reads[T](implicit r: Reads[T]): Reads[CaseClass[T]] =
  Json.reads[CaseClass[T]]
</code>```

Translates to:

```<code>_root_.play.api.libs.json.JsPath.$bslash("name").read(json.this.Reads.StringReads)
  .and(_root_.play.api.libs.json.JsPath.$bslash("t").read(r))
  .apply((CaseClass.apply: (() => <empty>)))
</code>```

Cleaned up, it looks like:

```<code>implicit def reads[T](implicit w: Reads[T]): Reads[CaseClass[T]] = (
  (JsPath \ "name").read(Reads.StringReads) and
  (JsPath \ "t" ).read(r)
)(CaseClass.apply _)
</code>```

Unfortunately, it doesn't compile because the type parameter of CaseClass.apply isn't supplied and is inferred as Nothing. Manually adding T to apply fixes the issue, but the macro likely doesn't know that T in CaseClass[T] is important.

To address the type inference issue with more detail, with the Reads combinators, we're calling FunctionalBuilder.CanBuild2#apply, which expects a (A1, A2) => B. But the compiler cannot properly infer A2.

For Writes, there is a similar issue, where we need a B => (A1, A2), but compiler is unable to infer B or A2 correctly (which is CaseClass[T] and T, respectively).

Format requires both of the above functions, and the compiler is able to reason that A2 must be T.

Body:
I have a parametrized case class CaseClass[T](name: String, t: T) for which I would like to have serialization/deserialization using play-json (2.5).

Of course, I cannot have this if I do not have the equivalent for the type T, so I define

object CaseClass {
  implicit def reads[T: Reads] = Json.reads[CaseClass[T]]
}

But I get the following compiler error:

overloaded method value apply with alternatives:
   [B](f: B => (String, T))(implicit fu: play.api.libs.functional.ContravariantFunctor[play.api.libs.json.Reads])play.api.libs.json.Reads[B] <and>
   [B](f: (String, T) => B)(implicit fu: play.api.libs.functional.Functor[play.api.libs.json.Reads])play.api.libs.json.Reads[B]
   cannot be applied to ((String, Nothing) => CaseClass[Nothing])

If I try to do the same with the Json.writes macro, I get the error

type mismatch;
   found   : CaseClass[Nothing] => (String, Nothing)
   required: CaseClass[T] => (String, T)

What is most surprising, is that neither error occur when I use the Json.format macro.

I know I have different solutions to by-pass this problem (using Json.format, writing my (de)serializer by hand, ...), but I'm rather curious about why this can occur here.

Body:
It's either a limitation in the Json.reads macro, type inference, or both. Type inference has a little bit to do with it at least, because you can see that something is being inferred as Nothing in the error message.

If you use the compiler flag -Ymacro-debug-lite, you can see the macro generated AST.

implicit def reads[T](implicit r: Reads[T]): Reads[CaseClass[T]] =
  Json.reads[CaseClass[T]]

Translates to:

_root_.play.api.libs.json.JsPath.$bslash("name").read(json.this.Reads.StringReads)
  .and(_root_.play.api.libs.json.JsPath.$bslash("t").read(r))
  .apply((CaseClass.apply: (() => <empty>)))

Cleaned up, it looks like:

implicit def reads[T](implicit w: Reads[T]): Reads[CaseClass[T]] = (
  (JsPath \ "name").read(Reads.StringReads) and
  (JsPath \ "t" ).read(r)
)(CaseClass.apply _)

Unfortunately, it doesn't compile because the type parameter of CaseClass.apply isn't supplied and is inferred as Nothing. Manually adding T to apply fixes the issue, but the macro likely doesn't know that T in CaseClass[T] is important.

To address the type inference issue with more detail, with the Reads combinators, we're calling FunctionalBuilder.CanBuild2#apply, which expects a (A1, A2) => B. But the compiler cannot properly infer A2.

For Writes, there is a similar issue, where we need a B => (A1, A2), but compiler is unable to infer B or A2 correctly (which is CaseClass[T] and T, respectively).

Format requires both of the above functions, and the compiler is able to reason that A2 must be T.


问:
auto numbered table rows (javafx)
My question is how to make a new Table in JavaFX with in the first column the index of the tableRow.

So i've created a class: NrCellFactory.

```<code>public class NrCellFactory<S, String> extends TableCellFactory<S,String> {

private class NrCell<S,String> extends TableCell<S,String>{

    public NrCell(){
        setText(this.getTableRow().getIndex()+"");
    }

}

@Override
protected TableCell<S, String> createTableCell(TableColumn<S, String> column) {
    return new NrCell();
}

}
</code>```

and then i set my column where the numbers should be displayed:

```<code> nrCol.setCellFactory(new NrCellFactory<Person,String>());
</code>```

when I load the project, the nrCol has no data...

Can anyone solve the problem?

Thanks

答:
This is a universal (Generic) cell factory you can simply use anywhere:

```<code>public class LineNumbersCellFactory<T, E> implements Callback<TableColumn<T, E>, TableCell<T, E>> {

    public LineNumbersCellFactory() {
    }

    @Override
    public TableCell<T, E> call(TableColumn<T, E> param) {
        return new TableCell<T, E>() {
            @Override
            protected void updateItem(E item, boolean empty) {
                super.updateItem(item, empty);

                if (!empty) {
                    setText(this.getTableRow().getIndex() + 1 + "");
                } else {
                    setText("");
                }
            }
        };
    }
}
</code>```

Usage: colRowNum.setCellFactory(new LineNumbersCellFactory());

Delete the +1 if you need 0-indexed rows.

EDIT: Added else block when deleting items

Title: auto numbered table rows (javafx)

Body:
My question is how to make a new Table in JavaFX with in the first column the index of the tableRow.

So i've created a class: NrCellFactory.

public class NrCellFactory<S, String> extends TableCellFactory<S,String> {

private class NrCell<S,String> extends TableCell<S,String>{

    public NrCell(){
        setText(this.getTableRow().getIndex()+"");
    }

}

@Override
protected TableCell<S, String> createTableCell(TableColumn<S, String> column) {
    return new NrCell();
}

}

and then i set my column where the numbers should be displayed:

 nrCol.setCellFactory(new NrCellFactory<Person,String>());

when I load the project, the nrCol has no data...

Can anyone solve the problem?

Thanks

Body:
This is a universal (Generic) cell factory you can simply use anywhere:

public class LineNumbersCellFactory<T, E> implements Callback<TableColumn<T, E>, TableCell<T, E>> {

    public LineNumbersCellFactory() {
    }

    @Override
    public TableCell<T, E> call(TableColumn<T, E> param) {
        return new TableCell<T, E>() {
            @Override
            protected void updateItem(E item, boolean empty) {
                super.updateItem(item, empty);

                if (!empty) {
                    setText(this.getTableRow().getIndex() + 1 + "");
                } else {
                    setText("");
                }
            }
        };
    }
}

Usage: colRowNum.setCellFactory(new LineNumbersCellFactory());

Delete the +1 if you need 0-indexed rows.

EDIT: Added else block when deleting items


问:
Conversion Failed when converting date and/or time
I am running into an issue. I get the Conversion failed error on the code sniped below.

I can't seem to pinpoint why this is happening, in my Dev environment I do not get the error and everything runs smoothly.

```<code>  Dim PrdDate As Date
        SQL.ReturnRead = 0
        PrdDate = dtpDataInput.Value.Date
        MsgBox(PrdDate)
        SQL.ReadQuery("SELECT CAST(DATEDIFF(second, TimeDown, TimeUp) / 60 / 60 % 24  AS NVARCHAR(50)) + '.'
               + CAST(DATEDIFF(second, TimeDown, TimeUp) / 60 % 60 AS NVARCHAR(50)) as HrsDown From UDOData
               WHERE (cast(TimeDown AS DATE) = '" & PrdDate & "'
               AND CAST(TimeUp AS DATE) = '" & PrdDate & "') and FleetNo = '" & FleetStr & "'")
        UDOHRS = SQL.ReturnRead
</code>```

I have checked the regional settings on the live environment and all seems ok.

Thank you for everyone's help

答:
When formatting for SQL Server it's better to always format it as YYYYMMDD.

Just use

```<code> WHERE (cast(TimeDown AS DATE) = '" & PrdDate.ToString("yyyyMMdd") & "'
</code>```

Body:
I am running into an issue. I get the Conversion failed error on the code sniped below.

I can't seem to pinpoint why this is happening, in my Dev environment I do not get the error and everything runs smoothly.

  Dim PrdDate As Date
        SQL.ReturnRead = 0
        PrdDate = dtpDataInput.Value.Date
        MsgBox(PrdDate)
        SQL.ReadQuery("SELECT CAST(DATEDIFF(second, TimeDown, TimeUp) / 60 / 60 % 24  AS NVARCHAR(50)) + '.'
               + CAST(DATEDIFF(second, TimeDown, TimeUp) / 60 % 60 AS NVARCHAR(50)) as HrsDown From UDOData
               WHERE (cast(TimeDown AS DATE) = '" & PrdDate & "'
               AND CAST(TimeUp AS DATE) = '" & PrdDate & "') and FleetNo = '" & FleetStr & "'")
        UDOHRS = SQL.ReturnRead

I have checked the regional settings on the live environment and all seems ok.

Thank you for everyone's help

Body:
When formatting for SQL Server it's better to always format it as YYYYMMDD.

Just use

 WHERE (cast(TimeDown AS DATE) = '" & PrdDate.ToString("yyyyMMdd") & "'


问:
same fish and bash command for detecting python executable name
Within a Makefile I need to check whether python2 command exists and, if not, try with just python. Currently it works for bash/sh as follows:

```<code>PYTHON?=$(type -p python2 || echo python)
</code>```

(and then using $(PYTHON) within make tasks).

However it fails when using fish shell because it does not support || (but instead requires using or, which does not work in bash/sh):

```<code>foo@bar ~> echo $(type -p python2 || echo python)

Unsupported use of '||'. In fish, please use 'COMMAND; or COMMAND'.
fish: echo $(type -p python2 || echo python)
                              ^
</code>```

I can not figure out any approach that works for both bash/sh and fish. Any help please?

答:
I can not figure out any approach that works for both bash/sh and fish. Any help please?

If you really need to do this in both fish and bash, you'll have to use an external script that runs in one of the two.

However, being mostly unfamiliar with Makefiles, I have no idea why this needs to run in fish and bash - are you using "the user's shell"? That's usually a mistake, because that could be anything (even things like python!). For your code, you'll always want to specify the interpreter it needs - if it runs in /bin/sh, use that, if it needs bash, use that. If it's ruby, use that.

Body:
Within a Makefile I need to check whether python2 command exists and, if not, try with just python. Currently it works for bash/sh as follows:

PYTHON?=$(type -p python2 || echo python)

(and then using $(PYTHON) within make tasks).

However it fails when using fish shell because it does not support || (but instead requires using or, which does not work in bash/sh):

foo@bar ~> echo $(type -p python2 || echo python)

Unsupported use of '||'. In fish, please use 'COMMAND; or COMMAND'.
fish: echo $(type -p python2 || echo python)
                              ^

I can not figure out any approach that works for both bash/sh and fish. Any help please?


问:
Two-way data binding for array collection in flex
I am using flex 3.5 sdk. I want to bind an array collection to a form. The structure of array collection is like this.

```<code>MyClass :
var value : String;
var arr : ArrayCollection;

Each element in arr above is an object of MySecondClass

MySecondClass :
var val1 : String;
var val2 : String;
var val3 : String;
</code>```

I want to bind array collection of MyClass objects (two-way) to a form which has a table and another table inside this table.

How can I accomplish that ?

答:
You can try set the var in MySecondClass to binable.

```<code>public class MySecondClass {
....
[bindable]
public var1:String;
[bindable]
public var2:String;
[bindable]
public var3:String;
}
</code>```

If you change the value of the object, the cell associated with this data should be change.

//P.S.

Answer after more input from questioner.

You can add the

```<code><mx:Binding destination="checkbox.selected" source="data.value"/>
</code>```

Body:
I am using flex 3.5 sdk. I want to bind an array collection to a form. The structure of array collection is like this.

MyClass :
var value : String;
var arr : ArrayCollection;

Each element in arr above is an object of MySecondClass

MySecondClass :
var val1 : String;
var val2 : String;
var val3 : String;

I want to bind array collection of MyClass objects (two-way) to a form which has a table and another table inside this table.

How can I accomplish that ?

Body:
You can try set the var in MySecondClass to binable.

public class MySecondClass {
....
[bindable]
public var1:String;
[bindable]
public var2:String;
[bindable]
public var3:String;
}

If you change the value of the object, the cell associated with this data should be change.

//P.S.

Answer after more input from questioner.

You can add the

<mx:Binding destination="checkbox.selected" source="data.value"/>


答:
Your syntax for the UPDATE statement is off, as you need to specifically set each of the columns and their new values:

```<code>string sql = @"UPDATE parameters
                  SET DateTime = @timestamp,
                      User = @user
                WHERE Key = @key";
</code>```

If you need a more generic format as a point of reference, you can use the following:

```<code>string sql = @"UPDATE [Table]
                  SET [Column] = [Value],
                      [OtherColumn] = [OtherValue]
                WHERE [Condition]";
</code>```

Example

A complete example, along with a connection (which I didn't see defined earlier) might look like this:

```<code>public int UpdatetData(int key, System.DateTime ts, string user)
{
     // Build parameterized query (with escaped DateTime)
     var sql = @"UPDATE parameters
                    SET [DateTime] = @timestamp,
                        User = @user
                  WHERE Key = @key";
     try
     {
          using(var connection = new MySqlConnection("{your-connection-string}"))
          {
               connection.Open();
               using (var command = new MySqlCommand(sql, connection))
               {

                    command.Parameters.AddWithValue("@key", key);
                    command.Parameters.AddWithValue("@timestamp", ts);
                    command.Parameters.AddWithValue("@user", user);
                    return command.ExecuteNonQuery();
               }
          }
    }
    catch (Exception ex)
    {
          Console.WriteLine(ex.ToString());
          return -1;
    }
}
</code>```

Body:
Your syntax for the UPDATE statement is off, as you need to specifically set each of the columns and their new values:

string sql = @"UPDATE parameters
                  SET DateTime = @timestamp,
                      User = @user
                WHERE Key = @key";

If you need a more generic format as a point of reference, you can use the following:

string sql = @"UPDATE [Table]
                  SET [Column] = [Value],
                      [OtherColumn] = [OtherValue]
                WHERE [Condition]";

Example

A complete example, along with a connection (which I didn't see defined earlier) might look like this:

public int UpdatetData(int key, System.DateTime ts, string user)
{
     // Build parameterized query (with escaped DateTime)
     var sql = @"UPDATE parameters
                    SET [DateTime] = @timestamp,
                        User = @user
                  WHERE Key = @key";
     try
     {
          using(var connection = new MySqlConnection("{your-connection-string}"))
          {
               connection.Open();
               using (var command = new MySqlCommand(sql, connection))
               {

                    command.Parameters.AddWithValue("@key", key);
                    command.Parameters.AddWithValue("@timestamp", ts);
                    command.Parameters.AddWithValue("@user", user);
                    return command.ExecuteNonQuery();
               }
          }
    }
    catch (Exception ex)
    {
          Console.WriteLine(ex.ToString());
          return -1;
    }
}


问:
og:event event:start_time not working
I have
<meta property="og:type" content="event" />
and the Object Graph Object Debugger from faceboook tells me type is invalid because a required property 'event:start_time' of type 'date_time' was not provided. I cannot find in any facebook documentation what the correct form is for event:start_time is.

I have tried the following:-

```<code><meta property="og:type"             content="event" />
<meta property="og:event:start_date" content="30/04/2017" />
</code>```

and

```<code><meta property="og:type"             content="event" />
<meta property="og:event:start_date" content="30/04/2017" />
</code>```

and

```<code><meta property="og:type"             content="event" />
<meta property="og:event:start_date" content="1490961953365" />
</code>```

and

```<code><meta property="og:type" content="event">
<meta property="og:event:start_date" content="2017-03-31T12:05:53.365Z">
</code>```

and

```<code><meta property="og:type" content="event">
<meta property="event:start_date" content="2017-03-31T12:05:53.365Z">
</code>```

答:
Error was

event:start_date

should have been

event:start_time

ISO Date is required (as CBroe identifies). Presence of Seconds, Microseconds and Timezone not specified in http://ogp.me/#data_types

Title: og:event event:start_time not working

Body:
I have
<meta property="og:type" content="event" />
and the Object Graph Object Debugger from faceboook tells me type is invalid because a required property 'event:start_time' of type 'date_time' was not provided. I cannot find in any facebook documentation what the correct form is for event:start_time is.

I have tried the following:-

<meta property="og:type"             content="event" />
<meta property="og:event:start_date" content="30/04/2017" />

and

<meta property="og:type"             content="event" />
<meta property="og:event:start_date" content="30/04/2017" />

and

<meta property="og:type"             content="event" />
<meta property="og:event:start_date" content="1490961953365" />

and

<meta property="og:type" content="event">
<meta property="og:event:start_date" content="2017-03-31T12:05:53.365Z">

and

<meta property="og:type" content="event">
<meta property="event:start_date" content="2017-03-31T12:05:53.365Z">


问:
c++ issues using cout and cin on same line (xcode8)
Using Xcode with c++ I'm trying to create a simple console application. However my usage of cout and cin does not seem to work as I intend it to.

I'm expecting:

```<code>Testing: 12
input was 12
</code>```

edit: i've cut down the code test as much as I can:

```<code>#include <iostream>

int main(int argc, const char * argv[]) {
    // insert code here...
    int num;
    std::cout << "Testing: ";
    std::cin >> num;
    std::cout << "input was " << num << std::endl;

    return 0;
}
</code>```

Sample output:

```<code>12
Testing: input was 12
Program ended with exit code: 0
</code>```

Is there something I'm missing here?

答:
Apparently is a specific problem with C++ streams, in Xcode debugger, Debug build.

Try this:

1. Project -> Edit Active Target ...

2. Search for "preprocessor" in Build

3. Delete the values:

Preprocessor Macros = _GLIBCXX_DEBUG=1 _GLIBCXX_DEBUG_PEDANTIC=1

I found a similar issue but for  Xcode 3.2.1 and C++ string fails!

You can try also this workaround:

Paste these lines at the very beginning of your program (before any #include statements):

```<code>#define _GLIBCXX_FULLY_DYNAMIC_STRING 1
#undef _GLIBCXX_DEBUG
#undef _GLIBCXX_DEBUG_PEDANTIC
</code>```

Body:
Using Xcode with c++ I'm trying to create a simple console application. However my usage of cout and cin does not seem to work as I intend it to.

I'm expecting:

Testing: 12
input was 12

edit: i've cut down the code test as much as I can:

#include <iostream>

int main(int argc, const char * argv[]) {
    // insert code here...
    int num;
    std::cout << "Testing: ";
    std::cin >> num;
    std::cout << "input was " << num << std::endl;

    return 0;
}

Sample output:

12
Testing: input was 12
Program ended with exit code: 0

Is there something I'm missing here?

Body:
Apparently is a specific problem with C++ streams, in Xcode debugger, Debug build.

Try this:

1. Project -> Edit Active Target ...

2. Search for "preprocessor" in Build

3. Delete the values:

Preprocessor Macros = _GLIBCXX_DEBUG=1 _GLIBCXX_DEBUG_PEDANTIC=1

I found a similar issue but for  Xcode 3.2.1 and C++ string fails!

You can try also this workaround:

Paste these lines at the very beginning of your program (before any #include statements):

#define _GLIBCXX_FULLY_DYNAMIC_STRING 1
#undef _GLIBCXX_DEBUG
#undef _GLIBCXX_DEBUG_PEDANTIC


问:
Display PDF as HTML Form
I want display a PDF as an html page - where the user will be allowed to enter the fillable data. My problem is not how to import/fill data (I was able to do it using FDF/XML and ITextSharp). My only concern is how to show it to the user so that he/she can see the form, fill/edit data, and should be done with it.

I tried saving the PDF as an image file, and showing it as an background-image - but it was very crude! - Iam hoping that there should be some elegant solution.

Thanks for you help!

答:
Here is what I used to populate a PDF form using HTML and PHP a while back. It worked great for me. <s> http://koivi.com/fill-pdf-form-fields/tutorial.php </s> (Working link: http://web.archive.org/web/20170315111519/http://koivi.com/fill-pdf-form-fields/)

You can always use a PDF generator to actually render a PDF with the data you submit from an HTML form. Here is an example of a class that does that http://www.fpdf.org/

Hope this works for you.

Title: Display PDF as HTML Form


问:
consulting database when data is today, tomorrow, after tomorrow
I need to consult a table using mysql...for today, tomorrow, after tomorrow,..

by now I use the following code where data is the day in format YYYY-MM-DD

```<code>$data_query = mysqli_query($conexionbd,'select * from `Meteo` where `data` >= "2017-03-31" ');
</code>```

what should I insert in where data >= in order to get the data for today, tomorrow...without inserting manually the date?

答:
To get tomorrow's date:

```<code>$tomorrow = date("Y-m-d", strtotime("+ 1 day"))
</code>```

Now you can add that variable to your query:

```<code>$data_query = mysqli_query($conexionbd,'select * from `Meteo` where `data` >= "'.$tomorrow.'" ');
</code>```

Then you can simply add more days as needed:

```<code>$after_tomorrow = date("Y-m-d", strtotime("+ 2 day"))
</code>```

Body:
I need to consult a table using mysql...for today, tomorrow, after tomorrow,..

by now I use the following code where data is the day in format YYYY-MM-DD

$data_query = mysqli_query($conexionbd,'select * from `Meteo` where `data` >= "2017-03-31" ');

what should I insert in where data >= in order to get the data for today, tomorrow...without inserting manually the date?

Body:
To get tomorrow's date:

$tomorrow = date("Y-m-d", strtotime("+ 1 day"))

Now you can add that variable to your query:

$data_query = mysqli_query($conexionbd,'select * from `Meteo` where `data` >= "'.$tomorrow.'" ');

Then you can simply add more days as needed:

$after_tomorrow = date("Y-m-d", strtotime("+ 2 day"))


问:
How to show my answer after few wrong attempt in HTML JavaScripts

Please help me to add a "Button" called "See your answer".

This "See your answer" button appear only after when user clicks "Check your answer" button 3 times, and 3 answers are wrong.

After click "See your answer" button, correct answer appear.

the correct answer is "100".

Thank you!!!

<title> </title>

How much is your profit?

<input id="id1" name = "id1" required>
  <button  type = "button" onclick="myFunction()">Check Your Answer</button>

```

答:
Hello,

See if it's what you need:

I put a global variable to be used as a counter.

I put a button to see the answer.

```<code><html>

<head>
<title> </title>
</head>

<body>

<p>How much is your profit?

<input id="id1" name = "id1" required>
  <button type="button" onclick="myFunction()">Check Your Answer</button>         </p>
  <button type="button" id="btn2" onclick="seeYourAnswer()" style="display:none;">See your answer</button> </p>
<p id="Q1"></p>

<script>
var errosCount = 0;
function myFunction() {
    var x, text;
    x = document.getElementById("id1").value;

      if (isNaN(x) || x != 100) {
          text = "Incorrect"; document.getElementById("Q1").style.color = "red";
          errosCount++;
      } else {
          text = "Correct"; document.getElementById("Q1").style.color = "green";
      }
      document.getElementById("Q1").innerHTML = text;

      if(errosCount === 3){
        errosCount = 0;
        document.getElementById('btn2').style.display = 'block';
        document.getElementById("Q1").innerHTML = '';
      } else {
        document.getElementById('btn2').style.display = 'none';
      }

}

function seeYourAnswer(){
  text = "the correct answer is '100'.";         document.getElementById("Q1").style.color = "red";
  document.getElementById("Q1").innerHTML = text;
}

</script>

</body>
</html>
</code>```

I hope it helped you!

Body:
Hello,

See if it's what you need:

I put a global variable to be used as a counter.

I put a button to see the answer.

<html>

<head>
<title> </title>
</head>

<body>

<p>How much is your profit?

<input id="id1" name = "id1" required>
  <button type="button" onclick="myFunction()">Check Your Answer</button>         </p>
  <button type="button" id="btn2" onclick="seeYourAnswer()" style="display:none;">See your answer</button> </p>
<p id="Q1"></p>

<script>
var errosCount = 0;
function myFunction() {
    var x, text;
    x = document.getElementById("id1").value;

      if (isNaN(x) || x != 100) {
          text = "Incorrect"; document.getElementById("Q1").style.color = "red";
          errosCount++;
      } else {
          text = "Correct"; document.getElementById("Q1").style.color = "green";
      }
      document.getElementById("Q1").innerHTML = text;

      if(errosCount === 3){
        errosCount = 0;
        document.getElementById('btn2').style.display = 'block';
        document.getElementById("Q1").innerHTML = '';
      } else {
        document.getElementById('btn2').style.display = 'none';
      }

}

function seeYourAnswer(){
  text = "the correct answer is '100'.";         document.getElementById("Q1").style.color = "red";
  document.getElementById("Q1").innerHTML = text;
}

</script>

</body>
</html>

I hope it helped you!


问:
Simplest way to read JSON from a URL in Java
This might be a dumb question but what is the simplest way to read and parse JSON from URL in Java?

In Groovy, it's a matter of few lines of code. Java examples that I find are ridiculously long (and have huge exception handling block).

All I want to do is to read the content of this link.

答:
Here are couple of alternatives versions with Jackson (since there are more than one ways you might want data as):

```<code>  ObjectMapper mapper = new ObjectMapper(); // just need one
  // Got a Java class that data maps to nicely? If so:
  FacebookGraph graph = mapper.readValue(url, FaceBookGraph.class);
  // Or: if no class (and don't need one), just map to Map.class:
  Map<String,Object> map = mapper.readValue(url, Map.class);
</code>```

And specifically the usual (IMO) case where you want to deal with Java objects, can be made one liner:

```<code>FacebookGraph graph = new ObjectMapper().readValue(url, FaceBookGraph.class);
</code>```

Other libs like Gson also support one-line methods; why many examples show much longer sections is odd. And even worse is that many examples use obsolete org.json library; it may have been the first thing around, but there are half a dozen better alternatives so there is very little reason to use it.

ContentLicense: CC BY-SA 4.0

Body:
Here are couple of alternatives versions with Jackson (since there are more than one ways you might want data as):

  ObjectMapper mapper = new ObjectMapper(); // just need one
  // Got a Java class that data maps to nicely? If so:
  FacebookGraph graph = mapper.readValue(url, FaceBookGraph.class);
  // Or: if no class (and don't need one), just map to Map.class:
  Map<String,Object> map = mapper.readValue(url, Map.class);

And specifically the usual (IMO) case where you want to deal with Java objects, can be made one liner:

FacebookGraph graph = new ObjectMapper().readValue(url, FaceBookGraph.class);

Other libs like Gson also support one-line methods; why many examples show much longer sections is odd. And even worse is that many examples use obsolete org.json library; it may have been the first thing around, but there are half a dozen better alternatives so there is very little reason to use it.


答:
```<code>$DTtoday = new DateTime(); //Current date
$DT2days = clone $DTtoday; //Create new object from $DTtoday
$DT2days->add(new DateInterval("P2D")); //Add 2 days
$data_query = mysqli_query($conexionbd,'select * from `Meteo` where `data` BETWEEN "'.$DTtoday->format("Y-m-d").'" AND "'.$DT2days->format("Y-m-d").'"');
</code>```

Title: consulting database when data is today, tomorrow, after tomorrow


问:
Do I need memory barrier for accessing memory modified by the thread that finished?
[Hereinafter, C++ terms]

I have a thread A and thread B that share access to the integer value P. Thread A initializes this value and updates it while running. Then thread A completes. Thread B waits for thread A to complete (standard OS API call, whatever OS is used) and wants to read P.

Does thread B need a memory barrier to read a coherent, last set by thread A, value of P? Is there a possibility that when OS API says "thread A finished", the changes of memory it modified are not visible to other threads yet?

Note that there only one thread writing the value here, which may or may not distinguish this question from "Is there an implicit memory barrier with synchronized-with relationship on thread::join?" asked before. My gut feeling tells me the answer should be the same, but...

答:
join synchronizes with the thread that calls join. That is, all writes that A makes will become visible to B when B calls A.join().

You can think of this as A executing std::atomic_thread_fence(memory_order_release) as it finishes and B executing std::atomic_thread_fence(std::memory_order_acquire as A joins.

Does thread B need a memory barrier

Yes, but they are implicit in join and you do not have to write them.

Is there a possibility that when OS API says "thread A finished", the changes of memory it modified are not visible to other threads yet?

Threads other than the caller of join will need additional synchronization, e.g. std::condition_variable or std::atomic_thread_fence(std::memory_order_acquire);


问:
Value in cell to match in a List I have and do it to every cell under that too(Title Not Good)
I would like the macro/code to take the Product that was entered in that cell (relative reference I guess) and scan a list of Products I have. If it doesn't match I would like the message box to tell me which product entered doesn't match with one in my product list and to return its row number where it was entered.

So to give you another example. Lets say we'll enter a number "1" in a cell. I need the macro to search my list of numbers 1-100, if 1 isn't in there I would like it to tell me. Let's say the next number entered (in the following cell under) was a 101. A message box would tell me 101 is not in my number list and its located in row 2.

It probably needs loops. As I will have a range of about 500 cells going down in that column that I would like it to search that product with a list.

答:
You could use a formula get what you want.

```<code>=IFERROR(MATCH(PRODUCT,LISTofPRODUCTS,0),"Not Found In List")
</code>```

Same formula using actual cell references:

```<code>=IFERROR(MATCH(A1,$B$1:$B$500,0),"Not Found In List")
</code>```

Where the value you want to look for is in cell A1, and the list you want to look in is B1:B500

To know what row the un-matched value is in, you could use this formula

```<code>=IF(ISERROR(MATCH(A1,$B$1:$B$500,0)),"Found","Value in row " & ROW(A1) & " not found")
</code>```

Body:
You could use a formula get what you want.

=IFERROR(MATCH(PRODUCT,LISTofPRODUCTS,0),"Not Found In List")

Same formula using actual cell references:

=IFERROR(MATCH(A1,$B$1:$B$500,0),"Not Found In List")

Where the value you want to look for is in cell A1, and the list you want to look in is B1:B500

To know what row the un-matched value is in, you could use this formula

=IF(ISERROR(MATCH(A1,$B$1:$B$500,0)),"Found","Value in row " & ROW(A1) & " not found")


问:
When does int++ get incremented?
I've got a line of code,

```<code>list[index++] = recursiveFunction();
</code>```

Does index get incremented before or after the call to recursiveFunction?

答:
The increment operation is executed before the function call. See http://msdn.microsoft.com/en-us/library/aa691322(v=VS.71).aspx. Note that this is not relevant to the precedence and associativity of operators.

The order of evaluation of operators in an expression is determined by the precedence and associativity of the operators (Section 7.2.1).

Operands in an expression are evaluated from left to right. For example, in F(i) + G(i++) * H(i), method F is called using the old value of i, then method G is called with the old value of i, and, finally, method H is called with the new value of i. This is separate from and unrelated to operator precedence.

Operator precedence and associativity only affect the way operators are bound to operands. The question here talks about side effects of the evaluation of operands.

```<code>using System;

class Obj {
   public bool Incremented {get;set;}
   public static Obj operator ++ (Obj o) {
     Console.WriteLine("Increment operator is executed.");
     return new Obj {Incremented = true};
   }
}

class L {
  public int this[Obj o] {
    set { Console.WriteLine("Assignment called with " +
            (o.Incremented ? "incremented" : "original") + " indexer value."); }
  }

}
class Test{
  static void Main() {
    Obj o = new Obj();
    L l = new L();
    l[o++] = Func();
  }

  static int Func() {
    Console.WriteLine("Function call.");
    return 10;
  }
}
</code>```

Prints:

```<code>Increment operator is executed.
Function call.
Assignment called with original indexer value.
</code>```

This behavior is clearly specified in the specification and should be identical in any conforming compiler.

Title: When does int++ get incremented?

Body:
I've got a line of code,

list[index++] = recursiveFunction();

Does index get incremented before or after the call to recursiveFunction?

Body:
The increment operation is executed before the function call. See http://msdn.microsoft.com/en-us/library/aa691322(v=VS.71).aspx. Note that this is not relevant to the precedence and associativity of operators.

The order of evaluation of operators in an expression is determined by the precedence and associativity of the operators (Section 7.2.1).

Operands in an expression are evaluated from left to right. For example, in F(i) + G(i++) * H(i), method F is called using the old value of i, then method G is called with the old value of i, and, finally, method H is called with the new value of i. This is separate from and unrelated to operator precedence.

Operator precedence and associativity only affect the way operators are bound to operands. The question here talks about side effects of the evaluation of operands.

using System;

class Obj {
   public bool Incremented {get;set;}
   public static Obj operator ++ (Obj o) {
     Console.WriteLine("Increment operator is executed.");
     return new Obj {Incremented = true};
   }
}

class L {
  public int this[Obj o] {
    set { Console.WriteLine("Assignment called with " +
            (o.Incremented ? "incremented" : "original") + " indexer value."); }
  }

}
class Test{
  static void Main() {
    Obj o = new Obj();
    L l = new L();
    l[o++] = Func();
  }

  static int Func() {
    Console.WriteLine("Function call.");
    return 10;
  }
}

Prints:

Increment operator is executed.
Function call.
Assignment called with original indexer value.

This behavior is clearly specified in the specification and should be identical in any conforming compiler.


问:
Error installing Google Cloud SDK on Windows 7
I recently installed Python 3.5 64-bit on Windows 7. Now while trying to install Google Cloud SDK I am getting following error:

```<code>Output folder: C:\Program Files (x86)\Google\Cloud SDK
Downloading Google Cloud SDK core.
Extracting Google Cloud SDK core.
Create Google Cloud SDK bat file: C:\Program Files (x86)\Google\Cloud SDK\cloud_env.bat
Installing components.
Welcome to the Google Cloud SDK!
  File "C:\Python\Lib\site.py", line 176
    file=sys.stderr)
        ^
SyntaxError: invalid syntax
  File "C:\Python\Lib\site.py", line 176
    file=sys.stderr)
        ^
SyntaxError: invalid syntax
Failed to install.
</code>```

I haven't modified any of the Python Lib files.

答:
This happens when GoogleCloud SDK doesn't find an executable python.exe. It downloads python27 by itself, but existing installations of more recent versions of python (such as 3x), and the corresponding Environment Variables will continue to interfere.

Thus, the best practice would be to:

Download and install Python 2.7 at any desired location, say  C:\Program Files\Python27

Now add a new Environment Variable named CLOUDSDK_PYTHON, and set its value to the location of the python.exe from the installation above.

In my case, it would be "C:\Program Files\Python27\python.exe"

Now re-run the setup.

If the problem still exists, add python 2.7 to your PYTHONPATH & Path Environment Variables(system).

After adding, move them UP, above any other python3x variables using the Move Up (Win10), or just paste the paths before any other python 3x variable.

This will ensure that your system always prioritizes python2.7 over any other version. To check if python2.7 is properly added, type in cmd

```<code> python -v
</code>```

This will tell you the version of python interpreter currently used.

Body:
I recently installed Python 3.5 64-bit on Windows 7. Now while trying to install Google Cloud SDK I am getting following error:

Output folder: C:\Program Files (x86)\Google\Cloud SDK
Downloading Google Cloud SDK core.
Extracting Google Cloud SDK core.
Create Google Cloud SDK bat file: C:\Program Files (x86)\Google\Cloud SDK\cloud_env.bat
Installing components.
Welcome to the Google Cloud SDK!
  File "C:\Python\Lib\site.py", line 176
    file=sys.stderr)
        ^
SyntaxError: invalid syntax
  File "C:\Python\Lib\site.py", line 176
    file=sys.stderr)
        ^
SyntaxError: invalid syntax
Failed to install.

I haven't modified any of the Python Lib files.

Body:
This happens when GoogleCloud SDK doesn't find an executable python.exe. It downloads python27 by itself, but existing installations of more recent versions of python (such as 3x), and the corresponding Environment Variables will continue to interfere.

Thus, the best practice would be to:

Download and install Python 2.7 at any desired location, say  C:\Program Files\Python27

Now add a new Environment Variable named CLOUDSDK_PYTHON, and set its value to the location of the python.exe from the installation above.

In my case, it would be "C:\Program Files\Python27\python.exe"

Now re-run the setup.

If the problem still exists, add python 2.7 to your PYTHONPATH & Path Environment Variables(system).

After adding, move them UP, above any other python3x variables using the Move Up (Win10), or just paste the paths before any other python 3x variable.

This will ensure that your system always prioritizes python2.7 over any other version. To check if python2.7 is properly added, type in cmd

 python -v

This will tell you the version of python interpreter currently used.


问:
Java parsing json array, Error parsing data org.json.JSONException
This is my code, in my log, i'm getting:

E/JSON Parser: Error parsing data org.json.JSONException Value xml of type java.lang.String cannot be converted to JSONObject

I really need a solution i have been searching for weeks now.

```<code>    @Override
    protected String doInBackground(String... para) {

        List<NameValuePair> params=new ArrayList<NameValuePair>();
        JSONObject json=jparser.makeHttpRequest(getDataUrl, "POST", params);

        try {
            success=json.getInt("success");
            if(success==1){

                drivers=new ArrayList<Driver>();

                JSONArray sounds=json.getJSONArray("location");
                for (int i = 0; i < sounds.length(); i++) {
                    JSONObject jobj=sounds.getJSONObject(i);
                    Driver d=new Driver();
                    d.setId(jobj.getString("id"));
                    d.setName(jobj.getString("name"));
                    d.setEmail(jobj.getString("email"));
                    d.setNumber(jobj.getString("number"));
                    d.setLatitude(jobj.getString("latitude"));
                    d.setLongitude(jobj.getString("longitude"));
                    d.setInfo(jobj.getString("info"));
                    d.setCost(jobj.getString("cost"));
                    drivers.add(d);

                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
            error=1;
        }catch (Exception e) {
            error=1;
        }
        return null;
    }
</code>```

And this is the JSONParser class

JSONParser.java

```<code>public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {
    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {
            // check for request method
            if(method.equals("POST")){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            } else if(method.equals("GET")) {
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();

                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;
    }
}
</code>```

 PHP File

```<code><?php
header('Content-Type: application/json');

$response = array();

// include db connect class
require_once 'core/db_connect.php';
$db = new DB_CONNECT();

$sql="SELECT * FROM locations WHERE online=1";
$result = mysqli_query($db->connect(), $sql) or die(mysqli_error($db->connect()));

if (mysqli_num_rows($result)>0) {
    $response["location"] = array();
        while ($row=mysqli_fetch_array($result)) {
            $files=array();
            $files["id"]=$row["id"];
            $files["name"]=$row["name"];
            $files["email"]=$row["email"];
            $files["number"]=$row["number"];
            $files["latitude"]=$row["latitude"];
            $files["longitude"]=$row["longitude"];
            $files["info"]=$row["vehicleinfo"];
            $files["cost"]=$row["costpkm"];

            array_push($response["location"], $files);

    }

    $response["success"]=1;
    echo json_encode($response);
} else {
    $response["success"]=0;
    $response["message"]="No Taxi found";

    echo json_encode($response);
}
?>
</code>```

答: Based on your error, the return result for makeHttpRequest is an xml object instead of json formated string. </p>

Body:
This is my code, in my log, i'm getting:

E/JSON Parser: Error parsing data org.json.JSONException Value xml of type java.lang.String cannot be converted to JSONObject

I really need a solution i have been searching for weeks now.

    @Override
    protected String doInBackground(String... para) {

        List<NameValuePair> params=new ArrayList<NameValuePair>();
        JSONObject json=jparser.makeHttpRequest(getDataUrl, "POST", params);

        try {
            success=json.getInt("success");
            if(success==1){

                drivers=new ArrayList<Driver>();

                JSONArray sounds=json.getJSONArray("location");
                for (int i = 0; i < sounds.length(); i++) {
                    JSONObject jobj=sounds.getJSONObject(i);
                    Driver d=new Driver();
                    d.setId(jobj.getString("id"));
                    d.setName(jobj.getString("name"));
                    d.setEmail(jobj.getString("email"));
                    d.setNumber(jobj.getString("number"));
                    d.setLatitude(jobj.getString("latitude"));
                    d.setLongitude(jobj.getString("longitude"));
                    d.setInfo(jobj.getString("info"));
                    d.setCost(jobj.getString("cost"));
                    drivers.add(d);

                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
            error=1;
        }catch (Exception e) {
            error=1;
        }
        return null;
    }

And this is the JSONParser class

JSONParser.java

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {
    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {
            // check for request method
            if(method.equals("POST")){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            } else if(method.equals("GET")) {
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();

                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;
    }
}

 PHP File

<?php
header('Content-Type: application/json');

$response = array();

// include db connect class
require_once 'core/db_connect.php';
$db = new DB_CONNECT();

$sql="SELECT * FROM locations WHERE online=1";
$result = mysqli_query($db->connect(), $sql) or die(mysqli_error($db->connect()));

if (mysqli_num_rows($result)>0) {
    $response["location"] = array();
        while ($row=mysqli_fetch_array($result)) {
            $files=array();
            $files["id"]=$row["id"];
            $files["name"]=$row["name"];
            $files["email"]=$row["email"];
            $files["number"]=$row["number"];
            $files["latitude"]=$row["latitude"];
            $files["longitude"]=$row["longitude"];
            $files["info"]=$row["vehicleinfo"];
            $files["cost"]=$row["costpkm"];

            array_push($response["location"], $files);

    }

    $response["success"]=1;
    echo json_encode($response);
} else {
    $response["success"]=0;
    $response["message"]="No Taxi found";

    echo json_encode($response);
}
?>


问:
How to prevent UIButton from exceeding its parent UIView's width with autolayout
Is that possible to create a MaxWidth constraint to prevent UIButton from exceeding its parent UIView's width?

UIButton is created programmatically and centered horizontally in its parent UIView using V:[ParentView]-(<=1)-[Button] constraint, but when the text is too large, button's width exceeds ParentView.

NOTE: I do not want to add leading/trailing constraints, which will force the button always be the same width as the parent. I really need the button to be center horizontally so when the text is short, it will not cover the whole width.

答:
You can set your button's widthAnchor to be less than or equal to its parentView's widthAnchor:

```<code>button.widthAnchor.constraint(lessThanOrEqualTo: parentView.widthAnchor, multiplier: 1).isActive = true
</code>```

Body:
You can set your button's widthAnchor to be less than or equal to its parentView's widthAnchor:

button.widthAnchor.constraint(lessThanOrEqualTo: parentView.widthAnchor, multiplier: 1).isActive = true


问:
Stratified Train/Test-split in scikit-learn
I need to split my data into a training set (75%) and test set (25%). I currently do that with the code below:

```<code>X, Xt, userInfo, userInfo_train = sklearn.cross_validation.train_test_split(X, userInfo)
</code>```

However, I'd like to stratify my training dataset. How do I do that? I've been looking into the StratifiedKFold method, but doesn't let me specifiy the 75%/25% split and only stratify the training dataset.

答:
In addition to the accepted answer by @Andreas Mueller, just want to add that as @tangy mentioned above:

StratifiedShuffleSplit most closely resembles train_test_split(stratify = y)
with added features of:

stratify by default

by specifying n_splits, it repeatedly splits the data

Body:
I need to split my data into a training set (75%) and test set (25%). I currently do that with the code below:

X, Xt, userInfo, userInfo_train = sklearn.cross_validation.train_test_split(X, userInfo)

However, I'd like to stratify my training dataset. How do I do that? I've been looking into the StratifiedKFold method, but doesn't let me specifiy the 75%/25% split and only stratify the training dataset.


问:
'init is unavailable: use 'withMemoryRebound(to:capacity:_)' to temporarily view memory as another layout-compatible type
since i converted my Code to Swift 3 the error occurs.

```<code>'init is unavailable: use 'withMemoryRebound(to:capacity:_)' to temporarily view memory as another layout-compatible type.
</code>```

Here is my Code:

```<code>func parseHRMData(data : NSData!)
{
    var flags : UInt8
    var count : Int = 1
    var zw = [UInt8](count: 2, repeatedValue: 0)

    flags = bytes[0]
    /*----------------FLAGS----------------*/
        //Heart Rate Value Format Bit
        if([flags & 0x01] == [0 & 0x01])
        {
            //Data Format is set to UINT8
            //convert UINT8 to UINT16
            zw[0] = bytes[count]
            zw[1] = 0
            bpm = UnsafePointer<UInt16>(zw).memory

            print("HRMLatitude.parseData Puls(UINT8): \(bpm)BPM")

            //count field index
            count = count + 1
        }
</code>```

How can I fix this error?

Thanks in advance!

答:
zw is an array of UInt8. To reinterpret the pointer to the element
storage as a pointer to UInt16, withMemoryRebound() has to be
called in Swift 3. In your case:

```<code>var zw = [UInt8](repeating: 0, count: 2)
// Alternatively:
var zw: [UInt8] = [0, 0]

// ...

let bpm = UnsafePointer(zw).withMemoryRebound(to: UInt16.self, capacity: 1) {
    $0.pointee
}
</code>```

An alternative solution is

```<code>let bpm = zw.withUnsafeBytes {
    $0.load(fromByteOffset: 0, as: UInt16.self)
}
</code>```

See SE-0107 UnsafeRawPointer API for
more information about raw pointers, typed pointers, and rebinding.

Body:
since i converted my Code to Swift 3 the error occurs.

'init is unavailable: use 'withMemoryRebound(to:capacity:_)' to temporarily view memory as another layout-compatible type.

Here is my Code:

func parseHRMData(data : NSData!)
{
    var flags : UInt8
    var count : Int = 1
    var zw = [UInt8](count: 2, repeatedValue: 0)

    flags = bytes[0]
    /*----------------FLAGS----------------*/
        //Heart Rate Value Format Bit
        if([flags & 0x01] == [0 & 0x01])
        {
            //Data Format is set to UINT8
            //convert UINT8 to UINT16
            zw[0] = bytes[count]
            zw[1] = 0
            bpm = UnsafePointer<UInt16>(zw).memory

            print("HRMLatitude.parseData Puls(UINT8): \(bpm)BPM")

            //count field index
            count = count + 1
        }

How can I fix this error?

Thanks in advance!

Body:
zw is an array of UInt8. To reinterpret the pointer to the element
storage as a pointer to UInt16, withMemoryRebound() has to be
called in Swift 3. In your case:

var zw = [UInt8](repeating: 0, count: 2)
// Alternatively:
var zw: [UInt8] = [0, 0]

// ...

let bpm = UnsafePointer(zw).withMemoryRebound(to: UInt16.self, capacity: 1) {
    $0.pointee
}

An alternative solution is

let bpm = zw.withUnsafeBytes {
    $0.load(fromByteOffset: 0, as: UInt16.self)
}

See SE-0107 UnsafeRawPointer API for
more information about raw pointers, typed pointers, and rebinding.


答:
You can it easy calculate with:

```<code>SELECT DATE (NOW()  + INTERVAL 1 DAY);
</code>```

sample

```<code>mysql> SELECT DATE (NOW()  + INTERVAL 1 DAY) as result;
+------------+
| result     |
+------------+
| 2017-03-30 |
+------------+
1 row in set (0,00 sec)

mysql>
</code>```

Body:
You can it easy calculate with:

SELECT DATE (NOW()  + INTERVAL 1 DAY);

sample

mysql> SELECT DATE (NOW()  + INTERVAL 1 DAY) as result;
+------------+
| result     |
+------------+
| 2017-03-30 |
+------------+
1 row in set (0,00 sec)

mysql>


问:
Converting 17 to "2017", SQL
BACKGROUND

I currently have two tables:

ActualSale.Year = "2017"

Note the text format

BudgetSale.Year = 17

Note the number format

I am looking to combine data from the ActualSale table and the BudgetSales table and join them on the year field.

APPROACH/PSEUDO CODE

```<code>SELECT
ActualSale.Year,
BudgetSales.Year

FROM
BudgetSale,
ActualSale

WHERE
ActualSales.year="2017"
</code>```

NOTE: Budget Sales tables are only inputted year-by-year, therefore the BudgetSale table only has data where year=17 (therefore, I do not necessarily have to filter for BudgetSales.Year=17.

QUESTIONS

Within SQL, how can I consistently convert "2017" (text) to 17 (number). I was thinking of removing the first two numbers in ActualSales.year to just leave "17" and then convert to a value using val(), but was wondering if there was a better way.

答:
CInt(ActualSale.Year)-2000 will do what you want without much fuss.

In case your database is old enough to have pre-2000 years, use IIF to check for that:

CInt(ActualSale.Year)-IIF(CInt(ActualSale.Year)<2000,1900,2000)

Title: Converting 17 to "2017", SQL

Body:
BACKGROUND

I currently have two tables:

ActualSale.Year = "2017"

Note the text format

BudgetSale.Year = 17

Note the number format

I am looking to combine data from the ActualSale table and the BudgetSales table and join them on the year field.

APPROACH/PSEUDO CODE

SELECT
ActualSale.Year,
BudgetSales.Year

FROM
BudgetSale,
ActualSale

WHERE
ActualSales.year="2017"

NOTE: Budget Sales tables are only inputted year-by-year, therefore the BudgetSale table only has data where year=17 (therefore, I do not necessarily have to filter for BudgetSales.Year=17.

QUESTIONS

Within SQL, how can I consistently convert "2017" (text) to 17 (number). I was thinking of removing the first two numbers in ActualSales.year to just leave "17" and then convert to a value using val(), but was wondering if there was a better way.


问:
How to check for broken images in React JS
I'm writing a module that takes article data from json and shows a large image over the article text, a hero module as they say.

I've got the data and have set it up so if there is an image, it will show that image and if there is no image in the data, it will show a default image.
Problem is that this method doesn't replace broken links to show the default image.

I'm still new to react and using state ... question is, should I be using state to check for the broken link and how do I do it?

This is how I get the data in as props in the module:

```<code>const { newsItemData: {
          headline = '',
          bylines = [],
          publishedDate: publishDate = '',
          updatedDate: updatedDate = '',
          link: newsLink = '',
          contentClassification: category = '',
          abstract: previewText = '',
          abstractimage: { filename: newsImage = '' } = {},
          surfaceable: { feature: { type: featureType = '' } = {} } = {},
        } = {},
        wideView,
        showPill,
        defaultImage } = this.props;
</code>```

I display the info in this way:

```<code><div className={imageContainerClassName} style={customBackgroundStyles}>
      {newsImage ? <img className="img-responsive" src={newsImage} alt={headline}/> : <img className="img-responsive" src={defaultImage} alt={headline}/>}
</div>
</code>```

What should I do in order to also check for broken images?
I think this is all the pertinent data needed, let me know if I should show anything else.
Thanks!

答:
As mentioned, onError is the way to go.

If you're looking for a component that handles this for you, try https://github.com/socialtables/react-image-fallback

Body:
I'm writing a module that takes article data from json and shows a large image over the article text, a hero module as they say.

I've got the data and have set it up so if there is an image, it will show that image and if there is no image in the data, it will show a default image.
Problem is that this method doesn't replace broken links to show the default image.

I'm still new to react and using state ... question is, should I be using state to check for the broken link and how do I do it?

This is how I get the data in as props in the module:

const { newsItemData: {
          headline = '',
          bylines = [],
          publishedDate: publishDate = '',
          updatedDate: updatedDate = '',
          link: newsLink = '',
          contentClassification: category = '',
          abstract: previewText = '',
          abstractimage: { filename: newsImage = '' } = {},
          surfaceable: { feature: { type: featureType = '' } = {} } = {},
        } = {},
        wideView,
        showPill,
        defaultImage } = this.props;

I display the info in this way:

      {newsImage ?  : }

What should I do in order to also check for broken images?
I think this is all the pertinent data needed, let me know if I should show anything else.
Thanks!