问:
Change between different background-images while you click on an image
I'm kind of a newbie to design websites at all, and I have tried to find answers on my question without any success. (at least not any answers that could help me understand how I should do it)

Anyway. I'm doing this website where I want to change the background image on the website (with the connected pages) between a handfull numbers of images, when I click on another image. I also want the background-image to stay the same, even when I jump between the different pages.

Can someone explain how I should do? Gladly in a "Web-design for dummies way". (I'm in a class for web design in school, but the teacher can't explain it)

答:
I will try to point you in the right directions.
To do something when a user interface element is clicked you need the onclick event (https://developer.mozilla.org/en/docs/Web/Events/click). The next thing that you have to do is somehow persist an image change for the user (or maybe for all users? you did not specify). You could do this for example with the cookies Web API (https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie). Then you would of course also need to load the image stored in that cookie.</p>


来源: stackexchange

问:
Adding camera profile correction to dng_validate.exe [Adobe DNG SDK]
Using Lightroom I know how to apply a camera profile (*.dcp file) to my *.DNG image.

I would like to do the same in an application which I'm writing, so I guess a good starting point would be to append this functionality to the dng_validate.exe application.

So I started to add:

```<code>#include "dng_camera_profile.h"
</code>```

Then added:

```<code>static dng_string gDumpDCP;
</code>```

And add the following to the error print:

```<code>"-dcp <file>   Load camera profile from <file>.dcp\"\n"
</code>```

Then I added the function to read the dcp from cli:

```<code>else if (option.Matches("dcp", true))
{
   gDumpDCP.Clear();
   if (index + 1 < argc)
   {
      gDumpDCP.Set(argv[++index]);
   }

   if (gDumpDCP.IsEmpty() || gDumpDCP.StartsWith("-"))
   {
      fprintf(stderr, "*** Missing file name after -dcp\n");
      return 1;
   }

   if (!gDumpDCP.EndsWith(".dcp"))
   {
      gDumpDCP.Append(".dcp");
   }

}
</code>```

Then I load the profile from disk [line 421]:

```<code>if (gDumpTIF.NotEmpty ())
{
   dng_camera_profile profile;
   if (gDumpDCP.NotEmpty())
   {
      dng_file_stream inStream(gDumpDCP.Get());
      profile.ParseExtended(inStream);
   }
   // Render final image.
   .... rest of code as it was
</code>```

So how do I now use the profile data to correct the render and write the corrected image?

答:
You need to add the profile to your negative with negative->AddProfile(profile);.

My project raw2dng does this (and more) and is available in source if you want to see an example. The profile is added here.

ContentLicense: CC BY-SA 3.0

Body:
Using Lightroom I know how to apply a camera profile (*.dcp file) to my *.DNG image.

I would like to do the same in an application which I'm writing, so I guess a good starting point would be to append this functionality to the dng_validate.exe application.

So I started to add:

#include "dng_camera_profile.h"

Then added:

static dng_string gDumpDCP;

And add the following to the error print:

"-dcp <file>   Load camera profile from <file>.dcp\"\n"

Then I added the function to read the dcp from cli:

else if (option.Matches("dcp", true))
{
   gDumpDCP.Clear();
   if (index + 1 < argc)
   {
      gDumpDCP.Set(argv[++index]);
   }

   if (gDumpDCP.IsEmpty() || gDumpDCP.StartsWith("-"))
   {
      fprintf(stderr, "*** Missing file name after -dcp\n");
      return 1;
   }

   if (!gDumpDCP.EndsWith(".dcp"))
   {
      gDumpDCP.Append(".dcp");
   }

}

Then I load the profile from disk [line 421]:

if (gDumpTIF.NotEmpty ())
{
   dng_camera_profile profile;
   if (gDumpDCP.NotEmpty())
   {
      dng_file_stream inStream(gDumpDCP.Get());
      profile.ParseExtended(inStream);
   }
   // Render final image.
   .... rest of code as it was

So how do I now use the profile data to correct the render and write the corrected image?


答:
I'm not sure what framework you are using, but I think the best way to do this is to include the background images in a css class like so:

.background-image-1 {
  background-image: url("../path/to/image1")
}

.background-image-2 {
  background-image: url("../path/to/image2")
}

Then adding an event handler to the click on the image that you want to change the background with. In the event handler you can then dynamically switch the css class of the body. That would probably look something like this:

document.getElementById('idForBody').className = 'background-image-2';

Hope this helps!

Title: Change between different background-images while you click on an image

Body:
I'm kind of a newbie to design websites at all, and I have tried to find answers on my question without any success. (at least not any answers that could help me understand how I should do it)

Anyway. I'm doing this website where I want to change the background image on the website (with the connected pages) between a handfull numbers of images, when I click on another image. I also want the background-image to stay the same, even when I jump between the different pages.

Can someone explain how I should do? Gladly in a "Web-design for dummies way". (I'm in a class for web design in school, but the teacher can't explain it)


问:
Website is not responsive
I'm at the moment building a simple website with a header, a vertical nav and a content box and I'm failing in some minor thing. After building the html structure

```<code><html>
    <head>
        <title>Website</title>
        <link href="style.css" type="text/css" rel="stylesheet">
    </head>
    <body>
        <div class="container">
            <div class="header"></div>
            <div class="nav_content_container">
                <div class="nav"></div>
                <div class="content"></div>
                <div class="floatkiller"></div>
            </div>
        </div>
    </body>
</html>
</code>```

and giving it some css

```<code>body {
    height: 100%;
    width: 100%;
    margin: 0px;
    padding: 0px;
    background-color: lightgray;
}

.container {
    height: 100%;
    width: 77%;
    margin: 0px auto;
    background-color: white;
    border: 3px solid black;
}

.header {
    height: 20%;
    width: 100%;
    background-color: yellowgreen;
    border-bottom: 3px solid black;
}

.nav_content_container {
    height: 80%;
    width: 100%;
    background-color: azure;
}

.nav {
    height: 100%;
    width: 20%;
    float: left;
    background-color: palevioletred;
    border-right: 3px solid black;
}

.content {
    height: 100%;
    width: 80%;
    float: left;
    background-color: cornflowerblue;
}

.floatkiller {
    float: none;
    clear: both;
}
</code>```

my website is failing in beeing responsiv or to be accurate, my site get's a height more than 100% and my content box drops out of the nav_content_container. If I'm not giving any borders, everything is alright, but after applying the borders my website is broken. Why is the border making everything broken?

答:
You need to add <meta name="viewport" content="width=device-width , initial-scale=1"> into your  tag. You also need to use @media query so that an element changes on a specific resolution, like this:

```<code>@media screen (max-width: 1366px)
 {
   /* element that changes on specific screen resouliton*/
   /* h1 { color: red; } AS AN EXAMPLE */
 }
</code>```

But, if you are using Bootstrap, then the only thing you need to do, is to add classes like col-lg-x , col-md-x col-xs-x ("x" is a number from 1 - 12), and those classes do the job for you.

Read about them here: http://getbootstrap.com/css/#grid-options

Title: Website is not responsive

Body:
I'm at the moment building a simple website with a header, a vertical nav and a content box and I'm failing in some minor thing. After building the html structure

        <title>Website</title>
        <link href="style.css" type="text/css" rel="stylesheet">

and giving it some css

body {
    height: 100%;
    width: 100%;
    margin: 0px;
    padding: 0px;
    background-color: lightgray;
}

.container {
    height: 100%;
    width: 77%;
    margin: 0px auto;
    background-color: white;
    border: 3px solid black;
}

.header {
    height: 20%;
    width: 100%;
    background-color: yellowgreen;
    border-bottom: 3px solid black;
}

.nav_content_container {
    height: 80%;
    width: 100%;
    background-color: azure;
}

.nav {
    height: 100%;
    width: 20%;
    float: left;
    background-color: palevioletred;
    border-right: 3px solid black;
}

.content {
    height: 100%;
    width: 80%;
    float: left;
    background-color: cornflowerblue;
}

.floatkiller {
    float: none;
    clear: both;
}

my website is failing in beeing responsiv or to be accurate, my site get's a height more than 100% and my content box drops out of the nav_content_container. If I'm not giving any borders, everything is alright, but after applying the borders my website is broken. Why is the border making everything broken?

Body:
You need to add <meta name="viewport" content="width=device-width , initial-scale=1"> into your <head> tag. You also need to use @media query so that an element changes on a specific resolution, like this:

@media screen (max-width: 1366px)
 {
   /* element that changes on specific screen resouliton*/
   /* h1 { color: red; } AS AN EXAMPLE */
 }

But, if you are using Bootstrap, then the only thing you need to do, is to add classes like col-lg-x , col-md-x col-xs-x ("x" is a number from 1 - 12), and those classes do the job for you.

Read about them here: http://getbootstrap.com/css/#grid-options


问:
Fullscreen operation is not working in selenium webdriver 3.x
Firefox Version: 52.0.2 (32-bit)

Platform: Windows 7

Selenium Webdriver version: 3.4.0 (Java bindings)

Problem statement:
While trying to perform full screen operation in firefox browser then it throws UnsupportedCommandException

Test Code:

```<code>public class GeckoTest {
    public static void main(String[] args) throws IOException {
        System.setProperty("webdriver.gecko.driver","<geckodriver executable>");
        FirefoxBinary binary = new FirefoxBinary(new File("firefox binary"));
        FirefoxOptions options = new FirefoxOptions();
        options.setBinary(binary);
        options.setLogLevel(Level.ALL);
        WebDriver browser = new FirefoxDriver(options);
        browser.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        browser.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
        browser.get("http://examples.sencha.com/extjs/6.5.0/examples/kitchensink/?classic#form-fieldtypes");
        browser.manage().window().fullscreen();
        WebDriverWait wait = new WebDriverWait(browser,20,3000);
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//div[contains(@class,'x-form-spinner x-form-spinner-default x-form-spinner-down x-form-spinner-down-default')]")));
        Actions builder = new Actions(browser);
        builder.doubleClick(browser.findElement(By.xpath(".//div[contains(@class,'x-form-spinner x-form-spinner-default x-form-spinner-down x-form-spinner-down-default')]"))).perform();
        browser.close();
    }
}
</code>```

EDIT: It seems this is an known issue and will be fixed in FF55 as per this enter link description here

答:
While you work with Selenium 3.4.x, geckodriver v0.16.1 and Mozilla Firefox 53.0, as you mentioned when we try to perform full screen operation in Mozilla Firefox browser then it throws UnsupportedCommandException is true. How ever there is an alternative to achieve the full screen operation in Mozilla Firefox which works perfect through sending F11 Keys. Here is the minimal code block to check full screen operation in Mozilla Firefox:

```<code>System.setProperty("webdriver.gecko.driver", "C:\\your_directory\\geckodriver.exe");
WebDriver browser = new FirefoxDriver();
browser.get("http://examples.sencha.com/extjs/6.5.0/examples/kitchensink/?classic#form-fieldtypes");
browser.findElement(By.tagName("body")).sendKeys(Keys.F11);
</code>```

Body:
Firefox Version: 52.0.2 (32-bit)

Platform: Windows 7

Selenium Webdriver version: 3.4.0 (Java bindings)

Problem statement:
While trying to perform full screen operation in firefox browser then it throws UnsupportedCommandException

Test Code:

public class GeckoTest {
    public static void main(String[] args) throws IOException {
        System.setProperty("webdriver.gecko.driver","<geckodriver executable>");
        FirefoxBinary binary = new FirefoxBinary(new File("firefox binary"));
        FirefoxOptions options = new FirefoxOptions();
        options.setBinary(binary);
        options.setLogLevel(Level.ALL);
        WebDriver browser = new FirefoxDriver(options);
        browser.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        browser.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
        browser.get("http://examples.sencha.com/extjs/6.5.0/examples/kitchensink/?classic#form-fieldtypes");
        browser.manage().window().fullscreen();
        WebDriverWait wait = new WebDriverWait(browser,20,3000);
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//div[contains(@class,'x-form-spinner x-form-spinner-default x-form-spinner-down x-form-spinner-down-default')]")));
        Actions builder = new Actions(browser);
        builder.doubleClick(browser.findElement(By.xpath(".//div[contains(@class,'x-form-spinner x-form-spinner-default x-form-spinner-down x-form-spinner-down-default')]"))).perform();
        browser.close();
    }
}

EDIT: It seems this is an known issue and will be fixed in FF55 as per this enter link description here

Body:
While you work with Selenium 3.4.x, geckodriver v0.16.1 and Mozilla Firefox 53.0, as you mentioned when we try to perform full screen operation in Mozilla Firefox browser then it throws UnsupportedCommandException is true. How ever there is an alternative to achieve the full screen operation in Mozilla Firefox which works perfect through sending F11 Keys. Here is the minimal code block to check full screen operation in Mozilla Firefox:

System.setProperty("webdriver.gecko.driver", "C:\\your_directory\\geckodriver.exe");
WebDriver browser = new FirefoxDriver();
browser.get("http://examples.sencha.com/extjs/6.5.0/examples/kitchensink/?classic#form-fieldtypes");
browser.findElement(By.tagName("body")).sendKeys(Keys.F11);

ContentLicense: CC BY-SA 4.0


问:
Fetching records from Cust table
```<code>1   abc_chg
2   a_dhj
3   axc_kk
4   sdsd
</code>```

I have four records in the table Cust. I want to get only those records which contain an underscore.

How do I do that?

答:
You can use LIKE with wildcards on this way:</p>

```<code>Select *
from   Cust
where  Field LIKE '%[_]%';
</code>```

Title: Fetching records from Cust table

Body:
1   abc_chg
2   a_dhj
3   axc_kk
4   sdsd

I have four records in the table Cust. I want to get only those records which contain an underscore.

How do I do that?

Body:
You can use LIKE with wildcards on this way:

Select *
from   Cust
where  Field LIKE '%[_]%';


问:
Xamarin forms toggle button default color on IOS
How could I change the toggle button default color which is green on IOS?</p>

答:
If you want to change it app-wide then the easiest way how to do it is in the FinishedLaunching method in the AppDelegate.cs file (in the iOS project):

```<code>UISwitch.Appearance.OnTintColor = UIColor.FromRGB(0xFF, 0x00, 0x00); // RED
</code>```

Full example:

```<code>public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
    // switch
    UISwitch.Appearance.OnTintColor = UIColor.FromRGB(0xFF, 0x00, 0x00);
    // required Xamarin.Forms code
    Forms.Init ();
    LoadApplication (new App ());
    return base.FinishedLaunching (app, options);
}
</code>```

Source: https://developer.xamarin.com/guides/xamarin-forms/platform-features/ios/theme/#UISwitch

Body:
If you want to change it app-wide then the easiest way how to do it is in the FinishedLaunching method in the AppDelegate.cs file (in the iOS project):

UISwitch.Appearance.OnTintColor = UIColor.FromRGB(0xFF, 0x00, 0x00); // RED

Full example:

public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
    // switch
    UISwitch.Appearance.OnTintColor = UIColor.FromRGB(0xFF, 0x00, 0x00);
    // required Xamarin.Forms code
    Forms.Init ();
    LoadApplication (new App ());
    return base.FinishedLaunching (app, options);
}

Source: https://developer.xamarin.com/guides/xamarin-forms/platform-features/ios/theme/#UISwitch


问:
Clearing data on a comboBox that's data bound
I need help with this part of my code. I'm trying to do 2 things here:

1st, I need my comboBox cmbTechSearch filled with a list of names retrieved from a SQL database. Those names belong to an object called Tecnico.
So far, so good. But if I click on the comboBox twice, I get the names duplicated... And so on.
Adding cmbTechSearch.Items.Clear(); didn't solve it because the box was data binded, firing an error message. So I added cmbTechSearch.DataSource = null; which solved the error message but didn't clear my box. Nor did cmbTechSearch.ResetText();
Right now I'm unsure about how to clear it so that data doesn't come duplicated if I click the box again.

2nd, that list retrieved from SQL database brings more than just the name attached. It brings an e-mail for each object too. And I can't figure out how to retrieve the mail associated to the chosen name on that comboBox.
Mind you, email is a global string var since I use it in other methods within the code. That part is commented because it doesn't work.

public void TechSearch_loaded(object sender, EventArgs e)

{

//all these 3 entries are supposedly to clear the comboBox cmbTechSearch; all of them fail but if I remove the 1st line I get an error saying that there's already some data bound to the box (but only if I click a 2nd time)

```<code>        cmbTechSearch.DataSource = null;
        cmbTechSearch.Items.Clear();
        cmbTechSearch.ResetText();
</code>```

//there's a class called Tecnico and all the info about that object is saved on a SQL db. This part populates a list of Tecnicos with info from the db.

```<code>        List<Tecnico> tecnicos = new List<Tecnico>();
        tecnicos = bd.ProcuraPerfisTipo("TEC");
</code>```

//then I get a list of Tecnicos and retrieve one attribute (Nome) for each tecnico in the list

```<code>        List<String> TechSearch = new List<String>();

        foreach (Tecnico obj in tecnicos)
        {
            TechSearch.Add(obj.Nome);
        }
</code>```

//lastly I populate the comboBox with the info I got from the list.

```<code>        cmbTechSearch.DataSource = TechSearch;

        //email = cmbTechSearch.ToString();
    }
</code>```

There's a class named Tecnico, another named BDTicketSQL and another named iBDTicketSQL (the first calling the SQL db and running updates, queries and inserts while the second is used for interface). Those classes are all external to this form. I just get date from them to populate the form with whatever info I need.

答:
Alright, so what you need to reduce your effort is DataBinding. Since you've mentioned databinding in your question, I am going to assume you know it. So I'll quickly run through the answer. Also since you hadn't mentioned any platform, I assumed it to be WPF but the code can be copied to WinRT or UWP if you want. Just incase it's a different platform, do let me know in the comments section Link to full solution In case you wana skip

Your XAML:
I've used basic binding to codebehind to avoid a lot of classes for a sample. below is the code:

```<code><StackPanel Margin="20">
    <ComboBox x:Name="UserCombobox"
              Height="20"
              Width="300"
              ItemsSource="{Binding DataFromSQLService,Mode=OneWay}"
              SelectedItem="{Binding CurrentSelectedUser,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
              ItemTemplate="{StaticResource UserDataTemplate}"
              SelectionChanged="UserCombobox_SelectionChanged"/>

    <Button Content="Clear Combo" Height="30" Width="100" Margin="10" Click="ClearData"/>

    <Button Content="Load Combo" Height="30" Width="100" Margin="10" Click="LoadData"/>

    <TextBlock Text="{Binding CurrentSelectedUser.Name,Mode=OneWay}" HorizontalAlignment="Center"/>

    <TextBlock Text="{Binding CurrentSelectedUser.Email,Mode=OneWay}" HorizontalAlignment="Center"/>

</StackPanel>
</code>```

Now, your Window.Resources where you put your dataTemplate for your combobox Items.

```<code> <Window.Resources>
    <DataTemplate x:Key="UserDataTemplate">
        <StackPanel>
            <TextBlock Text="{Binding Name}"/>
        </StackPanel>
    </DataTemplate>
</Window.Resources>
</code>```

Now, self bind the view to it's codebehind, so in the Window Declaration add

```<code>DataContext = "{Binding RelativeSource={RelativeSource Self}}"
</code>```

Now that the view is ready, let's quickly get our code behind ready.

A Dummy User Class you can replace this with your model class.

```<code>public class MyDummyUser
{
    public MyDummyUser(string name, string email)
    {
        Name = name;
        Email = email;
    }

    public string Name { get; set; }

    public string Email { get; set; }
}
</code>```

Now Create a quick property to hold your currently selected user.

```<code>  private MyDummyUser currentSelectedUser;

  public MyDummyUser CurrentSelectedUser
    {
        get { return currentSelectedUser; }
        set { currentSelectedUser = value; RaisePropertyChanged(nameof(CurrentSelectedUser)); }
    }
</code>```

Now create an observable collection to hold your data from the SQL service:

```<code>private ObservableCollection<MyDummyUser> dataFromSQLService;
    public ObservableCollection<MyDummyUser> DataFromSQLService
    {
        get { return dataFromSQLService; }
        set { dataFromSQLService = value; RaisePropertyChanged(nameof(DataFromSQLService)); }
    }
</code>```

Now Implement INotifyPropertyChanged

```<code>public event PropertyChangedEventHandler PropertyChanged;
    public void RaisePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    //if using c# 6.0 or later replace the above with
    //public void RaisePropertyChanged(string propertyName)=>
    //        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
</code>```

Now Add a listener to the combobox.SelectionChanged event so that you know when the selected user changed:

```<code> private void UserCombobox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
    {
        if (CurrentSelectedUser != null && !string.IsNullOrEmpty(CurrentSelectedUser?.Email?.Trim()))
        {
            //perform what you wana do with the email.
        }
    }
</code>```

Create Two methods: LoadData and ClearData.

```<code> private void ClearData(object sender, RoutedEventArgs e)
    {
        DataFromSQLService = null;
    }

    private void LoadData(object sender, RoutedEventArgs e)
    {
        List<MyDummyUser> someData = new List<MyDummyUser>()
        {
            new MyDummyUser("User 1","User1@gmail.com"),
            new MyDummyUser("User 2","User2@gmail.com"),
            new MyDummyUser("User 3","User3@gmail.com"),
            new MyDummyUser("User 4","User4@gmail.com"),
            new MyDummyUser("User 5","User5@gmail.com"),
            new MyDummyUser("User 6","User6@gmail.com"),
        };

        DataFromSQLService = new ObservableCollection<MyDummyUser>(someData);
    }
</code>```

Please Note I've used an example of a WPF but even if you want to use the code for WinRT or UWP it'll work, just remember to switch Window.Resources with Page.Resources also, in UWP you can use x:Bind and using x:Bind can help you get rid of the RelativeResource=self

Body:
I need help with this part of my code. I'm trying to do 2 things here:

1st, I need my comboBox cmbTechSearch filled with a list of names retrieved from a SQL database. Those names belong to an object called Tecnico.
So far, so good. But if I click on the comboBox twice, I get the names duplicated... And so on.
Adding cmbTechSearch.Items.Clear(); didn't solve it because the box was data binded, firing an error message. So I added cmbTechSearch.DataSource = null; which solved the error message but didn't clear my box. Nor did cmbTechSearch.ResetText();
Right now I'm unsure about how to clear it so that data doesn't come duplicated if I click the box again.

2nd, that list retrieved from SQL database brings more than just the name attached. It brings an e-mail for each object too. And I can't figure out how to retrieve the mail associated to the chosen name on that comboBox.
Mind you, email is a global string var since I use it in other methods within the code. That part is commented because it doesn't work.

public void TechSearch_loaded(object sender, EventArgs e)

{

//all these 3 entries are supposedly to clear the comboBox cmbTechSearch; all of them fail but if I remove the 1st line I get an error saying that there's already some data bound to the box (but only if I click a 2nd time)

        cmbTechSearch.DataSource = null;
        cmbTechSearch.Items.Clear();
        cmbTechSearch.ResetText();

//there's a class called Tecnico and all the info about that object is saved on a SQL db. This part populates a list of Tecnicos with info from the db.

        List<Tecnico> tecnicos = new List<Tecnico>();
        tecnicos = bd.ProcuraPerfisTipo("TEC");

//then I get a list of Tecnicos and retrieve one attribute (Nome) for each tecnico in the list

        List<String> TechSearch = new List<String>();

        foreach (Tecnico obj in tecnicos)
        {
            TechSearch.Add(obj.Nome);
        }

//lastly I populate the comboBox with the info I got from the list.

        cmbTechSearch.DataSource = TechSearch;

        //email = cmbTechSearch.ToString();
    }

There's a class named Tecnico, another named BDTicketSQL and another named iBDTicketSQL (the first calling the SQL db and running updates, queries and inserts while the second is used for interface). Those classes are all external to this form. I just get date from them to populate the form with whatever info I need.

Body:
Alright, so what you need to reduce your effort is DataBinding. Since you've mentioned databinding in your question, I am going to assume you know it. So I'll quickly run through the answer. Also since you hadn't mentioned any platform, I assumed it to be WPF but the code can be copied to WinRT or UWP if you want. Just incase it's a different platform, do let me know in the comments section Link to full solution In case you wana skip

Your XAML:
I've used basic binding to codebehind to avoid a lot of classes for a sample. below is the code:

<StackPanel Margin="20">
    <ComboBox x:Name="UserCombobox"
              Height="20"
              Width="300"
              ItemsSource="{Binding DataFromSQLService,Mode=OneWay}"
              SelectedItem="{Binding CurrentSelectedUser,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
              ItemTemplate="{StaticResource UserDataTemplate}"
              SelectionChanged="UserCombobox_SelectionChanged"/>

    <Button Content="Clear Combo" Height="30" Width="100" Margin="10" Click="ClearData"/>

    <Button Content="Load Combo" Height="30" Width="100" Margin="10" Click="LoadData"/>

    <TextBlock Text="{Binding CurrentSelectedUser.Name,Mode=OneWay}" HorizontalAlignment="Center"/>

    <TextBlock Text="{Binding CurrentSelectedUser.Email,Mode=OneWay}" HorizontalAlignment="Center"/>

</StackPanel>

Now, your Window.Resources where you put your dataTemplate for your combobox Items.

 <Window.Resources>
    <DataTemplate x:Key="UserDataTemplate">
        <StackPanel>
            <TextBlock Text="{Binding Name}"/>
        </StackPanel>
    </DataTemplate>
</Window.Resources>

Now, self bind the view to it's codebehind, so in the Window Declaration add

DataContext = "{Binding RelativeSource={RelativeSource Self}}"

Now that the view is ready, let's quickly get our code behind ready.

A Dummy User Class you can replace this with your model class.

public class MyDummyUser
{
    public MyDummyUser(string name, string email)
    {
        Name = name;
        Email = email;
    }

    public string Name { get; set; }

    public string Email { get; set; }
}

Now Create a quick property to hold your currently selected user.

  private MyDummyUser currentSelectedUser;

  public MyDummyUser CurrentSelectedUser
    {
        get { return currentSelectedUser; }
        set { currentSelectedUser = value; RaisePropertyChanged(nameof(CurrentSelectedUser)); }
    }

Now create an observable collection to hold your data from the SQL service:

private ObservableCollection<MyDummyUser> dataFromSQLService;
    public ObservableCollection<MyDummyUser> DataFromSQLService
    {
        get { return dataFromSQLService; }
        set { dataFromSQLService = value; RaisePropertyChanged(nameof(DataFromSQLService)); }
    }

Now Implement INotifyPropertyChanged

public event PropertyChangedEventHandler PropertyChanged;
    public void RaisePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    //if using c# 6.0 or later replace the above with
    //public void RaisePropertyChanged(string propertyName)=>
    //        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

Now Add a listener to the combobox.SelectionChanged event so that you know when the selected user changed:

 private void UserCombobox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
    {
        if (CurrentSelectedUser != null && !string.IsNullOrEmpty(CurrentSelectedUser?.Email?.Trim()))
        {
            //perform what you wana do with the email.
        }
    }

Create Two methods: LoadData and ClearData.

 private void ClearData(object sender, RoutedEventArgs e)
    {
        DataFromSQLService = null;
    }

    private void LoadData(object sender, RoutedEventArgs e)
    {
        List<MyDummyUser> someData = new List<MyDummyUser>()
        {
            new MyDummyUser("User 1","User1@gmail.com"),
            new MyDummyUser("User 2","User2@gmail.com"),
            new MyDummyUser("User 3","User3@gmail.com"),
            new MyDummyUser("User 4","User4@gmail.com"),
            new MyDummyUser("User 5","User5@gmail.com"),
            new MyDummyUser("User 6","User6@gmail.com"),
        };

        DataFromSQLService = new ObservableCollection<MyDummyUser>(someData);
    }

Please Note I've used an example of a WPF but even if you want to use the code for WinRT or UWP it'll work, just remember to switch Window.Resources with Page.Resources also, in UWP you can use x:Bind and using x:Bind can help you get rid of the RelativeResource=self


问:
AWS: what is bucket name?
I want to setup CodeDeploy from AWS and I'm following this guide:

```<code>http://docs.aws.amazon.com/codedeploy/latest/userguide/codedeploy-agent-operations-install.html#codedeploy-agent-operations-install-linux
</code>```

What is bucket-name?
As I can see some bucket, but how will I be able to download something from this? I'm talking about this command:

```<code>wget https://bucket-name.s3.amazonaws.com/latest/install
</code>```

答:
The document there states as follows

bucket-name represents one of the following:

aws-codedeploy-us-east-2 for instances in the US East (Ohio) region

aws-codedeploy-us-east-1 for instances in the US East (N. Virginia) region

aws-codedeploy-us-west-1 for instances in the US West (N. California) region

aws-codedeploy-us-west-2 for instances in the US West (Oregon) region

aws-codedeploy-ca-central-1 for instances in the Canada (Central) region

aws-codedeploy-eu-west-1 for instances in the EU (Ireland) region

aws-codedeploy-eu-west-2 for instances in the EU (London) region

aws-codedeploy-eu-central-1 for instances in the EU (Frankfurt) region

aws-codedeploy-ap-northeast-1 for instances in the Asia Pacific (Tokyo) region

aws-codedeploy-ap-northeast-2 for instances in the Asia Pacific (Seoul) region

aws-codedeploy-ap-southeast-1 for instances in the Asia Pacific (Singapore) region

aws-codedeploy-ap-southeast-2 for instances in the Asia Pacific (Sydney) region

aws-codedeploy-ap-south-1 for instances in the Asia Pacific (Mumbai) region

aws-codedeploy-sa-east-1 for instances in the South America (São Paulo) region

So just check your region and accordingly select the bucket name

E.g. If your region is US East (N. Virginia) region then the bucket name is aws-codedeploy-us-east-1 and accordingly the wget URL is https://aws-codedeploy-us-east-1.s3.amazonaws.com/latest/install

Title: AWS: what is bucket name?

Body:
I want to setup CodeDeploy from AWS and I'm following this guide:

http://docs.aws.amazon.com/codedeploy/latest/userguide/codedeploy-agent-operations-install.html#codedeploy-agent-operations-install-linux

What is bucket-name?
As I can see some bucket, but how will I be able to download something from this? I'm talking about this command:

wget https://bucket-name.s3.amazonaws.com/latest/install


问:
PHP - array_diff all similar values are compared and removed
I would appreciate a little help . I have tried array_diff(), intersect combos but not able to get my expected return.

Here is an example what i want to do.

First array.

```<code>Array
(
    [0] => 21
    [1] => 2
    [2] => 1
    [3] => 2
)
</code>```

Second array

```<code>Array
(
    [0] => 21
    [1] => 2
)
</code>```

using array_diff(firstarray, secondarray) i get following.

```<code>Array
(
    [2] => 1
)
</code>```

But what i want

```<code>Array
(
    [2] => 1
    [3] => 2
)
</code>```

keys from firstarray and secondarray wont necessarily be same.

答:
Try below function:</p>

```<code>function arrayDiff( $a, $b ) {

    $a = array_count_values($a);
    $b = array_count_values($b);

    $out = array();

    foreach( $a as $key => $value ) {

        if( isset( $b[ $key ] ) ) {
            $value -= $b[ $key ];
        }

        $out = array_merge( $out, array_fill( 0, $value, $key ) );
    }

    return $out;
}

print_r( arrayDiff( $a, $b ) );
</code>```

Body:
I would appreciate a little help . I have tried array_diff(), intersect combos but not able to get my expected return.

Here is an example what i want to do.

First array.

Array
(
    [0] => 21
    [1] => 2
    [2] => 1
    [3] => 2
)

Second array

Array
(
    [0] => 21
    [1] => 2
)

using array_diff(firstarray, secondarray) i get following.

Array
(
    [2] => 1
)

But what i want

Array
(
    [2] => 1
    [3] => 2
)

keys from firstarray and secondarray wont necessarily be same.

Body:
Try below function:

function arrayDiff( $a, $b ) {

    $a = array_count_values($a);
    $b = array_count_values($b);

    $out = array();

    foreach( $a as $key => $value ) {

        if( isset( $b[ $key ] ) ) {
            $value -= $b[ $key ];
        }

        $out = array_merge( $out, array_fill( 0, $value, $key ) );
    }

    return $out;
}

print_r( arrayDiff( $a, $b ) );


问:
How to install g++ in Cygwin?
I'm trying to compile a piece of MATLAB code containing a makefile. For the reason that I'm using Windows, I need to use Cygwin.

I have downloaded and installed Cygwin. When I tried to compile the code using make, there was an error that g++ is not found.

I searched for Cygwin package manager on the net and I installed apt-cyg but when I search for g++ using apt-cyg search g++, there is no result there!

I have updated package list (apt-cyg update) but finally I could not find c++ compiler for Cygwin!

How can I do it by apt-cyg package manager or any other way?

答: Try installing the package cygport.  It will take care of many of the dependencies you need, including g++.

Title: How to install g++ in Cygwin?


问:
Javascript load each file in folder
In my project I have got a folder with .csv files. I dont know how much - it could be 1, 0 or even 50. How can I load all of them with javascript or with some javascript plugin?</p>

答: Best way of doing so would be to use the fs module of NodeJS. You can read a file by using fs.readFile() and write to a file by using fs.writeFile().

Title: Javascript load each file in folder


问:
A warning message "No matching signal for" when executing my application
When executing my application some warning messages appear:

QMetaObject::connectSlotsByName: No matching signal for on_actionUndo_triggered(),
QMetaObject::connectSlotsByName: No matching signal for on_actionRedo_triggered()

I have implemented the rule void on_objectName_signalName(signalParameters); to the signal and slot that I have created and I don't know why that messages appear, note that the signal and slot work fine.

Declaration:

```<code>class Widget : public QWidget {
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

private:
    Ui::Widget *ui;
    QAction *actionUndo;
    QAction *actionRedo;

private slots:
    void on_actionUndo_triggered();
    void on_actionRedo_triggered();
};
</code>```

Definition:

```<code>Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) {
    ui->setupUi(this);
    QVBoxLayout *layout = new QVBoxLayout(this);
    QMenuBar *menuBar = new QMenuBar();
    QMenu *editMenu = new QMenu("&Edit");
    menuBar->addMenu(editMenu);

    this->actionUndo = new QAction("&Undo", editMenu);
    this->actionUndo->setShortcut(QKeySequence::Undo);
    QObject::connect(this->actionUndo, SIGNAL(triggered()), this, SLOT(on_actionUndo_triggered()));

    this->actionRedo = new QAction("&Redo", editMenu);
    this->actionRedo->setShortcut(QKeySequence::Redo);
    QObject::connect(this->actionRedo, SIGNAL(triggered()), this, SLOT(on_actionRedo_triggered()));

    editMenu->addAction(this->actionUndo);
    editMenu->addAction(this->actionRedo);

    this->layout()->setMenuBar(menuBar);
}

Widget::~Widget() {
    delete ui;
}

void Widget::on_actionUndo_triggered() {

}

void Widget::on_actionRedo_triggered() {

}
</code>```

答:
The warning arises because within the function setupUi calls the function connectSlotsByName.

```<code>void setupUi(QWidget *Widget)
{
    [...]
    QMetaObject::connectSlotsByName(Widget);
}
</code>```

According to the documentation:

void QMetaObject::connectSlotsByName(QObject * object)

Searches recursively for all child objects of the given object, and
  connects matching signals from them to slots of object that follow the
  following form:

void on_<object name>_<signal name>(<signal parameters>);

Then this function looks for objects actionUndo and actionRedo and does not find them because they are not created, a simple solution is to create them before setupUi and pass a name with setObjectName:

```<code>actionUndo = new QAction("&Undo", this);
actionUndo->setObjectName("actionUndo");
actionRedo = new QAction("&Redo", this);
actionRedo->setObjectName("actionRedo");
ui->setupUi(this);
</code>```

With this configuration you will no longer need to make the connections, ie you do not need to implement the next line.

```<code>QObject::connect(this->actionUndo, SIGNAL(triggered()), this, SLOT(on_actionUndo_triggered()));
QObject::connect(this->actionRedo, SIGNAL(triggered()), this, SLOT(on_actionRedo_triggered()));
</code>```

complete code:

.h

```<code>class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

private slots:
    void on_actionUndo_triggered();
    void on_actionRedo_triggered();

private:
    Ui::Widget *ui;
    QAction *actionUndo;
    QAction *actionRedo;
};
</code>```

.cpp

```<code>Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    actionUndo = new QAction("&Undo", this);
    actionUndo->setObjectName("actionUndo");
    actionUndo->setShortcut(QKeySequence::Undo);

    actionRedo = new QAction("&Redo", this);
    actionRedo->setObjectName("actionRedo");
    actionRedo->setShortcut(QKeySequence::Redo);

    ui->setupUi(this);

    setLayout(new QVBoxLayout);

    QMenuBar *menuBar = new QMenuBar(this);
    QMenu *editMenu = new QMenu("&Edit");

    menuBar->addMenu(editMenu);
    editMenu->addAction(actionUndo);
    editMenu->addAction(actionRedo);

    layout()->setMenuBar(menuBar);

}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_actionUndo_triggered()
{
    qDebug()<<"undo";
}

void Widget::on_actionRedo_triggered()
{
    qDebug()<<"redo";
}
</code>```

Body:
When executing my application some warning messages appear:

QMetaObject::connectSlotsByName: No matching signal for on_actionUndo_triggered(),
QMetaObject::connectSlotsByName: No matching signal for on_actionRedo_triggered()

I have implemented the rule void on_objectName_signalName(signalParameters); to the signal and slot that I have created and I don't know why that messages appear, note that the signal and slot work fine.

Declaration:

class Widget : public QWidget {
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

private:
    Ui::Widget *ui;
    QAction *actionUndo;
    QAction *actionRedo;

private slots:
    void on_actionUndo_triggered();
    void on_actionRedo_triggered();
};

Definition:

Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) {
    ui->setupUi(this);
    QVBoxLayout *layout = new QVBoxLayout(this);
    QMenuBar *menuBar = new QMenuBar();
    QMenu *editMenu = new QMenu("&Edit");
    menuBar->addMenu(editMenu);

    this->actionUndo = new QAction("&Undo", editMenu);
    this->actionUndo->setShortcut(QKeySequence::Undo);
    QObject::connect(this->actionUndo, SIGNAL(triggered()), this, SLOT(on_actionUndo_triggered()));

    this->actionRedo = new QAction("&Redo", editMenu);
    this->actionRedo->setShortcut(QKeySequence::Redo);
    QObject::connect(this->actionRedo, SIGNAL(triggered()), this, SLOT(on_actionRedo_triggered()));

    editMenu->addAction(this->actionUndo);
    editMenu->addAction(this->actionRedo);

    this->layout()->setMenuBar(menuBar);
}

Widget::~Widget() {
    delete ui;
}

void Widget::on_actionUndo_triggered() {

}

void Widget::on_actionRedo_triggered() {

}

Body:
The warning arises because within the function setupUi calls the function connectSlotsByName.

void setupUi(QWidget *Widget)
{
    [...]
    QMetaObject::connectSlotsByName(Widget);
}

According to the documentation:

void QMetaObject::connectSlotsByName(QObject * object)

Searches recursively for all child objects of the given object, and
  connects matching signals from them to slots of object that follow the
  following form:

void on_<object name>_<signal name>(<signal parameters>);

Then this function looks for objects actionUndo and actionRedo and does not find them because they are not created, a simple solution is to create them before setupUi and pass a name with setObjectName:

actionUndo = new QAction("&Undo", this);
actionUndo->setObjectName("actionUndo");
actionRedo = new QAction("&Redo", this);
actionRedo->setObjectName("actionRedo");
ui->setupUi(this);

With this configuration you will no longer need to make the connections, ie you do not need to implement the next line.

QObject::connect(this->actionUndo, SIGNAL(triggered()), this, SLOT(on_actionUndo_triggered()));
QObject::connect(this->actionRedo, SIGNAL(triggered()), this, SLOT(on_actionRedo_triggered()));

complete code:

.h

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

private slots:
    void on_actionUndo_triggered();
    void on_actionRedo_triggered();

private:
    Ui::Widget *ui;
    QAction *actionUndo;
    QAction *actionRedo;
};

