问:
iOS - UIPickerView Dismiss with button or without a button?
Good Afternoon/Evening/Morning Folks,

I recently encountered a discussion with another developer on dismissing a UIPickerView. We work on a legacy enterprise application that had a lot of issues and was written very poorly (among other things). Since then, we revamped and fixed a lot of bugs with this program, strictly adhering to Apple's Human Interface Guidelines as much as possible while keeping to original requirements.

We seem to have a difference in opinion as Human Interface Guidelines do not really go into any detail about picker views. We implemented our new UIPickerView with a "Done," Button to confirm a selected value to be placed in a UITextField. Screen's input would be locked until they selected a value or clicked done.

Legacy application prior to our changes allowed users to utilize a done button but also by way of tapping a value selected in a picker. In addition, legacy application would also show selected UIPickerView value in UITextField prior to selection, wiping out original contents , if any was selected prior to opening a UIPickerView.

So, What is correct way to implement a UIPickerView per common practice or Strict Apple Documentation (if any exists). What is common practice?

Sorry, I cannot post any screen shots or code snippets due to business process reasons. I will do my best to explain if any questions arise.

Thanks,

答:
We can figure this out through apps designed by Apple. Here are two examples

1. Contacts

Find a contact person in the Contacts app and set birthday. The picker shows up. While you are dragging the pickers, it does not set value to the text field. It happens only when you release the wheel. There is no Done button to hide the picker it self. To dismiss it, you can either click on the done button  on navigation bar to end editing for the whole page, or click on another text field which pops a different keyboard.

2.Setting - Date&Time

Basically the same as Contacts app. Here you cannot even dismiss the picker.


来源: stackexchange

问:
How to add a dictionary within firebase friendly data structure
I'm trying to get my data ready to update my firebase database,
the problem is that I don't know how to insert a dictionary within a "firebase friendly" data structure.

My aproach:

```<code>class func updateGroup(group: Group){
   let ref = Database.database().reference().child("groups")
   let groupValues = ["description": group.description,
                      "name": group.name,
                       "users": group.users]
   let childUpdates = [group.id! : groupValues]
   ref.updateChildValues(childUpdates)
 }
</code>```

name and description properties are String while users is a [String: String] dictionary:

```<code>class Group{
    public var name: String?
    public var description: String?
    public var id: String?
    public var users: [String: String]?
    ...
}
</code>```

What is the proper way to achieve this?
Thanks in advance.

答:
You must define the dictionary as [String: Any] since it has another dictionary within it.

```<code>let groupValues = ["description": group.description,
                   "name": group.name,
                   "users": group.users] as [String: Any]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to get my data ready to update my firebase database,
the problem is that I don't know how to insert a dictionary within a "firebase friendly" data structure.

My aproach:

class func updateGroup(group: Group){
   let ref = Database.database().reference().child("groups")
   let groupValues = ["description": group.description,
                      "name": group.name,
                       "users": group.users]
   let childUpdates = [group.id! : groupValues]
   ref.updateChildValues(childUpdates)
 }

name and description properties are String while users is a [String: String] dictionary:

class Group{
    public var name: String?
    public var description: String?
    public var id: String?
    public var users: [String: String]?
    ...
}

What is the proper way to achieve this?
Thanks in advance.

Body:
You must define the dictionary as [String: Any] since it has another dictionary within it.

let groupValues = ["description": group.description,
                   "name": group.name,
                   "users": group.users] as [String: Any]


问:
Updating a list entry as a value to a nested dictionary
I have the following nested dictionary: facebook. You'll note that one of the key value pairs is friends: ["friend1","friend2" etc). In trying to append the various friends to the list, it does so but not in the correct format.

Question 1: Could someone please provide an answer/solution to solve this problem. The desired output on appending the information given should be in the same format as for John and Mary (keys) in the dictionary.

Note: the keys are: John, Mary  (and in register_user, I attempt to add the key: Mr x) The values are as shown, where the friends for each individual (key) are stored in a list. What I am not sure of is, when you "append" keys and values to a dictionary, you can add the values, but how do you add the keys, or reference the keys when adding the values?

Code so far:

```<code>facebook={'John': {'Friends': ['Bobby', 'Charlie', 'Dalia', 'Ellie'],
            'Gender': 'Male',
            'Hobby': 'Chess'},

            'Mary': {'Friends': ['Bobby', 'Xavier', 'Dalia', 'Zanpoodle'],
            'Gender': 'Female',
            'Hobbies': 'Chequers'}}

def main():
  register_user()

#create a dictionary that stores the profiles of users

def register_user():
  name=input("Enter Name:")
  friend1=input("Friend 1:")
  friend2=input("Friend 2:")
  friend3=input("Friend 3:")
  friend4=input("Friend 4:")
  #gender=input("Enter Gender:")
  #hobby=input("Enter your main hobby:")

  #this adds an entry to the dictionary
  facebook.update({name:[friend1,friend2,friend3,friend4]})
  for i in facebook.items():
    print(i)

  print()

  print(facebook.items())

main()
</code>```

Erroneous output:
*As mentioned, I would like Friend1, Friend 2 etc, to be added to a list value for key: friends, in Mr X's new entry.

```<code>Enter Name: Mr X
Friend 1: Friend1
Friend 2: Friend2
Friend 3: Friend3
Friend 4: Friend4
('John', {'Friends': ['Bobby', 'Charlie', 'Dalia', 'Ellie'], 'Gender': 'Male', 'Hobby': 'Chess'})
('Mary', {'Friends': ['Bobby', 'Xavier', 'Dalia', 'Zanpoodle'], 'Gender': 'Female', 'Hobbies': 'Chequers'})
('Mr X', ['Friend1', 'Friend2', 'Friend3', 'Friend4'])

dict_items([('John', {'Friends': ['Bobby', 'Charlie', 'Dalia', 'Ellie'], 'Gender': 'Male', 'Hobby': 'Chess'}), ('Mary', {'Friends': ['Bobby', 'Xavier', 'Dalia', 'Zanpoodle'], 'Gender': 'Female', 'Hobbies': 'Chequers'}), **('Mr X', ['Friend1', 'Friend2', 'Friend3', 'Friend4'])])**
</code>```

Update:
I also tried this:
    facebook.update({name:{Friends:[friend1,friend2,friend3,friend4]}})

but it came up with the following error:

```<code>Traceback (most recent call last):
  File "python", line 35, in <module>
  File "python", line 11, in main
  File "python", line 26, in register_user
NameError: name 'Friends' is not defined
</code>```

Another try:

```<code>facebook[name]={'Friends':[friend1,friend2,friend3,friend4]}
</code>```

unfortunately still an error:

```<code>Traceback (most recent call last):
  File "python", line 35, in <module>
  File "python", line 11, in main
  File "python", line 27, in register_user
