问:
Xamarin.Forms+Prism Navigation target control
I have a Xamarin app made up of several page types. I'm using Prism.

I'd like the navigation target of the app to be a nested view in the app within the main page, not the main page itself, so that the MainPage is used as an outer frame that's always there, and a nested page hosts the app's navigation service.

In this way I can have some controls (i.e. back/forward/home) always present.
How do I configure the NavigationService's 'MainPage' to be a nested page within the actual MainPage?

I'm pretty new to XF, and haven't used the NavigationPage before, but could it be of any use here?

答:
Prism's INavigationService isn't designed to do what you're looking to do. Luckily custom Views are! You could do as previously suggested, but I would generally avoid creating a custom page, and instead create a custom View which would have it's own content property.

EDIT:

The terminology can get particularly confusing with Xamarin Forms, especially if you are new to MVVM and Xamarin Forms, and/or have moved from developing on other platforms.

What Xamarin Forms refers to as a View is more often referred to as a Control on other platforms. This is especially confusing when working with an MVVM framework such as Prism, because our MVVM Views are actually Xamarin Forms Pages.

While from time to time we need to create a custom type of Page, more often than not, we are just implementing some page type. For instance say I have a page that I am going to use for a Login Page:

LoginPage.xaml

```<code><?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             Title="{Binding Title}"
             x:Class="MyAwesomeApp.Views.LoginPage">

    <Grid BackgroundColor="{DynamicResource primary}">
        <Grid.RowDefinitions>
            <RowDefinition Height="1*" />
            <RowDefinition Height="3*" />
            <RowDefinition Height="1*" />
        </Grid.RowDefinitions>
        <Grid.Resources>
            <ResourceDictionary>
                <Style TargetType="StackLayout">
                    <Setter Property="BackgroundColor" Value="White" />
                    <Setter Property="VerticalOptions" Value="FillAndExpand" />
                </Style>
                <Style TargetType="Entry">
                    <Setter Property="Margin" Value="40,10" />
                </Style>
                <Style TargetType="Button">
                    <Setter Property="Margin" Value="20" />
                    <Setter Property="BackgroundColor" Value="{DynamicResource primaryDark}" />
                    <Setter Property="TextColor" Value="White" />
                    <Setter Property="BorderRadius" Value="5" />
                    <Setter Property="BorderWidth" Value="1" />
                    <Setter Property="BorderColor" Value="Black" />
                </Style>
            </ResourceDictionary>
        </Grid.Resources>

        <Image Source="logo.png"
               Aspect="AspectFit"
               HorizontalOptions="Center"
               VerticalOptions="Center" />

        <StackLayout Grid.Row="1">
            <Entry Text="{Binding UserName}"
                   Placeholder="Enter your username"
                   x:Name="userNameEntry"
                   VerticalOptions="EndAndExpand" />
            <Entry Text="{Binding Password}"
                   Placeholder="Enter your password"
                   IsPassword="True"
                   x:Name="passwordEntry"
                   VerticalOptions="StartAndExpand" />
            <Button Text="Submit"
                    Command="{Binding LoginCommand}" />
        </StackLayout>

    </Grid>

</ContentPage>
</code>```

LoginPage.xaml.cs

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

While there is a lot going on in the XAML, this is just simply a page that is a ContentPage. It is NOT by any Means a Custom Page. You'll notice there is absolutely nothing in the code behind here. I might create some event handlers for instance if the user hits the Done/Enter on the keyboard that they go to the next field or it invokes a button click, but that still does not make this a Custom Page.

For an example of a "Custom Page" you can check out the XLabs ExtendedTabbedPage. One thing you'll notice is there there are several new properties on their version of the TabbedPage. Of course their page only works because of the renderer

Sticking with the example I already showed, let's say we wanted to take the Login Layout that I created in my page and wanted to be able to reuse it across projects, or perhaps on different pages of my App. Then I would want to do something like:

LoginView.xaml

```<code><?xml version="1.0" encoding="UTF-8"?>
<Grid xmlns="http://xamarin.com/schemas/2014/forms"
      xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
      BackgroundColor="{DynamicResource primary}"
      x:Name="grid"
      x:Class="MyAwesomeApp.Controls.LoginView">

    <Grid.RowDefinitions>
        <RowDefinition Height="1*" />
        <RowDefinition Height="3*" />
        <RowDefinition Height="1*" />
    </Grid.RowDefinitions>
    <Grid.Resources>
        <ResourceDictionary>
            <Style TargetType="StackLayout">
                <Setter Property="BackgroundColor" Value="White" />
                <Setter Property="VerticalOptions" Value="FillAndExpand" />
            </Style>
            <Style TargetType="Entry">
                <Setter Property="Margin" Value="40,10" />
            </Style>
            <Style TargetType="Button">
                <Setter Property="Margin" Value="20" />
                <Setter Property="BackgroundColor" Value="{DynamicResource primaryDark}" />
                <Setter Property="TextColor" Value="White" />
                <Setter Property="BorderRadius" Value="5" />
                <Setter Property="BorderWidth" Value="1" />
                <Setter Property="BorderColor" Value="Black" />
            </Style>
        </ResourceDictionary>
    </Grid.Resources>

    <Image Source="logo.png"
           Aspect="AspectFit"
           HorizontalOptions="Center"
           VerticalOptions="Center" />

    <StackLayout Grid.Row="1" BindingContext="{x:Reference grid}">
        <Entry Text="{Binding UserName}"
               Placeholder="Enter your username"
               x:Name="userNameEntry"
               VerticalOptions="EndAndExpand" />
        <Entry Text="{Binding Password}"
               Placeholder="Enter your password"
               IsPassword="True"
               x:Name="passwordEntry"
               VerticalOptions="StartAndExpand" />
        <Button Text="Submit"
                Command="{Binding LoginCommand}" />
    </StackLayout>

</Grid>
</code>```

LoginView.xaml.cs

```<code>public partial class LoginView : Grid
{
    public static readonly BindableProperty UserNameProperty =
        BindableProperty.Create(nameof(UserName), typeof(string), typeof(LoginView), string.Empty);

    public static readonly BindableProperty PasswordProperty =
        BindableProperty.Create(nameof(Password), typeof(string), typeof(LoginView), string.Empty);

    public static readonly BindableProperty LoginCommandProperty =
        BindableProperty.Create(nameof(LoginCommand), typeof(ICommand), typeof(LoginView), null);

    public LoginView()
    {
        InitializeComponent();
    }

    public string UserName
    {
        get { return (string)GetValue(UserNameProperty); }
        set { SetValue(UserNameProperty,value); }
    }

    public string Password
    {
        get { return (string)GetValue(PasswordProperty); }
        set { SetValue(PasswordProperty, value); }
    }

    public ICommand LoginCommand
    {
        get { return (ICommand)GetValue(LoginCommandProperty); }
        set { SetValue(LoginCommandProperty, value); }
    }
}
</code>```

Refractored LoginPage.xaml

```<code><?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:controls="clr-namespace:MyAwesomeApp.Controls"
             Title="{Binding Title}"
             x:Class="MyAwesomeApp.Views.LoginPage">

        <controls:LoginView UserName="{Binding UserName}"
                            Password="{Binding Password}"
                            LoginCommand="{Binding LoginCommand}" />
</ContentPage>
</code>```

What you would end up with for a LoginView would in fact be a custom control. While it might be deriving from a Grid, you generally don't care about how I decided to create the layout... You only care that I am giving you some control that has UserName and Password properties you can attach to and some LoginCommand that can execute. It is that inherent difference that in fact makes it a Custom View.

Body:
Prism's INavigationService isn't designed to do what you're looking to do. Luckily custom Views are! You could do as previously suggested, but I would generally avoid creating a custom page, and instead create a custom View which would have it's own content property.

EDIT:

The terminology can get particularly confusing with Xamarin Forms, especially if you are new to MVVM and Xamarin Forms, and/or have moved from developing on other platforms.

What Xamarin Forms refers to as a View is more often referred to as a Control on other platforms. This is especially confusing when working with an MVVM framework such as Prism, because our MVVM Views are actually Xamarin Forms Pages.

While from time to time we need to create a custom type of Page, more often than not, we are just implementing some page type. For instance say I have a page that I am going to use for a Login Page:

LoginPage.xaml

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             Title="{Binding Title}"
             x:Class="MyAwesomeApp.Views.LoginPage">

    <Grid BackgroundColor="{DynamicResource primary}">
        <Grid.RowDefinitions>
            <RowDefinition Height="1*" />
            <RowDefinition Height="3*" />
            <RowDefinition Height="1*" />
        </Grid.RowDefinitions>
        <Grid.Resources>
            <ResourceDictionary>
                <Style TargetType="StackLayout">
                    <Setter Property="BackgroundColor" Value="White" />
                    <Setter Property="VerticalOptions" Value="FillAndExpand" />
                </Style>
                <Style TargetType="Entry">
                    <Setter Property="Margin" Value="40,10" />
                </Style>
                <Style TargetType="Button">
                    <Setter Property="Margin" Value="20" />
                    <Setter Property="BackgroundColor" Value="{DynamicResource primaryDark}" />
                    <Setter Property="TextColor" Value="White" />
                    <Setter Property="BorderRadius" Value="5" />
                    <Setter Property="BorderWidth" Value="1" />
                    <Setter Property="BorderColor" Value="Black" />
                </Style>
            </ResourceDictionary>
        </Grid.Resources>

        <Image Source="logo.png"
               Aspect="AspectFit"
               HorizontalOptions="Center"
               VerticalOptions="Center" />

        <StackLayout Grid.Row="1">
            <Entry Text="{Binding UserName}"
                   Placeholder="Enter your username"
                   x:Name="userNameEntry"
                   VerticalOptions="EndAndExpand" />
            <Entry Text="{Binding Password}"
                   Placeholder="Enter your password"
                   IsPassword="True"
                   x:Name="passwordEntry"
                   VerticalOptions="StartAndExpand" />
            <Button Text="Submit"
                    Command="{Binding LoginCommand}" />
        </StackLayout>

    </Grid>

</ContentPage>

LoginPage.xaml.cs

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

While there is a lot going on in the XAML, this is just simply a page that is a ContentPage. It is NOT by any Means a Custom Page. You'll notice there is absolutely nothing in the code behind here. I might create some event handlers for instance if the user hits the Done/Enter on the keyboard that they go to the next field or it invokes a button click, but that still does not make this a Custom Page.

For an example of a "Custom Page" you can check out the XLabs ExtendedTabbedPage. One thing you'll notice is there there are several new properties on their version of the TabbedPage. Of course their page only works because of the renderer

Sticking with the example I already showed, let's say we wanted to take the Login Layout that I created in my page and wanted to be able to reuse it across projects, or perhaps on different pages of my App. Then I would want to do something like:

LoginView.xaml