.cpp

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    actionUndo = new QAction("&Undo", this);
    actionUndo->setObjectName("actionUndo");
    actionUndo->setShortcut(QKeySequence::Undo);

    actionRedo = new QAction("&Redo", this);
    actionRedo->setObjectName("actionRedo");
    actionRedo->setShortcut(QKeySequence::Redo);

    ui->setupUi(this);

    setLayout(new QVBoxLayout);

    QMenuBar *menuBar = new QMenuBar(this);
    QMenu *editMenu = new QMenu("&Edit");

    menuBar->addMenu(editMenu);
    editMenu->addAction(actionUndo);
    editMenu->addAction(actionRedo);

    layout()->setMenuBar(menuBar);

}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_actionUndo_triggered()
{
    qDebug()<<"undo";
}

void Widget::on_actionRedo_triggered()
{
    qDebug()<<"redo";
}


问:
PHP - How to get all urls from many img's src?
Let's assume we have string like this:

```<code>Its really great to <img src="image2.png" /> hear from you "Today is good <img src="http://www.google.com/picture2.png" /> day" Let's listen song together! ---------<img src="images/profile.png" />\\\\\\
</code>```

This is the whole string. We have 3 img inside.

We want to produce variable from this string like

```<code>output[0] = 'image2.png';
output[1] = 'http://www.google.com/picture2.png';
output[2] = 'images/profile.png';
</code>```