TypeError: 'type' object does not support item assignment
</code>```

Finally, I have also tried adding the names to a list and then appending this list like this:

```<code>   newfriends=[friend1,friend2,friend3,friend4]
   facebook.update({name:{[newfriends]})
</code>```

Resultant in a syntax error

along with just trying to use append:

```<code>friendslist=[friend1,friend2,friend3,friend4]
  facebook['name'].append(friendlist)
</code>```

ERROR:

```<code>KeyError: 'name'
</code>```

This attempt gets close, but not quite:

```<code>facebook.update({"Name":name,"Friends":[friend1,friend2,friend3,friend4]})
</code>```

producing the following output:

```<code>Enter Name: t
Friend 1: 1
Friend 2: 2
Friend 3: 3
Friend 4: 4
{'John': {'Friends': ['Bobby', 'Charlie', 'Dalia', 'Ellie'], 'Gender': 'Male', 'Hobby': 'Chess'}, 'Mary': {'Friends': ['Bobby', 'Xavier', 'Dalia', 'Zanpoodle'], 'Gender': 'Female', 'Hobbies': 'Chequers'}, 'Name': 't', 'Friends': ['1', '2', '3', '4']}
</code>```

Clarification: I realise there may be several different ways of approaching this. I would like a simple fix to the problem WITHOUT introducing anything new (like lambda or having to import anything)

答:
One way to solve your problem is to convert the facebook dictionary to a defaultdict.

```<code>from collections import defaultdict

dd_facebook = defaultdict(lambda: {"Friends": []}, facebook)
</code>```

To update the friends list you could simply do the following:

```<code>dd_facebook[name]['Friends'].extend([friend1,friend2,friend3,friend4])
</code>```

Body:
I have the following nested dictionary: facebook. You'll note that one of the key value pairs is friends: ["friend1","friend2" etc). In trying to append the various friends to the list, it does so but not in the correct format.

Question 1: Could someone please provide an answer/solution to solve this problem. The desired output on appending the information given should be in the same format as for John and Mary (keys) in the dictionary.

Note: the keys are: John, Mary  (and in register_user, I attempt to add the key: Mr x) The values are as shown, where the friends for each individual (key) are stored in a list. What I am not sure of is, when you "append" keys and values to a dictionary, you can add the values, but how do you add the keys, or reference the keys when adding the values?

Code so far:

facebook={'John': {'Friends': ['Bobby', 'Charlie', 'Dalia', 'Ellie'],
            'Gender': 'Male',
            'Hobby': 'Chess'},

            'Mary': {'Friends': ['Bobby', 'Xavier', 'Dalia', 'Zanpoodle'],
            'Gender': 'Female',
            'Hobbies': 'Chequers'}}

def main():
  register_user()

#create a dictionary that stores the profiles of users

def register_user():
  name=input("Enter Name:")
  friend1=input("Friend 1:")
  friend2=input("Friend 2:")
  friend3=input("Friend 3:")
  friend4=input("Friend 4:")
  #gender=input("Enter Gender:")
  #hobby=input("Enter your main hobby:")

  #this adds an entry to the dictionary
  facebook.update({name:[friend1,friend2,friend3,friend4]})
  for i in facebook.items():
    print(i)

  print()

  print(facebook.items())

main()

Erroneous output:
*As mentioned, I would like Friend1, Friend 2 etc, to be added to a list value for key: friends, in Mr X's new entry.

Enter Name: Mr X
Friend 1: Friend1
Friend 2: Friend2
Friend 3: Friend3
Friend 4: Friend4
('John', {'Friends': ['Bobby', 'Charlie', 'Dalia', 'Ellie'], 'Gender': 'Male', 'Hobby': 'Chess'})
('Mary', {'Friends': ['Bobby', 'Xavier', 'Dalia', 'Zanpoodle'], 'Gender': 'Female', 'Hobbies': 'Chequers'})
('Mr X', ['Friend1', 'Friend2', 'Friend3', 'Friend4'])

dict_items([('John', {'Friends': ['Bobby', 'Charlie', 'Dalia', 'Ellie'], 'Gender': 'Male', 'Hobby': 'Chess'}), ('Mary', {'Friends': ['Bobby', 'Xavier', 'Dalia', 'Zanpoodle'], 'Gender': 'Female', 'Hobbies': 'Chequers'}), **('Mr X', ['Friend1', 'Friend2', 'Friend3', 'Friend4'])])**

Update:
I also tried this:
    facebook.update({name:{Friends:[friend1,friend2,friend3,friend4]}})

but it came up with the following error:

Traceback (most recent call last):
  File "python", line 35, in <module>
  File "python", line 11, in main
  File "python", line 26, in register_user
NameError: name 'Friends' is not defined

Another try:

facebook[name]={'Friends':[friend1,friend2,friend3,friend4]}

unfortunately still an error:

Traceback (most recent call last):
  File "python", line 35, in <module>
  File "python", line 11, in main
  File "python", line 27, in register_user
TypeError: 'type' object does not support item assignment

Finally, I have also tried adding the names to a list and then appending this list like this:

   newfriends=[friend1,friend2,friend3,friend4]
   facebook.update({name:{[newfriends]})

Resultant in a syntax error

along with just trying to use append:

friendslist=[friend1,friend2,friend3,friend4]
  facebook['name'].append(friendlist)

ERROR:

KeyError: 'name'

This attempt gets close, but not quite:

facebook.update({"Name":name,"Friends":[friend1,friend2,friend3,friend4]})

producing the following output:

Enter Name: t
Friend 1: 1
Friend 2: 2
Friend 3: 3
Friend 4: 4
{'John': {'Friends': ['Bobby', 'Charlie', 'Dalia', 'Ellie'], 'Gender': 'Male', 'Hobby': 'Chess'}, 'Mary': {'Friends': ['Bobby', 'Xavier', 'Dalia', 'Zanpoodle'], 'Gender': 'Female', 'Hobbies': 'Chequers'}, 'Name': 't', 'Friends': ['1', '2', '3', '4']}

Clarification: I realise there may be several different ways of approaching this. I would like a simple fix to the problem WITHOUT introducing anything new (like lambda or having to import anything)

Body:
One way to solve your problem is to convert the facebook dictionary to a defaultdict.

from collections import defaultdict

dd_facebook = defaultdict(lambda: {"Friends": []}, facebook)

To update the friends list you could simply do the following:

dd_facebook[name]['Friends'].extend([friend1,friend2,friend3,friend4])


问:
how to fix ChakraCore NuGet package error?
When initializing a new React Native Windows WPF project, this error happens:

NuGet Package restore failed for project Native: Unable to find version '1.4.1-preview-00010-42060' of package 'Microsoft.ChakraCore'.
https://www.myget.org/F/chakracore-preview/api/v3/index.json: Package 'Microsoft.ChakraCore.1.4.1-preview-00010-42060' is not found on source 'https://www.myget.org/F/chakracore-preview/api/v3/index.json'.
https://api.nuget.org/v3/index.json: Package 'Microsoft.ChakraCore.1.4.1-preview-00010-42060' is not found on source 'https://api.nuget.org/v3/index.json'.

If I create a standalone project and add the same NuGet package reference, I get the same error -- even on Xamarin Studio Mac.

答:
The problem is that the project was referencing the "preview" feed on myget.org, instead of the official release feed on nuget.org. In the NuGet.Config file(s) in your project, remove line that references the preview feed that looks like this:

<add key="ChakraCore" value="https://www.myget.org/F/chakracore-preview/api/v3/index.json" />

In the Visual Studio 2015 (or Xamarin/Visual Studio Mac) project, right-click on the project and select Manage NuGet References. From there, you can click on the Updates tab, select ChakraCore from the list, and click "Update". This should update the packages.config and other files for you. Note that if you had the project open while editing the config files you'll need to close and re-open the project to get the new settings to take hold. In some cases, the upgrade may leave behind the reference to the previous 1.4.1-preview package and you'll need to hand-edit the csproj file to get rid of it.

If you need to make this change without Visual/Xamarin Studio, you just have to edit a few text files. In the packages.config (in Visual Studio 2015), change the line referencing the 1.4.1-preview version to the latest release (1.5.2 as of this writing):

<package id="Microsoft.ChakraCore" version="1.4.1-preview-00010-42060" targetFramework="net46" developmentDependency="true" />

becomes

<package id="Microsoft.ChakraCore" version="1.5.2" targetFramework="net46" developmentDependency="true" />

In your project's csproj file:
<Import Project="$(SolutionDir)\packages\Microsoft.ChakraCore.1.4.1\build\netstandard1.0\Microsoft.ChakraCore.props" Condition="Exists('$(SolutionDir)\packages\Microsoft.ChakraCore.1.4.1\build\netstandard1.0\Microsoft.ChakraCore.props')" />

becomes

<Import Project="$(SolutionDir)\packages\Microsoft.ChakraCore.1.5.2\build\netstandard1.0\Microsoft.ChakraCore.props" Condition="Exists('$(SolutionDir)\packages\Microsoft.ChakraCore.1.5.2\build\netstandard1.0\Microsoft.ChakraCore.props')" />

and

<Error Condition="!Exists('$(SolutionDir)\packages\Microsoft.ChakraCore.1.4.1\build\netstandard1.0\Microsoft.ChakraCore.props')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\packages\Microsoft.ChakraCore.1.4.1\build\netstandard1.0\Microsoft.ChakraCore.props'))" />

becomes

<Error Condition="!Exists('$(SolutionDir)\packages\Microsoft.ChakraCore.1.5.2\build\netstandard1.0\Microsoft.ChakraCore.props')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\packages\Microsoft.ChakraCore.1.5.2\build\netstandard1.0\Microsoft.ChakraCore.props'))" />

Generally speaking, don't reference preview packages from myget.org in production projects or project templates others will use. They can be removed at any time, and security updates may not be published there with the same regularity as official channels.


问:
add values with PHP
I have a database table with two fields both id and value and I'd like to add the two entries for value together and then echo out the total of the sum.

So far I've been able to display both entries for value by using the following.

```<code>function showTotal() {

global $connection;
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);

if (!$result) {

die('Query FAILED' . mysqli_error());

} else if (isset($failed)) {

echo "Failed";

}

while ($row = mysqli_fetch_assoc($result)) {

$value = $row['value'];

echo "$value";

            }
                }
</code>```

What I really want is these values added together rather than displaying alongside each other.

Thanks
James

答:
Using php you could sum up the values like so:</p>

```<code>$value = 0;
while ($row = mysqli_fetch_assoc($result)) {

    $value += $row['value'];

}