<?xml version="1.0" encoding="UTF-8"?>
<Grid xmlns="http://xamarin.com/schemas/2014/forms"
      xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
      BackgroundColor="{DynamicResource primary}"
      x:Name="grid"
      x:Class="MyAwesomeApp.Controls.LoginView">

    <Grid.RowDefinitions>
        <RowDefinition Height="1*" />
        <RowDefinition Height="3*" />
        <RowDefinition Height="1*" />
    </Grid.RowDefinitions>
    <Grid.Resources>
        <ResourceDictionary>
            <Style TargetType="StackLayout">
                <Setter Property="BackgroundColor" Value="White" />
                <Setter Property="VerticalOptions" Value="FillAndExpand" />
            </Style>
            <Style TargetType="Entry">
                <Setter Property="Margin" Value="40,10" />
            </Style>
            <Style TargetType="Button">
                <Setter Property="Margin" Value="20" />
                <Setter Property="BackgroundColor" Value="{DynamicResource primaryDark}" />
                <Setter Property="TextColor" Value="White" />
                <Setter Property="BorderRadius" Value="5" />
                <Setter Property="BorderWidth" Value="1" />
                <Setter Property="BorderColor" Value="Black" />
            </Style>
        </ResourceDictionary>
    </Grid.Resources>

    <Image Source="logo.png"
           Aspect="AspectFit"
           HorizontalOptions="Center"
           VerticalOptions="Center" />

    <StackLayout Grid.Row="1" BindingContext="{x:Reference grid}">
        <Entry Text="{Binding UserName}"
               Placeholder="Enter your username"
               x:Name="userNameEntry"
               VerticalOptions="EndAndExpand" />
        <Entry Text="{Binding Password}"
               Placeholder="Enter your password"
               IsPassword="True"
               x:Name="passwordEntry"
               VerticalOptions="StartAndExpand" />
        <Button Text="Submit"
                Command="{Binding LoginCommand}" />
    </StackLayout>

</Grid>

LoginView.xaml.cs

public partial class LoginView : Grid
{
    public static readonly BindableProperty UserNameProperty =
        BindableProperty.Create(nameof(UserName), typeof(string), typeof(LoginView), string.Empty);

    public static readonly BindableProperty PasswordProperty =
        BindableProperty.Create(nameof(Password), typeof(string), typeof(LoginView), string.Empty);

    public static readonly BindableProperty LoginCommandProperty =
        BindableProperty.Create(nameof(LoginCommand), typeof(ICommand), typeof(LoginView), null);

    public LoginView()
    {
        InitializeComponent();
    }

    public string UserName
    {
        get { return (string)GetValue(UserNameProperty); }
        set { SetValue(UserNameProperty,value); }
    }

    public string Password
    {
        get { return (string)GetValue(PasswordProperty); }
        set { SetValue(PasswordProperty, value); }
    }

    public ICommand LoginCommand
    {
        get { return (ICommand)GetValue(LoginCommandProperty); }
        set { SetValue(LoginCommandProperty, value); }
    }
}

Refractored LoginPage.xaml

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:controls="clr-namespace:MyAwesomeApp.Controls"
             Title="{Binding Title}"
             x:Class="MyAwesomeApp.Views.LoginPage">

        <controls:LoginView UserName="{Binding UserName}"
                            Password="{Binding Password}"
                            LoginCommand="{Binding LoginCommand}" />
</ContentPage>

What you would end up with for a LoginView would in fact be a custom control. While it might be deriving from a Grid, you generally don't care about how I decided to create the layout... You only care that I am giving you some control that has UserName and Password properties you can attach to and some LoginCommand that can execute. It is that inherent difference that in fact makes it a Custom View.


来源: stackexchange

问:
Temporary property for Laravel Eloquent model
I have a Laravel Eloquent model User, which has a table with username and email columns. I need to add a property for the model on runtime, something like $user->secure. This property doesn't need to go to database.

When i add this property and hit $user->save() i get an error saying i don't have database column 'secure'. I can unset 'secure' before save but somehow it feels there should be a better way to do so. Any suggestions?

答:
If you intend to make use of that add-on property, then $append will blow your mind.

http://laraveldaily.com/why-use-appends-with-accessors-in-eloquent/

ContentLicense: CC BY-SA 3.0


问:
How to display actual window size (width and height) automatically?
I have a simple code, which by clicking shows the actual size of window (width and height) but I want to do this without clicking, for example when I change the size of window i want to changed the size automatically and displayed.
thanks.</p>

```<code><!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">show the window size</button>
<p id="demo"></p>
<script>
function myFunction() {
    var w = window.innerWidth;
    var h = window.innerHeight;
    document.getElementById("demo").innerHTML = "Width: " + w + "<br>Height: " + h;
}
</script>
</body>
</html>
</code>```

答:
You can try this

```<code>window.addEventListener('resize',myFunction)
</code>```

DEMO

Body:
I have a simple code, which by clicking shows the actual size of window (width and height) but I want to do this without clicking, for example when I change the size of window i want to changed the size automatically and displayed.
thanks.

<!DOCTYPE html>

<button onclick="myFunction()">show the window size</button>

Body:
You can try this

window.addEventListener('resize',myFunction)

DEMO


问:
Is there a JSON equivalent of XQuery/XPath?
When searching for items in complex JSON arrays and hashes, like:

```<code>[
    { "id": 1, "name": "One", "objects": [
        { "id": 1, "name": "Response 1", "objects": [
            // etc.
        }]
    }
]
</code>```

Is there some kind of query language I can used to find an item in [0].objects where id = 3?

答:
Try this out - https://github.com/satyapaul/jpath/blob/master/JSONDataReader.java

It's a very simple implementation on similar line of xpath for xml. It's names as jpath.

Body:
When searching for items in complex JSON arrays and hashes, like:

[
    { "id": 1, "name": "One", "objects": [
        { "id": 1, "name": "Response 1", "objects": [
            // etc.
        }]
    }
]

Is there some kind of query language I can used to find an item in [0].objects where id = 3?


问:
Android suspend mode
What mechanism let the (OS) daemons know that the phone enters the sleep/suspend mode in Android?

Does the init process (which is the parent of all daemons) send a kill signal when the phone switch to suspend mode?

答: This is controlled through wake locks.  There isn't something deciding when to put the CPU to sleep; apps hold a wake lock to prevent it from going to sleep.  If there are no wake locks being held, the CPU goes to sleep and will not come back out of sleep until an external event (button press, network activity, alarm) wakes it up.</p>

ContentLicense: CC BY-SA 2.5

Title: Android suspend mode


问:
Java Sockets. Server-Client communication
I am trying to connect a client with gui with a server withoout gui. Connection is being done, but i cant see any messages between these two apps.
(i should get SERVER HERE in client, and CLIENT HERE in server)

Client Connection Code:

```<code>@Override
public void ClientRunning(){
    try {
       connectToServer();
        setStreams();
        ClientRun();

    }catch(EOFException oefException){
        showMessage("\n Client terminated the connection\n");
    }catch(IOException ioException){
        ioException.printStackTrace();
    }finally{
        close();
    }
}

public void connectToServer() throws IOException{
    showMessage("Attempting Connection... \n");
    connection = new Socket(InetAddress.getByName(serverIP),6789);
    showMessage("Connected to: "+ connection.getInetAddress().getHostName());
}

public void setStreams() throws IOException{
   output = new PrintWriter(connection.getOutputStream(),true);
   output.flush();
   input= new BufferedReader(new InputStreamReader(connection.getInputStream()));

    showMessage("\n Streams are now set. \n");
}

public void close(){
    showMessage("\n closing...");
    try{
      output.close();
      input.close();
      connection.close();

    }catch(IOException ioException){
        ioException.printStackTrace();
    }
}
public void showMessage(final String text){
    SwingUtilities.invokeLater(new Runnable(){
        public void run(){
            cwindow.append(text);
        }
    });
}

public void sendMessage(String message){
    output.write("CLIENT - "+message);
    output.flush();
    showMessage("\nCLIENT - "+message);
}

private void ClientRun() throws IOException{
    String message="CLIENT HERE!";
    sendMessage(message);
    do{
        try{
            message=input.readLine();
            showMessage("\n"+message);
        }catch(EOFException eofException){
                showMessage("\n Server ended the connection!");
    }

    }while(message!="EXIT");
    }
</code>```

(input and output are defined in GUI class in which this Client class is extended to. Defined as "protected BufferedReader input;
protected PrintWriter output;")

Also, servers code:

```<code>public class ServerClass {

private ServerSocket server;
private Socket connection;
private BufferedReader input;
private BufferedWriter output;

public void startServer(){
    try{
        server=new ServerSocket(6789,100);
        while(true){
            try{
                waitForConnection();
                setStreams();
                ServerRunning();
            }catch(EOFException eofException){
                showMessage("\n Server ended the connection!");

            }finally{
            close();

        }
        }

    }catch(IOException ioException){
        ioException.printStackTrace();
    }
}

private void waitForConnection() throws IOException{
    showMessage("Waiting for someone to connect... \n");
    connection=server.accept();
    showMessage("Now connected to "+ connection.getInetAddress().getHostName());
}

private void setStreams() throws IOException{
   output = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
   output.flush();
   input= new BufferedReader(new InputStreamReader(connection.getInputStream()));

    showMessage("\n Streams are now set. \n");
}
public void ServerRunning() throws IOException{
    String message="SERVER HERE!";
    sendMessage(message);
    do{
        try{

            message=input.readLine();
            showMessage("\n"+message);
        }catch(EOFException eofException){
                showMessage("\n Server ended the connection!");
    }

    }while(message!="EXIT");

  }
private void close(){
    showMessage("\n Closing connections... \n");
    try{
        output.close();
        input.close();
        connection.close();

}catch(IOException ioException){
    ioException.printStackTrace();
}
}
private void showMessage(String text){
    System.out.println(text);
}

private void sendMessage(String message){
    try{
       output.write("SERVER - "+message);
        output.flush();
        showMessage(message);
    }catch(IOException ioException){
        System.out.println("\n ERROR!");
    }
}
</code>```

Connection seems to be ok, so i don't get whats wrong. Any help would be appreciated.

PS: i also tried PrintWriter in server as well and also tried a try catch in stream statement, the problem remains.

答: You're using readLine() which expects a newline character. either add a \n to the messages you are sending or don't use readLine().

Body:
I am trying to connect a client with gui with a server withoout gui. Connection is being done, but i cant see any messages between these two apps.
(i should get SERVER HERE in client, and CLIENT HERE in server)

Client Connection Code:

@Override
public void ClientRunning(){
    try {
       connectToServer();
        setStreams();
        ClientRun();

    }catch(EOFException oefException){
        showMessage("\n Client terminated the connection\n");
    }catch(IOException ioException){
        ioException.printStackTrace();
    }finally{
        close();
    }
}

public void connectToServer() throws IOException{
    showMessage("Attempting Connection... \n");
    connection = new Socket(InetAddress.getByName(serverIP),6789);
    showMessage("Connected to: "+ connection.getInetAddress().getHostName());
}

public void setStreams() throws IOException{
   output = new PrintWriter(connection.getOutputStream(),true);
   output.flush();
   input= new BufferedReader(new InputStreamReader(connection.getInputStream()));

    showMessage("\n Streams are now set. \n");
}

public void close(){
    showMessage("\n closing...");
    try{
      output.close();
      input.close();
      connection.close();

    }catch(IOException ioException){
        ioException.printStackTrace();
    }
}
public void showMessage(final String text){
    SwingUtilities.invokeLater(new Runnable(){
        public void run(){
            cwindow.append(text);
        }
    });
}

public void sendMessage(String message){
    output.write("CLIENT - "+message);
    output.flush();
    showMessage("\nCLIENT - "+message);
}

private void ClientRun() throws IOException{
    String message="CLIENT HERE!";
    sendMessage(message);
    do{
        try{
            message=input.readLine();
            showMessage("\n"+message);
        }catch(EOFException eofException){
                showMessage("\n Server ended the connection!");
    }

    }while(message!="EXIT");
    }

(input and output are defined in GUI class in which this Client class is extended to. Defined as "protected BufferedReader input;
protected PrintWriter output;")

Also, servers code:

public class ServerClass {

private ServerSocket server;
private Socket connection;
private BufferedReader input;
private BufferedWriter output;

public void startServer(){
    try{
        server=new ServerSocket(6789,100);
        while(true){
            try{
                waitForConnection();
                setStreams();
                ServerRunning();
            }catch(EOFException eofException){
                showMessage("\n Server ended the connection!");

            }finally{
            close();

        }
        }

    }catch(IOException ioException){
        ioException.printStackTrace();
    }
}

private void waitForConnection() throws IOException{
    showMessage("Waiting for someone to connect... \n");
    connection=server.accept();
    showMessage("Now connected to "+ connection.getInetAddress().getHostName());
}

private void setStreams() throws IOException{
   output = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
   output.flush();
   input= new BufferedReader(new InputStreamReader(connection.getInputStream()));

    showMessage("\n Streams are now set. \n");
}
public void ServerRunning() throws IOException{
    String message="SERVER HERE!";
    sendMessage(message);
    do{
        try{

            message=input.readLine();
            showMessage("\n"+message);
        }catch(EOFException eofException){
                showMessage("\n Server ended the connection!");
    }

    }while(message!="EXIT");

  }
private void close(){
    showMessage("\n Closing connections... \n");
    try{
        output.close();
        input.close();
        connection.close();

}catch(IOException ioException){
    ioException.printStackTrace();
}
}
private void showMessage(String text){
    System.out.println(text);
}

private void sendMessage(String message){
    try{
       output.write("SERVER - "+message);
        output.flush();
        showMessage(message);
    }catch(IOException ioException){
        System.out.println("\n ERROR!");
    }
}

Connection seems to be ok, so i don't get whats wrong. Any help would be appreciated.

PS: i also tried PrintWriter in server as well and also tried a try catch in stream statement, the problem remains.


问:
How to execute query over Amazon Athena with Ruby?
how to connect Amazon Athena with Ruby and execute query over Amazon Athena and get result.

we not able to find any gem or example with help us to connect Amazon Athena in ruby.

Please provide any reference using which we can use to build connection with Amazon Athena and build a custom query executor in Ruby.

just to clarify my application on production so changing SDK from Ruby to JRuby is not a suitable option for me.

答:
If using JRuby is not acceptable, there is another option that could work - but be warned that it's not 100% Ruby!

You could set up a Java Lambda function that encapsulates the query logic, taking in search parameters and then connecting directly to Athena using the JDBC driver.

Then call the Lambda function from Ruby - either via HTTP or through the Ruby client.

ContentLicense: CC BY-SA 4.0


问:
reading HDF5-format MATLAB file in python with h5py
I am trying to read a HDF5-format MATLAB file in python, using the h5py library. This file is called "Q_visSDF_accurate.mat" and has two keys: "filename" and "sdf". "filename contains a cell array strings. "sdf" is a  [6001, 49380] matrix containing floats. I had no problem to extract the variable sdf using the following code:

```<code>import h5py
data = h5py.File("Q_visSDF_accurate.mat", 'r')
sdf = data.get("sdf")[:,:]
sdf = sdf.astype(float)
</code>```

However, I cant read the filename variable. I tried:

```<code>filename = data.get("filename")[0]
</code>```

but the code returns:

```<code>array([<HDF5 object reference>, <HDF5 object reference>,
   <HDF5 object reference>, ..., <HDF5 object reference>,
   <HDF5 object reference>, <HDF5 object reference>], dtype=object)
</code>```

I can I de-reference the containt of the filename variable? Using the hdf5storage package is not a solution, as it works only for python 32 bits and can only read a subset of matlab variables.

答:
In Octave I created a file with cell and matrix

```<code>>> xmat = [1,2,3;4,5,6;7,8,9];
>> xcell = {1,2,3;4,5,6;7,8,9};
>> save -hdf5 testmat.h5 xmat xcell
</code>```

In ipython with h5py, I find that this file contains 2 groups

```<code>In [283]: F = h5py.File('../testmat.h5','r')
In [284]: list(F.keys())
Out[284]: ['xcell', 'xmat']
</code>```

The matrix group has a type and value dataset:

```<code>In [285]: F['xmat']
Out[285]: <HDF5 group "/xmat" (2 members)>
In [286]: list(F['xmat'].keys())
Out[286]: ['type', 'value']
In [287]: F['xmat']['type']
Out[287]: <HDF5 dataset "type": shape (), type "|S7">
In [288]: F['xmat']['value']
Out[288]: <HDF5 dataset "value": shape (3, 3), type "<f8">
In [289]: F['xmat']['value'][:]
Out[289]:
array([[ 1.,  4.,  7.],
       [ 2.,  5.,  8.],
       [ 3.,  6.,  9.]])
</code>```

The cell has the same type and value, but value is another group:

```<code>In [291]: F['xcell']['type']
Out[291]: <HDF5 dataset "type": shape (), type "|S5">
In [292]: F['xcell']['value']
Out[292]: <HDF5 group "/xcell/value" (10 members)>

In [294]: list(F['xcell']['value'].keys())
Out[294]: ['_0', '_1', '_2', '_3', '_4', '_5', '_6', '_7', '_8', 'dims']
...
In [296]: F['xcell']['value']['dims'][:]
Out[296]: array([3, 3])
</code>```

I had to use the [...] to fetch the value of a cell, since it is a 0d array:

```<code>In [301]: F['xcell']['value']['_0']['value'][...]
Out[301]: array(1.0)
</code>```

To really replicate the question I should have created string cells values, but I think this illustrates well enough how a cells are stored - as named datasets within a data group.

I'm assuming the Octave h5 storage is compatible with MATLAB's.

Body:
I am trying to read a HDF5-format MATLAB file in python, using the h5py library. This file is called "Q_visSDF_accurate.mat" and has two keys: "filename" and "sdf". "filename contains a cell array strings. "sdf" is a  [6001, 49380] matrix containing floats. I had no problem to extract the variable sdf using the following code:

import h5py
data = h5py.File("Q_visSDF_accurate.mat", 'r')
sdf = data.get("sdf")[:,:]
sdf = sdf.astype(float)

However, I cant read the filename variable. I tried:

filename = data.get("filename")[0]

but the code returns:

array([<HDF5 object reference>, <HDF5 object reference>,
   <HDF5 object reference>, ..., <HDF5 object reference>,
   <HDF5 object reference>, <HDF5 object reference>], dtype=object)

I can I de-reference the containt of the filename variable? Using the hdf5storage package is not a solution, as it works only for python 32 bits and can only read a subset of matlab variables.

Body:
In Octave I created a file with cell and matrix

>> xmat = [1,2,3;4,5,6;7,8,9];
>> xcell = {1,2,3;4,5,6;7,8,9};
>> save -hdf5 testmat.h5 xmat xcell

In ipython with h5py, I find that this file contains 2 groups

In [283]: F = h5py.File('../testmat.h5','r')
In [284]: list(F.keys())
Out[284]: ['xcell', 'xmat']

The matrix group has a type and value dataset:

In [285]: F['xmat']
Out[285]: <HDF5 group "/xmat" (2 members)>
In [286]: list(F['xmat'].keys())
Out[286]: ['type', 'value']
In [287]: F['xmat']['type']
Out[287]: <HDF5 dataset "type": shape (), type "|S7">
In [288]: F['xmat']['value']
Out[288]: <HDF5 dataset "value": shape (3, 3), type "<f8">
In [289]: F['xmat']['value'][:]
Out[289]:
array([[ 1.,  4.,  7.],
       [ 2.,  5.,  8.],
       [ 3.,  6.,  9.]])

The cell has the same type and value, but value is another group:

In [291]: F['xcell']['type']
Out[291]: <HDF5 dataset "type": shape (), type "|S5">
In [292]: F['xcell']['value']
Out[292]: <HDF5 group "/xcell/value" (10 members)>

In [294]: list(F['xcell']['value'].keys())
Out[294]: ['_0', '_1', '_2', '_3', '_4', '_5', '_6', '_7', '_8', 'dims']
...
In [296]: F['xcell']['value']['dims'][:]
Out[296]: array([3, 3])

I had to use the [...] to fetch the value of a cell, since it is a 0d array:

In [301]: F['xcell']['value']['_0']['value'][...]
Out[301]: array(1.0)

To really replicate the question I should have created string cells values, but I think this illustrates well enough how a cells are stored - as named datasets within a data group.

I'm assuming the Octave h5 storage is compatible with MATLAB's.


问:
Cannot retrieve Apache environment variables in PHP

Background

I have an Apache/2.2.15 (Win32) with PHP/5.3.2 set up, handling authentication.

```<code><Directory /usr/www/myhost/private>
  # core authentication and mod_auth_basic configuration
  # for mod_authn_dbd
  AuthType Basic
  AuthName "My Server"
  AuthBasicProvider dbd

  # core authorization configuration
  Require valid-user

  # mod_authn_dbd SQL query to authenticate a user
  AuthDBDUserPWQuery "SELECT Password,UserName,Realm,Access FROM authn WHERE user = %s"
</Directory>
</code>```

The authentication works fine! No problems.

But regarding to the documentation, any extra field returned back from the AuthDBDUserPWQuery will be put into an AUTHENTICATION_fieldname variable in the Environment.

With phpinfo(), I can see these variables with he correct values under "Apache Environment".

AUTHENTICATE_USERNAME

AUTHENTICATE_REALM

AUTHENTICATE_ACCESS

Problem

I can't fetch those environment variables from my php.

```<code>1 <?php
2   $Access = apache_getenv('AUTHENTICATE_ACCESS',true);
3   var_dump($Access);
4 ?>
</code>```

Line 3 prints bool(false) indicating that the variable wasn't found!

However if I  change to another Apache Environment variable such as 'HTTP_HOST' it works.

..and yes, I have tried getenv() also, same result.

There is also a note that the Apache server needs to be compiled with APR 1.3.0 to work. I used the Apache msi build from httpd.apache.org and it seems to be compiled with APR above version 2. Since I can see them with phpinfo() they must be accessible from PHP.

答:
I made a work around,

It seems like this might be a PHP bug. Found some related bugs reported for PHP 4 and maybe they haven't fixed them yet...

I did a solution that I really don't like (because I'm accessing the Apache userdata table), but it seems that I have no choice.

```<code>//*************************************************************
// If PHP failed to retrieve the AuthDBDUserPWQuery fields.
// Connect to Apache authentication databaseand create the
// envirnment variables manually
//
if (empty($_ENV['AUTHENTICATE_ACCESS'])) {
  $Apache = mysql_connect('MyServerIP','MyUserName','MyPassword',false,MYSQL_CLIENT_SSL|MYSQL_CLIENT_COMPRESS);
  mysql_select_db('MyDatabase',$Apache);
  $SQLSet = mysql_query("SELECT Realm, Access FROM authenticationtable WHERE UserName='".$_SERVER['PHP_AUTH_USER']."' AND Password='".$_SERVER['PHP_AUTH_PW']."'");
  $SQLRow = mysql_fetch_array($SQLSet);
  $_ENV['AUTHENTICATE_REALM'] = $SQLRow['Realm'];
  $_ENV['AUTHENTICATE_ACCESS']= $SQLRow['Access'];
  mysql_close($Apache);
}
</code>```

If PHP has failed to update $_ENV correct, this will retrieve the current logged in user from the same database and table that Apache is using for authentication.
Then the extra fields will be written into the global $_ENV variable so it can be used as it is supposed.
Later when the "bug" is fixed, it will automatically use the original $_ENV.

If anyone can bring some up to date information on this topic, I would be happy...

Body:
Background

I have an Apache/2.2.15 (Win32) with PHP/5.3.2 set up, handling authentication.

<Directory /usr/www/myhost/private>
  # core authentication and mod_auth_basic configuration
  # for mod_authn_dbd
  AuthType Basic
  AuthName "My Server"
  AuthBasicProvider dbd

  # core authorization configuration
  Require valid-user

  # mod_authn_dbd SQL query to authenticate a user
  AuthDBDUserPWQuery "SELECT Password,UserName,Realm,Access FROM authn WHERE user = %s"
</Directory>

The authentication works fine! No problems.

But regarding to the documentation, any extra field returned back from the AuthDBDUserPWQuery will be put into an AUTHENTICATION_fieldname variable in the Environment.

With phpinfo(), I can see these variables with he correct values under "Apache Environment".

AUTHENTICATE_USERNAME

AUTHENTICATE_REALM

AUTHENTICATE_ACCESS

Problem

I can't fetch those environment variables from my php.

1 <?php
2   $Access = apache_getenv('AUTHENTICATE_ACCESS',true);
3   var_dump($Access);
4 ?>

Line 3 prints bool(false) indicating that the variable wasn't found!

However if I  change to another Apache Environment variable such as 'HTTP_HOST' it works.

..and yes, I have tried getenv() also, same result.

There is also a note that the Apache server needs to be compiled with APR 1.3.0 to work. I used the Apache msi build from httpd.apache.org and it seems to be compiled with APR above version 2. Since I can see them with phpinfo() they must be accessible from PHP.

Body:
I made a work around,

It seems like this might be a PHP bug. Found some related bugs reported for PHP 4 and maybe they haven't fixed them yet...

I did a solution that I really don't like (because I'm accessing the Apache userdata table), but it seems that I have no choice.

//*************************************************************
// If PHP failed to retrieve the AuthDBDUserPWQuery fields.
// Connect to Apache authentication databaseand create the
// envirnment variables manually
//
if (empty($_ENV['AUTHENTICATE_ACCESS'])) {
  $Apache = mysql_connect('MyServerIP','MyUserName','MyPassword',false,MYSQL_CLIENT_SSL|MYSQL_CLIENT_COMPRESS);
  mysql_select_db('MyDatabase',$Apache);
  $SQLSet = mysql_query("SELECT Realm, Access FROM authenticationtable WHERE UserName='".$_SERVER['PHP_AUTH_USER']."' AND Password='".$_SERVER['PHP_AUTH_PW']."'");
  $SQLRow = mysql_fetch_array($SQLSet);
  $_ENV['AUTHENTICATE_REALM'] = $SQLRow['Realm'];
  $_ENV['AUTHENTICATE_ACCESS']= $SQLRow['Access'];
  mysql_close($Apache);
}

If PHP has failed to update $_ENV correct, this will retrieve the current logged in user from the same database and table that Apache is using for authentication.
Then the extra fields will be written into the global $_ENV variable so it can be used as it is supposed.
Later when the "bug" is fixed, it will automatically use the original $_ENV.

If anyone can bring some up to date information on this topic, I would be happy...


问:
How nginx reload work ? why it is zero-downtime
refer to nginx official docs . the reload command of nginx is for reload of configuration files ，and during the progress , there's no downtime of the service .

i've learned that  it wait requests that already connected until it finished ,and stop accept any new request . the idea is cool , but how does it deal with the keep-live connections ? because those long-live connections won't close and there continuous request comes along .

答:
Here's the summary:

http://nginx.org/en/docs/control.html

The master process first checks the syntax validity, then tries to
  apply new configuration. If this succeeds, it starts new worker
  processes, and sends messages to old worker processes requesting them
  to shut down gracefully.

That means it would keep older processes handling unclosed connections while having new processes working according to the updated configuration.
From this perspective connections with keep-alive are no different from other unclosed connections.

In versions prior to 1.11.11 such "old" processes could hang indefinitely long (according to @Alexey, haven't checked it though), from 1.11.11 there’s a configuration setting controlling this
http://nginx.org/en/docs/ngx_core_module.html#worker_shutdown_timeout


问:
InvalidModuleError on local dev server when adding job to GAE TaskeQueue
Can someone please tell me how to resolve the GAE python 2.7 error shown below:

It just started happening after I upgraded GCloud and I don't understand what changed.
My import looks like this:

from google.appengine.api import taskqueue

but I see some newer docs showing it like this:

from google.appengine.api.taskqueue import taskqueue

But no clear deprecation or change notice and I'm afraid to deploy without understanding this first.

```<code>File "/Users/dgaedcke/dev/TouchstoneMicroservices/common/async_tasks/push_notify.py", line 49, in registerPush
    taskqueue.add(target='task', queue_name=GAEQ_FOR_PUSH_NOTIFY, url=url, params=params )
File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/google/appengine/api/taskqueue/taskqueue.py", line 2505, in add
    return Task(*args, **kwargs).add(
File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/google/appengine/api/taskqueue/taskqueue.py", line 823, in __init__
    self.__resolve_hostname_and_target()
File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/google/appengine/api/taskqueue/taskqueue.py", line 877, in __resolve_hostname_and_target
    host = self.__host_from_target(self.__target)
File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/google/appengine/api/taskqueue/taskqueue.py", line 957, in __host_from_target
    instance=instance)
File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/google/appengine/api/modules/modules.py", line 459, in get_hostname
    _ResultHook).get_result()
File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/google/appengine/api/apiproxy_stub_map.py", line 613, in get_result
    return self.__get_result_hook(self)
File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/google/appengine/api/modules/modules.py", line 442, in _ResultHook
    _CheckAsyncResult(rpc, mapped_errors, [])
File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/google/appengine/api/modules/modules.py", line 147, in _CheckAsyncResult
    raise mapped_error()
InvalidModuleError
</code>```

答:
OK....I found the problem.
The dev server was starting up without the taskqueue server running and so I guess the whole taskqueue package was not added to the google.api package....

Seems like a better error would be useful in that case....

Body:
Can someone please tell me how to resolve the GAE python 2.7 error shown below:

It just started happening after I upgraded GCloud and I don't understand what changed.
My import looks like this:

from google.appengine.api import taskqueue

but I see some newer docs showing it like this:

from google.appengine.api.taskqueue import taskqueue

But no clear deprecation or change notice and I'm afraid to deploy without understanding this first.

File "/Users/dgaedcke/dev/TouchstoneMicroservices/common/async_tasks/push_notify.py", line 49, in registerPush
    taskqueue.add(target='task', queue_name=GAEQ_FOR_PUSH_NOTIFY, url=url, params=params )
File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/google/appengine/api/taskqueue/taskqueue.py", line 2505, in add
    return Task(*args, **kwargs).add(
File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/google/appengine/api/taskqueue/taskqueue.py", line 823, in __init__
    self.__resolve_hostname_and_target()
File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/google/appengine/api/taskqueue/taskqueue.py", line 877, in __resolve_hostname_and_target
    host = self.__host_from_target(self.__target)
File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/google/appengine/api/taskqueue/taskqueue.py", line 957, in __host_from_target
    instance=instance)
File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/google/appengine/api/modules/modules.py", line 459, in get_hostname
    _ResultHook).get_result()
File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/google/appengine/api/apiproxy_stub_map.py", line 613, in get_result
    return self.__get_result_hook(self)
File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/google/appengine/api/modules/modules.py", line 442, in _ResultHook
    _CheckAsyncResult(rpc, mapped_errors, [])
File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/google/appengine/api/modules/modules.py", line 147, in _CheckAsyncResult
    raise mapped_error()
InvalidModuleError


问:
R package xtable, how to create a latextable with multiple rows and columns from R
My goal is to create latextable with multirow/multicolumn features from R.
The latextable I want should look like this:

```<code>               colLabel  |  colLabel2
                         |
                 a1  a2  |   a3    a4
 -------------------------------------
             b1  1    2  |   5     6
 rowLabel1               |
             b2  3    4  |   7     8
 --------------------------------------
             b3  9   10  |   13    14
 rowLabel2               |
             b4  11  12  |   15    16
 --------------------------------------
</code>```

I am currently using xtable but I cannot figure out how to create multirow using this package.
Could anyone tell me how to create such table?

Thank you in advance

答:
Here is a way to do this with the huxtable package (I am the author):

```<code>library(huxtable)
mydf <- data.frame(rowFactor1 = sample(letters[1:2], 100, replace = TRUE),
  colFactor1 = sample(LETTERS[1:2], 100, replace = TRUE),
  x = rnorm(100),
  rowFactor2 = sample(1:2, 100, replace = TRUE),
  colFactor2 = sample(1:2, 100, replace = TRUE))

tbl <- ftable(colFactor1 + colFactor2  ~ rowFactor1 + rowFactor2, data = mydf)
ht <- as_hux(tbl)

rowspan(ht)[c(4, 6), "V1"] <- 2 # these cells span 2 rows
colspan(ht)[1, c(4, 6)] <- 2    # these cells span 2 columns

ht[3, 1:2] <- '' # clean up some extraneous colum names
ht[1:2, 3] <- ''

right_border(ht)[,3] <- 1
bottom_border(ht)[c(2, 5, 7), ] <- 1
bottom_border(ht)[c(4,6), 1] <- 1
ht
</code>```

When printed to LaTeX this looks like:

Body:
My goal is to create latextable with multirow/multicolumn features from R.
The latextable I want should look like this:

               colLabel  |  colLabel2
                         |
                 a1  a2  |   a3    a4
 -------------------------------------
             b1  1    2  |   5     6
 rowLabel1               |
             b2  3    4  |   7     8
 --------------------------------------
             b3  9   10  |   13    14
 rowLabel2               |
             b4  11  12  |   15    16
 --------------------------------------

I am currently using xtable but I cannot figure out how to create multirow using this package.
Could anyone tell me how to create such table?

Thank you in advance

Body:
Here is a way to do this with the huxtable package (I am the author):

library(huxtable)
mydf <- data.frame(rowFactor1 = sample(letters[1:2], 100, replace = TRUE),
  colFactor1 = sample(LETTERS[1:2], 100, replace = TRUE),
  x = rnorm(100),
  rowFactor2 = sample(1:2, 100, replace = TRUE),
  colFactor2 = sample(1:2, 100, replace = TRUE))

tbl <- ftable(colFactor1 + colFactor2  ~ rowFactor1 + rowFactor2, data = mydf)
ht <- as_hux(tbl)

rowspan(ht)[c(4, 6), "V1"] <- 2 # these cells span 2 rows
colspan(ht)[1, c(4, 6)] <- 2    # these cells span 2 columns

ht[3, 1:2] <- '' # clean up some extraneous colum names
ht[1:2, 3] <- ''

right_border(ht)[,3] <- 1
bottom_border(ht)[c(2, 5, 7), ] <- 1
bottom_border(ht)[c(4,6), 1] <- 1
ht

When printed to LaTeX this looks like:


问:
DrawableLeft in center with text
I can't center my drawableLeft icon.

I can easily put icon on the left of text, but if I set gravity to center, then only text is centered, but no icon.

```<code><Button
    android:id="@+id/patient_list_button"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/patientList"
    android:drawableLeft="@drawable/ic_icon_two_heads"
    android:layout_marginBottom="15dp"
    style="@style/darkBlueButtonWithImage"/>
</code>```

This is what I want:

This is what I have:

```<code><style name="darkBlueButtonWithImage">
    <item name="android:drawablePadding">10dp</item>
    <item name="android:textColor">@color/white</item>
    <item name="android:paddingLeft">10dp</item>
    <item name="android:background">@drawable/radius_dark_blue_button</item>
    <item name="android:gravity">center_vertical|left</item>
    <item name="android:drawableTint">@color/white</item> <!-- has to be set in activity.java -->
</style>
</code>```

How can I achieve this?

答:
Using Button attributes android:drawableLeft and android:drawablePadding you won't be able to get your expected result. You can create a custom button using RelativeLayout or LinearLayout, TextView and ImageView. Use <selector> to define your button state(normal/pressed) behavior.

Here is an working example. Try this:

```<code><!--- Custom Button -->
<RelativeLayout
    android:id="@+id/patient_list_button"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:clickable="true"
    android:background="@drawable/custom_button_selector">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_centerInParent="true"
        android:gravity="center_vertical">

        <ImageView
            android:layout_width="24dp"
            android:layout_height="24dp"
            android:src="@drawable/icon_refresh"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:textSize="16dp"
            android:text="CUSTOM BUTTON"
            android:textStyle="bold"
            android:textColor="#FFFFFF"/>

    </LinearLayout>
</RelativeLayout>
</code>```

custom_button_selector.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_pressed="true"
        android:state_enabled="true"
        android:drawable="@drawable/bg_custom_button_pressed" />
    <item
        android:state_focused="true"
        android:state_enabled="true"
        android:drawable="@drawable/bg_custom_button_pressed" />
    <item
        android:state_enabled="true"
        android:drawable="@drawable/bg_custom_button_normal" />
</selector>
</code>```

bg_custom_button_normal.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <!-- view background color -->
    <solid
        android:color="#01A1DD" >
    </solid>

    <!-- Here is the corner radius -->
    <corners android:radius="8dp" >
    </corners>

</shape>
</code>```

bg_custom_button_pressed.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <!-- view background color -->
    <solid
        android:color="#303F9F">
    </solid>

    <!-- Here is the corner radius -->
    <corners android:radius="8dp" >
    </corners>

</shape>
</code>```

OUTPUT:

Hope this will help~

Title: DrawableLeft in center with text

Body:
I can't center my drawableLeft icon.

I can easily put icon on the left of text, but if I set gravity to center, then only text is centered, but no icon.

<Button
    android:id="@+id/patient_list_button"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/patientList"
    android:drawableLeft="@drawable/ic_icon_two_heads"
    android:layout_marginBottom="15dp"
    style="@style/darkBlueButtonWithImage"/>

This is what I want:

This is what I have:

How can I achieve this?

Body:
Using Button attributes android:drawableLeft and android:drawablePadding you won't be able to get your expected result. You can create a custom button using RelativeLayout or LinearLayout, TextView and ImageView. Use <selector> to define your button state(normal/pressed) behavior.

Here is an working example. Try this:

<!--- Custom Button -->
<RelativeLayout
    android:id="@+id/patient_list_button"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:clickable="true"
    android:background="@drawable/custom_button_selector">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_centerInParent="true"
        android:gravity="center_vertical">

        <ImageView
            android:layout_width="24dp"
            android:layout_height="24dp"
            android:src="@drawable/icon_refresh"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:textSize="16dp"
            android:text="CUSTOM BUTTON"
            android:textStyle="bold"
            android:textColor="#FFFFFF"/>

    </LinearLayout>
</RelativeLayout>

custom_button_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_pressed="true"
        android:state_enabled="true"
        android:drawable="@drawable/bg_custom_button_pressed" />
    <item
        android:state_focused="true"
        android:state_enabled="true"
        android:drawable="@drawable/bg_custom_button_pressed" />
    <item
        android:state_enabled="true"
        android:drawable="@drawable/bg_custom_button_normal" />
</selector>

bg_custom_button_normal.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <!-- view background color -->
    <solid
        android:color="#01A1DD" >
    </solid>

    <!-- Here is the corner radius -->
    <corners android:radius="8dp" >
    </corners>

</shape>

bg_custom_button_pressed.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <!-- view background color -->
    <solid
        android:color="#303F9F">
    </solid>

    <!-- Here is the corner radius -->
    <corners android:radius="8dp" >
    </corners>

</shape>

OUTPUT:

Hope this will help~


问:
Django migrations not detecting all changes
I have the following models.
BaseClass1 and BaseClass2 are abstract models used by models.

In this case, the model AdBreak is used by a viewset and a serializer.
When I run python manage.py makemigrations, the changes on AdBreak model is detected. The model AdBreakStatus is not getting created.

Since, AdBreakStatus is linked to AdBreak, I am expecting a migration for AdBreakStatus also. Is my understanding wrong?

Edit

In the initial state, there was only AdBreak and BaseClass1 model. The new state, AdBreakStatus and BaseClass2 models were added. Some of the fields from AdBreak were moved to AdBreakStatus.

Thanks in advance for the help.

```<code>class BaseClass1(models.Model):
    class Meta:
        abstract=True
    timestamp = models.DateTimeField(auto_now_add=True)

class BaseClass2(models.Model):
    class Meta:
        abstract=True
    other_field = models.IntegerField()

class AdBreak(BaseClass1):
    class Meta:
        db_table = "ad_break"
    ad_break_id = models.AutoField(primary_key=True)
    ... # Other fields

class AdBreakStatus(BaseClass2):
    class Meta:
        db_table = "ad_break_status"
    ad_break = models.ForeignKey(AdBreak)
    ... # Other Fields
</code>```

答:
I solved it in multiple ways.

Solution 1

There is a serializer AdBreakSerializer which serializes the model AdBreak.
Import AdBreakStatus model into the AdBreakSerializer file.
Now AdBreakStatus model is detected and migrated.

Problem in this approach is that, the import is not used, and hence will not follow the standards.

Solution 2

Write the AdBreakStatus model class inside the same file of AdBreak. This will also solve the problem.

Finding / Understanding

The makemigrations script looks for models which are connected from urls.py. The script navigates from urls.py to all the viewset, then the corresponding serializers and models.

All the models which needs to be migrated should come in the path of this traversal. OR Only those models which are traversed in this manner will be migrated.

Body:
I have the following models.
BaseClass1 and BaseClass2 are abstract models used by models.

In this case, the model AdBreak is used by a viewset and a serializer.
When I run python manage.py makemigrations, the changes on AdBreak model is detected. The model AdBreakStatus is not getting created.

Since, AdBreakStatus is linked to AdBreak, I am expecting a migration for AdBreakStatus also. Is my understanding wrong?

Edit

In the initial state, there was only AdBreak and BaseClass1 model. The new state, AdBreakStatus and BaseClass2 models were added. Some of the fields from AdBreak were moved to AdBreakStatus.

Thanks in advance for the help.

class BaseClass1(models.Model):
    class Meta:
        abstract=True
    timestamp = models.DateTimeField(auto_now_add=True)

class BaseClass2(models.Model):
    class Meta:
        abstract=True
    other_field = models.IntegerField()

class AdBreak(BaseClass1):
    class Meta:
        db_table = "ad_break"
    ad_break_id = models.AutoField(primary_key=True)
    ... # Other fields

class AdBreakStatus(BaseClass2):
    class Meta:
        db_table = "ad_break_status"
    ad_break = models.ForeignKey(AdBreak)
    ... # Other Fields


问:
Tricky substring usage in Oracle
I am looking for a way to retrieve always the 2 numbers after the last "/"character in a string. If there is something after the 2 numbers that I want, I don't care.

the code that I came up with is this:

```<code>CASE when INSTRUMENT like '%/%' then   SUBSTR(INSTRUMENT,INSTR(INSTRUMENT,'/',-3,1)+1,2) else '0' end
</code>```

This seems to work fine.
The problem is that when it does not find any "/"character, then it does not fill them with a 0 as I would like.

To give you an example of what I would like to perform:

```<code>XXX/YYY/ZZZ/92           ---> Returns 92
XXX/YYY/ZZZ/42 (test)    ---> Returns 42
XXX YYY ZZZ 10           ---> Returns 0
</code>```

All of this must be "plugged" in a select case statement, but this should not change the solution.

Thanks in advance

答:
Perhaps regexp_substr will work for you.  If it returns NULL, meaning the pattern of a slash followed by 2 digits and 0 or more characters to the end of the string was not found, replace with a '0' by using NVL().</p>

```<code>SQL> with tbl(str) as (
      select 'XXX/YYY/ZZZ/92' from dual union
      select 'XXX/YYY/ZZZ/42 (test)' from dual union
      select 'XXX YYY ZZZ 10' from dual
    )
    select nvl(regexp_substr(str, '/(\d{2}).*$', 1, 1, NULL, 1), '0') digits
    from tbl;

DIGITS
---------------------
0
42
92

SQL>
</code>```

Title: Tricky substring usage in Oracle

Body:
I am looking for a way to retrieve always the 2 numbers after the last "/"character in a string. If there is something after the 2 numbers that I want, I don't care.

the code that I came up with is this:

CASE when INSTRUMENT like '%/%' then   SUBSTR(INSTRUMENT,INSTR(INSTRUMENT,'/',-3,1)+1,2) else '0' end

This seems to work fine.
The problem is that when it does not find any "/"character, then it does not fill them with a 0 as I would like.

To give you an example of what I would like to perform:

XXX/YYY/ZZZ/92           ---> Returns 92
XXX/YYY/ZZZ/42 (test)    ---> Returns 42
XXX YYY ZZZ 10           ---> Returns 0

All of this must be "plugged" in a select case statement, but this should not change the solution.

Thanks in advance

Body:
Perhaps regexp_substr will work for you.  If it returns NULL, meaning the pattern of a slash followed by 2 digits and 0 or more characters to the end of the string was not found, replace with a '0' by using NVL().

SQL> with tbl(str) as (
      select 'XXX/YYY/ZZZ/92' from dual union
      select 'XXX/YYY/ZZZ/42 (test)' from dual union
      select 'XXX YYY ZZZ 10' from dual
    )
    select nvl(regexp_substr(str, '/(\d{2}).*$', 1, 1, NULL, 1), '0') digits
    from tbl;

DIGITS
---------------------
0
42
92

SQL>


问:
ComboBox: Empty string sent on POST when it's valueField is numeric. How can I pass null to Server?
All,

I am getting a cast exception when attempting to create a new record via a POST using Extjs' JSONStore.  The exception happens when an empty string is passed to the server and the server attempts to convert it into an Integer.  The comboBox's valueField is set to an int defined field.  The datastore fields are as follows:

```<code>  fields: [
            { name: 'id', type: 'int' },
            { name: 'displayOrder', mapping: 'displayOrder', type: 'int' },
            { name: 'displayName', mapping: 'displayName', type: 'string' },
            { name: 'enabled', mapping: 'enabled', type: 'boolean' },
            { name: 'letterCode', mapping: 'letterCode', type: 'string' }
        ],
</code>```

the combobox definition is:

```<code> {
                xtype: 'combo',
                id:"secondaryIncidentCombo",
                hiddenName: 'secondaryIncidentTypeId',
                forceSelection: true,
                width:"200",
                selectOnFocus: true,
                emptyText: 'Secondary Incident',
                editable: false,
                mode: 'local',
                displayField:   'displayName',
                valueField:     'id',
                store: this.secondaryIncidentTypeArrayStore,
                triggerAction: 'all'
            },
</code>```

The JSONStore used to send the POST is, oddly enough, sending the value of the combobox as an empty string, even though I've configured the JSONWriter not to send unchanged fields:

```<code> writer: new Ext.data.JsonWriter({
            encode: false,
            writeAllFields:false
        }),
</code>```

And the POST value sent to the server:  ....,"secondaryIncidentTypeId":"",... <-- notice the empty string after the colon.

Here is the secondaryIncidentTypeArrayStore:

```<code>    secondaryIncidentTypeArrayStore: new Ext.data.ArrayStore({
    idProperty: 'id',
    fields: [
        { name: 'id', mapping: 'id', type: 'int' },
        { name: 'displayOrder', mapping: 'displayOrder', type: 'int' },
        { name: 'displayName', mapping: 'displayName', type: 'string' },
        { name: 'enabled', mapping: 'enabled', type: 'boolean' },
        { name: 'letterCode', mapping: 'letterCode', type: 'string' }
    ],
    data: []
})
</code>```

I'm on the verge of writing a manual check for an empty string and setting it to null if the string is empty.  This seems pretty kludgy.  What's the correct way to send either nothing back or a null value to the server on form submit?

Thanks!

答:
What's happening is that because the type of your id field is integer it's coercing it into an integer. A falsy value will therefore be 0.

If you remove the type it won't do any conversion, and won't add the id when it's undefined.

e.g.

```<code>new Ext.data.ArrayStore({
  idProperty: 'id',
  fields: [
    { name: 'id', mapping: 'id' },
    { name: 'displayOrder', mapping: 'displayOrder', type: 'int' },
    { name: 'displayName', mapping: 'displayName', type: 'string' },
    { name: 'enabled', mapping: 'enabled', type: 'boolean' },
    { name: 'letterCode', mapping: 'letterCode', type: 'string' }
  ],
  data: []
})
</code>```

If you have to send id=null to get the backend to behave one way of dealing with it is to add a custom Ext.data.Type.

Other ways to solve it are also available if neither of those take your fancy.

EDIT: Aha! Try the allowNull property.

Body:
All,

I am getting a cast exception when attempting to create a new record via a POST using Extjs' JSONStore.  The exception happens when an empty string is passed to the server and the server attempts to convert it into an Integer.  The comboBox's valueField is set to an int defined field.  The datastore fields are as follows:

  fields: [
            { name: 'id', type: 'int' },
            { name: 'displayOrder', mapping: 'displayOrder', type: 'int' },
            { name: 'displayName', mapping: 'displayName', type: 'string' },
            { name: 'enabled', mapping: 'enabled', type: 'boolean' },
            { name: 'letterCode', mapping: 'letterCode', type: 'string' }
        ],

the combobox definition is:

 {
                xtype: 'combo',
                id:"secondaryIncidentCombo",
                hiddenName: 'secondaryIncidentTypeId',
                forceSelection: true,
                width:"200",
                selectOnFocus: true,
                emptyText: 'Secondary Incident',
                editable: false,
                mode: 'local',
                displayField:   'displayName',
                valueField:     'id',
                store: this.secondaryIncidentTypeArrayStore,
                triggerAction: 'all'
            },

The JSONStore used to send the POST is, oddly enough, sending the value of the combobox as an empty string, even though I've configured the JSONWriter not to send unchanged fields:

 writer: new Ext.data.JsonWriter({
            encode: false,
            writeAllFields:false
        }),

And the POST value sent to the server:  ....,"secondaryIncidentTypeId":"",... <-- notice the empty string after the colon.

Here is the secondaryIncidentTypeArrayStore:

    secondaryIncidentTypeArrayStore: new Ext.data.ArrayStore({
    idProperty: 'id',
    fields: [
        { name: 'id', mapping: 'id', type: 'int' },
        { name: 'displayOrder', mapping: 'displayOrder', type: 'int' },
        { name: 'displayName', mapping: 'displayName', type: 'string' },
        { name: 'enabled', mapping: 'enabled', type: 'boolean' },
        { name: 'letterCode', mapping: 'letterCode', type: 'string' }
    ],
    data: []
})

I'm on the verge of writing a manual check for an empty string and setting it to null if the string is empty.  This seems pretty kludgy.  What's the correct way to send either nothing back or a null value to the server on form submit?

Thanks!

Body:
What's happening is that because the type of your id field is integer it's coercing it into an integer. A falsy value will therefore be 0.

If you remove the type it won't do any conversion, and won't add the id when it's undefined.

e.g.

new Ext.data.ArrayStore({
  idProperty: 'id',
  fields: [
    { name: 'id', mapping: 'id' },
    { name: 'displayOrder', mapping: 'displayOrder', type: 'int' },
    { name: 'displayName', mapping: 'displayName', type: 'string' },
    { name: 'enabled', mapping: 'enabled', type: 'boolean' },
    { name: 'letterCode', mapping: 'letterCode', type: 'string' }
  ],
  data: []
})

If you have to send id=null to get the backend to behave one way of dealing with it is to add a custom Ext.data.Type.

Other ways to solve it are also available if neither of those take your fancy.

EDIT: Aha! Try the allowNull property.


问:
How to add additional request body values to Apollo GraphQL request?
I'm using Apollo with the Scaphold.io service and for writing blobs to that service I need to be able to add additional options to the request body.

The full Scaphold example can be found here: https://scaphold.io/docs/#uploading-files

But it does something like this:

```<code>form.append("variables", JSON.stringify({
  "input": {
    "name": "Mark Zuck Profile Picture",
    "userId": "VXNlcjoxMA==",
    "blobFieldName": "myBlobField"
  }
}));
// The file's key matches the value of the field `blobFieldName` in the variables
form.append("myBlobField", fs.createReadStream('./mark-zuckerberg.jpg'));

fetch("https://us-west-2.api.scaphold.io/graphql/scaphold-graphql", {
  method: 'POST',
  body: form
}).then(function(res) {
  return res.text();
}).then(function(body) {
  console.log(body);
});
</code>```

Where it adds a blobField to the request body.

Based on this, I need to pass into the variables a blobFieldName property, and then add to the request body the value passed to that property with the blob. However, using Apollo I can't add to the request body. I tried the following, but it's absent from the request body when I check in the network inspector:

```<code>export const withCreateCoverPhoto = graphql(CreateCoverPhoto, {
  props: ({mutate}) => ({
    createCoverPhoto: (name, file) => mutate({
      variables: {
        input: {
          blobFieldName: name,
        },
      },
      [name]: file
    }),
  }),
});
</code>```

Please advise.

答: Thanks for the question. Currently the best way to upload files is by [appending it to FormData and sending it up to the server using fetch] (https://medium.com/@danielbuechele/file-uploads-with-graphql-and-apollo-5502bbf3941e). Basically, you won't be able to have caching here for the file itself, but this is the best way to handle uploading files on Scaphold using a multipart request.</p>

Body:
I'm using Apollo with the Scaphold.io service and for writing blobs to that service I need to be able to add additional options to the request body.

The full Scaphold example can be found here: https://scaphold.io/docs/#uploading-files

But it does something like this:

form.append("variables", JSON.stringify({
  "input": {
    "name": "Mark Zuck Profile Picture",
    "userId": "VXNlcjoxMA==",
    "blobFieldName": "myBlobField"
  }
}));
// The file's key matches the value of the field `blobFieldName` in the variables
form.append("myBlobField", fs.createReadStream('./mark-zuckerberg.jpg'));

fetch("https://us-west-2.api.scaphold.io/graphql/scaphold-graphql", {
  method: 'POST',
  body: form
}).then(function(res) {
  return res.text();
}).then(function(body) {
  console.log(body);
});

Where it adds a blobField to the request body.

Based on this, I need to pass into the variables a blobFieldName property, and then add to the request body the value passed to that property with the blob. However, using Apollo I can't add to the request body. I tried the following, but it's absent from the request body when I check in the network inspector:

export const withCreateCoverPhoto = graphql(CreateCoverPhoto, {
  props: ({mutate}) => ({
    createCoverPhoto: (name, file) => mutate({
      variables: {
        input: {
          blobFieldName: name,
        },
      },
      [name]: file
    }),
  }),
});

Please advise.


问:
Multiple checkboxes in QDockWidget
So I've been trying to make multiple checkboxes inside a QDockwidget but I seem to only be able to add one. This is what I have

```<code>def createDockWindows(self):
    cboxes = gui.QDockWidget("Cboxes", self)
    #cboxes.setWidget(gui.QCheckBox())
    cboxes.setAllowedAreas(core.Qt.LeftDockWidgetArea)

    self.c0 = gui.QCheckBox("B0")
    self.c0.setChecked(False)
    self.c0.stateChanged.connect(lambda:self.btnstate(self.c0))
    cboxes.setWidget(self.c0)

    self.c1 = gui.QCheckBox("B1")
    self.c1.setChecked(False)
    self.c1.stateChanged.connect(lambda:self.btnstate(self.c1))
    cboxes.setWidget(self.c1)

    self.addDockWidget(core.Qt.LeftDockWidgetArea, cboxes)
</code>```

The output only gives me the box for B1.

I've done the dock method because I have some matplotlib graphs over to the right, a modified version of this example. If there is a better way to do this I'd be happy to change I'm just not finding much with google.

答:
You must create a new widget, place a layout and add the checkboxes, that new widget you should add it to the QDockWidget.

```<code>def createDockWindows(self):
    cboxes = QtGui.QDockWidget("Cboxes", self)
    cboxes.setAllowedAreas(QtCore.Qt.LeftDockWidgetArea)

    w = QtGui.QWidget()
    layout = QtGui.QVBoxLayout()
    w.setLayout(layout)

    self.c0 = QtGui.QCheckBox("B0")
    layout.addWidget(self.c0)

    self.c1 = QtGui.QCheckBox("B1")
    layout.addWidget(self.c1)

    cboxes.setWidget(w)
    self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, cboxes)
</code>```

plus [add QSpacer]:

```<code>def createDockWindows(self):
    cboxes = QtGui.QDockWidget("Cboxes", self)
    cboxes.setAllowedAreas(QtCore.Qt.LeftDockWidgetArea)

    w = QtGui.QWidget()
    layout = QtGui.QVBoxLayout()
    w.setLayout(layout)

    self.c0 = QtGui.QCheckBox("B0")
    layout.addWidget(self.c0)

    self.c1 = QtGui.QCheckBox("B1")
    layout.addWidget(self.c1)

    spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
    layout.addItem(spacerItem)

    cboxes.setWidget(w)
    self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, cboxes)