I mean, we have this string, and how to process him to extract all "src" from img tags and collect it in one new array variable.

How to do it? How we can achieve that?

In addition I use CodeIgniter framework. Maybe it can be done with only this framework's method but I don't see it possible.

答:
You need to use PHP DOM Extension. The DOM extension allows you to operate on XML documents through the DOM API with PHP.

Also you can go through below code:

```<code>function fetchImages($content) {
    $doc = new DOMDocument();
    $doc->loadHTML($content);
    $imgElements = $doc->getElementsByTagName('img');

    $images = array();

    for($i = 0; $i < $imgElements->length; $i++) {
        $images[] = $imgElements->item($i)->getAttribute('src');
    }

    return $images;
}
$content = file_get_contents('http://www.example.com/');
$images = fetchImages($content);

print_r($images);
</code>```

Body:
Let's assume we have string like this:

Its really great to  hear from you "Today is good  day" Let's listen song together! ---------\\\\\\

This is the whole string. We have 3 img inside.

We want to produce variable from this string like

output[0] = 'image2.png';
output[1] = 'http://www.google.com/picture2.png';
output[2] = 'images/profile.png';

I mean, we have this string, and how to process him to extract all "src" from img tags and collect it in one new array variable.

How to do it? How we can achieve that?

In addition I use CodeIgniter framework. Maybe it can be done with only this framework's method but I don't see it possible.