echo $value;
</code>```

Title: add values with PHP

Body:
I have a database table with two fields both id and value and I'd like to add the two entries for value together and then echo out the total of the sum.

So far I've been able to display both entries for value by using the following.

function showTotal() {

global $connection;
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);

if (!$result) {

die('Query FAILED' . mysqli_error());

} else if (isset($failed)) {

echo "Failed";

}

while ($row = mysqli_fetch_assoc($result)) {

$value = $row['value'];

echo "$value";

            }
                }

What I really want is these values added together rather than displaying alongside each other.

Thanks
James

Body:
Using php you could sum up the values like so:

$value = 0;
while ($row = mysqli_fetch_assoc($result)) {

    $value += $row['value'];

}

echo $value;


问:
Ruby operations on template variables - Chef
I have written following template in my chef cookbook recipe

```<code>template '/etc/app.conf' do
   variables({
   my_id: Chef::HTTP.new(https://example.com).get('/',{header})
})
end
</code>```

And my erb file is

```<code>Output is : <%= @my_id %>
</code>```

I actually want to perform some ruby operations(mainly filter out and count the components of my_id) and then pass those values(count of each component) back to the template and use it further. What should be erb configuration or anything thats need to be added in template block?

(Here, my_id actually has the subnets and I want to get those the count of those subnets and its values so that I can use it further to perform another http request and get the nodes in each of the subnet).

答:
The thing you pasted from (hopefully you were summarizing since you missed a bunch of quotes in there) was only a quick tip. To get JSON data you want to use Chef::HTTP::SimpleJSON, the will do the parsing for you and whatnot.

```<code>variables data: Chef::HTTP::SimpleJSON.new('https://whatever.com/').get('/foo')
</code>```

Body:
I have written following template in my chef cookbook recipe

template '/etc/app.conf' do
   variables({
   my_id: Chef::HTTP.new(https://example.com).get('/',{header})
})
end

And my erb file is

Output is : <%= @my_id %>

I actually want to perform some ruby operations(mainly filter out and count the components of my_id) and then pass those values(count of each component) back to the template and use it further. What should be erb configuration or anything thats need to be added in template block?

(Here, my_id actually has the subnets and I want to get those the count of those subnets and its values so that I can use it further to perform another http request and get the nodes in each of the subnet).

Body:
The thing you pasted from (hopefully you were summarizing since you missed a bunch of quotes in there) was only a quick tip. To get JSON data you want to use Chef::HTTP::SimpleJSON, the will do the parsing for you and whatnot.

variables data: Chef::HTTP::SimpleJSON.new('https://whatever.com/').get('/foo')


问:
Switch Pages In WPF using MahApps
First of all, thank you for taking your time to read this.
Im pretty new to WPF and especially to using MahApps - http://mahapps.com

Im having problems switching between pages that I have created using MahApps in my window.

Here is my starting window (MainWindow):

```<code><Window
                  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                  xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
                  xmlns:Dialogs="clr-namespace:MahApps.Metro.Controls.Dialogs;assembly=MahApps.Metro" x:Class="WpfApplication.MainWindow"
                  xmlns:Dialog="clr-namespace:MahApps.Metro.Controls.Dialogs;assembly=MahApps.Metro"
                  Dialog:DialogParticipation.Register="{Binding}"
                  Title="MainWindow"
                  Height="600"
                  Width="800">
<Grid>
    <Frame x:Name="Main"/>
</Grid>
</code>```

Here is the page that I want to move to (I created a frame in the main so I could put the content of this page on it):

```<code><Controls:MetroWindow
                  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                  xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
                  xmlns:Dialogs="clr-namespace:MahApps.Metro.Controls.Dialogs;assembly=MahApps.Metro" x:Class="WpfApplication.MainMenu"
                  xmlns:Dialog="clr-namespace:MahApps.Metro.Controls.Dialogs;assembly=MahApps.Metro"
                  Dialog:DialogParticipation.Register="{Binding}"
                  Title="MainMenu"
                  Height="600"
                  Width="800" NonActiveBorderBrush="#FFC32C2C">
<Grid>

    <Image x:Name="Background" Source="C:\Users\User\Desktop\Iddo Work\C#Learning\WpfApplication/teaserBackground.jpg" Stretch="UniformToFill">
        <Image.BitmapEffect>
            <BlurBitmapEffect Radius="17" />
        </Image.BitmapEffect>
    </Image>
    <Image x:Name="Logo" Source="C:\Users\User\Desktop\Iddo Work\C#Learning\WpfApplication/Trivia.png" Margin="0,60,0,320" VerticalAlignment="Center" HorizontalAlignment="Center"/>
    <TextBox x:Name="Username" Controls:TextBoxHelper.Watermark="       USERNAME" Margin="0,308,0,226" Width="200" Height="35" TextAlignment="Justify" FontSize="20" FontWeight="Bold" HorizontalAlignment="Center" />
    <TextBox x:Name="Password" Controls:TextBoxHelper.Watermark="       PASSWORD" Margin="0,378,0,156" Width="200" Height="35" TextAlignment="Justify" FontSize="20" FontWeight="Bold" />
    <Button x:Name="SignIn" Content="" HorizontalAlignment="Left" Margin="407,435,0,0" VerticalAlignment="Top" Width="80" Style="{DynamicResource MetroCircleButtonStyle}" Height="80" BorderBrush="{x:Null}" Foreground="{x:Null}" Click="SignIn_Click">
        <Button.Background>
            <ImageBrush ImageSource="C:\Users\User\Desktop\Iddo Work\C#Learning\WpfApplication/signIn.png"/>
        </Button.Background>
    </Button>
    <Button x:Name="SignUp" Content="" HorizontalAlignment="Left" Margin="310,435,0,0" VerticalAlignment="Top" Width="80" Style="{DynamicResource MetroCircleButtonStyle}" Height="80" BorderBrush="{x:Null}" Foreground="{x:Null}" Click="SignUp_Click">
        <Button.Background>
            <ImageBrush ImageSource="C:\Users\User\Desktop\Iddo Work\C#Learning\WpfApplication/sign-add-icon.png"/>
        </Button.Background>
    </Button>

</Grid>
</code>```

Thank you in advance!

答:
Updated answer:
Frames themselves are meant to load pages and your menu item is inheriting from a window so that will never work.

Here are the mods you need to make:

In your MainWindow.xaml change the Window tag to Controls:MetroWindow (like you have in your MainMenu xaml

In your MainWindow.xaml.cs remove the base class reference for the MainWindow (MainWindow : Window becomes just MainWindow)

In your MainMenu.xaml change Controls:MetroWindow to just UserControl

Back in your MainWindow.xaml, add a ref to your namespace xmlns:my="clr-namespace:WhateverHere"

In MainWindow.xaml, remove the  and add your control directly instead

MainWindow.xaml

```<code>    <Controls:MetroWindow x:Class="WPFDeleteMe.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
            xmlns:Dialogs="clr-namespace:MahApps.Metro.Controls.Dialogs;assembly=MahApps.Metro"
            xmlns:Dialog="clr-namespace:MahApps.Metro.Controls.Dialogs;assembly=MahApps.Metro"
            xmlns:my="clr-namespace:WPFDeleteMe"
            Title="MainWindow" Height="700" Width="900">
        <Grid x:Name="RootGrid">
            <my:MainMenu></my:MainMenu>
        </Grid>
    </Controls:MetroWindow>
</code>```

MainWindow.xaml.cs

```<code>    public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
</code>```

MainMenu.xaml

```<code>    <UserControl x:Class="WPFDeleteMe.MainMenu"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                 xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                 mc:Ignorable="d"
                 d:DesignHeight="600" d:DesignWidth="800">
        <Grid>
            <Image x:Name="Background" Source="d:\images\doll-161405_960_720.png" Stretch="UniformToFill">
                <Image.BitmapEffect>
                    <BlurBitmapEffect Radius="17" />
                </Image.BitmapEffect>
            </Image>
            <Image x:Name="Logo" Source="d:\images\Carestream_Solutions.gif" Margin="0,0,0,0" Width="150" Height="40" VerticalAlignment="Center" HorizontalAlignment="Center"/>
            <Button x:Name="SignIn" Content="" HorizontalAlignment="Left" Margin="407,435,0,0" VerticalAlignment="Top" Width="80" Height="80" BorderBrush="{x:Null}" Foreground="{x:Null}" Click="SignIn_Click">
                <Button.Background>
                    <ImageBrush ImageSource="d:\images\war_kitten.jpg"/>
                </Button.Background>
            </Button>
            <Button x:Name="SignUp" Content="" HorizontalAlignment="Left" Margin="310,435,0,0" VerticalAlignment="Top" Width="80" Height="80" BorderBrush="{x:Null}" Foreground="{x:Null}" Click="SignUp_Click">
                <Button.Background>
                    <ImageBrush ImageSource="d:\images\war_kitten.jpg"/>
                </Button.Background>
            </Button>
        </Grid>
    </UserControl>
</code>```

Title: Switch Pages In WPF using MahApps

Body:
First of all, thank you for taking your time to read this.
Im pretty new to WPF and especially to using MahApps - http://mahapps.com

Im having problems switching between pages that I have created using MahApps in my window.

Here is my starting window (MainWindow):

<Window
                  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                  xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
                  xmlns:Dialogs="clr-namespace:MahApps.Metro.Controls.Dialogs;assembly=MahApps.Metro" x:Class="WpfApplication.MainWindow"
                  xmlns:Dialog="clr-namespace:MahApps.Metro.Controls.Dialogs;assembly=MahApps.Metro"
                  Dialog:DialogParticipation.Register="{Binding}"
                  Title="MainWindow"
                  Height="600"
                  Width="800">
<Grid>
    <Frame x:Name="Main"/>
</Grid>

Here is the page that I want to move to (I created a frame in the main so I could put the content of this page on it):

<Controls:MetroWindow
                  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                  xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
                  xmlns:Dialogs="clr-namespace:MahApps.Metro.Controls.Dialogs;assembly=MahApps.Metro" x:Class="WpfApplication.MainMenu"
                  xmlns:Dialog="clr-namespace:MahApps.Metro.Controls.Dialogs;assembly=MahApps.Metro"
                  Dialog:DialogParticipation.Register="{Binding}"
                  Title="MainMenu"
                  Height="600"
                  Width="800" NonActiveBorderBrush="#FFC32C2C">
<Grid>

    <Image x:Name="Background" Source="C:\Users\User\Desktop\Iddo Work\C#Learning\WpfApplication/teaserBackground.jpg" Stretch="UniformToFill">
        <Image.BitmapEffect>
            <BlurBitmapEffect Radius="17" />
        </Image.BitmapEffect>
    </Image>
    <Image x:Name="Logo" Source="C:\Users\User\Desktop\Iddo Work\C#Learning\WpfApplication/Trivia.png" Margin="0,60,0,320" VerticalAlignment="Center" HorizontalAlignment="Center"/>
    <TextBox x:Name="Username" Controls:TextBoxHelper.Watermark="       USERNAME" Margin="0,308,0,226" Width="200" Height="35" TextAlignment="Justify" FontSize="20" FontWeight="Bold" HorizontalAlignment="Center" />
    <TextBox x:Name="Password" Controls:TextBoxHelper.Watermark="       PASSWORD" Margin="0,378,0,156" Width="200" Height="35" TextAlignment="Justify" FontSize="20" FontWeight="Bold" />
    <Button x:Name="SignIn" Content="" HorizontalAlignment="Left" Margin="407,435,0,0" VerticalAlignment="Top" Width="80" Style="{DynamicResource MetroCircleButtonStyle}" Height="80" BorderBrush="{x:Null}" Foreground="{x:Null}" Click="SignIn_Click">
        <Button.Background>
            <ImageBrush ImageSource="C:\Users\User\Desktop\Iddo Work\C#Learning\WpfApplication/signIn.png"/>
        </Button.Background>
    </Button>
    <Button x:Name="SignUp" Content="" HorizontalAlignment="Left" Margin="310,435,0,0" VerticalAlignment="Top" Width="80" Style="{DynamicResource MetroCircleButtonStyle}" Height="80" BorderBrush="{x:Null}" Foreground="{x:Null}" Click="SignUp_Click">
        <Button.Background>
            <ImageBrush ImageSource="C:\Users\User\Desktop\Iddo Work\C#Learning\WpfApplication/sign-add-icon.png"/>
        </Button.Background>
    </Button>

</Grid>

Thank you in advance!

Body:
Updated answer:
Frames themselves are meant to load pages and your menu item is inheriting from a window so that will never work.

Here are the mods you need to make:

In your MainWindow.xaml change the Window tag to Controls:MetroWindow (like you have in your MainMenu xaml

In your MainWindow.xaml.cs remove the base class reference for the MainWindow (MainWindow : Window becomes just MainWindow)

In your MainMenu.xaml change Controls:MetroWindow to just UserControl

Back in your MainWindow.xaml, add a ref to your namespace xmlns:my="clr-namespace:WhateverHere"

In MainWindow.xaml, remove the  and add your control directly instead

MainWindow.xaml

    <Controls:MetroWindow x:Class="WPFDeleteMe.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
            xmlns:Dialogs="clr-namespace:MahApps.Metro.Controls.Dialogs;assembly=MahApps.Metro"
            xmlns:Dialog="clr-namespace:MahApps.Metro.Controls.Dialogs;assembly=MahApps.Metro"
            xmlns:my="clr-namespace:WPFDeleteMe"
            Title="MainWindow" Height="700" Width="900">
        <Grid x:Name="RootGrid">
            <my:MainMenu></my:MainMenu>
        </Grid>
    </Controls:MetroWindow>

MainWindow.xaml.cs

    public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }

MainMenu.xaml

    <UserControl x:Class="WPFDeleteMe.MainMenu"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                 xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                 mc:Ignorable="d"
                 d:DesignHeight="600" d:DesignWidth="800">
        <Grid>
            <Image x:Name="Background" Source="d:\images\doll-161405_960_720.png" Stretch="UniformToFill">
                <Image.BitmapEffect>
                    <BlurBitmapEffect Radius="17" />
                </Image.BitmapEffect>
            </Image>
            <Image x:Name="Logo" Source="d:\images\Carestream_Solutions.gif" Margin="0,0,0,0" Width="150" Height="40" VerticalAlignment="Center" HorizontalAlignment="Center"/>
            <Button x:Name="SignIn" Content="" HorizontalAlignment="Left" Margin="407,435,0,0" VerticalAlignment="Top" Width="80" Height="80" BorderBrush="{x:Null}" Foreground="{x:Null}" Click="SignIn_Click">
                <Button.Background>
                    <ImageBrush ImageSource="d:\images\war_kitten.jpg"/>
                </Button.Background>
            </Button>
            <Button x:Name="SignUp" Content="" HorizontalAlignment="Left" Margin="310,435,0,0" VerticalAlignment="Top" Width="80" Height="80" BorderBrush="{x:Null}" Foreground="{x:Null}" Click="SignUp_Click">
                <Button.Background>
                    <ImageBrush ImageSource="d:\images\war_kitten.jpg"/>
                </Button.Background>
            </Button>
        </Grid>
    </UserControl>


问:
Understanding macros in C
Why is the output from the following code the value 5?</p>

```<code>#include<stdio.h>

#define A -B
#define B -C
#define C 5

int main()
{
  printf("The value of A is %d\n", A);
  return 0;
}
</code>```

答:
Question doesn't really make sense, but I still decided to give it a go.

Visual Studio 2013 and 2015: error C2105: '--' needs l-value

Reason is that the following line:

```<code>printf("The value of A is %d\n", A);
</code>```

is first translated into (A becomes -B):

```<code>printf("The value of A is %d\n", -B);
</code>```

then into (B becomes -C);

```<code>printf("The value of A is %d\n", --C);
</code>```

and then into (C becomes 5):

```<code>printf("The value of A is %d\n", --5);
</code>```

And since 5 is not an l-value, you cannot decrement it, hence the error.
Seems quite logical, knowing the preprocessor will just do a simple string replace.

Title: Understanding macros in C

Body:
Why is the output from the following code the value 5?

#include<stdio.h>

#define A -B
#define B -C
#define C 5

int main()
{
  printf("The value of A is %d\n", A);
  return 0;
}

Body:
Question doesn't really make sense, but I still decided to give it a go.

Visual Studio 2013 and 2015: error C2105: '--' needs l-value

Reason is that the following line:

printf("The value of A is %d\n", A);

is first translated into (A becomes -B):

printf("The value of A is %d\n", -B);

then into (B becomes -C);

printf("The value of A is %d\n", --C);

and then into (C becomes 5):

printf("The value of A is %d\n", --5);

And since 5 is not an l-value, you cannot decrement it, hence the error.
Seems quite logical, knowing the preprocessor will just do a simple string replace.


问:
Input shrinks when user starts typing
The contactfields on my website are shrinking as soon as the user starts typing on a mobile device. I could not detect this behavior in a desktop browser window at any size.

The contactfield is structured with the relativly new css grid.

How to recreate the bug:

Open my website on your mobile device

Scroll down to the input field

Focus one and start typing

I already tried to fix it trough applying a width and min-width to the inputs but this did not fixed it.

I gathered information in a spreadsheet about different browsers and devices to find out wether the bug appears or not.

https://docs.google.com/spreadsheets/d/1D3_7zh8u2MFAx5vt_mKCA9bjEI9crdDwwOSlucLLwfM/edit?usp=sharing

I think that it might be a browser bug since css grid is relatively new?! Are you able to recreate the bug? Do you have any ideas how to fix it other than removing the css grid and structuring it with flexbox?

I would like to try to get the browser companies notified if it appears to be a browser bug so they can fix it...

/*I actually use SCSS so this code will not run */
/* The grid */
.grid__form {
  display: grid;
  grid-template-columns: 50% 50%;
  grid-template-areas: "name email" "textarea textarea" "feedback submit";
  grid-gap: 10px;
  @media screen and (max-width: 500px) {
    grid-template-columns: 100%;
    grid-template-areas: "feedback" "name" "email" "textarea" "submit";
}

/* The contact form */
.contact {
  grid-area: contact;
  margin-bottom: 100px;
  &__header {
    font-size: 500;
    color: $text-dark-primary;
    font-size: 2rem;
    text-align: center;
    margin: 0 0 30px 0;
      @media screen and (max-width: 500px) {
      font-size: 1.5rem;
    }
    &--link {
      text-decoration: none;
      color: rgba($color-secondary-400, 0.87);
      cursor: pointer;
      transition: $transition-standard;
      @media screen and (max-width: 359px) {
        font-size: 1.3rem;
      }
      &:hover {
        text-decoration: underline;
      }
    }
  }
  &__input {
    font-family: 'Roboto', 'Noto Sans', sans-serif;
    line-height: 1.5;
    font-size: 1rem;
    padding: 0.5em;
    border: 2px solid rgba(black, 0.20);
    border-radius: 2px;
    width: 100%;
    min-width: 100%;
    color: $text-dark-primary;
    background-color: white;
    cursor: text;
    outline: none;
    transition: $transition-standard;
    &--name {
      grid-area: name;
    }
    &--email {
      grid-area: email;
    }
    &--textarea {
      grid-area: textarea;
      resize: none;
      min-height: 250px;
    }
    &:focus {
      border: 2px solid $color-secondary-200;
      width: 100%;
      min-width: 100%;
    }
  }
  &__submit {
    font-family: 'Roboto', 'Noto Sans', sans-serif;
    line-height: 1.5;
    grid-area: submit;
    justify-self: end;
  }
  &__feedback {
    grid-area: feedback;
    align-self: center;
    margin: 0;
    font-size: 1rem;
    font-weight: 500;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="contact__form grid__form" action="_assets/php/sendMail.php" method="POST" novalidate>
  <input id="name" class="contact__input contact__input--name" type="text" name="name" placeholder="Name" />
  <input id="email" class="contact__input contact__input--email" type="email" name="email" placeholder="Email" />
  <textarea id="message" class="contact__input contact__input--textarea" type="text" name="message" placeholder="Message"></textarea>
  <p class="contact__feedback"></p>
  <button class="contact__submit button--raised" type="submit">submit</button>
</form></code>```

答:
The problem may be caused by input elements as grid items. Some browsers may be quirky with form elements in a grid container, being that this technology is so new.

Instead, wrap each input in a div. These divs now become the grid items and the inputs become their children (and are now outside the scope of grid layout).

Give each input a width: 100%, if necessary.

Title: Input shrinks when user starts typing

Body:
The contactfields on my website are shrinking as soon as the user starts typing on a mobile device. I could not detect this behavior in a desktop browser window at any size.

The contactfield is structured with the relativly new css grid.

How to recreate the bug:

Open my website on your mobile device

Scroll down to the input field

Focus one and start typing

I already tried to fix it trough applying a width and min-width to the inputs but this did not fixed it.

I gathered information in a spreadsheet about different browsers and devices to find out wether the bug appears or not.

https://docs.google.com/spreadsheets/d/1D3_7zh8u2MFAx5vt_mKCA9bjEI9crdDwwOSlucLLwfM/edit?usp=sharing

I think that it might be a browser bug since css grid is relatively new?! Are you able to recreate the bug? Do you have any ideas how to fix it other than removing the css grid and structuring it with flexbox?

I would like to try to get the browser companies notified if it appears to be a browser bug so they can fix it...

/*I actually use SCSS so this code will not run */
/* The grid */
.grid__form {
  display: grid;
  grid-template-columns: 50% 50%;
  grid-template-areas: "name email" "textarea textarea" "feedback submit";
  grid-gap: 10px;
  @media screen and (max-width: 500px) {
    grid-template-columns: 100%;
    grid-template-areas: "feedback" "name" "email" "textarea" "submit";
}

/* The contact form */
.contact {
  grid-area: contact;
  margin-bottom: 100px;
  &__header {
    font-size: 500;
    color: $text-dark-primary;
    font-size: 2rem;
    text-align: center;
    margin: 0 0 30px 0;
      @media screen and (max-width: 500px) {
      font-size: 1.5rem;
    }
    &--link {
      text-decoration: none;
      color: rgba($color-secondary-400, 0.87);
      cursor: pointer;
      transition: $transition-standard;
      @media screen and (max-width: 359px) {
        font-size: 1.3rem;
      }
      &:hover {
        text-decoration: underline;
      }
    }
  }
  &__input {
    font-family: 'Roboto', 'Noto Sans', sans-serif;
    line-height: 1.5;
    font-size: 1rem;
    padding: 0.5em;
    border: 2px solid rgba(black, 0.20);
    border-radius: 2px;
    width: 100%;
    min-width: 100%;
    color: $text-dark-primary;
    background-color: white;
    cursor: text;
    outline: none;
    transition: $transition-standard;
    &--name {
      grid-area: name;
    }
    &--email {
      grid-area: email;
    }
    &--textarea {
      grid-area: textarea;
      resize: none;
      min-height: 250px;
    }
    &:focus {
      border: 2px solid $color-secondary-200;
      width: 100%;
      min-width: 100%;
    }
  }
  &__submit {
    font-family: 'Roboto', 'Noto Sans', sans-serif;
    line-height: 1.5;
    grid-area: submit;
    justify-self: end;
  }
  &__feedback {
    grid-area: feedback;
    align-self: center;
    margin: 0;
    font-size: 1rem;
    font-weight: 500;
  }
}

<form class="contact__form grid__form" action="_assets/php/sendMail.php" method="POST" novalidate>
  <input id="name" class="contact__input contact__input--name" type="text" name="name" placeholder="Name" />
  <input id="email" class="contact__input contact__input--email" type="email" name="email" placeholder="Email" />
  <textarea id="message" class="contact__input contact__input--textarea" type="text" name="message" placeholder="Message"></textarea>

  <button class="contact__submit button--raised" type="submit">submit</button>
</form>


问:
Spring Integration java.lang.IllegalArgumentException: Found ambiguous parameter type
I received the following error when trying to send a request to an http outbound gateway. After getting the response, I am converting the json payload to a list of objects from other posts I have read it could be a problem with the service activator or the transformer. I am still trying to get a handle on EIP and SI.

```<code>    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'httpPostAtms' defined in class path resource [com/backbase/atm/config/InfrastructorConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.integration.dsl.IntegrationFlow]: Factory method 'httpPostAtms' threw exception; nested exception is java.lang.IllegalArgumentException: Found ambiguous parameter type [class java.lang.Object] for method match: [public default java.util.stream.Stream java.util.Collection.parallelStream(), public void java.util.Arrays$ArrayList.forEach(java.util.function.Consumer), public void java.util.Arrays$ArrayList.sort(java.util.Comparator), public boolean java.util.AbstractCollection.remove(java.lang.Object), public java.util.ListIterator java.util.AbstractList.listIterator(int), public java.lang.Object[] java.util.Arrays$ArrayList.toArray(java.lang.Object[]), public default boolean java.util.Collection.removeIf(java.util.function.Predicate), public boolean java.util.AbstractCollection.retainAll(java.util.Collection), public void java.util.Arrays$ArrayList.replaceAll(java.util.function.UnaryOperator)]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at com.backbase.atm.IngAtmApplication.main(IngAtmApplication.java:23) [classes/:na]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.integration.dsl.IntegrationFlow]: Factory method 'httpPostAtms' threw exception; nested exception is java.lang.IllegalArgumentException: Found ambiguous parameter type [class java.lang.Object] for method match: [public default java.util.stream.Stream java.util.Collection.parallelStream(), public void java.util.Arrays$ArrayList.forEach(java.util.function.Consumer), public void java.util.Arrays$ArrayList.sort(java.util.Comparator), public boolean java.util.AbstractCollection.remove(java.lang.Object), public java.util.ListIterator java.util.AbstractList.listIterator(int), public java.lang.Object[] java.util.Arrays$ArrayList.toArray(java.lang.Object[]), public default boolean java.util.Collection.removeIf(java.util.function.Predicate), public boolean java.util.AbstractCollection.retainAll(java.util.Collection), public void java.util.Arrays$ArrayList.replaceAll(java.util.function.UnaryOperator)]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    ... 18 common frames omitted
Caused by: java.lang.IllegalArgumentException: Found ambiguous parameter type [class java.lang.Object] for method match: [public default java.util.stream.Stream java.util.Collection.parallelStream(), public void java.util.Arrays$ArrayList.forEach(java.util.function.Consumer), public void java.util.Arrays$ArrayList.sort(java.util.Comparator), public boolean java.util.AbstractCollection.remove(java.lang.Object), public java.util.ListIterator java.util.AbstractList.listIterator(int), public java.lang.Object[] java.util.Arrays$ArrayList.toArray(java.lang.Object[]), public default boolean java.util.Collection.removeIf(java.util.function.Predicate), public boolean java.util.AbstractCollection.retainAll(java.util.Collection), public void java.util.Arrays$ArrayList.replaceAll(java.util.function.UnaryOperator)]
    at org.springframework.util.Assert.isNull(Assert.java:113) ~[spring-core-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.integration.util.MessagingMethodInvokerHelper.findHandlerMethodsForTarget(MessagingMethodInvokerHelper.java:499) ~[spring-integration-core-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.integration.util.MessagingMethodInvokerHelper.<init>(MessagingMethodInvokerHelper.java:226) ~[spring-integration-core-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.integration.util.MessagingMethodInvokerHelper.<init>(MessagingMethodInvokerHelper.java:149) ~[spring-integration-core-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.integration.util.MessagingMethodInvokerHelper.<init>(MessagingMethodInvokerHelper.java:144) ~[spring-integration-core-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.integration.handler.MethodInvokingMessageProcessor.<init>(MethodInvokingMessageProcessor.java:60) ~[spring-integration-core-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.integration.transformer.MethodInvokingTransformer.<init>(MethodInvokingTransformer.java:47) ~[spring-integration-core-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.integration.dsl.IntegrationFlowDefinition.transform(IntegrationFlowDefinition.java:516) ~[spring-integration-java-dsl-1.2.2.RELEASE.jar:na]
    at org.springframework.integration.dsl.IntegrationFlowDefinition.transform(IntegrationFlowDefinition.java:496) ~[spring-integration-java-dsl-1.2.2.RELEASE.jar:na]
    at org.springframework.integration.dsl.IntegrationFlowDefinition.transform(IntegrationFlowDefinition.java:483) ~[spring-integration-java-dsl-1.2.2.RELEASE.jar:na]
    at com.backbase.atm.config.InfrastructorConfig.httpPostAtms(InfrastructorConfig.java:50) ~[classes/:na]
    at com.backbase.atm.config.InfrastructorConfig$$EnhancerBySpringCGLIB$$154e5ed2.CGLIB$httpPostAtms$1(<generated>) ~[classes/:na]
    at com.backbase.atm.config.InfrastructorConfig$$EnhancerBySpringCGLIB$$154e5ed2$$FastClassBySpringCGLIB$$30080451.invoke(<generated>) ~[classes/:na]
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358) ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at com.backbase.atm.config.InfrastructorConfig$$EnhancerBySpringCGLIB$$154e5ed2.httpPostAtms(<generated>) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_45]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_45]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_45]
    at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_45]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    ... 19 common frames omitted
</code>```

my config

```<code>    package com.backbase.atm.config;

import java.util.Arrays;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.integration.annotation.IntegrationComponentScan;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.config.EnableIntegration;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.IntegrationFlows;
import org.springframework.integration.dsl.core.Pollers;
import org.springframework.integration.dsl.http.Http;
import org.springframework.integration.dsl.support.Transformers;
import org.springframework.integration.scheduling.PollerMetadata;
import org.springframework.messaging.MessageChannel;

import com.backbase.atm.model.Atm;

@IntegrationComponentScan
@Configuration
@EnableIntegration
@ComponentScan
public class InfrastructorConfig {

    @Bean
    public MessageChannel requestChannel() {
        return new DirectChannel() ;
    }

    @Bean(name = PollerMetadata.DEFAULT_POLLER)
    public PollerMetadata poller() {
        return Pollers.fixedRate(500).get();
    }

    @Bean
    public IntegrationFlow httpPostAtms() {

        return IntegrationFlows.from("requestChannel")
                .handle(Http.outboundGateway("https://www.ing.nl/api/locator/atms/")
                        .httpMethod(HttpMethod.GET)
                        .expectedResponseType(String.class))
                .<String, String>transform(p -> p.substring(5))
                .transform(Arrays.asList(Transformers.fromJson(Atm[].class)))
                .channel("responseChannel")
                .get();

    }

}
</code>```

my gateway

```<code>package com.backbase.atm.service;

import java.util.List;

import org.springframework.integration.annotation.Gateway;
import org.springframework.integration.annotation.MessagingGateway;
import org.springframework.messaging.handler.annotation.Payload;

import com.backbase.atm.model.Atm;

@MessagingGateway
public interface IntegrationService {

    @Gateway(requestChannel = "requestChannel")
    @Payload("'string'")
    List<Atm> getAllAtms();
}
</code>```

the object that I am trying to convert the payload to

```<code> package com.backbase.atm.model;

public class Atm {

    private Address address;
    String distance;
    String type;

    public Atm() {
        super();
    }

    public Atm(Address address) {
        setAddress(address);
    }

    public Atm(Address address, String distance, String type) {
        super();
        this.address = address;
        this.distance = distance;
        this.type = type;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public String getDistance() {
        return distance;
    }

    public void setDistance(String distance) {
        this.distance = distance;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Atm: address=").append(address).append(", distance=").append(distance).append(", type=")
                .append(type).append("");
        return builder.toString();
    }
}
</code>```

sample payload response

```<code>[{"address":{"street":"Molenwerf","housenumber":"20","postalcode":"1541 WR","city":"Koog aan de Zaan","geoLocation":{"lat":"52.457912","lng":"4.799866"}},"distance":0,"type":"ING"}]
</code>```

答:
You have suspicious code:

```<code>.transform(Arrays.asList(Transformers.fromJson(Atm[].class)))
</code>```

What drives you to use Arrays.asList() there?

You use Transformers.fromJson() which is just a factory and returns for you valid Transformer object. The .transform() can simply deal with that one.

Body:
I received the following error when trying to send a request to an http outbound gateway. After getting the response, I am converting the json payload to a list of objects from other posts I have read it could be a problem with the service activator or the transformer. I am still trying to get a handle on EIP and SI.

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'httpPostAtms' defined in class path resource [com/backbase/atm/config/InfrastructorConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.integration.dsl.IntegrationFlow]: Factory method 'httpPostAtms' threw exception; nested exception is java.lang.IllegalArgumentException: Found ambiguous parameter type [class java.lang.Object] for method match: [public default java.util.stream.Stream java.util.Collection.parallelStream(), public void java.util.Arrays$ArrayList.forEach(java.util.function.Consumer), public void java.util.Arrays$ArrayList.sort(java.util.Comparator), public boolean java.util.AbstractCollection.remove(java.lang.Object), public java.util.ListIterator java.util.AbstractList.listIterator(int), public java.lang.Object[] java.util.Arrays$ArrayList.toArray(java.lang.Object[]), public default boolean java.util.Collection.removeIf(java.util.function.Predicate), public boolean java.util.AbstractCollection.retainAll(java.util.Collection), public void java.util.Arrays$ArrayList.replaceAll(java.util.function.UnaryOperator)]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at com.backbase.atm.IngAtmApplication.main(IngAtmApplication.java:23) [classes/:na]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.integration.dsl.IntegrationFlow]: Factory method 'httpPostAtms' threw exception; nested exception is java.lang.IllegalArgumentException: Found ambiguous parameter type [class java.lang.Object] for method match: [public default java.util.stream.Stream java.util.Collection.parallelStream(), public void java.util.Arrays$ArrayList.forEach(java.util.function.Consumer), public void java.util.Arrays$ArrayList.sort(java.util.Comparator), public boolean java.util.AbstractCollection.remove(java.lang.Object), public java.util.ListIterator java.util.AbstractList.listIterator(int), public java.lang.Object[] java.util.Arrays$ArrayList.toArray(java.lang.Object[]), public default boolean java.util.Collection.removeIf(java.util.function.Predicate), public boolean java.util.AbstractCollection.retainAll(java.util.Collection), public void java.util.Arrays$ArrayList.replaceAll(java.util.function.UnaryOperator)]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    ... 18 common frames omitted
Caused by: java.lang.IllegalArgumentException: Found ambiguous parameter type [class java.lang.Object] for method match: [public default java.util.stream.Stream java.util.Collection.parallelStream(), public void java.util.Arrays$ArrayList.forEach(java.util.function.Consumer), public void java.util.Arrays$ArrayList.sort(java.util.Comparator), public boolean java.util.AbstractCollection.remove(java.lang.Object), public java.util.ListIterator java.util.AbstractList.listIterator(int), public java.lang.Object[] java.util.Arrays$ArrayList.toArray(java.lang.Object[]), public default boolean java.util.Collection.removeIf(java.util.function.Predicate), public boolean java.util.AbstractCollection.retainAll(java.util.Collection), public void java.util.Arrays$ArrayList.replaceAll(java.util.function.UnaryOperator)]
    at org.springframework.util.Assert.isNull(Assert.java:113) ~[spring-core-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.integration.util.MessagingMethodInvokerHelper.findHandlerMethodsForTarget(MessagingMethodInvokerHelper.java:499) ~[spring-integration-core-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.integration.util.MessagingMethodInvokerHelper.<init>(MessagingMethodInvokerHelper.java:226) ~[spring-integration-core-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.integration.util.MessagingMethodInvokerHelper.<init>(MessagingMethodInvokerHelper.java:149) ~[spring-integration-core-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.integration.util.MessagingMethodInvokerHelper.<init>(MessagingMethodInvokerHelper.java:144) ~[spring-integration-core-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.integration.handler.MethodInvokingMessageProcessor.<init>(MethodInvokingMessageProcessor.java:60) ~[spring-integration-core-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.integration.transformer.MethodInvokingTransformer.<init>(MethodInvokingTransformer.java:47) ~[spring-integration-core-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.integration.dsl.IntegrationFlowDefinition.transform(IntegrationFlowDefinition.java:516) ~[spring-integration-java-dsl-1.2.2.RELEASE.jar:na]
    at org.springframework.integration.dsl.IntegrationFlowDefinition.transform(IntegrationFlowDefinition.java:496) ~[spring-integration-java-dsl-1.2.2.RELEASE.jar:na]
    at org.springframework.integration.dsl.IntegrationFlowDefinition.transform(IntegrationFlowDefinition.java:483) ~[spring-integration-java-dsl-1.2.2.RELEASE.jar:na]
    at com.backbase.atm.config.InfrastructorConfig.httpPostAtms(InfrastructorConfig.java:50) ~[classes/:na]
    at com.backbase.atm.config.InfrastructorConfig$$EnhancerBySpringCGLIB$$154e5ed2.CGLIB$httpPostAtms$1(<generated>) ~[classes/:na]
    at com.backbase.atm.config.InfrastructorConfig$$EnhancerBySpringCGLIB$$154e5ed2$$FastClassBySpringCGLIB$$30080451.invoke(<generated>) ~[classes/:na]
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358) ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at com.backbase.atm.config.InfrastructorConfig$$EnhancerBySpringCGLIB$$154e5ed2.httpPostAtms(<generated>) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_45]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_45]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_45]
    at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_45]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    ... 19 common frames omitted

my config

    package com.backbase.atm.config;

import java.util.Arrays;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.integration.annotation.IntegrationComponentScan;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.config.EnableIntegration;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.IntegrationFlows;
import org.springframework.integration.dsl.core.Pollers;
import org.springframework.integration.dsl.http.Http;
import org.springframework.integration.dsl.support.Transformers;
import org.springframework.integration.scheduling.PollerMetadata;
import org.springframework.messaging.MessageChannel;

import com.backbase.atm.model.Atm;

@IntegrationComponentScan
@Configuration
@EnableIntegration
@ComponentScan
public class InfrastructorConfig {

    @Bean
    public MessageChannel requestChannel() {
        return new DirectChannel() ;
    }

    @Bean(name = PollerMetadata.DEFAULT_POLLER)
    public PollerMetadata poller() {
        return Pollers.fixedRate(500).get();
    }

    @Bean
    public IntegrationFlow httpPostAtms() {

        return IntegrationFlows.from("requestChannel")
                .handle(Http.outboundGateway("https://www.ing.nl/api/locator/atms/")
                        .httpMethod(HttpMethod.GET)
                        .expectedResponseType(String.class))
                .<String, String>transform(p -> p.substring(5))
                .transform(Arrays.asList(Transformers.fromJson(Atm[].class)))
                .channel("responseChannel")
                .get();

    }

}

my gateway

package com.backbase.atm.service;

import java.util.List;

import org.springframework.integration.annotation.Gateway;
import org.springframework.integration.annotation.MessagingGateway;
import org.springframework.messaging.handler.annotation.Payload;

import com.backbase.atm.model.Atm;

@MessagingGateway
public interface IntegrationService {

    @Gateway(requestChannel = "requestChannel")
    @Payload("'string'")
    List<Atm> getAllAtms();
}

the object that I am trying to convert the payload to

 package com.backbase.atm.model;

public class Atm {

    private Address address;
    String distance;
    String type;

    public Atm() {
        super();
    }

    public Atm(Address address) {
        setAddress(address);
    }

    public Atm(Address address, String distance, String type) {
        super();
        this.address = address;
        this.distance = distance;
        this.type = type;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public String getDistance() {
        return distance;
    }

    public void setDistance(String distance) {
        this.distance = distance;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Atm: address=").append(address).append(", distance=").append(distance).append(", type=")
                .append(type).append("");
        return builder.toString();
    }
}

sample payload response

[{"address":{"street":"Molenwerf","housenumber":"20","postalcode":"1541 WR","city":"Koog aan de Zaan","geoLocation":{"lat":"52.457912","lng":"4.799866"}},"distance":0,"type":"ING"}]

Body:
You have suspicious code:

.transform(Arrays.asList(Transformers.fromJson(Atm[].class)))

What drives you to use Arrays.asList() there?

You use Transformers.fromJson() which is just a factory and returns for you valid Transformer object. The .transform() can simply deal with that one.


问:
RoR : JQuery and Ajax request
I am a fan of Ruby on Rails and currently looking into tutorials
about adding AJAX to the page.
I tried this tutorial, with the source also there.
I kinda understand the code, but on my computer, after sliding the stock-list does not update and keeps on displaying the entire stock list, but clearly the values are passed around correctly, as I can check it in the controller.

I tried modifying the code and adding JRails in app/views/index.js.erb instead of

```<code>respond_to do |format|
  format.html
  format.js do
    render :update do |page|
      page.replace_html 'x_stock_list', :partial => 'stocks/stock_list', :locals => { :stocks => @stocks }
    end
</code>```

or even adding a simple alert js function into this file, but it shows it as plain text, when i force it to use that file (by deleting the 'format.html' line above).
Apparently, the javascript did not get executed.

According to a lot of tutorials by Ryan Bates (RailsCasts) , this line had to be added to
application.js:

```<code>jQuery.ajaxSetup({  'beforeSend': function(xhr)
</code>```

{xhr.setRequestHeader("Accept", "text/javascript")}})

to force javascript to get executed, but that did not help either.

Has anybody an idea or is it only on my pc that the slider does not update?

答: Move your format.html down to the last format in the list. I had this problem a while back and apparently the order matters.</p>

Title: RoR : JQuery and Ajax request

Body:
I am a fan of Ruby on Rails and currently looking into tutorials
about adding AJAX to the page.
I tried this tutorial, with the source also there.
I kinda understand the code, but on my computer, after sliding the stock-list does not update and keeps on displaying the entire stock list, but clearly the values are passed around correctly, as I can check it in the controller.

I tried modifying the code and adding JRails in app/views/index.js.erb instead of

respond_to do |format|
  format.html
  format.js do
    render :update do |page|
      page.replace_html 'x_stock_list', :partial => 'stocks/stock_list', :locals => { :stocks => @stocks }
    end

or even adding a simple alert js function into this file, but it shows it as plain text, when i force it to use that file (by deleting the 'format.html' line above).
Apparently, the javascript did not get executed.

According to a lot of tutorials by Ryan Bates (RailsCasts) , this line had to be added to
application.js:

jQuery.ajaxSetup({  'beforeSend': function(xhr)

{xhr.setRequestHeader("Accept", "text/javascript")}})

to force javascript to get executed, but that did not help either.

Has anybody an idea or is it only on my pc that the slider does not update?

ContentLicense: CC BY-SA 2.5


问:
Angular Material Default CSS Change ( md-select )
I'm interested in changing the default material blue color to say "green" in dropdown box. I am not able to find the div class responsible for this transition, any help much appreciated.

DEMO from materials Website

Changing the border-bottom-color of the underline upon touch.

Changing the border-bottom-color when the saved option is touched.

Changing the color when dropdown is populated with saved data.

I was able to change the CSS element for form labels but md-select is being a nightmare. below snipped would change all the element color to defined one without default color transition ( black to blue ).

```<code>.md-text.ng-binding{
    color: orangered;
}
</code>```

答:
Angular Material Inputs, Selects, Radio buttons and etc work on the primary theme selected. Default is blue so you see that. You can define your custom primary theme color and all inputs should start utilizing it.

Put the following index.js main config function. Make sure to inject $mdThemingProvider in the config function.

```<code>$mdThemingProvider.theme('default').primaryPalette('cyan', { 'default': '700' });
$mdThemingProvider.theme('default').accentPalette('blue-grey', { 'default': '500' });
</code>```

Body:
I'm interested in changing the default material blue color to say "green" in dropdown box. I am not able to find the div class responsible for this transition, any help much appreciated.

DEMO from materials Website

Changing the border-bottom-color of the underline upon touch.

Changing the border-bottom-color when the saved option is touched.

Changing the color when dropdown is populated with saved data.

I was able to change the CSS element for form labels but md-select is being a nightmare. below snipped would change all the element color to defined one without default color transition ( black to blue ).

.md-text.ng-binding{
    color: orangered;
}

Body:
Angular Material Inputs, Selects, Radio buttons and etc work on the primary theme selected. Default is blue so you see that. You can define your custom primary theme color and all inputs should start utilizing it.

Put the following index.js main config function. Make sure to inject $mdThemingProvider in the config function.

$mdThemingProvider.theme('default').primaryPalette('cyan', { 'default': '700' });
$mdThemingProvider.theme('default').accentPalette('blue-grey', { 'default': '500' });


问:
List of strings from split() cant convert to int()
I'm unable to get list values to have int() called upon them. The list is build from user input(), a split() and append(). Code looks like:

```<code>coords = []

fcoords = input("Enter first coordinate pair:\n")

urlat, urlon = fcoords.split()
coords.append(urlat)
coords.append(urlon)

scoords = input("Enter second coordinate pair:\n")
lllat, lllon = scoords.split()
coords.append(lllat)
coords.append(lllon)

for coord in coords:
    print (int(coord))
</code>```

Gives me a ValueError: invalid literal for int() with base 10: '-122.4444'.

I can switch the int(coord) with float(coord) but that's just extra work since I am converting decimal degree to dms. Using int() gets the base without remainder which is what I want!

Is the split() method not correct here, or are extra characters being hidden?

答: Since the literal is -122.4444, it represents a float; convert it to float first and then round to int: print(int(float(coord)))

Body:
I'm unable to get list values to have int() called upon them. The list is build from user input(), a split() and append(). Code looks like:

coords = []

fcoords = input("Enter first coordinate pair:\n")

urlat, urlon = fcoords.split()
coords.append(urlat)
coords.append(urlon)

scoords = input("Enter second coordinate pair:\n")
lllat, lllon = scoords.split()
coords.append(lllat)
coords.append(lllon)

for coord in coords:
    print (int(coord))

Gives me a ValueError: invalid literal for int() with base 10: '-122.4444'.

I can switch the int(coord) with float(coord) but that's just extra work since I am converting decimal degree to dms. Using int() gets the base without remainder which is what I want!

Is the split() method not correct here, or are extra characters being hidden?


问:
Upload my php project files to use with google cloud AppEngine
I've spent 10+ hours yesterday reading up about / testing tutorials with google cloud and how I can use them as a host for my dynamic website.

With all of the new information in my head, I'm scrambled on what to do.

I already have my Virtual Machine Instance built with an IP that links to my domain, this works fine. However, I cannot for the life of me figure out how to put my project files on there. I figured it would have been something like "upload project files", "link with appengine", "link with cloud sql", but it seems like I was wrong?

In the tutorials, I uploaded googles sample projects (tutorials) by cloning a github link in the shell.

```<code>git clone https://github.com/GoogleCloudPlatform/getting-started-php.git
</code>```

They also said a zip file could be extracted as an alternative.

Are those the only way of doing this? Should I create my own github and cone it in the shell?

Is it possible to link an AppEngine with a bucket that has my project files on there? (just throwing the question out there)

bonus question: once the files are uploaded, am I able to edit/develop through google cloud or do I need to edit changes in my files, then re-upload it to the cloud as an update?

This is my first time trying to have google (or any company) host my website, and this is completely foreign territory for me so any direction is much appreciated.

答:
there are couple things mixed up in your question. Let me try to untangle them.

You don't need to create virtual machine if you want to run your PHP powered website on App Engine. There's a great overview in this article https://cloud.google.com/appengine/docs/standard/php/an-overview-of-app-engine

The way you run your PHP website on App Engine is by deploying your code to the version, you can do it using gcloud app deploy tool from your sources on your local machine. I recommend you to start by going through tutorial on here: https://cloud.google.com/appengine/docs/standard/php/quickstart

There's currently no way to link Google Cloud Storage bucket with App Engine version, you have to deploy your code yourself using either gloud app deploy or using App Engine Admin API that gcloud is using internally.

There's no way to edit your App Engine application code in the cloud.

Body:
I've spent 10+ hours yesterday reading up about / testing tutorials with google cloud and how I can use them as a host for my dynamic website.

With all of the new information in my head, I'm scrambled on what to do.

I already have my Virtual Machine Instance built with an IP that links to my domain, this works fine. However, I cannot for the life of me figure out how to put my project files on there. I figured it would have been something like "upload project files", "link with appengine", "link with cloud sql", but it seems like I was wrong?

In the tutorials, I uploaded googles sample projects (tutorials) by cloning a github link in the shell.

git clone https://github.com/GoogleCloudPlatform/getting-started-php.git

They also said a zip file could be extracted as an alternative.

Are those the only way of doing this? Should I create my own github and cone it in the shell?

Is it possible to link an AppEngine with a bucket that has my project files on there? (just throwing the question out there)

bonus question: once the files are uploaded, am I able to edit/develop through google cloud or do I need to edit changes in my files, then re-upload it to the cloud as an update?

This is my first time trying to have google (or any company) host my website, and this is completely foreign territory for me so any direction is much appreciated.


问:
How to factorize selected columns in pandas
I want to implement a function that automatically assigns a numeric value to an object.
Here is my code:

```<code>column_list = ['datum', 'parameter_name', 'sample_duration', 'pollutant_standard', 'units_of_measure']
def gnumeric_func(data, columns):
    data[columns] = pd.factorize(data.columns)[0]

data = pd.DataFrame(data, column_list)
gnumeric_func(data, column_list)
</code>```

What's wrong?

答:
Use:

```<code>def gnumeric_func (data, columns):
  data[columns] = data[columns].apply(lambda x: pd.factorize(x)[0])
  return data
</code>```

For all columns:

```<code>def gnumeric_func (data):
  data = data.apply(lambda x: pd.factorize(x)[0])
  return data
</code>```

Body:
I want to implement a function that automatically assigns a numeric value to an object.
Here is my code:

column_list = ['datum', 'parameter_name', 'sample_duration', 'pollutant_standard', 'units_of_measure']
def gnumeric_func(data, columns):
    data[columns] = pd.factorize(data.columns)[0]

data = pd.DataFrame(data, column_list)
gnumeric_func(data, column_list)

What's wrong?

Body:
Use:

def gnumeric_func (data, columns):
  data[columns] = data[columns].apply(lambda x: pd.factorize(x)[0])
  return data

For all columns:

def gnumeric_func (data):
  data = data.apply(lambda x: pd.factorize(x)[0])
  return data


问:
How to solve this JNA issue?
I have application which use JNA and gets the audio and video. It works in my Linux box. But when i am testing it in Windows. It just never working. Because i am still learning, i will appreciate your suggestion how to fix it, i already spent few days and weeks only to work it out, but just dont get this why JAVA does not work simply, its a cross platform. Why should it require again System path or etc configuration.

I am totally lost now, why it works in Linux and it does not work in Windows XP ? How can i run it then ?

```<code>Inside the lib direcotry i have my JNA and Audio libraries.
C:\Documents and Settings\test\Desktop\test>dir
 Volume in drive C has no label.
 Volume Serial Number is 680F-0963

 Directory of C:\Documents and Settings\test\Desktop\test

19/12/2010  22:09    <DIR>          .
19/12/2010  22:09    <DIR>          ..
19/12/2010  22:09            51.791 Audio.jar
19/12/2010  22:09    <DIR>          lib
               1 File(s)         51.791 bytes
               3 Dir(s)     487.002.112 bytes free

Now trying to run Audio.jar, gets Fail 1:

C:\Documents and Settings\test\Desktop\test>java -Djava.library.path=~/jni -jar
Audio.jar
Exception in thread "main" java.lang.UnsatisfiedLinkError: Could not load librar
y gstreamer-0.10
        at org.gstreamer.lowlevel.GNative.loadWin32Library(GNative.java:83)
        at org.gstreamer.lowlevel.GNative.loadLibrary(GNative.java:43)
        at org.gstreamer.lowlevel.GstNative.load(GstNative.java:42)
        at org.gstreamer.lowlevel.GstNative.load(GstNative.java:39)
        at org.gstreamer.Gst.<clinit>(Gst.java:59)
        at video.MyVideo.simpletest(MyVideo.java:31)
        at sipphone.MainApplet.run(MainApplet.java:58)
        at sipphone.MainApplet.main(MainApplet.java:43)

Fail 2:
C:\Documents and Settings\test\Desktop\test>java -Djna.library.path=. -jar Audio
.jar
Exception in thread "main" java.lang.UnsatisfiedLinkError: Could not load librar
y gstreamer-0.10
        at org.gstreamer.lowlevel.GNative.loadWin32Library(GNative.java:83)
        at org.gstreamer.lowlevel.GNative.loadLibrary(GNative.java:43)
        at org.gstreamer.lowlevel.GstNative.load(GstNative.java:42)
        at org.gstreamer.lowlevel.GstNative.load(GstNative.java:39)
        at org.gstreamer.Gst.<clinit>(Gst.java:59)
        at video.MyVideo.simpletest(MyVideo.java:31)
        at sipphone.MainApplet.run(MainApplet.java:58)
        at sipphone.MainApplet.main(MainApplet.java:43)
</code>```

答:
You'll need to have the DLL installed, or at least in your JNA library path as others have pointed out.

It does add an extra dependency on Windows. It would be an extra dependency on Linux but gstreamer is preinstalled by your distribution. I ran into this same problem when I was making something to use a USB port from Java.

The only solution I know of to avoid the DLL would be to have a second version of the code you could call on Windows that would only use Win32 stuff (i.e. stuff that ships with Windows) but that would be a very large undertaking.

Title: How to solve this JNA issue?

Body:
I have application which use JNA and gets the audio and video. It works in my Linux box. But when i am testing it in Windows. It just never working. Because i am still learning, i will appreciate your suggestion how to fix it, i already spent few days and weeks only to work it out, but just dont get this why JAVA does not work simply, its a cross platform. Why should it require again System path or etc configuration.

I am totally lost now, why it works in Linux and it does not work in Windows XP ? How can i run it then ?

Inside the lib direcotry i have my JNA and Audio libraries.
C:\Documents and Settings\test\Desktop\test>dir
 Volume in drive C has no label.
 Volume Serial Number is 680F-0963

 Directory of C:\Documents and Settings\test\Desktop\test

19/12/2010  22:09    <DIR>          .
19/12/2010  22:09    <DIR>          ..
19/12/2010  22:09            51.791 Audio.jar
19/12/2010  22:09    <DIR>          lib
               1 File(s)         51.791 bytes
               3 Dir(s)     487.002.112 bytes free

Now trying to run Audio.jar, gets Fail 1:

C:\Documents and Settings\test\Desktop\test>java -Djava.library.path=~/jni -jar
Audio.jar
Exception in thread "main" java.lang.UnsatisfiedLinkError: Could not load librar
y gstreamer-0.10
        at org.gstreamer.lowlevel.GNative.loadWin32Library(GNative.java:83)
        at org.gstreamer.lowlevel.GNative.loadLibrary(GNative.java:43)
        at org.gstreamer.lowlevel.GstNative.load(GstNative.java:42)
        at org.gstreamer.lowlevel.GstNative.load(GstNative.java:39)
        at org.gstreamer.Gst.<clinit>(Gst.java:59)
        at video.MyVideo.simpletest(MyVideo.java:31)
        at sipphone.MainApplet.run(MainApplet.java:58)
        at sipphone.MainApplet.main(MainApplet.java:43)

Fail 2:
C:\Documents and Settings\test\Desktop\test>java -Djna.library.path=. -jar Audio
.jar
Exception in thread "main" java.lang.UnsatisfiedLinkError: Could not load librar
y gstreamer-0.10
        at org.gstreamer.lowlevel.GNative.loadWin32Library(GNative.java:83)
        at org.gstreamer.lowlevel.GNative.loadLibrary(GNative.java:43)
        at org.gstreamer.lowlevel.GstNative.load(GstNative.java:42)
        at org.gstreamer.lowlevel.GstNative.load(GstNative.java:39)
        at org.gstreamer.Gst.<clinit>(Gst.java:59)
        at video.MyVideo.simpletest(MyVideo.java:31)
        at sipphone.MainApplet.run(MainApplet.java:58)
        at sipphone.MainApplet.main(MainApplet.java:43)


问:
Comparing Files in 2 directories
I have this code that tell me if the 2 files have the same content. However, I want to expand this to not just one file but to directory Files. In other words, compare files in one folder to files in another to see if they have same or different contents and if so print it out.

In doing this is it just a matter of modifying the directory paths? My code is below. I think I remember reading somewhere that I may need import another library. Any help would be appreciated.

Problem now I am having is printing out the file name from the area that are the same and that are not the same I tried .getName it is not working my result come back (true) (instead of the names of the files that meet the condition

Code below

```<code>import java.io.File;

public class F2FCompare {

 public static void main(String[] args)
    {
     File folderA = new File("C:/Users/hoflerj/Desktop/FolderA");
     File[] listOfFilesInA = folderA.listFiles();

     File folderB = new File("/C:/Users/hoflerj/Desktop/FolderB");
     File[] listOfFilesInB = folderB.listFiles();

     for (File fileA : listOfFilesInA){
         if (fileA.isFile())
         {
             for (File fileB : listOfFilesInB) {
                  if(fileB.isFile())
                    {
                      if ( fileA.equals(fileB))
                      {
                          System.out.println( "FolderA same as FolderB" + listOfFilesInA.equals(listOfFilesInB) );
                          //File[] files = folder.listFiles();
                      }

                     // txtfile.getName()
                      else
                      {
                          //System.out.println(! fileA.getName().equals(fileB) + "    Folder A diff B" );
                          System.out.println( "Folder same as FolderB  " + !fileA.getName().equals(fileB) );
                      }

                    }
                }
            }
        }
    }
}
</code>```

答:
This code will iterate over every file in folder A and compare it to every file in folder B.

```<code>File folderA = new File("/Users/you/folderA/");
File[] listOfFilesInA = folderA.listFiles();
File folderB = new File("/Users/you/folderB/");
File[] listOfFilesInB = folderB.listFiles();
for (File fileA : listOfFilesInA) {
    if (fileA.isFile())
    {
        for (File fileB : listOfFilesInB) {
             if(fileB.isFile())
             {
                //your code
             }
         }
    }
}
</code>```

Credits to David Robles: https://stackoverflow.com/a/1844695/4788664

Title: Comparing Files in 2 directories

Body:
I have this code that tell me if the 2 files have the same content. However, I want to expand this to not just one file but to directory Files. In other words, compare files in one folder to files in another to see if they have same or different contents and if so print it out.

In doing this is it just a matter of modifying the directory paths? My code is below. I think I remember reading somewhere that I may need import another library. Any help would be appreciated.

Problem now I am having is printing out the file name from the area that are the same and that are not the same I tried .getName it is not working my result come back (true) (instead of the names of the files that meet the condition

Code below

import java.io.File;

public class F2FCompare {

 public static void main(String[] args)
    {
     File folderA = new File("C:/Users/hoflerj/Desktop/FolderA");
     File[] listOfFilesInA = folderA.listFiles();

     File folderB = new File("/C:/Users/hoflerj/Desktop/FolderB");
     File[] listOfFilesInB = folderB.listFiles();

     for (File fileA : listOfFilesInA){
         if (fileA.isFile())
         {
             for (File fileB : listOfFilesInB) {
                  if(fileB.isFile())
                    {
                      if ( fileA.equals(fileB))
                      {
                          System.out.println( "FolderA same as FolderB" + listOfFilesInA.equals(listOfFilesInB) );
                          //File[] files = folder.listFiles();
                      }

                     // txtfile.getName()
                      else
                      {
                          //System.out.println(! fileA.getName().equals(fileB) + "    Folder A diff B" );
                          System.out.println( "Folder same as FolderB  " + !fileA.getName().equals(fileB) );
                      }

                    }
                }
            }
        }
    }
}

Body:
This code will iterate over every file in folder A and compare it to every file in folder B.

File folderA = new File("/Users/you/folderA/");
File[] listOfFilesInA = folderA.listFiles();
File folderB = new File("/Users/you/folderB/");
File[] listOfFilesInB = folderB.listFiles();
for (File fileA : listOfFilesInA) {
    if (fileA.isFile())
    {
        for (File fileB : listOfFilesInB) {
             if(fileB.isFile())
             {
                //your code
             }
         }
    }
}

Credits to David Robles: https://stackoverflow.com/a/1844695/4788664


答:
'-122.4444'  is not an int, so you can't parse it as int.

If you don't want to use float(coord) you could do:

```<code>print (int(coord.split('.')[0]))
</code>```

This will ignore the decimal part of your number and take only the integer part

Title: List of strings from split() cant convert to int()

Body:
'-122.4444'  is not an int, so you can't parse it as int.

If you don't want to use float(coord) you could do:

print (int(coord.split('.')[0]))

This will ignore the decimal part of your number and take only the integer part


问:
How to unwrapped dictionary optional value?
typealias of dictionary  key with optional value

```<code>typealias JSON = [String:Any?]
</code>```

And here is my dictionary

```<code>    var createAfterStr: String? = nil
    var createBeforeStr: String? = nil

    if let createdAfter = statesByScope.createdAfter, let afterStr = toString(date: createdAfter) {
        createAfterStr = afterStr
    }
    if let createdBefore = statesByScope.createdBefore, let beforeStr = toString(date: createdBefore) {
        createBeforeStr = beforeStr
    }

 let params:  JSON  = [
            "scope_id": statesByScope.scopeId,
            "createdAfter" : createAfterStr ?? nil,
            "createdBefore" : createBeforeStr ?? nil,
            "limit" : "4"]
</code>```

and when i send it with as a parameter curl request . i seem url make :

```<code> var request = URLRequest(baseUrl: baseUrl, path: path, method: method, params: params)
     request.setValue(token, forHTTPHeaderField: "Authorization")
 var urlrequst : URLRequest?
        do{
            urlrequst =  try  Alamofire.JSONEncoding.default.encode(request, with: params)
        }catch let error {
           completion(nil, ServiceError.custom(String(describing: error)))
        }
          print(urlrequst)
</code>```

https://www.demo.life/post?limit=Optional(%224%22)&createdBefore=nil&scope_id=Optional(%22a409f4c8-d62b-4e03-ae62-4aa17d8c74fa%22)&createdAfter=nil

it is really wired part with Optional.

so how  to unwrapped
dictionally optional value? or  do i miss anything?  thanks

答:
Don't do that. A JSON dictionary has never optional values.

Create params with the distinct non-optional values and then add the key / value pairs which can be nil.
If createAfterStr or createBeforeStr are nil the key will be skipped.

```<code>typealias JSON = [String:Any]

var params: JSON = ["scope_id": statesByScope.scopeId, "limit" : "4"]
params["createdAfter"] = createAfterStr
params["createdBefore"] = createBeforeStr
</code>```

Body:
typealias of dictionary  key with optional value

typealias JSON = [String:Any?]

And here is my dictionary

    var createAfterStr: String? = nil
    var createBeforeStr: String? = nil

    if let createdAfter = statesByScope.createdAfter, let afterStr = toString(date: createdAfter) {
        createAfterStr = afterStr
    }
    if let createdBefore = statesByScope.createdBefore, let beforeStr = toString(date: createdBefore) {
        createBeforeStr = beforeStr
    }

 let params:  JSON  = [
            "scope_id": statesByScope.scopeId,
            "createdAfter" : createAfterStr ?? nil,
            "createdBefore" : createBeforeStr ?? nil,
            "limit" : "4"]

and when i send it with as a parameter curl request . i seem url make :

 var request = URLRequest(baseUrl: baseUrl, path: path, method: method, params: params)
     request.setValue(token, forHTTPHeaderField: "Authorization")
 var urlrequst : URLRequest?
        do{
            urlrequst =  try  Alamofire.JSONEncoding.default.encode(request, with: params)
        }catch let error {
           completion(nil, ServiceError.custom(String(describing: error)))
        }
          print(urlrequst)

https://www.demo.life/post?limit=Optional(%224%22)&createdBefore=nil&scope_id=Optional(%22a409f4c8-d62b-4e03-ae62-4aa17d8c74fa%22)&createdAfter=nil

it is really wired part with Optional.

so how  to unwrapped
dictionally optional value? or  do i miss anything?  thanks

Body:
Don't do that. A JSON dictionary has never optional values.

Create params with the distinct non-optional values and then add the key / value pairs which can be nil.
If createAfterStr or createBeforeStr are nil the key will be skipped.

typealias JSON = [String:Any]

var params: JSON = ["scope_id": statesByScope.scopeId, "limit" : "4"]
params["createdAfter"] = createAfterStr
params["createdBefore"] = createBeforeStr