</code>```

Title: Multiple checkboxes in QDockWidget

Body:
So I've been trying to make multiple checkboxes inside a QDockwidget but I seem to only be able to add one. This is what I have

def createDockWindows(self):
    cboxes = gui.QDockWidget("Cboxes", self)
    #cboxes.setWidget(gui.QCheckBox())
    cboxes.setAllowedAreas(core.Qt.LeftDockWidgetArea)

    self.c0 = gui.QCheckBox("B0")
    self.c0.setChecked(False)
    self.c0.stateChanged.connect(lambda:self.btnstate(self.c0))
    cboxes.setWidget(self.c0)

    self.c1 = gui.QCheckBox("B1")
    self.c1.setChecked(False)
    self.c1.stateChanged.connect(lambda:self.btnstate(self.c1))
    cboxes.setWidget(self.c1)

    self.addDockWidget(core.Qt.LeftDockWidgetArea, cboxes)

The output only gives me the box for B1.

I've done the dock method because I have some matplotlib graphs over to the right, a modified version of this example. If there is a better way to do this I'd be happy to change I'm just not finding much with google.

Body:
You must create a new widget, place a layout and add the checkboxes, that new widget you should add it to the QDockWidget.

def createDockWindows(self):
    cboxes = QtGui.QDockWidget("Cboxes", self)
    cboxes.setAllowedAreas(QtCore.Qt.LeftDockWidgetArea)

    w = QtGui.QWidget()
    layout = QtGui.QVBoxLayout()
    w.setLayout(layout)

    self.c0 = QtGui.QCheckBox("B0")
    layout.addWidget(self.c0)

    self.c1 = QtGui.QCheckBox("B1")
    layout.addWidget(self.c1)

    cboxes.setWidget(w)
    self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, cboxes)

plus [add QSpacer]:

def createDockWindows(self):
    cboxes = QtGui.QDockWidget("Cboxes", self)
    cboxes.setAllowedAreas(QtCore.Qt.LeftDockWidgetArea)

    w = QtGui.QWidget()
    layout = QtGui.QVBoxLayout()
    w.setLayout(layout)

    self.c0 = QtGui.QCheckBox("B0")
    layout.addWidget(self.c0)

    self.c1 = QtGui.QCheckBox("B1")
    layout.addWidget(self.c1)

    spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
    layout.addItem(spacerItem)

    cboxes.setWidget(w)
    self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, cboxes)


问:
android Map get whole Earth first
Iam using google map  and on Activity Ready first it`s show whole earth
and then camera move to my Location