Body:
You need to use PHP DOM Extension. The DOM extension allows you to operate on XML documents through the DOM API with PHP.

Also you can go through below code:

function fetchImages($content) {
    $doc = new DOMDocument();
    $doc->loadHTML($content);
    $imgElements = $doc->getElementsByTagName('img');

    $images = array();

    for($i = 0; $i < $imgElements->length; $i++) {
        $images[] = $imgElements->item($i)->getAttribute('src');
    }

    return $images;
}
$content = file_get_contents('http://www.example.com/');
$images = fetchImages($content);

print_r($images);


问:
How to find whether an element exists in std::map?
My use case:

```<code>map<string, Car> cars;
bool exists(const string& name) {
  // somehow I should find whether my MAP has a car
  // with the name provided
  return false;
}
</code>```

Could you please suggest the best and the most elegant way to do it in C++? Thanks.

答:
```<code>#define itertype(v) typeof((v).begin())
itertype(cars) it = cars.find(name);
return it != cars.end();
</code>```

ContentLicense: CC BY-SA 2.5

Body:
My use case:

map<string, Car> cars;
bool exists(const string& name) {
  // somehow I should find whether my MAP has a car
  // with the name provided
  return false;
}

Could you please suggest the best and the most elegant way to do it in C++? Thanks.


问:
CSS text-align does not work
I tried to use the text-align in CSS but it does not work.
here is the CSS and I also had all the body set to center, does that have to do with something?
Here is my CSS:

#Swell {
 text-align: left;
}```
</div>
</div>
</p>

<p>Here is my HTML:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>Use Swell Bottles<img src="https://s-media-cache-ak0.pinimg.com/originals/f9/93/95/f99395b48463ee8d3bfa16f32df51c98.jpg" height="50"></code>```

Also my CSS body text-align:

body {
font-family: sans-serif;
text-align: center;
background-color: rgb(128, 212, 255);
}```

Dose the text-align: center have to do with the error and if that is true then how do I overwrite/fix this error

答:
html

```<code><div id="parentdiv">
    <a id="Swell" href="https://www.swell.com">Use Swell Bottles<img src="https://s-media-cache-ak0.pinimg.com/originals/f9/93/95/f99395b48463ee8d3bfa16f32df51c98.jpg" height="50"></a>
</div>
</code>```

css

```<code>body {
font-family: sans-serif;
text-align: center;
background-color: rgb(128, 212, 255);
}

#parentdiv {
    text-align: left;
}
</code>```

Example

Use Swell Bottles

```

Title: CSS text-align does not work

Body:
I tried to use the text-align in CSS but it does not work.
here is the CSS and I also had all the body set to center, does that have to do with something?
Here is my CSS:

#Swell {
 text-align: left;
}

Here is my HTML:

Use Swell Bottles

Also my CSS body text-align:

body {
font-family: sans-serif;
text-align: center;
background-color: rgb(128, 212, 255);
}

Dose the text-align: center have to do with the error and if that is true then how do I overwrite/fix this error

Body:
html

<div id="parentdiv">
    <a id="Swell" href="https://www.swell.com">Use Swell Bottles<img src="https://s-media-cache-ak0.pinimg.com/originals/f9/93/95/f99395b48463ee8d3bfa16f32df51c98.jpg" height="50"></a>
</div>

css

body {
font-family: sans-serif;
text-align: center;
background-color: rgb(128, 212, 255);
}

#parentdiv {
    text-align: left;
}

Example

<html>
<style>
body {
font-family: sans-serif;
text-align: center;
background-color: rgb(128, 212, 255);
}

#parentdiv {
text-align: left;
}
</style>
<div id="parentdiv">
<a id="Swell" href="https://www.swell.com">Use Swell Bottles<img src="https://s-media-cache-ak0.pinimg.com/originals/f9/93/95/f99395b48463ee8d3bfa16f32df51c98.jpg" height="50"></a>
</div>
</html>


问:
jackson serialize by type with mixing?
I have a something like this as a json and need to convert it to a Java User-Instance by Jackson.

```<code>"userid" : "1",
"myMixes" : [ {
     "data" : {
       "id" : 1,
       "ref": "my-Object-instance"
     },
     "type" : "object"
   }, {
     "data" : [ [ 0, 1], [ 1, 2 ] ],
     "type" : "list"
   }]
</code>```

I have this in my class "User":

```<code>    // jackson should use this, if type="list"
    @JsonProperty("data")
    public List<List<Integer>> data_list = new ArrayList<>();

    // jackson should use this, if type="object"
    @JsonProperty("data")
    public Data data_object;

    @JsonProperty("id")
    public String id;

    // if type = "object", then jackson should convert json-data-property to Java-Data-Instance
// if type = "list",then jackson should convert json-data-property to List<List<Integer>> data
    @JsonProperty("type")
    public String type;
</code>```

How can I tell jackson to generate a Data-Instance of the json-data-property, if value of json-type-property is called "object" and to generate a List-Instance, if value of json-type-property is called "list".

答:
I guess, I found the best solution:

```<code>@JsonCreator
    public MyMixes(Map<String,Object> props)
    {
        ...

        ObjectMapper mapper = new ObjectMapper();

        if(this.type.equals("object")){

            this.data_object = mapper.convertValue(props.get("data"), Data.class);
        }
        else{
            this.data = mapper.convertValue(props.get("data"), new TypeReference<List<List<Integer>>>() { });
        }

    }
</code>```

If someone has a shorter/faster way, then let me know.

Title: jackson serialize by type with mixing?

Body:
I have a something like this as a json and need to convert it to a Java User-Instance by Jackson.

"userid" : "1",
"myMixes" : [ {
     "data" : {
       "id" : 1,
       "ref": "my-Object-instance"
     },
     "type" : "object"
   }, {
     "data" : [ [ 0, 1], [ 1, 2 ] ],
     "type" : "list"
   }]

I have this in my class "User":

    // jackson should use this, if type="list"
    @JsonProperty("data")
    public List<List<Integer>> data_list = new ArrayList<>();

    // jackson should use this, if type="object"
    @JsonProperty("data")
    public Data data_object;

    @JsonProperty("id")
    public String id;

    // if type = "object", then jackson should convert json-data-property to Java-Data-Instance
// if type = "list",then jackson should convert json-data-property to List<List<Integer>> data
    @JsonProperty("type")
    public String type;

How can I tell jackson to generate a Data-Instance of the json-data-property, if value of json-type-property is called "object" and to generate a List-Instance, if value of json-type-property is called "list".

Body:
I guess, I found the best solution:

@JsonCreator
    public MyMixes(Map<String,Object> props)
    {
        ...

        ObjectMapper mapper = new ObjectMapper();

        if(this.type.equals("object")){

            this.data_object = mapper.convertValue(props.get("data"), Data.class);
        }
        else{
            this.data = mapper.convertValue(props.get("data"), new TypeReference<List<List<Integer>>>() { });
        }

    }

If someone has a shorter/faster way, then let me know.


问:
Parsing and displaying nested JSON in Django Template
I am trying to print the results of an API call which is returning JSON results nested relatively deeply. I am doing this project with Python 2.7 and Django 1.11.

I have the following view.py function:

```<code>def nlu_analysis(request):
  if request.method == 'POST':
    text2send = request.POST.get('text2send')
    natural_language_understanding = NaturalLanguageUnderstandingV1(
        version='2017-02-27',
        username='####',
        password='####')

    response = natural_language_understanding.analyze(
        text=text2send,
        features=[features.Entities(), ..., features.SemanticRoles()])

  return render(request, 'watson_nlu/analysis.html', {'data': response})
</code>```

When I use the following template code in my .html file:

```<code>{% for k in data.keywords %}
    <p>Text - {{ k.text }}</p>
    <p>Relevance - {{ k.relevance }}</p>
{% endfor %}
</code>```

to parse and display JSON with one level of nesting like this:

```<code> 'keywords': [{
    'relevance': 0.946673,
    'text': 'eyes'
}]
</code>```

Everything is great and it displays 'eyes' and 0.946673 as expected.

I can't figure out the appropriate syntax for getting to the 'anger', 'joy', etc. results that are nested more deeply such as this:

```<code>{
'emotion': {
    'document': {
        'emotion': {
            'anger': 0.195192,
            'joy': 0.082313,
            'sadness': 0.644314,
            'fear': 0.207166,
            'disgust': 0.103676
        }
    }
}
</code>```

What is the most efficient method for accomplishing this objective?

It is definitely NOT:

```<code><p>Anger - {{ data['emotion.document.template.anger'] }}</p>
</code>```

Advance newbie gratitude and good juju for your help.

答: You can access the dict of dict with . so the solution to your question is data.emotion.document.emotion.anger

Body:
I am trying to print the results of an API call which is returning JSON results nested relatively deeply. I am doing this project with Python 2.7 and Django 1.11.

I have the following view.py function:

def nlu_analysis(request):
  if request.method == 'POST':
    text2send = request.POST.get('text2send')
    natural_language_understanding = NaturalLanguageUnderstandingV1(
        version='2017-02-27',
        username='####',
        password='####')

    response = natural_language_understanding.analyze(
        text=text2send,
        features=[features.Entities(), ..., features.SemanticRoles()])

  return render(request, 'watson_nlu/analysis.html', {'data': response})

When I use the following template code in my .html file:

{% for k in data.keywords %}

Text - {{ k.text }}

Relevance - {{ k.relevance }}

{% endfor %}

to parse and display JSON with one level of nesting like this:

 'keywords': [{
    'relevance': 0.946673,
    'text': 'eyes'
}]

Everything is great and it displays 'eyes' and 0.946673 as expected.

I can't figure out the appropriate syntax for getting to the 'anger', 'joy', etc. results that are nested more deeply such as this:

{
'emotion': {
    'document': {
        'emotion': {
            'anger': 0.195192,
            'joy': 0.082313,
            'sadness': 0.644314,
            'fear': 0.207166,
            'disgust': 0.103676
        }
    }
}

What is the most efficient method for accomplishing this objective?

It is definitely NOT:

Anger - {{ data['emotion.document.template.anger'] }}

Advance newbie gratitude and good juju for your help.


问:
No pqxx::tuple in libpqxx library?
Ive got the newest ubuntu and Ive done:

```<code>sudo apt-get install postgresql postgresql-contrib
sudo apt-get install libpqxx-4.0v5
sudo apt-get install libpqxx-dev
</code>```

I can`t compile program which uses pqxx::tuple.

Compilation:

```<code>g++ test.cpp -I/usr/local/include/ -lpqxx -lpq
or
g++ test.cpp -lpqxx -lpq -o test
</code>```

Console output:

```<code>test.cpp: In function ‘int main()’:
test.cpp:15:21: error: ‘tuple’ in namespace ‘pqxx’ does not name a type
const pqxx::tuple row = r[rownum];
</code>```

This is the problematic line:

```<code>const pqxx::tuple row = r[rownum];
</code>```

When I remove this line, program works correctly.

```<code>#include <iostream>
#include <pqxx/pqxx>
int main()
{
  try {
    pqxx::connection c("dbname=mydb user=postgres port=5432 password=*** hostaddr=127.0.0.1");
    pqxx::work w(c);
    pqxx::result r = w.exec("SELECT * FROM get_player_data_function()");
    w.commit();
    const int num_rows = r.size();
    for (int rownum=0; rownum < num_rows; ++rownum) {
        const pqxx::tuple row = r[rownum];
    }
  }
  catch (const std::exception &e) {
    std::cerr << e.what() << std::endl;
  }
}
</code>```

答:
Not sure... but if I understand correctly this page, you have to substitute pqxx::tuple with pqxx::row.

So, I suppose

```<code>const pqxx::row row = r[rownum];
</code>```

Title: No pqxx::tuple in libpqxx library?

Body:
Ive got the newest ubuntu and Ive done:

sudo apt-get install postgresql postgresql-contrib
sudo apt-get install libpqxx-4.0v5
sudo apt-get install libpqxx-dev

I can`t compile program which uses pqxx::tuple.

Compilation:

g++ test.cpp -I/usr/local/include/ -lpqxx -lpq
or
g++ test.cpp -lpqxx -lpq -o test

Console output:

test.cpp: In function ‘int main()’:
test.cpp:15:21: error: ‘tuple’ in namespace ‘pqxx’ does not name a type
const pqxx::tuple row = r[rownum];

This is the problematic line:

const pqxx::tuple row = r[rownum];

When I remove this line, program works correctly.

#include <iostream>
#include <pqxx/pqxx>
int main()
{
  try {
    pqxx::connection c("dbname=mydb user=postgres port=5432 password=*** hostaddr=127.0.0.1");
    pqxx::work w(c);
    pqxx::result r = w.exec("SELECT * FROM get_player_data_function()");
    w.commit();
    const int num_rows = r.size();
    for (int rownum=0; rownum < num_rows; ++rownum) {
        const pqxx::tuple row = r[rownum];
    }
  }
  catch (const std::exception &e) {
    std::cerr << e.what() << std::endl;
  }
}

Body:
Not sure... but if I understand correctly this page, you have to substitute pqxx::tuple with pqxx::row.

So, I suppose

const pqxx::row row = r[rownum];


问:
Creating a web interface for a database using asp.net mvc 5
I'm working on an online store web project. Currently, I'm trying to display the content from a database table on a web page.

The table looks like this:

This is the Model:

```<code>using System;
using System.ComponentModel.DataAnnotations;

namespace Vidly.Models
{
    public class Rental
    {
        public int Id { get; set; }

        [Required]
        public Customer Customer { get; set; }

        [Required]
        public Movie Movie { get; set; }

        public DateTime DateRented { get; set; }

        public DateTime? DateReturned { get; set; }
    }
}
</code>```

I've created an API Controller which looks like this

```<code>using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Vidly.Dtos;
using Vidly.Models;
using System.Data.Entity;

namespace Vidly.Controllers.Api
{
    public class RentalsController : ApiController
    {

        private ApplicationDbContext _context;

        public RentalsController()
        {
            _context = new ApplicationDbContext();
        }

        // GET /api/rentals
        public IHttpActionResult GetRentals(string query = null)
        {
            var rentalsQuery = _context.Rentals
                .Include(r => r.Customer)
                .Include(r => r.Movie);

            var rentalDtos = rentalsQuery
                .ToList()
                .Select(Mapper.Map<Rental, RentalDto>);

            return Ok(rentalDtos);
        }

        // GET /api/rentals/1
        public IHttpActionResult GetRental(int id)
        {
            var rental = _context.Rentals.SingleOrDefault(r => r.Id == id);

            if (rental == null)
                return NotFound();

            return Ok(Mapper.Map<Rental, RentalDto>(rental));
        }
    }
}
</code>```

and another Controller which looks like this:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Vidly.Models;
using System.Data.Entity;
using Vidly.ViewModels;

namespace Vidly.Controllers
{
    public class RentalsController : Controller
    {
        private ApplicationDbContext _context;

        [Authorize(Roles = RoleName.CanManageMovies)]
        public ViewResult Index()
        {
            if (User.IsInRole(RoleName.CanManageMovies))
                return View("Index");
            else
                return View("Home");
        }
        public ActionResult New()
        {
            return View();
        }

        public ActionResult Details(int id)
        {
            var rental = _context.Rentals.Include(r => r.Movie).Include(r => r.Customer).SingleOrDefault(r => r.Id == id);

            if (rental == null)
                return HttpNotFound();

            return View(rental);
        }

    }
}
</code>```

Finally, the cshtml file looks something like this:

```<code>@model IEnumerable<Vidly.Models.Rental>
@{
    ViewBag.Title = "Rentals";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Rentals</h2>

<table id="rentals" class="table table-bordered table-hover">
    <thead>
        <tr>
            <th>Customer</th>
            <th>Movie</th>
            <th>Date Rented</th>
        </tr>
    </thead>
    <tbody></tbody>
</table>

@section scripts
{
    <script>
        $(document).ready(function () {
            var table = $("#rentals").DataTable({
                ajax: {
                    url: "/api/rentals",
                    dataSrc: ""
                },
                columns: [
                    {
                        data: "customer.name"
                    },
                    {
                        data: "movie.name"
                    },
                    {
                        data: "daterented"
                    }
                ]
            });

        });
    </script>
}
</code>```

The problem is that whenever I'm trying to access the web page, I'm getting this error message 5 times, for every entry in the table:

DataTables warning: table id=rentals - Requested unknown parameter
  'daterented' for row 0, column 2. For more information about this
  error, please see http://datatables.net/tn/4

The table looks like this:

And the XML file (available when accessing https://localhost:44300/api/rentals) from where the data for the table should be fetched looks like this:

I would be very glad if you could help me out with this problem!
Many thanks!

答:
Well it seems that i had the Camelcase enabled.

https://en.wikipedia.org/wiki/Camel_case

Therefore, instead of

```<code>columns: [
                {
                    data: "customer.name"
                },
                {
                    data: "movie.name"
                },
                {
                    data: "daterented"
                }
            ]
</code>```

My code should have been

```<code>columns: [
                {
                    data: "customer.name"
                },
                {
                    data: "movie.name"
                },
                {
                    data: "dateRented"
                }
            ]
</code>```

Body:
I'm working on an online store web project. Currently, I'm trying to display the content from a database table on a web page.

The table looks like this:

This is the Model:

using System;
using System.ComponentModel.DataAnnotations;

namespace Vidly.Models
{
    public class Rental
    {
        public int Id { get; set; }

        [Required]
        public Customer Customer { get; set; }

        [Required]
        public Movie Movie { get; set; }

        public DateTime DateRented { get; set; }

        public DateTime? DateReturned { get; set; }
    }
}

I've created an API Controller which looks like this

using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Vidly.Dtos;
using Vidly.Models;
using System.Data.Entity;

namespace Vidly.Controllers.Api
{
    public class RentalsController : ApiController
    {

        private ApplicationDbContext _context;

        public RentalsController()
        {
            _context = new ApplicationDbContext();
        }

        // GET /api/rentals
        public IHttpActionResult GetRentals(string query = null)
        {
            var rentalsQuery = _context.Rentals
                .Include(r => r.Customer)
                .Include(r => r.Movie);

            var rentalDtos = rentalsQuery
                .ToList()
                .Select(Mapper.Map<Rental, RentalDto>);

            return Ok(rentalDtos);
        }

        // GET /api/rentals/1
        public IHttpActionResult GetRental(int id)
        {
            var rental = _context.Rentals.SingleOrDefault(r => r.Id == id);

            if (rental == null)
                return NotFound();

            return Ok(Mapper.Map<Rental, RentalDto>(rental));
        }
    }
}

and another Controller which looks like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Vidly.Models;
using System.Data.Entity;
using Vidly.ViewModels;

namespace Vidly.Controllers
{
    public class RentalsController : Controller
    {
        private ApplicationDbContext _context;

        [Authorize(Roles = RoleName.CanManageMovies)]
        public ViewResult Index()
        {
            if (User.IsInRole(RoleName.CanManageMovies))
                return View("Index");
            else
                return View("Home");
        }
        public ActionResult New()
        {
            return View();
        }

        public ActionResult Details(int id)
        {
            var rental = _context.Rentals.Include(r => r.Movie).Include(r => r.Customer).SingleOrDefault(r => r.Id == id);

            if (rental == null)
                return HttpNotFound();

            return View(rental);
        }

    }
}

Finally, the cshtml file looks something like this:

@model IEnumerable<Vidly.Models.Rental>
@{
    ViewBag.Title = "Rentals";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Rentals

            Customer
            Movie
            Date Rented

@section scripts
{

}

The problem is that whenever I'm trying to access the web page, I'm getting this error message 5 times, for every entry in the table:

DataTables warning: table id=rentals - Requested unknown parameter
  'daterented' for row 0, column 2. For more information about this
  error, please see http://datatables.net/tn/4

The table looks like this:

And the XML file (available when accessing https://localhost:44300/api/rentals) from where the data for the table should be fetched looks like this:

I would be very glad if you could help me out with this problem!
Many thanks!

Body:
Well it seems that i had the Camelcase enabled.

https://en.wikipedia.org/wiki/Camel_case

Therefore, instead of

columns: [
                {
                    data: "customer.name"
                },
                {
                    data: "movie.name"
                },
                {
                    data: "daterented"
                }
            ]

My code should have been

columns: [
                {
                    data: "customer.name"
                },
                {
                    data: "movie.name"
                },
                {
                    data: "dateRented"
                }
            ]


问:
Output files returned after training a alexnet model...?
Code is written in Python 3.5.X

Please try to make the answer simple for a 3rd year Computer Science Student

The output files from train_model.py seems to be a model.meta file but the test_model.py is asking for a .model file. The tutorial user has a .model file as well I can't seem to understand why i am getting a file with .model.meta

I am trying to play GTA San Andreas through Python or more precisely the car in GTA is driven by the model.
It takes screen frames as Input and recorded the key i Input during training. This training data is used to train the model.

Code for training the model

```<code>import numpy as np
from alexnet import alexnet

WIDTH = 80
HEIGHT = 60
LR = 1e-3
EPOCHS = 8
MODEL_NAME = 'pygta_sa-car-{}-{}-{}-epochs.model'.format(LR, 'alextnetv2', EPOCHS)

model = alexnet(WIDTH, HEIGHT, LR)

train_data = np.load('training_data_v2.npy')

train = train_data[:-500]
test = train_data[-500:]

X = np.array([i[0] for i in train]).reshape(-1,WIDTH,HEIGHT,1)
Y = [i[1] for i in train]

test_x = np.array([i[0] for i in test]).reshape(-1,WIDTH,HEIGHT,1)
test_y = [i[1] for i in test]

model.fit({'input': X}, {'targets': Y}, n_epoch=EPOCHS, validation_set=({'input': test_x}, {'targets': test_y}),
    snapshot_step=500, show_metric=True, run_id=MODEL_NAME)

# tensorboard --logdir=foo:F:\play_gta_sa\log

model.save(MODEL_NAME)
</code>```

training completes successfully and returns files

Files returned on the video of the Tutorial i am using to do this project

sent_dex files returned

Content of Checkpoint file

model_checkpoint_path: "F:\play_gta_sa\pygta_sa-car-0.001-alextnetv2-8-epochs.model"
all_model_checkpoint_paths: "F:\play_gta_sa\pygta_sa-car-0.001-alextnetv2-8-epochs.model"

Code for testing the model on the game

```<code>import numpy as np
import cv2
import time
from grabscreen import grab_screen
from getkeys import key_check
from directkeys import PressKey, ReleaseKey, W, A, S, D
from alexnet import alexnet

WIDTH = 80
HEIGHT = 60
LR = 1e-3
EPOCHS = 8
MODEL_NAME = 'pygta_sa-car-{}-{}-{}-epochs.model'.format(LR, 'alexnetv2',EPOCHS)

def straight():
    PressKey(W)
    ReleaseKey(A)
    ReleaseKey(D)

def left():
    PressKey(W)
    PressKey(A)
    ReleaseKey(D)

def right():
    PressKey(W)
    PressKey(D)
    ReleaseKey(A)

model = alexnet(WIDTH, HEIGHT, LR)
model.load(MODEL_NAME)

def main():

    for i in list(range(10))[::-1]:
        print(i+1)
        time.sleep(1)

    last_time = time.time()

    paused = False

    while True:
        if not paused:

            screen = grab_screen(region=(0,40,800,640))
            screen = cv2.cvtColor(screen,cv2.COLOR_BGR2GRAY)
            screen = cv2.resize(screen,(80,60))
            print('Frame took {} seconds'.format(time.time()-last_time))
            last_time = time.time()

            moves = list(np.around(model.predict([screen.reshape(80,60,1)])[0]))
            print(moves, prediction)

            if moves == [1,0,0]:
                left()
            elif moves == [0,1,0]:
                straight()
            elif moves == [0,0,1]:
                right()

        keys = key_check()

    # p pauses game and can get annoying.
        if 'T' in keys:
            if paused:
                paused = False
                time.sleep(1)
            else:
                paused = True
                ReleaseKey(A)
                ReleaseKey(W)
                ReleaseKey(D)
                time.sleep(1)

main()
</code>```

the error message on running test model

```<code>Traceback (most recent call last):
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1039, in _do_call
    return fn(*args)
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1021, in _run_fn
    status, run_metadata)
  File "C:\Program Files\Python35\lib\contextlib.py", line 66, in __exit__
    next(self.gen)
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 466, in raise_exception_on_not_ok_status
    pywrap_tensorflow.TF_GetCode(status))