I want to get my location direct without moving camera

```<code>  @Override
        public void onMapReady(GoogleMap googleMap) {
            aroundmemap = googleMap;
            Location locat = myLocationService.mycurrentlocationn;
            if (locat != null) {
                CameraPosition position = new CameraPosition.Builder()
                        .target(new LatLng(locat.getLatitude(), locat.getLongitude()))
                        .zoom(15).build();
                aroundmemap.animateCamera(CameraUpdateFactory.newCameraPosition(position));

            }}
</code>```

答: To move the camera without animating, use aroundmemap.moveCamera instead of animateCamera. See the Maps API documentation for more about moving the camera.

Title: android Map get whole Earth first

Body:
Iam using google map  and on Activity Ready first it`s show whole earth
and then camera move to my Location

I want to get my location direct without moving camera

  @Override
        public void onMapReady(GoogleMap googleMap) {
            aroundmemap = googleMap;
            Location locat = myLocationService.mycurrentlocationn;
            if (locat != null) {
                CameraPosition position = new CameraPosition.Builder()
                        .target(new LatLng(locat.getLatitude(), locat.getLongitude()))
                        .zoom(15).build();
                aroundmemap.animateCamera(CameraUpdateFactory.newCameraPosition(position));

            }}


问:
React, javascript object, if key value exists render an element
How do I check to see if a javascript object item has a key and render an element if it does exist.

This is my javascript object which is then parsed through and each item is made into a bootstrap list item.  Under items.title = Groups, there is an additional key "dropdown": "true" which is the element I would like to create a dropdown menu for.

```<code>var linksNav = {
    items: [
        {
            "type": "heading",
            "title": "News",
            "href": "#",
            "target": "_self"
        },
        {
            "type": "link",
            "title": "People",
            "href": "#",
            "target": "_self"
        },
        {
            "type": "link",
            "title": "Events",
            "href": "#",
            "target": "_self"
        },
        {
            "type": "link",
            "title": "Groups",
            "href": "#",
            "target": "_self",
            "dropdown": "true"
        },
        {
            "type": "heading",
            "title": "Capabilities",
            "href": "#",
            "target": "_self"
        },
        {
            "type": "link",
            "title": "Initiatives",
            "href": "#",
            "target": "_self"
        },
        {
            "type": "link",
            "title": "Who we are",
            "href": "#",
            "target": "_blank"
        },
    ]
}
</code>```

And this is my code (that doesn't work) to try to conditionally render a dropdown (the <NavSub /> tag) if that key exists for that menu item.
The result I get is my dropdown menu for each of my list items is
Nothing
.  Everything else shows up as normal, so I figure there's something wrong with my conditional statement.

```<code>render: function() {
  let dropdownMenu;
  if (this.props.dropdown=="true") {
    dropdownMenu = (<Navsub />)
  } else {
     dropdownMenu = (<div>Nothing</div>)
  }
  return (
    <li className={this.props.title + ' nav-items'}>
      <a href={this.props.href} target={this.props.target} className={this.state.color + ' dropdown-toggle'} onClick={this.onClick} data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">{this.props.title}</a>

      //I want to conditionall render this dropdown menu
      <ul className="dropdown-menu fade">
        {dropdownMenu}
      </ul>

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

答:
This approach may be overkill for your situation where the following will work for your situation:

```<code>if ((this.props.dropdown) && this.props.dropdown === "true"){
  dropdownMenu = <Navsub />;
} else {
  dropdownMenu = <div>Nothing</div>
}
</code>```

An alternative approach to checking whether the property dropdown exists  on the object this.props, you can use Object#hasOwnProperty with the shortcut && binary operator in your condition:

```<code>// the condition will only check if dropdown is true if it exists on this.props
if (this.props.hasOwnProperty('dropdown') && this.props.dropdown === "true") {
  dropdownMenu = <Navsub />;
} else {
  dropdownMenu = <div>Nothing</div>
}
</code>```

Object#hasOwnProperty is useful in scenarios where you want to
  ensure that the property exists on the object even in the case where
  its value is null or undefined.

Body:
How do I check to see if a javascript object item has a key and render an element if it does exist.

This is my javascript object which is then parsed through and each item is made into a bootstrap list item.  Under items.title = Groups, there is an additional key "dropdown": "true" which is the element I would like to create a dropdown menu for.

var linksNav = {
    items: [
        {
            "type": "heading",
            "title": "News",
            "href": "#",
            "target": "_self"
        },
        {
            "type": "link",
            "title": "People",
            "href": "#",
            "target": "_self"
        },
        {
            "type": "link",
            "title": "Events",
            "href": "#",
            "target": "_self"
        },
        {
            "type": "link",
            "title": "Groups",
            "href": "#",
            "target": "_self",
            "dropdown": "true"
        },
        {
            "type": "heading",
            "title": "Capabilities",
            "href": "#",
            "target": "_self"
        },
        {
            "type": "link",
            "title": "Initiatives",
            "href": "#",
            "target": "_self"
        },
        {
            "type": "link",
            "title": "Who we are",
            "href": "#",
            "target": "_blank"
        },
    ]
}

And this is my code (that doesn't work) to try to conditionally render a dropdown (the <NavSub /> tag) if that key exists for that menu item.
The result I get is my dropdown menu for each of my list items is
Nothing
.  Everything else shows up as normal, so I figure there's something wrong with my conditional statement.

render: function() {
  let dropdownMenu;
  if (this.props.dropdown=="true") {
    dropdownMenu = (<Navsub />)
  } else {
     dropdownMenu = (
Nothing
)
  }
  return (

      {this.props.title}

      //I want to conditionall render this dropdown menu

        {dropdownMenu}

  );
}

Body:
This approach may be overkill for your situation where the following will work for your situation:

if ((this.props.dropdown) && this.props.dropdown === "true"){
  dropdownMenu = <Navsub />;
} else {
  dropdownMenu = <div>Nothing</div>
}

An alternative approach to checking whether the property dropdown exists  on the object this.props, you can use Object#hasOwnProperty with the shortcut && binary operator in your condition:

// the condition will only check if dropdown is true if it exists on this.props
if (this.props.hasOwnProperty('dropdown') && this.props.dropdown === "true") {
  dropdownMenu = <Navsub />;
} else {
  dropdownMenu = <div>Nothing</div>
}

Object#hasOwnProperty is useful in scenarios where you want to
  ensure that the property exists on the object even in the case where
  its value is null or undefined.


问:
R Shiny Dashboard does not load rendered UI inside of sidebarMenu on initialization
I'm trying to generate a UI element that is dynamic based on how the user wishes to provide their input. I'm using the Shiny Dashboard for simplicity but I have encountered an issue with the sidebarMenu. Previously when I was placing static UI elements directly into the sidebarMenu, I had no issue, however when trying to place dynamic UI elements into the sidebarMenu I have problems. I'm using R 3.3.2 and Shiny 1.0.0 and Dashboard 0.5.3.

The specific problem I have is that when the program first loads up, the dynamic UI elements do not load. There does not appear to be any holdup in the code, as all the features of the interface work fine even while the dynamic UI is unloaded. I am able to get the dynamic UI to load by selecting one of the tabs in the navbar, or by hovering over something that I have implemented a tooltip on.

I am unable to provide the exact code but I have recreated a much smaller reproducible example that has all the same problems that my larger version does.

```<code>library("shiny")
library("shinydashboard")

header = dashboardHeader(
    title = "Dynamic UI Example"
)
sidebar = dashboardSidebar(
    sidebarMenu(
        menuItemOutput("dynamic_sidebar")
    )
)
body = dashboardBody(
    tabBox(
        tabPanel(
            strong("One")
        ),
        tabPanel(
            strong("Two")
        )
    )
)
ui = dashboardPage(header, sidebar, body)

server = shinyServer(function(input,output,session){
output$dynamic_sidebar = renderMenu({
        sidebarMenu(
            menuItem(
                "Slider or numeric problem",
                radioButtons("slider_or_numeric",
                   label = "Slider or Numeric Input",
                   choices = c("Slider", "Numeric"),
                   selected = "Slider",
                   inline = TRUE
                ),
                uiOutput("input")
            )
        )
    })
    output$input = renderUI({
        if (input$slider_or_numeric == "Slider"){
            sliderInput("slider",
                label = "slider",
                min = 0, max = 1,
                value = 0
            )
        } else {
            numericInput("numeric",
                label = "numeric",
                min = 0, max = 1,
                value = 0
            )
        }
    })
})

shinyApp(ui, server)
</code>```

To verify the problem, after loading it up just open the menu item and you'll see the radio buttons but nothing else. Switch the tab on the navbar from one to two, and the input should appear in the menu (must be done while the menu is open).

I'm really just grasping at straws here, I have been troubleshooting this for hours and I think it's just an incompatibility with these features. I'm really hoping someone can prove me wrong and show me that I'm just doing it wrong. I've already found alternatives for my main program but they don't have the same aesthetic with what I'm trying to accomplish here.

Thanks for any and all help!

答:
So I have found a solution from another SO post: r shiny - uiOutput not rendering inside menuItem and I'm slightly ashamed I did not manage to find this in my first set of search efforts. To sum up what the post says in more detail, the UI element I am rendering inside the menuItem is initialized as hidden, and hidden items are suspended by default. As the post details, you can change this option via the outputOptions function. Here is an updated version that works exactly as I wanted it to originally:

```<code>library("shiny")
library("shinydashboard")

header = dashboardHeader(
    title = "Dynamic UI Example"
)
sidebar = dashboardSidebar(
    sidebarMenu(
        menuItemOutput("dynamic_sidebar")
    )
)
body = dashboardBody(
    tabBox(
        tabPanel(
            strong("One")
        ),
        tabPanel(
            strong("Two")
        )
    )
)
ui = dashboardPage(header, sidebar, body)

server = shinyServer(function(input,output,session){

    output$input <- renderUI({})
    outputOptions(output, "input", suspendWhenHidden = FALSE)

output$dynamic_sidebar = renderMenu({
        sidebarMenu(
            menuItem(
                "Slider or numeric problem",
                radioButtons("slider_or_numeric",
                   label = "Slider or Numeric Input",
                   choices = c("Slider", "Numeric"),
                   selected = "Slider",
                   inline = TRUE
                ),
                uiOutput("input")
            )
        )
    })
    output$input = renderUI({
        if (input$slider_or_numeric == "Slider"){
            sliderInput("slider",
                label = "slider",
                min = 0, max = 1,
                value = 0
            )
        } else {
            numericInput("numeric",
                label = "numeric",
                min = 0, max = 1,
                value = 0
            )
        }
    })
})

shinyApp(ui, server)
</code>```

Note that it is necessary to initialize the output object BEFORE setting it's options or else it would be null and cause an error.

Thanks to Mike for attempting to answer the question, hopefully if someone else stumbles onto this problem they'll find this solution useful.

Body:
I'm trying to generate a UI element that is dynamic based on how the user wishes to provide their input. I'm using the Shiny Dashboard for simplicity but I have encountered an issue with the sidebarMenu. Previously when I was placing static UI elements directly into the sidebarMenu, I had no issue, however when trying to place dynamic UI elements into the sidebarMenu I have problems. I'm using R 3.3.2 and Shiny 1.0.0 and Dashboard 0.5.3.

The specific problem I have is that when the program first loads up, the dynamic UI elements do not load. There does not appear to be any holdup in the code, as all the features of the interface work fine even while the dynamic UI is unloaded. I am able to get the dynamic UI to load by selecting one of the tabs in the navbar, or by hovering over something that I have implemented a tooltip on.

I am unable to provide the exact code but I have recreated a much smaller reproducible example that has all the same problems that my larger version does.

library("shiny")
library("shinydashboard")

header = dashboardHeader(
    title = "Dynamic UI Example"
)
sidebar = dashboardSidebar(
    sidebarMenu(
        menuItemOutput("dynamic_sidebar")
    )
)
body = dashboardBody(
    tabBox(
        tabPanel(
            strong("One")
        ),
        tabPanel(
            strong("Two")
        )
    )
)
ui = dashboardPage(header, sidebar, body)

server = shinyServer(function(input,output,session){
output$dynamic_sidebar = renderMenu({
        sidebarMenu(
            menuItem(
                "Slider or numeric problem",
                radioButtons("slider_or_numeric",
                   label = "Slider or Numeric Input",
                   choices = c("Slider", "Numeric"),
                   selected = "Slider",
                   inline = TRUE
                ),
                uiOutput("input")
            )
        )
    })
    output$input = renderUI({
        if (input$slider_or_numeric == "Slider"){
            sliderInput("slider",
                label = "slider",
                min = 0, max = 1,
                value = 0
            )
        } else {
            numericInput("numeric",
                label = "numeric",
                min = 0, max = 1,
                value = 0
            )
        }
    })
})

shinyApp(ui, server)

To verify the problem, after loading it up just open the menu item and you'll see the radio buttons but nothing else. Switch the tab on the navbar from one to two, and the input should appear in the menu (must be done while the menu is open).

I'm really just grasping at straws here, I have been troubleshooting this for hours and I think it's just an incompatibility with these features. I'm really hoping someone can prove me wrong and show me that I'm just doing it wrong. I've already found alternatives for my main program but they don't have the same aesthetic with what I'm trying to accomplish here.

Thanks for any and all help!

Body:
So I have found a solution from another SO post: r shiny - uiOutput not rendering inside menuItem and I'm slightly ashamed I did not manage to find this in my first set of search efforts. To sum up what the post says in more detail, the UI element I am rendering inside the menuItem is initialized as hidden, and hidden items are suspended by default. As the post details, you can change this option via the outputOptions function. Here is an updated version that works exactly as I wanted it to originally:

library("shiny")
library("shinydashboard")

header = dashboardHeader(
    title = "Dynamic UI Example"
)
sidebar = dashboardSidebar(
    sidebarMenu(
        menuItemOutput("dynamic_sidebar")
    )
)
body = dashboardBody(
    tabBox(
        tabPanel(
            strong("One")
        ),
        tabPanel(
            strong("Two")
        )
    )
)
ui = dashboardPage(header, sidebar, body)

server = shinyServer(function(input,output,session){

    output$input <- renderUI({})
    outputOptions(output, "input", suspendWhenHidden = FALSE)

output$dynamic_sidebar = renderMenu({
        sidebarMenu(
            menuItem(
                "Slider or numeric problem",
                radioButtons("slider_or_numeric",
                   label = "Slider or Numeric Input",
                   choices = c("Slider", "Numeric"),
                   selected = "Slider",
                   inline = TRUE
                ),
                uiOutput("input")
            )
        )
    })
    output$input = renderUI({
        if (input$slider_or_numeric == "Slider"){
            sliderInput("slider",
                label = "slider",
                min = 0, max = 1,
                value = 0
            )
        } else {
            numericInput("numeric",
                label = "numeric",
                min = 0, max = 1,
                value = 0
            )
        }
    })
})

shinyApp(ui, server)

Note that it is necessary to initialize the output object BEFORE setting it's options or else it would be null and cause an error.

Thanks to Mike for attempting to answer the question, hopefully if someone else stumbles onto this problem they'll find this solution useful.


问:
nodejs : Parsing multipart/mixed
I want through nodejs to parse a "Multipart/mlixed" content, I tried using the following code but the req.body is always null:

```<code>    var express = require('express');
    var bodyParser = require('body-parser');
    app.use(bodyParser.urlencoded({ extended: true }));
    var app = express();

    app.post('/documents/videoCollect', function(req, res, nexr){
        console.log(req.body);
        res.send(req.body);
});
</code>```

below an example of a multipart/mixed content:

```<code>'content-type': 'multipart/mixed; boundary="----=_XXXXXXX"'
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<test>
  <name>testName</name>
</test>
</code>```

Do you know if there is a parser module for this, or how I could do it?
I tried with body-parser,body-parser-xml and formidable and the req.body is always null.

答:
body-parser does not handle multipart bodies, due to their complex and typically large nature. For multipart bodies, you may be interested in the following modules:

busboy and connect-busboy

multiparty and connect-multiparty

formidable

multer

This module provides the following parsers:

JSON body parser

Raw body parser

Text body parser

URL-encoded form body parser

Title: nodejs : Parsing multipart/mixed

Body:
I want through nodejs to parse a "Multipart/mlixed" content, I tried using the following code but the req.body is always null:

    var express = require('express');
    var bodyParser = require('body-parser');
    app.use(bodyParser.urlencoded({ extended: true }));
    var app = express();

    app.post('/documents/videoCollect', function(req, res, nexr){
        console.log(req.body);
        res.send(req.body);
});

below an example of a multipart/mixed content:

'content-type': 'multipart/mixed; boundary="----=_XXXXXXX"'
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<test>
  <name>testName</name>
</test>

Do you know if there is a parser module for this, or how I could do it?
I tried with body-parser,body-parser-xml and formidable and the req.body is always null.


问:
Facebook $_GET or $_REQUEST data?
I'm trying to figure out if this is possible or not within a facebook tab on a page.

My page url looks like this:

http://www.facebook.com/pages/appname/342342342?v=app_1234234

I simply want to pass it another param like this:

http://www.facebook.com/pages/appname/342342342?v=app_1234234&donated=1

I can do in within the app, but it doesnt work on tab - any ideas?

Tried these two:

```<code><?php echo $_GET["donated"]; ?>

<?php echo $_REQUEST["donated"]; ?>
</code>```

答:
Wes, I am not sure this is possible at this time.

I am also seeking a solution to this problem. It looks like iFrames in the Tabs will be available soon, and hopefully this change will allow access to the parent URL, similar to iFrame canvas applications.

I have asked a similar question here: http://developers.facebook.com/blog/post/434

Let me know if you come across any solutions!

Title: Facebook $_GET or $_REQUEST data?

Body:
I'm trying to figure out if this is possible or not within a facebook tab on a page.

My page url looks like this:

http://www.facebook.com/pages/appname/342342342?v=app_1234234

I simply want to pass it another param like this:

http://www.facebook.com/pages/appname/342342342?v=app_1234234&donated=1

I can do in within the app, but it doesnt work on tab - any ideas?

Tried these two:

<?php echo $_GET["donated"]; ?>

<?php echo $_REQUEST["donated"]; ?>