tensorflow.python.framework.errors_impl.NotFoundError: Unsuccessful TensorSliceReader constructor: Failed to find any matching files for F:\play_gta_sa\pygta_sa-car-0.001-alexnetv2-8-epochs.model
     [[Node: save_1/RestoreV2 = RestoreV2[dtypes=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_save_1/Const_0, save_1/RestoreV2/tensor_names, save_1/RestoreV2/shape_and_slices)]]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "F:\play_gta_sa\test_model.py", line 33, in <module>
    model.load(MODEL_NAME)
  File "C:\Program Files\Python35\lib\site-packages\tflearn\models\dnn.py", line 282, in load
    self.trainer.restore(model_file, weights_only, **optargs)
  File "C:\Program Files\Python35\lib\site-packages\tflearn\helpers\trainer.py", line 452, in restore
    self.restorer.restore(self.session, model_file)
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\training\saver.py", line 1457, in restore
    {self.saver_def.filename_tensor_name: save_path})
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 778, in run
    run_metadata_ptr)
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 982, in _run
    feed_dict_string, options, run_metadata)
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1032, in _do_run
    target_list, options, run_metadata)
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1052, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.NotFoundError: Unsuccessful TensorSliceReader constructor: Failed to find any matching files for F:\play_gta_sa\pygta_sa-car-0.001-alexnetv2-8-epochs.model
     [[Node: save_1/RestoreV2 = RestoreV2[dtypes=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_save_1/Const_0, save_1/RestoreV2/tensor_names, save_1/RestoreV2/shape_and_slices)]]

Caused by op 'save_1/RestoreV2', defined at:
  File "<string>", line 1, in <module>
  File "C:\Program Files\Python35\lib\idlelib\run.py", line 124, in main
    ret = method(*args, **kwargs)
  File "C:\Program Files\Python35\lib\idlelib\run.py", line 351, in runcode
    exec(code, self.locals)
  File "F:\play_gta_sa\test_model.py", line 32, in <module>
    model = alexnet(WIDTH, HEIGHT, LR)
  File "F:\play_gta_sa\alexnet.py", line 40, in alexnet
    max_checkpoints=1, tensorboard_verbose=0, tensorboard_dir='log')
  File "C:\Program Files\Python35\lib\site-packages\tflearn\models\dnn.py", line 64, in __init__
    best_val_accuracy=best_val_accuracy)
  File "C:\Program Files\Python35\lib\site-packages\tflearn\helpers\trainer.py", line 147, in __init__
    allow_empty=True)
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\training\saver.py", line 1056, in __init__
    self.build()
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\training\saver.py", line 1086, in build
    restore_sequentially=self._restore_sequentially)
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\training\saver.py", line 691, in build
    restore_sequentially, reshape)
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\training\saver.py", line 407, in _AddRestoreOps
    tensors = self.restore_op(filename_tensor, saveable, preferred_shard)
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\training\saver.py", line 247, in restore_op
    [spec.tensor.dtype])[0])
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\gen_io_ops.py", line 669, in restore_v2
    dtypes=dtypes, name=name)
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 768, in apply_op
    op_def=op_def)
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\framework\ops.py", line 2336, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\framework\ops.py", line 1228, in __init__
    self._traceback = _extract_stack()

NotFoundError (see above for traceback): Unsuccessful TensorSliceReader constructor: Failed to find any matching files for F:\play_gta_sa\pygta_sa-car-0.001-alexnetv2-8-epochs.model
     [[Node: save_1/RestoreV2 = RestoreV2[dtypes=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_save_1/Const_0, save_1/RestoreV2/tensor_names, save_1/RestoreV2/shape_and_slices)]]
</code>```

答:
Thanks for the update.

Edit:

Try add this line before tf.reset_default_graph() loading model. That is

```<code>import tensorflow as tf
tf.reset_default_graph()
model = alexnet(WIDTH, HEIGHT, LR)
model.load(MODEL_NAME)
</code>```

Body:
Code is written in Python 3.5.X

Please try to make the answer simple for a 3rd year Computer Science Student

The output files from train_model.py seems to be a model.meta file but the test_model.py is asking for a .model file. The tutorial user has a .model file as well I can't seem to understand why i am getting a file with .model.meta

I am trying to play GTA San Andreas through Python or more precisely the car in GTA is driven by the model.
It takes screen frames as Input and recorded the key i Input during training. This training data is used to train the model.

Code for training the model

import numpy as np
from alexnet import alexnet

WIDTH = 80
HEIGHT = 60
LR = 1e-3
EPOCHS = 8
MODEL_NAME = 'pygta_sa-car-{}-{}-{}-epochs.model'.format(LR, 'alextnetv2', EPOCHS)

model = alexnet(WIDTH, HEIGHT, LR)

train_data = np.load('training_data_v2.npy')

train = train_data[:-500]
test = train_data[-500:]

X = np.array([i[0] for i in train]).reshape(-1,WIDTH,HEIGHT,1)
Y = [i[1] for i in train]

test_x = np.array([i[0] for i in test]).reshape(-1,WIDTH,HEIGHT,1)
test_y = [i[1] for i in test]

model.fit({'input': X}, {'targets': Y}, n_epoch=EPOCHS, validation_set=({'input': test_x}, {'targets': test_y}),
    snapshot_step=500, show_metric=True, run_id=MODEL_NAME)

# tensorboard --logdir=foo:F:\play_gta_sa\log

model.save(MODEL_NAME)

training completes successfully and returns files

Files returned on the video of the Tutorial i am using to do this project

sent_dex files returned

Content of Checkpoint file

model_checkpoint_path: "F:\play_gta_sa\pygta_sa-car-0.001-alextnetv2-8-epochs.model"
all_model_checkpoint_paths: "F:\play_gta_sa\pygta_sa-car-0.001-alextnetv2-8-epochs.model"

Code for testing the model on the game

import numpy as np
import cv2
import time
from grabscreen import grab_screen
from getkeys import key_check
from directkeys import PressKey, ReleaseKey, W, A, S, D
from alexnet import alexnet

WIDTH = 80
HEIGHT = 60
LR = 1e-3
EPOCHS = 8
MODEL_NAME = 'pygta_sa-car-{}-{}-{}-epochs.model'.format(LR, 'alexnetv2',EPOCHS)

def straight():
    PressKey(W)
    ReleaseKey(A)
    ReleaseKey(D)

def left():
    PressKey(W)
    PressKey(A)
    ReleaseKey(D)

def right():
    PressKey(W)
    PressKey(D)
    ReleaseKey(A)

model = alexnet(WIDTH, HEIGHT, LR)
model.load(MODEL_NAME)

def main():

    for i in list(range(10))[::-1]:
        print(i+1)
        time.sleep(1)

    last_time = time.time()

    paused = False

    while True:
        if not paused:

            screen = grab_screen(region=(0,40,800,640))
            screen = cv2.cvtColor(screen,cv2.COLOR_BGR2GRAY)
            screen = cv2.resize(screen,(80,60))
            print('Frame took {} seconds'.format(time.time()-last_time))
            last_time = time.time()

            moves = list(np.around(model.predict([screen.reshape(80,60,1)])[0]))
            print(moves, prediction)

            if moves == [1,0,0]:
                left()
            elif moves == [0,1,0]:
                straight()
            elif moves == [0,0,1]:
                right()

        keys = key_check()

    # p pauses game and can get annoying.
        if 'T' in keys:
            if paused:
                paused = False
                time.sleep(1)
            else:
                paused = True
                ReleaseKey(A)
                ReleaseKey(W)
                ReleaseKey(D)
                time.sleep(1)

main()

the error message on running test model

Traceback (most recent call last):
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1039, in _do_call
    return fn(*args)
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1021, in _run_fn
    status, run_metadata)
  File "C:\Program Files\Python35\lib\contextlib.py", line 66, in __exit__
    next(self.gen)
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 466, in raise_exception_on_not_ok_status
    pywrap_tensorflow.TF_GetCode(status))
tensorflow.python.framework.errors_impl.NotFoundError: Unsuccessful TensorSliceReader constructor: Failed to find any matching files for F:\play_gta_sa\pygta_sa-car-0.001-alexnetv2-8-epochs.model
     [[Node: save_1/RestoreV2 = RestoreV2[dtypes=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_save_1/Const_0, save_1/RestoreV2/tensor_names, save_1/RestoreV2/shape_and_slices)]]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "F:\play_gta_sa\test_model.py", line 33, in <module>
    model.load(MODEL_NAME)
  File "C:\Program Files\Python35\lib\site-packages\tflearn\models\dnn.py", line 282, in load
    self.trainer.restore(model_file, weights_only, **optargs)
  File "C:\Program Files\Python35\lib\site-packages\tflearn\helpers\trainer.py", line 452, in restore
    self.restorer.restore(self.session, model_file)
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\training\saver.py", line 1457, in restore
    {self.saver_def.filename_tensor_name: save_path})
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 778, in run
    run_metadata_ptr)
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 982, in _run
    feed_dict_string, options, run_metadata)
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1032, in _do_run
    target_list, options, run_metadata)
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1052, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.NotFoundError: Unsuccessful TensorSliceReader constructor: Failed to find any matching files for F:\play_gta_sa\pygta_sa-car-0.001-alexnetv2-8-epochs.model
     [[Node: save_1/RestoreV2 = RestoreV2[dtypes=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_save_1/Const_0, save_1/RestoreV2/tensor_names, save_1/RestoreV2/shape_and_slices)]]

Caused by op 'save_1/RestoreV2', defined at:
  File "<string>", line 1, in <module>
  File "C:\Program Files\Python35\lib\idlelib\run.py", line 124, in main
    ret = method(*args, **kwargs)
  File "C:\Program Files\Python35\lib\idlelib\run.py", line 351, in runcode
    exec(code, self.locals)
  File "F:\play_gta_sa\test_model.py", line 32, in <module>
    model = alexnet(WIDTH, HEIGHT, LR)
  File "F:\play_gta_sa\alexnet.py", line 40, in alexnet
    max_checkpoints=1, tensorboard_verbose=0, tensorboard_dir='log')
  File "C:\Program Files\Python35\lib\site-packages\tflearn\models\dnn.py", line 64, in __init__
    best_val_accuracy=best_val_accuracy)
  File "C:\Program Files\Python35\lib\site-packages\tflearn\helpers\trainer.py", line 147, in __init__
    allow_empty=True)
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\training\saver.py", line 1056, in __init__
    self.build()
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\training\saver.py", line 1086, in build
    restore_sequentially=self._restore_sequentially)
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\training\saver.py", line 691, in build
    restore_sequentially, reshape)
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\training\saver.py", line 407, in _AddRestoreOps
    tensors = self.restore_op(filename_tensor, saveable, preferred_shard)
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\training\saver.py", line 247, in restore_op
    [spec.tensor.dtype])[0])
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\ops\gen_io_ops.py", line 669, in restore_v2
    dtypes=dtypes, name=name)
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 768, in apply_op
    op_def=op_def)
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\framework\ops.py", line 2336, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\framework\ops.py", line 1228, in __init__
    self._traceback = _extract_stack()

NotFoundError (see above for traceback): Unsuccessful TensorSliceReader constructor: Failed to find any matching files for F:\play_gta_sa\pygta_sa-car-0.001-alexnetv2-8-epochs.model
     [[Node: save_1/RestoreV2 = RestoreV2[dtypes=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_save_1/Const_0, save_1/RestoreV2/tensor_names, save_1/RestoreV2/shape_and_slices)]]

Body:
Thanks for the update.

Edit:

Try add this line before tf.reset_default_graph() loading model. That is

import tensorflow as tf
tf.reset_default_graph()
model = alexnet(WIDTH, HEIGHT, LR)
model.load(MODEL_NAME)


问:
Pandas: Generate a timeseries filled with the last day of the year
Say I have a Pandas timeseries with irregular intervals.

```<code>2010-01-04   88.82
2010-11-29   90.70
2010-12-01   90.09
2011-02-26   90.10
2011-08-01   90.55
2011-09-21   89.50
2012-04-01   89.06
2012-04-30   90.22
2012-05-03   90.21
</code>```

I would like to create from the index another timeseries where the column is populated by the last date of the year. So for 2010 dates, it will show 2010-12-01 and for 2011 dates, it will show 2011-09-21, etc. The desired output is

```<code>2010-01-04   2010-12-01
2010-11-29   2010-12-01
2010-12-01   2010-12-01
2011-02-26   2011-09-21
2011-08-01   2011-09-21
2011-09-21   2011-09-21
2012-04-01   2012-05-03
2012-04-30   2012-05-03
2012-05-03   2012-05-03
</code>```

I can extract out the index and group them by year.

```<code>end_dates=[]
df_idx = df.index
year_df = df_idx.groupby(df_idx.year)
for yr in year_df.keys():
    end_dates.append(max(year_df[yr]))
</code>```

This gives me a list of yearly end dates. But how do I associate these end dates back to the original index to arrive at the desired output?

Body:
Say I have a Pandas timeseries with irregular intervals.

2010-01-04   88.82
2010-11-29   90.70
2010-12-01   90.09
2011-02-26   90.10
2011-08-01   90.55
2011-09-21   89.50
2012-04-01   89.06
2012-04-30   90.22
2012-05-03   90.21

I would like to create from the index another timeseries where the column is populated by the last date of the year. So for 2010 dates, it will show 2010-12-01 and for 2011 dates, it will show 2011-09-21, etc. The desired output is

2010-01-04   2010-12-01
2010-11-29   2010-12-01
2010-12-01   2010-12-01
2011-02-26   2011-09-21
2011-08-01   2011-09-21
2011-09-21   2011-09-21
2012-04-01   2012-05-03
2012-04-30   2012-05-03
2012-05-03   2012-05-03

I can extract out the index and group them by year.

end_dates=[]
df_idx = df.index
year_df = df_idx.groupby(df_idx.year)
for yr in year_df.keys():
    end_dates.append(max(year_df[yr]))

This gives me a list of yearly end dates. But how do I associate these end dates back to the original index to arrive at the desired output?

Body:
Make sure your index is a datetimeindex object.

If you have pandas series you can use this:

s.to_frame().assign(end_dates=s.groupby(s.index.year).transform(lambda x: x.index.max()))

or if you already have a dataframe:

df.assign(end_dates=df.groupby(df.index.year)['A'].transform(lambda x: x.index.max()))

Output:

                1  end_dates
0
2010-01-04  88.82 2010-12-01
2010-11-29  90.70 2010-12-01
2010-12-01  90.09 2010-12-01
2011-02-26  90.10 2011-09-21
2011-08-01  90.55 2011-09-21
2011-09-21  89.50 2011-09-21
2012-04-01  89.06 2012-05-03
2012-04-30  90.22 2012-05-03
2012-05-03  90.21 2012-05-03


问:
Copy the cell value to another cell if
I'm writing VBA in Excel and I have a cell with some numbers in it and I have a "shopping cart" range and I when I click on the button I want to copy the cell value to the "cart" but if the first row in the cart is already full it should move on the next row and do this until it finds a row that it empty and paste it in there.

I tried to do it but got a problem

```<code>Sub Gumb1_Klikni()

  Range("B1").Select
  Selection.Copy
  Range("J2").Select
  If IsEmpty(ActiveCell) Then
  Selection.PasteSpecial xlPasteAll
  Else
  Set nextcell = ActiveCell.Offset(1, 0)
  Range(nextcell).Select
  ActiveSheet.Paste
  End If

End Sub
</code>```

It gives me Error 1004 "Method 'Range' of object '_Global' failed" at

```<code>Range(nextcell).Select
</code>```

答:
If you would define Dim nextcell as Range at the beginning of your Sub , all you need to do is:

```<code>nextcell.Select
</code>```

However, you could use the "Cleaner" version below, without the need to use Select or Selection :

```<code>Option Explicit

Sub Gumb1_Klikni()

Dim nextCell As Range

Range("B1").Copy
If IsEmpty(Range("J2")) Then
    Range("J2").PasteSpecial xlPasteAll
Else
    Set nextCell = Range("J2").Offset(1, 0)
    nextCell.PasteSpecial
End If

End Sub
</code>```

Edit 1: after PO clarification:

```<code>Sub Gumb1_Klikni()

Dim LastRow As Long

' get last row with data in column "J"
LastRow = Cells(Rows.Count, "J").End(xlUp).Row
If LastRow < 1 Then LastRow = 1

Range("B1").Copy
Range("J" & LastRow + 1).PasteSpecial xlPasteAll

End Sub
</code>```

Title: Copy the cell value to another cell if

Body:
I'm writing VBA in Excel and I have a cell with some numbers in it and I have a "shopping cart" range and I when I click on the button I want to copy the cell value to the "cart" but if the first row in the cart is already full it should move on the next row and do this until it finds a row that it empty and paste it in there.

I tried to do it but got a problem

Sub Gumb1_Klikni()

  Range("B1").Select
  Selection.Copy
  Range("J2").Select
  If IsEmpty(ActiveCell) Then
  Selection.PasteSpecial xlPasteAll
  Else
  Set nextcell = ActiveCell.Offset(1, 0)
  Range(nextcell).Select
  ActiveSheet.Paste
  End If

End Sub

It gives me Error 1004 "Method 'Range' of object '_Global' failed" at

Range(nextcell).Select

Body:
If you would define Dim nextcell as Range at the beginning of your Sub , all you need to do is:

nextcell.Select

However, you could use the "Cleaner" version below, without the need to use Select or Selection :

Option Explicit

Sub Gumb1_Klikni()

Dim nextCell As Range

Range("B1").Copy
If IsEmpty(Range("J2")) Then
    Range("J2").PasteSpecial xlPasteAll
Else
    Set nextCell = Range("J2").Offset(1, 0)
    nextCell.PasteSpecial
End If

End Sub

Edit 1: after PO clarification:

Sub Gumb1_Klikni()

Dim LastRow As Long

' get last row with data in column "J"
LastRow = Cells(Rows.Count, "J").End(xlUp).Row
If LastRow < 1 Then LastRow = 1

Range("B1").Copy
Range("J" & LastRow + 1).PasteSpecial xlPasteAll

End Sub


问:
Laravel 5.4 different value validation rule in array
I have an input with an array of entities with an ID which must be unique
I've tried this:

```<code>'authors.*.id' => 'different:authors.*.id'
</code>```

But it says 'The authors.0.id and authors.0.id must be different'
So what is a right way to validate this?

答:
You want to use distinct rule.

When working with arrays, the field under validation must not have any duplicate values.

'foo.*.id' => 'distinct'

Body:
I have an input with an array of entities with an ID which must be unique
I've tried this:

'authors.*.id' => 'different:authors.*.id'

But it says 'The authors.0.id and authors.0.id must be different'
So what is a right way to validate this?


问:
Graphite Installation on MacOS Sierra 10.12.4
I do many tries to install graphite on my MacBook. I follow this tutorial
https://gist.github.com/trusche/bfab931c538bd1a63c80

I install all mandatory packages, but it stops at this command: python manage.py syncdb
There is no file named manage.py on my mac.

this file should be present in /opt/graphite/webapp/graphite.

I don't understand why this file is missing.

Thanks for your help

答:
I think you are using a newer version of Graphite than the tutorial assumes. The command to configure the Django database changed a while back. It should be something like:

django-admin.py migrate --settings=graphite.settings --run-syncdb

See https://graphite.readthedocs.io/en/latest/config-database-setup.html for more information.


问:
from xml to arraylist by xstream
I want to read data from XML to ArrayList by xstream.

I can read only one Object with this code:

```<code>List<Event> events = new ArrayList<Event>();
XStream xstream = new XStream();
xstream.alias("Event", Event.class);
FileInputStream fis = null;

try {
    fis = new FileInputStream(path);
    events.add((Event) xstream.fromXML(fis));
} catch(FileNotFoundException e) {
    e.printStackTrace();
} catch(IOException e) {
    e.printStackTrace();
} finally {
     try {
         fis.close();
     } catch(IOException e) {
         e.printStackTrace();
     }
}
</code>```

How can I get next Object?

答:
You're getting an Event instance from "fromXML" method. Try to get the list of events using this method.
So you need to update alias to retrieve list/collection of events and cast result of "fromXML" method to this collection.
It will be possible only if your XML assumes the list/collection of events (if it assumes just Event, I think you will get an error).</p>

Title: from xml to arraylist by xstream

Body:
I want to read data from XML to ArrayList by xstream.

I can read only one Object with this code:

List<Event> events = new ArrayList<Event>();
XStream xstream = new XStream();
xstream.alias("Event", Event.class);
FileInputStream fis = null;

try {
    fis = new FileInputStream(path);
    events.add((Event) xstream.fromXML(fis));
} catch(FileNotFoundException e) {
    e.printStackTrace();
} catch(IOException e) {
    e.printStackTrace();
} finally {
     try {
         fis.close();
     } catch(IOException e) {
         e.printStackTrace();
     }
}

How can I get next Object?


问:
Sorting MySQL results in PHP...?
I have a page on my site that lists a bunch of products, each with a user rating. I use one query to pull some data points for each product ("details query"), and a second query that returns the average user rating for each product ("ratings query").

I want to append the user rating for each product onto the "details query" result set, then sort by rating in descending order. I've read a bunch of entries on Stack Overflow, php.net etc. and I think I need to use usort() with a custom function, but every time I pass my MySQL result to usort() I get a php error saying the object I'm passing to usort() isn't an array. For example, I've tried:

```<code>$data = mysql_fetch_array($details_query);
usort($data,"compare");
</code>```

Doing the above will throw an error saying $data isn't an array. What am I doing wrong?

Also, if anyone has any other suggestions on how to get this done I'd really appreciate. I'm having a really tough time with this for some reason...

Thanks!

答:
You're mis-using the MySQL functions - mysql_fetch_array doesn't take a SQL query, it takes a MySQL result resource:

http://php.net/manual/en/function.mysql-fetch-array.php

So you want something like:

```<code>$all_data = array();

$sql = "SELECT blah FROM blah";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
    $all_data[] = $row;
}

// $all_data is now a 2-D array with all your data.
usort($all_data, "compare");
</code>```

Title: Sorting MySQL results in PHP...?

Body:
I have a page on my site that lists a bunch of products, each with a user rating. I use one query to pull some data points for each product ("details query"), and a second query that returns the average user rating for each product ("ratings query").

I want to append the user rating for each product onto the "details query" result set, then sort by rating in descending order. I've read a bunch of entries on Stack Overflow, php.net etc. and I think I need to use usort() with a custom function, but every time I pass my MySQL result to usort() I get a php error saying the object I'm passing to usort() isn't an array. For example, I've tried:

$data = mysql_fetch_array($details_query);
usort($data,"compare");

Doing the above will throw an error saying $data isn't an array. What am I doing wrong?

Also, if anyone has any other suggestions on how to get this done I'd really appreciate. I'm having a really tough time with this for some reason...

Thanks!

Body:
You're mis-using the MySQL functions - mysql_fetch_array doesn't take a SQL query, it takes a MySQL result resource:

http://php.net/manual/en/function.mysql-fetch-array.php

So you want something like:

$all_data = array();

$sql = "SELECT blah FROM blah";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
    $all_data[] = $row;
}

// $all_data is now a 2-D array with all your data.
usort($all_data, "compare");