问:
Changing text from another activity
How to dynamically change the content of a TextView from another part of the screen?

I have a TabActivity class that draws a RelativeLayout that contains a TextView followed by a  with several tabs. Within each tab is a separate Intent. From one of the tab intents, I would like to change the text (via .setText) of the TextView from the parent TabActvity.

Is this possible?

答:
In a case of changing text from asynctask file, you need to implement an interface with a listener. Example:

AsynctaskFile:

```<code>OnReadyListener onReadyListener;

public class ABCAsynctaskFile{

   ...

   onReadyListener.onReady();

}

public interface OnReadyListener{

void onReady();

}

public void setOnReadyListener(OnReadyListener onReadyListener){

this.onReadyListener = onReadyListener;

}
</code>```

ActivityFile:

```<code>public class ABC extends AppCompactActivity implements ABCAsynctaskFile.OnReadyListener{
   ..

   ABCAsynctaskFile aBCAsynctaskFileObj = new ABCAsynctaskFile(context);

   aBCAsynctaskFile.setOnReadyListener(ABC.this)

}

@Override

public void onReady(){

   // Your wished changed in edit text.

}
</code>```

This structure will help you to prevent null pointer exception.

Title: Changing text from another activity

Body:
In a case of changing text from asynctask file, you need to implement an interface with a listener. Example:

AsynctaskFile:

OnReadyListener onReadyListener;

public class ABCAsynctaskFile{

   ...

   onReadyListener.onReady();

}

public interface OnReadyListener{

void onReady();

}

public void setOnReadyListener(OnReadyListener onReadyListener){

this.onReadyListener = onReadyListener;

}

ActivityFile:

public class ABC extends AppCompactActivity implements ABCAsynctaskFile.OnReadyListener{
   ..

   ABCAsynctaskFile aBCAsynctaskFileObj = new ABCAsynctaskFile(context);

   aBCAsynctaskFile.setOnReadyListener(ABC.this)

}

@Override

public void onReady(){

   // Your wished changed in edit text.

}

This structure will help you to prevent null pointer exception.


来源: stackexchange

问:
how to add zeros for integer variable
I'm very new to c# programming. I want to know how to add leading zeros for a integer type in c#.

ex:

int value = 23;

I want to use it like this ;

0023

Thanks in advance

答:
You can't. There's no such contextual information in an int. An integer is just an integer.

If you're talking about formatting, you could use something like:

```<code>string formatted = value.ToString("0000");
</code>```

... that will ensure there are at least 4 digits. (A format string of "D4" will have the same effect.) But you need to be very clear in your mind that this is only relevant in the string representation... it's not part of the integer value represented by value. Similarly, value has no notion of whether it's in decimal or hex - again, that's a property of how you format it.

(It's really important to understand this in reasonably simple cases like this, as it tends to make a lot more difference for things like date/time values, which again don't store any formatting information, and people often get confused.)

Note that there's one type which may surprise you: decimal. While it doesn't consider leading zeroes, it does have a notion of trailing zeroes (implicitly in the way it's stored), so 1.0m and 1.00m are distinguishable values.

ContentLicense: CC BY-SA 3.0

Title: how to add zeros for integer variable

Body:
You can't. There's no such contextual information in an int. An integer is just an integer.

If you're talking about formatting, you could use something like:

string formatted = value.ToString("0000");

... that will ensure there are at least 4 digits. (A format string of "D4" will have the same effect.) But you need to be very clear in your mind that this is only relevant in the string representation... it's not part of the integer value represented by value. Similarly, value has no notion of whether it's in decimal or hex - again, that's a property of how you format it.

(It's really important to understand this in reasonably simple cases like this, as it tends to make a lot more difference for things like date/time values, which again don't store any formatting information, and people often get confused.)

Note that there's one type which may surprise you: decimal. While it doesn't consider leading zeroes, it does have a notion of trailing zeroes (implicitly in the way it's stored), so 1.0m and 1.00m are distinguishable values.


问:
temporary column name in data.table
I want to give custom but temporary names (i.e., I dont want to alter the data.table using ":=") to the columns of a data.table after a column expression like mean. I have looked at some examples which use eval function but I want to do this in a single line of code. How can we do it? thank you!

I have this data

```<code>steps.dt = data.table(steps=rep(0:2, each=3),
date=as.factor(rep(c("10/2/2012", "10/3/2012", "10/4/2012"), each = 3)), interval = as.factor(rep(c(0,5,10), each = 3)))

steps.dt

   steps      date interval
1:     0 10/2/2012        0
2:     0 10/2/2012        0
3:     0 10/2/2012        0
4:     1 10/3/2012        5
5:     1 10/3/2012        5
6:     1 10/3/2012        5
7:     2 10/4/2012       10
8:     2 10/4/2012       10
9:     2 10/4/2012       10
</code>```

Now when I calculate means only to get a sense of the data and not modify it

```<code>steps.dt[,mean(steps), by = interval]
   interval V1
1:        0  0
2:        5  1
3:       10  2
</code>```

I get the result under a column named "V1". I want to give it a custom name like "steps.mean" without altering the data table using ":=" in the column expression.

答:
We can do this with base R

```<code>aggregate(steps~interval, steps.dt, mean)
</code>```

Title: temporary column name in data.table

Body:
I want to give custom but temporary names (i.e., I dont want to alter the data.table using ":=") to the columns of a data.table after a column expression like mean. I have looked at some examples which use eval function but I want to do this in a single line of code. How can we do it? thank you!

I have this data

steps.dt = data.table(steps=rep(0:2, each=3),
date=as.factor(rep(c("10/2/2012", "10/3/2012", "10/4/2012"), each = 3)), interval = as.factor(rep(c(0,5,10), each = 3)))

steps.dt

   steps      date interval
1:     0 10/2/2012        0
2:     0 10/2/2012        0
3:     0 10/2/2012        0
4:     1 10/3/2012        5
5:     1 10/3/2012        5
6:     1 10/3/2012        5
7:     2 10/4/2012       10
8:     2 10/4/2012       10
9:     2 10/4/2012       10

Now when I calculate means only to get a sense of the data and not modify it

steps.dt[,mean(steps), by = interval]
   interval V1
1:        0  0
2:        5  1
3:       10  2

I get the result under a column named "V1". I want to give it a custom name like "steps.mean" without altering the data table using ":=" in the column expression.

Body:
We can do this with base R

aggregate(steps~interval, steps.dt, mean)


问:
How do I turn off "comment is required" when leaving a rating on a product in woocommerce
I am using woocommerce and I allow comments on each product. The Star rating is included. In the woocommerce settings > products > reviews the box for "ratings are required to leave a review" is NOT checked. But, when testing and submitting a rating I get the message that a comment is required. Is there a way to turn this off that I'm missing?
If I turn off allow comments on each product than ratings are also turned off. </p>

答:
Have a try with this hook, place it in your theme's functions.php file</p>

```<code>add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );

function custom_override_checkout_fields( $fields ) {
     $fields['order']['order_comments']['required'] = false;
     return $fields;
}
</code>```

Body:
Have a try with this hook, place it in your theme's functions.php file

add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );

function custom_override_checkout_fields( $fields ) {
     $fields['order']['order_comments']['required'] = false;
     return $fields;
}


问:
Retrofit + GET method + www-form-urlencoded in Android
I am trying to fetch a list from a server. Problem is, Retrofit 2.0 is converting my request to an encoded request which is not acceptable to my server. So I need to remove that automatic encoding from the request. I have tried almost all solutions by putting encoded = true/false in the Request but it's not working at all.

Now, the situation is: All things are working good with "POST" Requests. Is there any similar way to do it with a "GET" Call? GET requests giving me "400 Bad Request" due to the encoded URL. The Main Issue with Encoding in GET.

POST call:

Working POST

```<code>@FormUrlEncoded
    @POST("login")
    Call<UserBean> getLogin(@FieldMap Map<String,String> params);
</code>```

POST ENCODED URL:(working)

```<code>https://---.---.com/---/webservice/login?
jhobject=%7B%22data%22%3A%22%7B%5C%22username%5C%22%3A%5C%22abz%40cbv.com%5C%22%2C%5C%22password%5C%22%3A%5C%221234%40567%5C%22%2C%5C%22manufacturername%5C%22%3A%5C%22Android%5C%22%2C%5C%22modelname%5C%22%3A%5C%22XT1068%5C%22%2C%5C%22osversion%5C%22%3A%5C%223.4.42-g0a0ded4%5C%22%2C%5C%22countrycode%5C%22%3A%5C%22in%5C%22%2C%5C%22appversion%5C%22%3A%5C%221.0%5C%22%2C%5C%22imei%5C%22%3A%5C%22353325060286683%5C%22%2C%5C%22appfor%5C%22%3A%5C%22Sony%5C%22%7D%22%2C%22enc%22%3A%220%22%7D
</code>```

Not Working GET

```<code> @Headers({"Content-Type:application/x-www-form-urlencoded"})
    @GET("getlisting")
    Call<MyBean> getListing(@QueryMap Map<String,String> params);
</code>```

GET ENCODED URL:(Not working)

```<code>    https://---.---.com/---/webservice/getlisting?
 jhobject=%257B%2522data%2522%253A%257B%2522pageno%2522%253A%25221%2522%252C%2522totalpages%2522%253A%25220%2522%252C%2522recordperpages%2522%253A%252210%2522%252C%2522cstatus%2522%253A%25221%2522%252C%2522reportid%2522%253A%252253%2522%257D%252C%2522enc%2522%253A%25220%2522%252C%2522token%2522%253A%252209046d74-c047-4534-be0b-050dadad18b8%257E%257E23717%2522%257D
</code>```

答:
You are doing double encoding

in post

```<code>jhobject=%7B
</code>```

in get

```<code>jhobject=%257B
</code>```

Body:
I am trying to fetch a list from a server. Problem is, Retrofit 2.0 is converting my request to an encoded request which is not acceptable to my server. So I need to remove that automatic encoding from the request. I have tried almost all solutions by putting encoded = true/false in the Request but it's not working at all.

Now, the situation is: All things are working good with "POST" Requests. Is there any similar way to do it with a "GET" Call? GET requests giving me "400 Bad Request" due to the encoded URL. The Main Issue with Encoding in GET.

POST call:

Working POST

@FormUrlEncoded
    @POST("login")
    Call<UserBean> getLogin(@FieldMap Map<String,String> params);

POST ENCODED URL:(working)

https://---.---.com/---/webservice/login?
jhobject=%7B%22data%22%3A%22%7B%5C%22username%5C%22%3A%5C%22abz%40cbv.com%5C%22%2C%5C%22password%5C%22%3A%5C%221234%40567%5C%22%2C%5C%22manufacturername%5C%22%3A%5C%22Android%5C%22%2C%5C%22modelname%5C%22%3A%5C%22XT1068%5C%22%2C%5C%22osversion%5C%22%3A%5C%223.4.42-g0a0ded4%5C%22%2C%5C%22countrycode%5C%22%3A%5C%22in%5C%22%2C%5C%22appversion%5C%22%3A%5C%221.0%5C%22%2C%5C%22imei%5C%22%3A%5C%22353325060286683%5C%22%2C%5C%22appfor%5C%22%3A%5C%22Sony%5C%22%7D%22%2C%22enc%22%3A%220%22%7D

Not Working GET

 @Headers({"Content-Type:application/x-www-form-urlencoded"})
    @GET("getlisting")
    Call<MyBean> getListing(@QueryMap Map<String,String> params);

GET ENCODED URL:(Not working)

    https://---.---.com/---/webservice/getlisting?
 jhobject=%257B%2522data%2522%253A%257B%2522pageno%2522%253A%25221%2522%252C%2522totalpages%2522%253A%25220%2522%252C%2522recordperpages%2522%253A%252210%2522%252C%2522cstatus%2522%253A%25221%2522%252C%2522reportid%2522%253A%252253%2522%257D%252C%2522enc%2522%253A%25220%2522%252C%2522token%2522%253A%252209046d74-c047-4534-be0b-050dadad18b8%257E%257E23717%2522%257D

Body:
You are doing double encoding

in post

jhobject=%7B

in get

jhobject=%257B


问:
How to order by custom time format in laravel?
I have to order a database table with a custom time format.
 The time format used in the table is like this:

1:30:PM

8:35:PM

5:50:PM

7:00 PM

I tried the following, but it does not sort them all in the correct order.

```<code>            ->orderBy('time_schedule.start_time', 'asc');
</code>```

After sorting the with the above method the result comes like

1:30:PM

5:50:PM

8:35:PM

7:00 PM

I'm not able to change the format saved, as i'm not working on that part of the application.

Also the data have to come sorted form laravel, cannot use front end sorting in my situation.

Please let me know whether there is a way to sort this with laravel.

答:
You can try SQL Date Function here:

```<code>ORDER BY DATE(time_schedule.start_time) DESC, time_schedule.start_time ASC
</code>```

Hope this helps.

Body:
I have to order a database table with a custom time format.
 The time format used in the table is like this:

1:30:PM

8:35:PM

5:50:PM

7:00 PM

I tried the following, but it does not sort them all in the correct order.

            ->orderBy('time_schedule.start_time', 'asc');

After sorting the with the above method the result comes like

1:30:PM

5:50:PM

8:35:PM

7:00 PM

I'm not able to change the format saved, as i'm not working on that part of the application.

Also the data have to come sorted form laravel, cannot use front end sorting in my situation.

Please let me know whether there is a way to sort this with laravel.

Body:
You can try SQL Date Function here:

ORDER BY DATE(time_schedule.start_time) DESC, time_schedule.start_time ASC

Hope this helps.


问:
How to use a programmatic 'get' equivalent in a WPF dependency property?
Where this is the clr way of writing a property:

```<code>public byte Value
{
   get{
     return GetByteData();
   }
   set{
     SetByteData(value);
   }
}
</code>```

I've read up on how to do the same the dependency property way, and this is all I could do by myself:

```<code>public byte Value
{
    get { return (byte)GetValue(ValueProperty); }
    set { SetValue(ValueProperty, value); }
}

public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
    "Value", typeof(byte), typeof(MyControl),
    new FrameworkPropertyMetadata((byte)0, ValueChanged));

public static void ValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    byte r = (byte)e.NewValue;
    MyControl v = (MyControl)d;
    v.SetByteData(r);
}
</code>```

With the examples I've looked at, from which I've made the above snippet, I can't find a place to put the GetByteData(), which calculates an output value for the current UI-state when the user interacts, so as to update the 'Value'.

Until previously I was putting it in the getter anyway like with clr, but I get the feeling that it's the wrong approach, but I could be wrong. Where should I be putting it? If not, what should be my approach? Is it at all possible to have a programmatic getter for a dependency property?

It's possible that I've been using the wrong keywords to look for a solution. Any help putting me in the right direction would be much appreciated. Thanks in advance.

答:
As long as it is only the source (and not the target) property of a Binding, as in

```<code>{Binding Value, ElementName=MyControlName}
</code>```

and you don't want to apply a value by a Style Setter, or animate the value, the property does not need to be a dependency property.

Just implement INotifyPropertyChanged like this:

```<code>public partial class MyControl : UserControl, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public byte Value
    {
       get { return GetByteData(); }
       set
       {
           SetByteData(value);
           PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Value)));
       }
    }

    ...
}
</code>```

Body:
Where this is the clr way of writing a property:

public byte Value
{
   get{
     return GetByteData();
   }
   set{
     SetByteData(value);
   }
}

I've read up on how to do the same the dependency property way, and this is all I could do by myself:

public byte Value
{
    get { return (byte)GetValue(ValueProperty); }
    set { SetValue(ValueProperty, value); }
}

public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
    "Value", typeof(byte), typeof(MyControl),
    new FrameworkPropertyMetadata((byte)0, ValueChanged));

public static void ValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    byte r = (byte)e.NewValue;
    MyControl v = (MyControl)d;
    v.SetByteData(r);
}

With the examples I've looked at, from which I've made the above snippet, I can't find a place to put the GetByteData(), which calculates an output value for the current UI-state when the user interacts, so as to update the 'Value'.

Until previously I was putting it in the getter anyway like with clr, but I get the feeling that it's the wrong approach, but I could be wrong. Where should I be putting it? If not, what should be my approach? Is it at all possible to have a programmatic getter for a dependency property?

It's possible that I've been using the wrong keywords to look for a solution. Any help putting me in the right direction would be much appreciated. Thanks in advance.

Body:
As long as it is only the source (and not the target) property of a Binding, as in

{Binding Value, ElementName=MyControlName}

and you don't want to apply a value by a Style Setter, or animate the value, the property does not need to be a dependency property.

Just implement INotifyPropertyChanged like this:

public partial class MyControl : UserControl, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public byte Value
    {
       get { return GetByteData(); }
       set
       {
           SetByteData(value);
           PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Value)));
       }
    }

    ...
}


问:
# symbol in URL bar of the browser
I have this in my jsx, # is used to stop the link if user click on the a tag.

```<code><a target={obj.handlerName === 'detail' ? `_blank` : ''} href={obj.handlerName === 'detail' ? `/products/${id}` : '#'} >{obj.name}</a>
</code>```

but I will have the extra # if the handlerName is not equal to 'detail'

Any clue how to get rid of that?

答:
What about using the includes() method?

```<code><a target={obj.handlerName.includes('detail') ? `_blank` : ''} href={obj.handlerName === 'detail' ? `/products/${id}` : '#'} >{obj.name}</a>
</code>```

Here's some useful reference:

https://www.w3schools.com/jsref/jsref_includes.asp
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes

Title: # symbol in URL bar of the browser

Body:
I have this in my jsx, # is used to stop the link if user click on the a tag.

<a target={obj.handlerName === 'detail' ? `_blank` : ''} href={obj.handlerName === 'detail' ? `/products/${id}` : '#'} >{obj.name}

but I will have the extra # if the handlerName is not equal to 'detail'

Any clue how to get rid of that?

Body:
What about using the includes() method?

<a target={obj.handlerName.includes('detail') ? `_blank` : ''} href={obj.handlerName === 'detail' ? `/products/${id}` : '#'} >{obj.name}</a>

Here's some useful reference:

https://www.w3schools.com/jsref/jsref_includes.asp
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes


问:
Getting ip address into my own code... (cordova - cordova-plugin-networkinterface)
I'm having a lot of troubles, trying to get the ip adress into a variable, in javascript.
This function, here, work correctly: it gives me an alert, with the correct ip address.

```<code>networkinterface.getIPAddress(function (ip) { alert(ip); });
</code>```

But when i try to get this ip in order to get it in my own code (myip), I can't seem to get it working :

```<code>myip = networkinterface.getIPAddress(function (ip) { return ip;} );
</code>```

What am i doing wrong, here ?

答:
My code can work like this: </p>

```<code>$window.networkinterface.getIPAddress(function (ip) { alert(ip); });
</code>```

Body:
I'm having a lot of troubles, trying to get the ip adress into a variable, in javascript.
This function, here, work correctly: it gives me an alert, with the correct ip address.

networkinterface.getIPAddress(function (ip) { alert(ip); });

But when i try to get this ip in order to get it in my own code (myip), I can't seem to get it working :

myip = networkinterface.getIPAddress(function (ip) { return ip;} );

What am i doing wrong, here ?

Body:
My code can work like this:

$window.networkinterface.getIPAddress(function (ip) { alert(ip); });


问:
Consuming web service from console app
We have a web app that contains web methods. I want to invoke one of those methods from a console app. I am new at this but I wrote a console app, added a service reference and tried to code invoking it.

If my web method is called "Transmit", I expected to see Transmit in the namespace I specified but instead I see "TransmitRequest", "TranmsitRequestBody", "TransmitResponse" and "TransmitResponseBody".

What are these things?
Have I done something wrong?
How do I invoke the web method in the web app from the console app?

Thank you for all help to this newbie. I am using VB.net 2008.

答:
If you expand the ServiceReference Folder in solutionExplorer, double click on your service and it should open the object explorer. Now you will see the class (the one without the I infront). In your code you will then instantiate a new variable with the [ServiceReferenceName].[ClassName] i.e.</p>

```<code>Dim svc as new ServiceReference1.MyWebService();
svc.Transmit();
</code>```

ContentLicense: CC BY-SA 2.5

Title: Consuming web service from console app

Body:
If you expand the ServiceReference Folder in solutionExplorer, double click on your service and it should open the object explorer. Now you will see the class (the one without the I infront). In your code you will then instantiate a new variable with the [ServiceReferenceName].[ClassName] i.e.

Dim svc as new ServiceReference1.MyWebService();
svc.Transmit();


问:
system io file not found exception/ error handling
I'm working in C# and I try to do a program that get some infoes the files in a Directory. I made it but i have a problem with the error Handling. When the program runs and for example I give just random numbers to list file infoes i get this error message:

"System.IO.DirectoryNotFoundException: "'Could not find a part of the path 'C:\Temp\first_project\first_project\bin\Debug\12345'.'"

Please someone help me to do the error handling.

Thank you in advance.

```<code>using System;
    using System.IO;
    class Test
        {
            static void Main(string[] args)
             {
                Console.WriteLine("Please :");
                string hely = Console.ReadLine();
                string[] __file = Directory.GetFiles(hely);
                string[] __dir = Directory.GetDirectories(hely);

                foreach (string i in __file)
                {
                    FileInfo fajl = new FileInfo(i);
                    Console.WriteLine("{0},{1},{2}", fajl.Name, fajl.Extension, fajl.LastWriteTime.ToString());
                }
                foreach (string i in __dir)
                {
                    DirectoryInfo _file = new DirectoryInfo(i);
                    Console.WriteLine("{0},{1},{2}", _file.Name, _file.Extension, _file.LastWriteTime.ToString());
                }

            Console.ReadKey();
             }

        }
</code>```

答:
Use try catch</p>

```<code>using System;
    using System.IO;
    class Test
        {
            static void Main(string[] args)
             {
                Console.WriteLine("Please :");
                string hely = Console.ReadLine();

                try
                {
                   string[] __file = Directory.GetFiles(hely);
                   string[] __dir = Directory.GetDirectories(hely);
                   foreach (string i in __file)
                   {
                      FileInfo fajl = new FileInfo(i);
                       Console.WriteLine("{0},{1},{2}", fajl.Name, fajl.Extension, fajl.LastWriteTime.ToString());
                   }

                   foreach (string i in __dir)
                   {
                      DirectoryInfo _file = new DirectoryInfo(i);
                      Console.WriteLine("{0},{1},{2}", _file.Name, _file.Extension, _file.LastWriteTime.ToString());
                   }
                }
                catch(System.IO.DirectoryNotFoundException ex)
                {
                    Console.WriteLine("Directory not found");
                }

                Console.ReadKey();
             }

        }
</code>```

Body:
I'm working in C# and I try to do a program that get some infoes the files in a Directory. I made it but i have a problem with the error Handling. When the program runs and for example I give just random numbers to list file infoes i get this error message:

"System.IO.DirectoryNotFoundException: "'Could not find a part of the path 'C:\Temp\first_project\first_project\bin\Debug\12345'.'"

Please someone help me to do the error handling.

Thank you in advance.

using System;
    using System.IO;
    class Test
        {
            static void Main(string[] args)
             {
                Console.WriteLine("Please :");
                string hely = Console.ReadLine();
                string[] __file = Directory.GetFiles(hely);
                string[] __dir = Directory.GetDirectories(hely);

                foreach (string i in __file)
                {
                    FileInfo fajl = new FileInfo(i);
                    Console.WriteLine("{0},{1},{2}", fajl.Name, fajl.Extension, fajl.LastWriteTime.ToString());
                }
                foreach (string i in __dir)
                {
                    DirectoryInfo _file = new DirectoryInfo(i);
                    Console.WriteLine("{0},{1},{2}", _file.Name, _file.Extension, _file.LastWriteTime.ToString());
                }

            Console.ReadKey();
             }

        }

Body:
Use try catch

using System;
    using System.IO;
    class Test
        {
            static void Main(string[] args)
             {
                Console.WriteLine("Please :");
                string hely = Console.ReadLine();

                try
                {
                   string[] __file = Directory.GetFiles(hely);
                   string[] __dir = Directory.GetDirectories(hely);
                   foreach (string i in __file)
                   {
                      FileInfo fajl = new FileInfo(i);
                       Console.WriteLine("{0},{1},{2}", fajl.Name, fajl.Extension, fajl.LastWriteTime.ToString());
                   }

                   foreach (string i in __dir)
                   {
                      DirectoryInfo _file = new DirectoryInfo(i);
                      Console.WriteLine("{0},{1},{2}", _file.Name, _file.Extension, _file.LastWriteTime.ToString());
                   }
                }
                catch(System.IO.DirectoryNotFoundException ex)
                {
                    Console.WriteLine("Directory not found");
                }

                Console.ReadKey();
             }

        }


问:
JQuery how to submit only changed fields when the form has some data array
I have a database structure with an one to many relationship. In the html form, there are similar inputs with a name 'item[]' or 'file[]' to make the data to be an array

```<code><form action="submit.php" method="get">
  Name:<input type="text" name="name"/><br/>
  Item:<input type="text" name="item[]"/><br/>
  File:<input type="file" name="file[]" multiple/>
  Item:<input type="text" name="item[]"/><br/>
  File:<input type="file" name="file[]" multiple/>
  Select:<select name="select" value="1" original="1">
  <option value="1">One</option>
  <option value="2">Two</option>
  </select>

</form>
</code>```

how can i submit only the changed field, and in the server side i can recongize which item is changed? I tried disable the inputs, but it seems not working.

another problem is that if i submit the form with ajax, how can i submit the files

答:
```<code>var data = {};
$(function(){
    $(document).on('change', 'input', function(){
    data[this.name] = this.value;
  });
});
</code>```

You can add a change event to the inputs and add the changed values to the data object or append fields to form data. So data object with contain only the changed values.

You can use formdata for sending files data. Please refer the this link.

How to use FormData for ajax file upload

Body:
I have a database structure with an one to many relationship. In the html form, there are similar inputs with a name 'item[]' or 'file[]' to make the data to be an array

<form action="submit.php" method="get">
  Name:<input type="text" name="name"/>

  Item:<input type="text" name="item[]"/>

  File:<input type="file" name="file[]" multiple/>
  Item:<input type="text" name="item[]"/>

  File:<input type="file" name="file[]" multiple/>
  Select:<select name="select" value="1" original="1">
  <option value="1">One</option>
  <option value="2">Two</option>
  </select>

</form>

how can i submit only the changed field, and in the server side i can recongize which item is changed? I tried disable the inputs, but it seems not working.

another problem is that if i submit the form with ajax, how can i submit the files

Body:
var data = {};
$(function(){
    $(document).on('change', 'input', function(){
    data[this.name] = this.value;
  });
});

You can add a change event to the inputs and add the changed values to the data object or append fields to form data. So data object with contain only the changed values.

You can use formdata for sending files data. Please refer the this link.

How to use FormData for ajax file upload


问:
Using Jquery/Ajax to display a result of codeigniter function in view
I'm currently working on a project by using codeigniter. Where I have a view page called dashboard.php. In dashboard, my task is to display a graph. From dashbord.php I'm calling the controller function which is stat(). I have created the graph using Morris.js and which is located in stat.php.

controller function stat()

```<code>  public function stat()
  {
    $this->load->view('template/admin_header', $data);
    $this->load->view('merchant/stat', $data);
    $this->load->view('template/footer', $data);
  }
</code>```

view page stat.php

```<code><script>
$(function() {
     Morris.Area({
        element: 'morris-area-chart-scan-payment',
        data: [
        {
            period: 'Mon',
            spoint: 2666,
            mpayment: null,
        },
        {
            period: 'Tue',
            spoint: 2778,
            mpayment: 1350,
        },
        {
            period: 'Wed',
            spoint: 4912,
            mpayment: 1969,
        }
      ],

      xkey: 'period',
     ykeys: ['spoint', 'mpayment'],
     labels: ['Scan Point', 'Payment'],
     parseTime: false,
     pointSize: 2,
     hideHover: 'auto',
     resize: true
     });
  });
 </script>

 <div id="morris-area-chart-scan-payment"></div>
</code>```

dashboard.php the view page

```<code><div id="div1"></div>
</code>```

I have created a div tag in the view page dashboard.php. How can I display the graph in stat.php in dashboard.php using JQuery/Ajax ?

答:
Codeigniter should return the array of morris data as json on the url which will be requested in the ajax below

```<code>$(function() {
  var morris_area = Morris.Area({
    element: 'morris-area-chart-scan-payment',
    data: [
      {
        period: 'Mon',
        spoint: 2666,
        mpayment: null,
      },
      {
        period: 'Tue',
        spoint: 2778,
        mpayment: 1350,
      },
      {
        period: 'Wed',
        spoint: 4912,
        mpayment: 1969,
      }
    ],
    xkey: 'period',
    ykeys: ['spoint', 'mpayment'],
    labels: ['Scan Point', 'Payment'],
    parseTime: false,
    pointSize: 2,
    hideHover: 'auto',
    resize: true
  });

  $('.some-button').on('click', function loadMorrisData() {
    $.ajax({
      url: "http://your-test-url.something",
      success: function(data) {
        morris_area.setData(data);
      }
    });
  });
});
</code>```

Body:
I'm currently working on a project by using codeigniter. Where I have a view page called dashboard.php. In dashboard, my task is to display a graph. From dashbord.php I'm calling the controller function which is stat(). I have created the graph using Morris.js and which is located in stat.php.

controller function stat()

  public function stat()
  {
    $this->load->view('template/admin_header', $data);
    $this->load->view('merchant/stat', $data);
    $this->load->view('template/footer', $data);
  }

view page stat.php

dashboard.php the view page

I have created a div tag in the view page dashboard.php. How can I display the graph in stat.php in dashboard.php using JQuery/Ajax ?

Body:
Codeigniter should return the array of morris data as json on the url which will be requested in the ajax below

$(function() {
  var morris_area = Morris.Area({
    element: 'morris-area-chart-scan-payment',
    data: [
      {
        period: 'Mon',
        spoint: 2666,
        mpayment: null,
      },
      {
        period: 'Tue',
        spoint: 2778,
        mpayment: 1350,
      },
      {
        period: 'Wed',
        spoint: 4912,
        mpayment: 1969,
      }
    ],
    xkey: 'period',
    ykeys: ['spoint', 'mpayment'],
    labels: ['Scan Point', 'Payment'],
    parseTime: false,
    pointSize: 2,
    hideHover: 'auto',
    resize: true
  });

  $('.some-button').on('click', function loadMorrisData() {
    $.ajax({
      url: "http://your-test-url.something",
      success: function(data) {
        morris_area.setData(data);
      }
    });
  });
});


问:
Emergency notification which does not prompt unlocking on locked screen to open activity
There is an emergency app named Medical Id. It has a marvelous feature in which it shows notification on locked screen. The user can just double tap on the notification to open the activity. For other app notifications, if the user tap, it prompts for unlocking first. I am looking for the same feature but unable to achieve the same. I have tried adding flags to the attached windows. </p>

```<code>@Override
    public void onAttachedToWindow()
    {
        super.onAttachedToWindow();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON &
                WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD &
                WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED &
                WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON &
                WindowManager.LayoutParams.FLAG_FULLSCREEN
        );
    }
</code>```

<p>Added shownonlockscreen to the activity in the manifest as well, But it prompts for unlocking the screen before opening the activity. Have a look on the medical id for clarity. I don't know what they are using to bypass unlock. The phone settings for notifications are public in my phone.  The amazing part is even if your phone notification setting is private, medical id notification will be present there even when no else notification is present. Any leads is helpful. </p>

答:
You should use pipes | instead of ampersands &

```<code>getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON|
            WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD|
            WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED|
            WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
</code>```

Also this only works above Android 4.4

ContentLicense: CC BY-SA 4.0

Body:
There is an emergency app named Medical Id. It has a marvelous feature in which it shows notification on locked screen. The user can just double tap on the notification to open the activity. For other app notifications, if the user tap, it prompts for unlocking first. I am looking for the same feature but unable to achieve the same. I have tried adding flags to the attached windows.

@Override
    public void onAttachedToWindow()
    {
        super.onAttachedToWindow();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON &
                WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD &
                WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED &
                WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON &
                WindowManager.LayoutParams.FLAG_FULLSCREEN
        );
    }

Added shownonlockscreen to the activity in the manifest as well, But it prompts for unlocking the screen before opening the activity. Have a look on the medical id for clarity. I don't know what they are using to bypass unlock. The phone settings for notifications are public in my phone.  The amazing part is even if your phone notification setting is private, medical id notification will be present there even when no else notification is present. Any leads is helpful.

Body:
You should use pipes | instead of ampersands &

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON|
            WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD|
            WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED|
            WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

Also this only works above Android 4.4


问:
FCM Multiple push notifications not working properly when app in background state
I am using fcm for push notifications, I am handling only data payload. Multiple Notifications are working fine when app is in foreground, here I am using id value from server in click_action to move the notification to related post when we tap on it.But, when app is in background/closed state whenever my getting multiple notifications, I will tap on one notification it will goes to related post but remaining all are not redirecting to related post, just cleared from notification. I didn't find out why this problem happening.Here is my code

```<code>public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "MyFirebaseMsgService";

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    Log.d(TAG, "From: " + remoteMessage.getFrom());

        Log.d(TAG, "Message data payload: " + remoteMessage.getData());

sendNotification(remoteMessage.getData().get("title"),remoteMessage.getData().get("body"),remoteMessage.getData().get("click_action"),image);
        }

private void sendNotification(String title, String message, String id, String image) {
    Log.d("notificationdetails",title+",,,"+message+",,"+id);
    Intent  intent = null;

int postid = Integer.valueOf(id);
        if(id.equals("")|| id==null) {
            intent = new Intent(this, SplashActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        }

else{

        Constants.PushId = postid;
        intent = new Intent(this, DetailActivity.class);
        Log.d("mypostid",postid+"");
        intent.putExtra("id", postid);
        intent.putExtra("backpage","main");
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    }

    PendingIntent pendingIntent = PendingIntent.getActivity(this, postid, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher_primepost)
            .setContentTitle(title)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(message))
            .setContentText(message)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    Random random = new Random();
    int num = random.nextInt(99999-1000)+1000;
    notificationManager.notify(num /* ID of notification */, notificationBuilder.build());
}

}
</code>```

Manifest.xml

```<code> <activity android:name="com.primepostnews.app.Activities.DetailActivity"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="Detail" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>

    </activity>
</code>```

答:
There are two types of messages data messages and notification messages. Data messages are handled here in onMessageReceived whether the app is in the foreground or background. Data messages are the type traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app is in the foreground. When the app is in the background an automatically generated notification is displayed.When the user taps on the notification they are returned to the app. Messages containing both notification and data payloads are treated as notification messages. The Firebase console always sends notification messages.</p>

```<code> if (remoteMessage.getData() != null && remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());

sendNotification(remoteMessage.getData().get("title"),remoteMessage.getData().get("body"),remoteMessage.getData().get("click_action"),image);

        } else if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());

sendNotification(remoteMessage.getNotification().getBody(), remoteMessage.getNotification().getBody(),remoteMessage.getData().get("click_action"),image);
        }
</code>```

Body:
I am using fcm for push notifications, I am handling only data payload. Multiple Notifications are working fine when app is in foreground, here I am using id value from server in click_action to move the notification to related post when we tap on it.But, when app is in background/closed state whenever my getting multiple notifications, I will tap on one notification it will goes to related post but remaining all are not redirecting to related post, just cleared from notification. I didn't find out why this problem happening.Here is my code

public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "MyFirebaseMsgService";

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    Log.d(TAG, "From: " + remoteMessage.getFrom());

        Log.d(TAG, "Message data payload: " + remoteMessage.getData());

sendNotification(remoteMessage.getData().get("title"),remoteMessage.getData().get("body"),remoteMessage.getData().get("click_action"),image);
        }

private void sendNotification(String title, String message, String id, String image) {
    Log.d("notificationdetails",title+",,,"+message+",,"+id);
    Intent  intent = null;

int postid = Integer.valueOf(id);
        if(id.equals("")|| id==null) {
            intent = new Intent(this, SplashActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        }

else{

        Constants.PushId = postid;
        intent = new Intent(this, DetailActivity.class);
        Log.d("mypostid",postid+"");
        intent.putExtra("id", postid);
        intent.putExtra("backpage","main");
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    }

    PendingIntent pendingIntent = PendingIntent.getActivity(this, postid, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher_primepost)
            .setContentTitle(title)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(message))
            .setContentText(message)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    Random random = new Random();
    int num = random.nextInt(99999-1000)+1000;
    notificationManager.notify(num /* ID of notification */, notificationBuilder.build());
}

}

Manifest.xml

 <activity android:name="com.primepostnews.app.Activities.DetailActivity"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="Detail" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>

    </activity>

Body:
There are two types of messages data messages and notification messages. Data messages are handled here in onMessageReceived whether the app is in the foreground or background. Data messages are the type traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app is in the foreground. When the app is in the background an automatically generated notification is displayed.When the user taps on the notification they are returned to the app. Messages containing both notification and data payloads are treated as notification messages. The Firebase console always sends notification messages.

 if (remoteMessage.getData() != null && remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());

sendNotification(remoteMessage.getData().get("title"),remoteMessage.getData().get("body"),remoteMessage.getData().get("click_action"),image);

        } else if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());

sendNotification(remoteMessage.getNotification().getBody(), remoteMessage.getNotification().getBody(),remoteMessage.getData().get("click_action"),image);
        }


问:
I can't fix the gap between body and footer
There seems to be a gap between the footer and main body. i want the body to touch the footer, as seen i want it to completely fill up the space in the middle.

https://ibb.co/dUpFJF

@charset "utf-8";

/* CSS Document */

body {
  font-family: 'Droid Sans', sans-serif;
  margin-top: 0px;
  margin-left: 0px;
  margin-right: 0px;
  margin-bottom: 0px;
  min-height: 100%;
}

.div_top1 {
  height: 30px;
  margin: 0 auto;
  width: 100%;
  border-bottom: 1px solid #FFF;
  background-color: #2d2d2d;
}

.div_top2 {
  height: 150px;
  width: 100%;
  background-color: #072135;
}

.main_container {
  width: 100%;
  margin: 0 auto;
  background-color: #FFF;
  overflow: auto;
  min-height: 100%;
  display: inline-block;
}

.container_right {
  height: 100%;
  padding-left: 20px;
  margin: 0 auto;
}

.container_left {
  float: left;
  text-align: left;
  border-right: 2px solid #5a5c5d;
  border-bottom: 1px solid #5a5c5d;
  height: 100%;
  overflow: hidden;
}

.bk {
  border-top: 4px solid #da6161;
  display: table;
  height: 200px;
  margin: 0 auto;
  margin-top: 30px;
  padding: 8px;
}

.icon {
  float: left;
  display: block;
}

.icon-bar {
  width: 70px;
  /* Set a specific width */
  background-color: #FFF;
  /* Dark-grey background */
  height: 100%;
}

.icon-bar a {
  display: block;
  /* Make the links appear below each other instead of side-by-side */
  text-align: center;
  /* Center-align text */
  padding: 16px;
  /* Add some padding */
  transition: all 0.3s ease;
  /* Add transition for hover effects */
  color: black;
  /* White text color */
  font-size: 27px;
  /* Increased font-size */
  height: 100%;
}

.icon-bar a:hover {
  background-color: #5a5c5d;
  /* Add a hover color */
}

.active {
  background-color: #818384;
  /* Add an active/current color */
}

答:
you made the footer element absolutely positioned relative to parent(body tag).

try wrapping your code in a  after  element

html

```<code><body>
<div class="wrapper">
<!-- your code here -->
</div>
</body>
</code>```

css

```<code>.wrapper
{
position:relative;
}
</code>```

hope this works...

Body:
you made the footer element absolutely positioned relative to parent(body tag).

try wrapping your code in a  after  element

html

<body>
<div class="wrapper">
<!-- your code here -->
</div>
</body>

css

.wrapper
{
position:relative;
}

hope this works...


问:
PhpStorm Testing: Cannot select PHPUnit to run test
I am unable to run a directory/folder as a PHPUnit test from the context menu - it offers browser debugging and running as a php script only. I can set one up tests in the "Edit configurations" panel, and they work fine, but I have hundreds of test files, and cannot set each one up individually.

At one point, in a previous project, I could Ctrl + T and it would run the file/test I was in as a PHPUnit test, without any previous configuration for the file. I've reviewed my setup and they look identical.

"Settings -> PHPUnit" script is set to vendor\autoload, default config file is pointed to local phpunit.xml.

"Edit Configurations -> Defaults -> PHPUnit" is set to use default configuration file.

Again, I can run PHPUnit tests, it just seems like my PhpStorm is no longer recognising the files as suitable for PHPUnit unless I specify each one.

PhpStorm 2017.1.3

PHPUnit 5.7.20

PHP 5.6

Any advice would be appreciated, thanks.

答: With Run this will send your script to php. With debug this will execute the phpunit tests you've configured. </p>


问:
Where to put enumerations in a Java project?
We put entities in a domain package. Something like com.acme.domain or com.acme.model.

Entities often have properties which represent codes, rather than free form strings. Something like a sort order code (ASC or DESC) or publish status code (DRAFT, SUBMITTED, PUBLISHED). I create enums for these, so I can make decisions in "business logic".

Question is: where do we put these enums? The same package as entities or a different package like com.acme.domain.support?

When you provide an answer, please explain why you'd put enum in one package vs another.

答:
Where to put enumerators is dependent on where they have to be used in the project.

Some use cases :

If we need these enums to be used across systems and multiple services then we can put them either in our clients or domains which are the modules made to be shared.

If we need the use of the enums just within our own service context then we should put it in our service package/module.

So, the cardinal rule is that we should never share the resources or put the resources in sharable modules/packages which are not of any use to clients or the services which are using our shared resources.


问:
How to measure execution time of query on Google Cloud
How to measure execution time of query on Google Cloud?

Earlier there was provision of Query Browser of Google. Which is now absolute and redirected to google cloud console.

Thanks.

答:
One easy way is to use Stackdriver Trace. You can search "Trace" in GCP console, and then it shows list of requests. Click on the requests you are interested and you can see execution timelines.

Appstats provides more details and customization, but definitely needs more work.


问:
Unable to use Python2 in Jupyter Notebook: Python in worker has different version 2.7 than that in driver 3.4
My knowledge with Jupyter and python is limited. You can sense it after reading this question. I have two set of servers: one set of servers running the spark-standalone cluster and one server running the Jupyter notebook.

I have installed Jupyter in my server twice with commands:

```<code>pip2 install jupyter
pip3 install jupyter
</code>```

After installing I set the following environments:

```<code>export PYSPARK_DRIVER_PYTHON=jupyter
export PYSPARK_DRIVER_PYTHON_OPTS="notebook --notebook-dir=./ --ip=* --no-browser"
</code>```

Then I used Jupyter to connect to the spark-standalone cluster with the following command:

```<code>./bin/pyspark --master spark://192.XXX.XXX.XXX:7077
</code>```

I can login in the Jupyter homepage in my laptop and in the right corner the message indicates that I am using Python2. However, I cannot execute Python2 codes while Python3 codes work.

I tried the following command

export PYSPARK_PYTHON=python2

and

  import os
    os.environ["PYSPARK_PYTHON"]="/usr/local/bin/python2"

but with no luck.

Is this because I am using a Jupyter notebook created by pip3? If it is, how can I switch to the Jupyter notebook created by pip2?

Thanks in advance if you have any suggestions. If you need more information to locate the cause, please feel free to let me know.

答:
I put this problem aside these days and picked it again today. To determine whether spark or jupyter was responsible for this problem, I launched the Jupyter Notebook without spark: jupyter notebook. The same problem arose again so I knew there was something wrong with my Jupyter Notebook.

I referred to this document: Installing the IPython kernel. After executing the following commands I could run Python2 codes.

python2 -m pip install ipykernel
python2 -m ipykernel install --user

I have tried these two commands before posting the questions but with no luck. I guess maybe I made some mistakes when coping/pasting? Anyway, the problem is now solved.

Body:
My knowledge with Jupyter and python is limited. You can sense it after reading this question. I have two set of servers: one set of servers running the spark-standalone cluster and one server running the Jupyter notebook.

I have installed Jupyter in my server twice with commands:

pip2 install jupyter
pip3 install jupyter

After installing I set the following environments:

export PYSPARK_DRIVER_PYTHON=jupyter
export PYSPARK_DRIVER_PYTHON_OPTS="notebook --notebook-dir=./ --ip=* --no-browser"

Then I used Jupyter to connect to the spark-standalone cluster with the following command:

./bin/pyspark --master spark://192.XXX.XXX.XXX:7077

I can login in the Jupyter homepage in my laptop and in the right corner the message indicates that I am using Python2. However, I cannot execute Python2 codes while Python3 codes work.

I tried the following command

export PYSPARK_PYTHON=python2

and

  import os
    os.environ["PYSPARK_PYTHON"]="/usr/local/bin/python2"

but with no luck.

Is this because I am using a Jupyter notebook created by pip3? If it is, how can I switch to the Jupyter notebook created by pip2?

Thanks in advance if you have any suggestions. If you need more information to locate the cause, please feel free to let me know.


问:
Wildfly treating concurrency management as transactional
I had a class that looked like this:

```<code>@Singleton
@ConcurrencyManagement(ConcurrencyManagementType.CONTAINER)
@Lock(LockType.WRITE)
@AccessTimeout(value = 20, unit = TimeUnit.MINUTES)
public class MyClass{

    public void someLongRunningQuery(){

    }

}
</code>```

However, this would fail with:

org.jboss.resteasy.spi.UnhandledException: javax.ejb.EJBTransactionRolledbackException: Transaction rolled back

I was able to resolve this by adding this annotation.

@TransactionTimeout(value = 20, unit = TimeUnit.MINUTES)

My question is - why is jboss treating this method as a transaction? My understanding is the concurrency management and transaction management are different things.

答:
Transaction timeout handling is not defined in EJB spec and JBoss uses a separate transaction management module to do that. Your example points at a REST access to your singleton - is the Singleton also a REST endpoint or is it invoked from some REST endpoint bean?  Just a couple of ideas:

If you have a REST endpoint that injects your singleton and invokes the long running op, isn't it by any chance a @Stateless bean? EJB beans are transaction enabled by default, therefore if a client(REST endpoint) initiates a transaction(it does by default - @TransactionAttribute(REQUIRED)), your singleton will also participate in the same transaction, but because its invocation takes longer than the default transaction timeout value(300s) it causes transaction rollback. If you do not need a transaction on the rest layer, try disabling it with @TransactionAttribute(NOT_SUPPORTED)

If you invoke this long running op from REST layer, wouldn't it be better to use @Asynchronous and return some kind of request/job handle to the client, so that it can query the status of the operation instead of waiting and blocking while it finishes? Keep in mind that EJBs are pooled resources, therefore invoking this long op multiple times can drain your pool and cause acquisition timeouts.

Body:
I had a class that looked like this:

@Singleton
@ConcurrencyManagement(ConcurrencyManagementType.CONTAINER)
@Lock(LockType.WRITE)
@AccessTimeout(value = 20, unit = TimeUnit.MINUTES)
public class MyClass{

    public void someLongRunningQuery(){

    }

}

However, this would fail with:

org.jboss.resteasy.spi.UnhandledException: javax.ejb.EJBTransactionRolledbackException: Transaction rolled back

I was able to resolve this by adding this annotation.

@TransactionTimeout(value = 20, unit = TimeUnit.MINUTES)

My question is - why is jboss treating this method as a transaction? My understanding is the concurrency management and transaction management are different things.


问:
JavaScript sort array not working
I'm trying to sort an array of objects with an attribute page.  This is being done in a computed property with Vue.

To do this I'm using the following function, which first builds the objects:

```<code> sorted: function(){
     var pages = this.selectedKKS['pages'];
     var list;
     try {
       list = [];
       Object.keys(pages).forEach(function(key){
         console.log(key + " is the key")
         var obj = {};
         obj.title = key;
         obj.page = pages[key]
         list.push(obj)
     });
     }
     catch(e){
       console.log(e);
     }
     var sorted = list.sort(function(a, b){
       console.log('a.page is ' + a.page + ' and b.page is ' + b.page);
       return a.page > b.page;

     });
     return sorted;
 }
</code>```

Just to make sure that I'm actually comparing pages as I intend, here's the console log:

```<code>a.page is 84 and b.page is 28
App.vue?077f:353 a.page is 84 and b.page is 46
App.vue?077f:353 a.page is 28 and b.page is 46
App.vue?077f:353 a.page is 84 and b.page is 35
App.vue?077f:353 a.page is 46 and b.page is 35
App.vue?077f:353 a.page is 28 and b.page is 35
App.vue?077f:353 a.page is 84 and b.page is 14
App.vue?077f:353 a.page is 46 and b.page is 14
App.vue?077f:353 a.page is 35 and b.page is 14
App.vue?077f:353 a.page is 28 and b.page is 14
App.vue?077f:353 a.page is 84 and b.page is 5
App.vue?077f:353 a.page is 46 and b.page is 5
App.vue?077f:353 a.page is 84 and b.page is 8
App.vue?077f:353 a.page is 5 and b.page is 8
</code>```

I'm looping over this computed property in my template, and since it's being sorted incorrectly it's giving me an undesirable result:

```<code>            <f7-list>
            <f7-list-item v-for="val in sorted" @click="openpdf(selectedKKS.url, val.page)">
                <f7-col><span style="color: black">{{ val.title }}</span></f7-col>
                <f7-col>{{ val.page }}</f7-col>
            </f7-list-item>
            </f7-list>
</code>```

Any ideas as to what could be going wrong?

答:
Because the values are strings, they're sorted in lexical (alphabetical) instead of numerical order.

Change your sort function as follows:

```<code>list.sort(function(a, b){
    return Number(a.page) > Number(b.page);
});
</code>```

Or better still:

```<code>list.sort(function(a, b){
    return Number(a.page) - Number(b.page);
});
</code>```

As noted in the comments, it's better to do the number conversion during object creation to avoid having to repeatedly carry it out for each comparison.

Title: JavaScript sort array not working

Body:
I'm trying to sort an array of objects with an attribute page.  This is being done in a computed property with Vue.

To do this I'm using the following function, which first builds the objects:

 sorted: function(){
     var pages = this.selectedKKS['pages'];
     var list;
     try {
       list = [];
       Object.keys(pages).forEach(function(key){
         console.log(key + " is the key")
         var obj = {};
         obj.title = key;
         obj.page = pages[key]
         list.push(obj)
     });
     }
     catch(e){
       console.log(e);
     }
     var sorted = list.sort(function(a, b){
       console.log('a.page is ' + a.page + ' and b.page is ' + b.page);
       return a.page > b.page;

     });
     return sorted;
 }

Just to make sure that I'm actually comparing pages as I intend, here's the console log:

a.page is 84 and b.page is 28
App.vue?077f:353 a.page is 84 and b.page is 46
App.vue?077f:353 a.page is 28 and b.page is 46
App.vue?077f:353 a.page is 84 and b.page is 35
App.vue?077f:353 a.page is 46 and b.page is 35
App.vue?077f:353 a.page is 28 and b.page is 35
App.vue?077f:353 a.page is 84 and b.page is 14
App.vue?077f:353 a.page is 46 and b.page is 14
App.vue?077f:353 a.page is 35 and b.page is 14
App.vue?077f:353 a.page is 28 and b.page is 14
App.vue?077f:353 a.page is 84 and b.page is 5
App.vue?077f:353 a.page is 46 and b.page is 5
App.vue?077f:353 a.page is 84 and b.page is 8
App.vue?077f:353 a.page is 5 and b.page is 8

I'm looping over this computed property in my template, and since it's being sorted incorrectly it's giving me an undesirable result:

            <f7-list>
            <f7-list-item v-for="val in sorted" @click="openpdf(selectedKKS.url, val.page)">
                <f7-col>{{ val.title }}</f7-col>
                <f7-col>{{ val.page }}</f7-col>
            </f7-list-item>
            </f7-list>

Any ideas as to what could be going wrong?

Body:
Because the values are strings, they're sorted in lexical (alphabetical) instead of numerical order.

Change your sort function as follows:

list.sort(function(a, b){
    return Number(a.page) > Number(b.page);
});

Or better still:

list.sort(function(a, b){
    return Number(a.page) - Number(b.page);
});

As noted in the comments, it's better to do the number conversion during object creation to avoid having to repeatedly carry it out for each comparison.


问:
HOWTO: CurvedAnimation in "Zero to One" Example
Can someone show an example of how a CurvedAnimation might be implemented into the Zero to One, or just alongside an AnimationController in general?</p>

答:
Wherever you would use an animation you can use a CurvedAnimation with the original animation as the parent. In this case, you could replace tween.animate(animation) with

```<code>tween.animate(
  new CurvedAnimation(
    parent: animation,
    curve: Curves.ease,
  ),
),
</code>```

Here's a full example that shows the bars animating to the same value using various curves.

```<code>import 'dart:math';

import 'package:flutter/animation.dart';
import 'package:flutter/material.dart';

import 'dart:ui' show lerpDouble;

class Bar {
  Bar(this.height);

  final double height;

  static Bar lerp(Bar begin, Bar end, double t) {
    return new Bar(lerpDouble(begin.height, end.height, t));
  }
}

class BarTween extends Tween<Bar> {
  BarTween(Bar begin, Bar end) : super(begin: begin, end: end);

  @override
  Bar lerp(double t) => Bar.lerp(begin, end, t);
}

class BarChartPainter extends CustomPainter {
  static const barWidth = 10.0;

  BarChartPainter(Animation<Bar> animation)
    : animation = animation,
      super(repaint: animation);

  final Animation<Bar> animation;

  @override
  void paint(Canvas canvas, Size size) {
    final bar = animation.value;
    final paint = new Paint()
      ..color = Colors.blue[400]
      ..style = PaintingStyle.fill;
    canvas.drawRect(
      new Rect.fromLTWH(
        (size.width - barWidth) / 2.0,
        size.height - bar.height,
        barWidth,
        bar.height,
      ),
      paint,
    );
  }

  @override
  bool shouldRepaint(BarChartPainter old) => false;
}

void main() {
  runApp(new MaterialApp(home: new ChartPage()));
}

class ChartPage extends StatefulWidget {
  @override
  ChartPageState createState() => new ChartPageState();
}

class ChartPageState extends State<ChartPage> with TickerProviderStateMixin {
  final random = new Random();
  AnimationController animation;
  BarTween tween;

  @override
  void initState() {
    super.initState();
    animation = new AnimationController(
      duration: const Duration(milliseconds: 900),
      vsync: this,
    );
    tween = new BarTween(new Bar(0.0), new Bar(50.0));
    animation.forward();
  }

  @override
  void dispose() {
    animation.dispose();
    super.dispose();
  }

  void changeData() {
    setState(() {
      tween = new BarTween(
        tween.evaluate(animation),
        new Bar(600.0 * random.nextDouble()),
      );
      animation.forward(from: 0.0);
    });
  }

  final List<Curve> curves = [
    Curves.bounceIn,
    Curves.bounceInOut,
    Curves.bounceOut,
    Curves.decelerate,
    Curves.ease,
    Curves.easeIn,
    Curves.easeInOut,
    Curves.easeOut,
    Curves.elasticIn,
    Curves.elasticInOut,
    Curves.elasticOut,
    Curves.fastOutSlowIn,
  ];

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Center(
        child: new Row(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: new List.generate(curves.length, (int index) {
            return new CustomPaint(
              painter: new BarChartPainter(
                tween.animate(
                  new CurvedAnimation(
                    parent: animation, curve: curves[index]),
                ),
              ),
            );
          }),
        ),
      ),
      floatingActionButton: new FloatingActionButton(
        child: new Icon(Icons.refresh),
        onPressed: changeData,
      ),
    );
  }
}
</code>```

Body:
Wherever you would use an animation you can use a CurvedAnimation with the original animation as the parent. In this case, you could replace tween.animate(animation) with

tween.animate(
  new CurvedAnimation(
    parent: animation,
    curve: Curves.ease,
  ),
),

Here's a full example that shows the bars animating to the same value using various curves.

import 'dart:math';

import 'package:flutter/animation.dart';
import 'package:flutter/material.dart';

import 'dart:ui' show lerpDouble;

class Bar {
  Bar(this.height);

  final double height;

  static Bar lerp(Bar begin, Bar end, double t) {
    return new Bar(lerpDouble(begin.height, end.height, t));
  }
}

class BarTween extends Tween<Bar> {
  BarTween(Bar begin, Bar end) : super(begin: begin, end: end);

  @override
  Bar lerp(double t) => Bar.lerp(begin, end, t);
}

class BarChartPainter extends CustomPainter {
  static const barWidth = 10.0;

  BarChartPainter(Animation<Bar> animation)
    : animation = animation,
      super(repaint: animation);

  final Animation<Bar> animation;

  @override
  void paint(Canvas canvas, Size size) {
    final bar = animation.value;
    final paint = new Paint()
      ..color = Colors.blue[400]
      ..style = PaintingStyle.fill;
    canvas.drawRect(
      new Rect.fromLTWH(
        (size.width - barWidth) / 2.0,
        size.height - bar.height,
        barWidth,
        bar.height,
      ),
      paint,
    );
  }

  @override
  bool shouldRepaint(BarChartPainter old) => false;
}

void main() {
  runApp(new MaterialApp(home: new ChartPage()));
}

class ChartPage extends StatefulWidget {
  @override
  ChartPageState createState() => new ChartPageState();
}

class ChartPageState extends State<ChartPage> with TickerProviderStateMixin {
  final random = new Random();
  AnimationController animation;
  BarTween tween;

  @override
  void initState() {
    super.initState();
    animation = new AnimationController(
      duration: const Duration(milliseconds: 900),
      vsync: this,
    );
    tween = new BarTween(new Bar(0.0), new Bar(50.0));
    animation.forward();
  }

  @override
  void dispose() {
    animation.dispose();
    super.dispose();
  }

  void changeData() {
    setState(() {
      tween = new BarTween(
        tween.evaluate(animation),
        new Bar(600.0 * random.nextDouble()),
      );
      animation.forward(from: 0.0);
    });
  }

  final List<Curve> curves = [
    Curves.bounceIn,
    Curves.bounceInOut,
    Curves.bounceOut,
    Curves.decelerate,
    Curves.ease,
    Curves.easeIn,
    Curves.easeInOut,
    Curves.easeOut,
    Curves.elasticIn,
    Curves.elasticInOut,
    Curves.elasticOut,
    Curves.fastOutSlowIn,
  ];

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Center(
        child: new Row(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: new List.generate(curves.length, (int index) {
            return new CustomPaint(
              painter: new BarChartPainter(
                tween.animate(
                  new CurvedAnimation(
                    parent: animation, curve: curves[index]),
                ),
              ),
            );
          }),
        ),
      ),
      floatingActionButton: new FloatingActionButton(
        child: new Icon(Icons.refresh),
        onPressed: changeData,
      ),
    );
  }
}


问:
Automatically create a value for every User in Firebase Database
I have created A User Login And register Android App.  I used Firebase Auth For User Register. I want that when an user Register A counter value will be added to my database For that user. It will be created for all user. Counter Value Will be "0".</p>

答:
Maybe the FirebaseAuth.AuthStateListener is something you need. See https://firebase.google.com/docs/reference/android/com/google/firebase/auth/FirebaseAuth.AuthStateListener

```<code>FirebaseAuth fa = FirebaseAuth.getInstance();

fa.addAuthStateListener(new FirebaseAuth.AuthStateListener() {

    @Override
    onAuthStateChanged(FirebaseAuth auth) {
        //not sure how to check for the login event. but this should work too
        FirebaseUser currentUser = auth.getCurrentUser()
        if(currentUser != null) {
            //add your data in your database.
        }
    }
});
</code>```

Body:
Maybe the FirebaseAuth.AuthStateListener is something you need. See https://firebase.google.com/docs/reference/android/com/google/firebase/auth/FirebaseAuth.AuthStateListener

FirebaseAuth fa = FirebaseAuth.getInstance();

fa.addAuthStateListener(new FirebaseAuth.AuthStateListener() {

    @Override
    onAuthStateChanged(FirebaseAuth auth) {
        //not sure how to check for the login event. but this should work too
        FirebaseUser currentUser = auth.getCurrentUser()
        if(currentUser != null) {
            //add your data in your database.
        }
    }
});


问:
how to ignore namespaces with XPath
My goal is to extract certain nodes from multiple XML files with multiple namespaces using XPath. Everything works fine as long as I know the namespace URIs. The namespace name itself remains constant, but the Schemas (XSD) are sometimes client-generated i.e. unknown to me. Then I am left with basically three choices:

Use just one schema for the namespace, hoping nothing goes wrong (can I be sure?).

Get the children nodes of the document and look for the first node with a namespace URI, hoping it's there and just use the URI, hoping it's the correct one. This can go wrong for multiple reasons

Somehow tell xpath : "look, I don't care about the namespaces, just find ALL nodes with this name, I can even tell you the name of the namespace, just not the URI". And this is the question here...

This is not a reiteration of numerous "my xpath expression doesn't work because I am not aware of namespace awareness" questions as found here or here. I know how to use namespace awareness, just not how to get rid of it.

答:
You can use the local-name() XPath function. Instead of selecting a node like

```<code>/path/to/x:somenode
</code>```

you can select all nodes and filter for the one with the correct local name:

```<code>/path/to/*[local-name() = 'somenode']
</code>```

Title: how to ignore namespaces with XPath

Body:
You can use the local-name() XPath function. Instead of selecting a node like

/path/to/x:somenode

you can select all nodes and filter for the one with the correct local name:

/path/to/*[local-name() = 'somenode']


问:
How to change Graphviz subgraph rank?
I want subgraph clusterCG to have same rank as 3 (clusterCG schould not contain 3)

```<code>digraph G{
 rankdir = LR;
 node [shape = none]

 1->2->3->4[arrowhead=none]

 node [shape = ellipse]

 A->A2->A3;

 subgraph clusterCG{
  shape = rect;
  rank=same;
  A2;
  B;
  C;
  color=blue;
  label="C";
 }

 { rank=same; 1; A;}
 { rank=same; 3; CG;}
 { rank=same; 4; A3;}
}
</code>```

CG is generated as independent node with rank 3.

I want the subgraph clusterCG to have rank 3.

答:
use different rank algorithm with "newrank=true"</p>

```<code> digraph G {
 newrank=true
 rankdir = LR;
 node [shape = none]

 1->2->3->4[arrowhead=none]

 node [shape = ellipse]

 A->A2->A3;

 subgraph clusterCG{
  shape = rect;
  rank=same;

  A2;
  B;
  C;
  color=blue;
  label="C";
 }

 { rank=same; 1; A;}
 { rank=same; 3; A2}
 { rank=same; 4; A3;}
}
</code>```

Title: How to change Graphviz subgraph rank?

Body:
I want subgraph clusterCG to have same rank as 3 (clusterCG schould not contain 3)

digraph G{
 rankdir = LR;
 node [shape = none]

 1->2->3->4[arrowhead=none]

 node [shape = ellipse]

 A->A2->A3;

 subgraph clusterCG{
  shape = rect;
  rank=same;
  A2;
  B;
  C;
  color=blue;
  label="C";
 }

 { rank=same; 1; A;}
 { rank=same; 3; CG;}
 { rank=same; 4; A3;}
}

CG is generated as independent node with rank 3.

I want the subgraph clusterCG to have rank 3.

Body:
use different rank algorithm with "newrank=true"

 digraph G {
 newrank=true
 rankdir = LR;
 node [shape = none]

 1->2->3->4[arrowhead=none]

 node [shape = ellipse]

 A->A2->A3;

 subgraph clusterCG{
  shape = rect;
  rank=same;

  A2;
  B;
  C;
  color=blue;
  label="C";
 }

 { rank=same; 1; A;}
 { rank=same; 3; A2}
 { rank=same; 4; A3;}
}


问:
Insert multiple image name in a single row in database
Mates Please Help me to solve this problem.
I ve created one from where multiple Image can Insert to a single row of database now my code is working well but it is not possible to store all image in a single data base row it is storing in multiple rows. Here what i ve done till yet.

```<code><?php
mysql_connect("localhost","root","");
mysql_select_db("test");

$uploads_dir = 'photo/';
foreach ($_FILES["image"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["image"]["tmp_name"][$key];
        $name = $_FILES["image"]["name"][$key];
        move_uploaded_file($tmp_name, "$uploads_dir/$name");
        $sql=mysql_query("INSERT INTO multiimg SET image='$name'");
    }
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
function addmore(num)
{
    if(num==1)
    {
        document.getElementById('field2').style.display='block';
        document.getElementById('ni1').style.display='block';
        return false;
    }
    else if(num==2)
    {
        document.getElementById('field3').style.display='block';
        return false;
    }

}
</script>
</head>

<body>
<form enctype="multipart/form-data" name="" action="" method="post">
    <div id="field1">Enter One Image :<input type="file" name="image[]" id="img1"/><a href="#" onclick="addmore(1)" id="ni1">addmore...</a></div>
    <div id="field2"  style="display:none;">Enter Two Image :<input type="file" name="image[]" id="img2"/><a href="#" onclick="addmore(2);">add more...</a></div>
    <div id="field3"  style="display:none;">Enter Three Image :<input type="file" name="image[]" id="img3"/><a href="#" onclick="addmore(3)" id="ni3">addmore...</a></div>
    <div id="field4" style="display:none">Enter Forth Image :<input type="file" name="image[]" id="img4"/><a href="#" onclick="addmore(4)" id="ni4">addmore...</a></div>

    <input type="submit" name="submit"/>

</form>

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

答:
```<code>       $img[$i] = array();
       $uploads_dir = "images/";
       $i=1;
       foreach ($_FILES["image"]["error"] as $key => $error)
        {
         $name[$i] == "";
         if  ($error == UPLOAD_ERR_OK) {
              $tmp_name = $_FILES["image"]["tmp_name"][$key];
              $img[$i] = $_FILES["image"]["name"][$key];
              move_uploaded_file($tmp_name, "$uploads_dir/$img[$i]");
                                       }
              $i++;
        }
    $sql1 = "INSERT INTO event(img1,img2,img3) VALUES('$img1','$img2','$img3')";
</code>```

Body:
Mates Please Help me to solve this problem.
I ve created one from where multiple Image can Insert to a single row of database now my code is working well but it is not possible to store all image in a single data base row it is storing in multiple rows. Here what i ve done till yet.

<?php
mysql_connect("localhost","root","");
mysql_select_db("test");

$uploads_dir = 'photo/';
foreach ($_FILES["image"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["image"]["tmp_name"][$key];
        $name = $_FILES["image"]["name"][$key];
        move_uploaded_file($tmp_name, "$uploads_dir/$name");
        $sql=mysql_query("INSERT INTO multiimg SET image='$name'");
    }
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<form enctype="multipart/form-data" name="" action="" method="post">

Enter One Image :<input type="file" name="image[]" id="img1"/>addmore...

Enter Two Image :<input type="file" name="image[]" id="img2"/>add more...

Enter Three Image :<input type="file" name="image[]" id="img3"/>addmore...

Enter Forth Image :<input type="file" name="image[]" id="img4"/>addmore...

    <input type="submit" name="submit"/>

</form>


问:
Optimized mysql queries in mysql database
I want to fetch 3 rows data from class table who is belongs to class 5,6 and 7 last row only.

Right now I'm using 3 sql queries to fetch data:

```<code> 1. SELECT * from class where class_name = '5';

 2. SELECT * from class where class_name = '6';

 3. SELECT * from class where class_name = '7';
</code>```

How can I use single sql query to retrieve 3 row data instead of 3 sql queries ?

```<code>**class table structure:**

|id | class_name | student  |
|---| -----------| ---------|
|1  |      5     | Student A|
|2  |      6     | Student B|
|3  |      4     | Student C|
|4  |      6     | Student D|
|5  |      7     | Student E|
|6  |      5     | Student F|
|7  |      4     | Student G|
|8  |      6     | Student H|
|9  |      5     | Student I|
|10 |      6     | Student J|
|11 |      7     | Student K|
|12 |      6     | Student L|
|13 |      8     | Student M|
|14 |      6     | Student N|
|15 |      8     | Student O|
</code>```

Result required:
Student I,Student N and Student K

答:
Use a subquery since GROUP BY cannot be used with a wildcard. Instead you have to group by every column that you select.

```<code>SELECT * FROM class
WHERE id IN (
    SELECT MAX(id) FROM class
    WHERE class_name IN (5, 6, 7) GROUP BY class_name ORDER BY id DESC
);
</code>```

Body:
I want to fetch 3 rows data from class table who is belongs to class 5,6 and 7 last row only.

Right now I'm using 3 sql queries to fetch data:

 1. SELECT * from class where class_name = '5';

 2. SELECT * from class where class_name = '6';

 3. SELECT * from class where class_name = '7';

How can I use single sql query to retrieve 3 row data instead of 3 sql queries ?

**class table structure:**

|id | class_name | student  |
|---| -----------| ---------|
|1  |      5     | Student A|
|2  |      6     | Student B|
|3  |      4     | Student C|
|4  |      6     | Student D|
|5  |      7     | Student E|
|6  |      5     | Student F|
|7  |      4     | Student G|
|8  |      6     | Student H|
|9  |      5     | Student I|
|10 |      6     | Student J|
|11 |      7     | Student K|
|12 |      6     | Student L|
|13 |      8     | Student M|
|14 |      6     | Student N|
|15 |      8     | Student O|

Result required:
Student I,Student N and Student K

Body:
Use a subquery since GROUP BY cannot be used with a wildcard. Instead you have to group by every column that you select.

SELECT * FROM class
WHERE id IN (
    SELECT MAX(id) FROM class
    WHERE class_name IN (5, 6, 7) GROUP BY class_name ORDER BY id DESC
);


问:
Why don't Django admin "Today" and "Now" buttons show up in Safari?
I'm developing a Django application that contains a model with a date/time field. On my local copy of the application, the admin page for that particular model shows this for the date/time field:

alt text http://www.cs.wm.edu/~mpd/images/bugs/django-date-local.png

This is as expected. However, when I deploy to my webserver and use the application from there, I get this:

alt text http://www.cs.wm.edu/~mpd/images/bugs/django-date-server.png

The application on the server is exactly the same as my local copy, except that I have debugging disabled on the server (but I don't think that should matter...should it?). Why does the admin app on the server differ from the local admin app?

Update

The issue seems localized to Safari. The "Today" and "Now" buttons appear when the admin site is accessed via Firefox. It looks like Safari can't download some of the JavaScript files necessary to show these widgets (strange that Firefox can, though).

I noticed that Safari is receiving a "304 Not Modified" code for the following files, but I'm not sure what that means, or how to fix it. Obviously, these are the JavaScript files and images that control the date/time widget:

RelatedObjectLookup.js

DateTimeShortcuts.js

icon_calendar.gif

icon_clock.gif

答:
Have you tried checking out firebug's NET tab to see if the admin javascript/css/image files are all loading correctly?

I had that problem once.

Compare all those files from the dev server against the production server.

OwnerDisplayName: mipadi

LastEditorDisplayName: mipadi

OwnerDisplayName: Bernard Chhun


问:
How can I add JAR files to the web-inf/lib folder in Eclipse?
I'm using Eclipse and I need to be able to add Java libraries (JAR files) into my web application's WEB-INF/lib folder. How do I achieve this?

答:
Add the jar file to your WEB-INF/lib folder.

Right-click your project in Eclipse, and go to "Build Path > Configure Build Path"

Add the "Web App Libraries" library

This will ensure all WEB-INF/lib jars are included on the classpath.


问:
system io file not found exception/ error handling
I'm working in C# and I try to do a program that get some infoes the files in a Directory. I made it but i have a problem with the error Handling. When the program runs and for example I give just random numbers to list file infoes i get this error message:

"System.IO.DirectoryNotFoundException: "'Could not find a part of the path 'C:\Temp\first_project\first_project\bin\Debug\12345'.'"

Please someone help me to do the error handling.

Thank you in advance.

```<code>using System;
    using System.IO;
    class Test
        {
            static void Main(string[] args)
             {
                Console.WriteLine("Please :");
                string hely = Console.ReadLine();
                string[] __file = Directory.GetFiles(hely);
                string[] __dir = Directory.GetDirectories(hely);

                foreach (string i in __file)
                {
                    FileInfo fajl = new FileInfo(i);
                    Console.WriteLine("{0},{1},{2}", fajl.Name, fajl.Extension, fajl.LastWriteTime.ToString());
                }
                foreach (string i in __dir)
                {
                    DirectoryInfo _file = new DirectoryInfo(i);
                    Console.WriteLine("{0},{1},{2}", _file.Name, _file.Extension, _file.LastWriteTime.ToString());
                }

            Console.ReadKey();
             }

        }
</code>```

答:
You can check if the file exists</p>

```<code>foreach (string i in __file)
{
    if (File.Exists(i))
    {
        FileInfo fajl = new FileInfo(i);
        Console.WriteLine("{0},{1},{2}", fajl.Name, fajl.Extension, fajl.LastWriteTime.ToString());
    }
}
</code>```

Body:
I'm working in C# and I try to do a program that get some infoes the files in a Directory. I made it but i have a problem with the error Handling. When the program runs and for example I give just random numbers to list file infoes i get this error message:

"System.IO.DirectoryNotFoundException: "'Could not find a part of the path 'C:\Temp\first_project\first_project\bin\Debug\12345'.'"

Please someone help me to do the error handling.

Thank you in advance.

using System;
    using System.IO;
    class Test
        {
            static void Main(string[] args)
             {
                Console.WriteLine("Please :");
                string hely = Console.ReadLine();
                string[] __file = Directory.GetFiles(hely);
                string[] __dir = Directory.GetDirectories(hely);

                foreach (string i in __file)
                {
                    FileInfo fajl = new FileInfo(i);
                    Console.WriteLine("{0},{1},{2}", fajl.Name, fajl.Extension, fajl.LastWriteTime.ToString());
                }
                foreach (string i in __dir)
                {
                    DirectoryInfo _file = new DirectoryInfo(i);
                    Console.WriteLine("{0},{1},{2}", _file.Name, _file.Extension, _file.LastWriteTime.ToString());
                }

            Console.ReadKey();
             }

        }

Body:
You can check if the file exists

foreach (string i in __file)
{
    if (File.Exists(i))
    {
        FileInfo fajl = new FileInfo(i);
        Console.WriteLine("{0},{1},{2}", fajl.Name, fajl.Extension, fajl.LastWriteTime.ToString());
    }
}


问:
Listening for socket input in multiple threads
I'm using python sockets.

Here's the problem. I've 2 threads:

One thread listens for socket input from remote and reply to it

One thread polls file and if something is present in file then send
to socket and expect a response.

Now the problem is in case of second thread when I send something, the response doesn't come to this thread. Rather it comes to thread mentioned in (1) point.

This is thread (1)

```<code>def client_handler(client):
    global client_name_to_sock_mapping
    client.send(first_response + server_name[:-1] + ", Press ^C to exit")
    user_name = None
    while True:
        request = client.recv(RECV_BUFFER_LIMIT)
        if not user_name:
            user_name = process_input(client, request.decode('utf-8'))
            user_name = user_name.rstrip()
            if user_name not in client_name_to_sock_mapping.keys():
                client_name_to_sock_mapping[user_name] = client
            else:
                msg = "Username not available".encode('ascii')
                client.send(msg)
        else:
            process_input(client, request.decode('utf-8'), user_name)
</code>```

This is run from thread (2)

```<code>def send_compute_to_client():
    time.sleep(20)
    print("Sleep over")
    for _, client_sock in client_name_to_sock_mapping.iteritems():
        print("client = {}".format(client_sock))
        client_sock.sendall("COMPUTE 1,2,3")
        print("send completed = {}".format(client_sock))
        data = client_sock.recv(1024)
        print("Computed results from client {}".format(data))
</code>```

Can someone please explain this behaviour?

答:
I have faced similar problems in the past. That happens when in one thread you start a blocking action listening for a connection while in the other thread you send through the same socket.

If I understand it well, you always want to receive the response from the previously send data. So in order to solve it I would use locks to force that behaviour, so just create a class:

```<code>from threading import Lock

class ConnectionSession:
  def __init__(self, address, conn):
    self.ip = address[0]  # Optional info
    self.port = address[1] # Optional info
    self.conn = conn
    self.lock = Lock()
</code>```

Here it goes how to create a ConnectionSession object properly when a listening socket is created:

```<code>address = ('127.0.0.1', 46140)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(address)
conn, addr = s.accept()
session = ConnectionSession(addr, conn)
</code>```

And here it goes when a 'sending' connection is created:

```<code>address = ('127.0.0.1', 46140)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(address)
session = ConnectionSession(address, s)
</code>```

Keep in mind that the created session instance is the one that needs to be shared among threads.

Afterwards, to send information through the shared socket you could do in each thread something like:

```<code># Previous code
try:
    session.lock.acquire()
    session.conn.sendall("Hi there buddy!")
    # Do something if needed
    message = session.conn.recv(1024)
except Exception as e:
    print "Exception e=%s should be handled properly" % e
finally:
    if session.lock.locked():
        session.lock.release()
# Other code
</code>```

Note that the finally block is important as it will free the locked connection whether if the action succeeded or not.

You can also wrap the previous code in a class, e.g: SocketManager with the following code in order to avoid having to explicitly acquire and release locks.

I hope it helps

Body:
I'm using python sockets.

Here's the problem. I've 2 threads:

One thread listens for socket input from remote and reply to it

One thread polls file and if something is present in file then send
to socket and expect a response.

Now the problem is in case of second thread when I send something, the response doesn't come to this thread. Rather it comes to thread mentioned in (1) point.

This is thread (1)

def client_handler(client):
    global client_name_to_sock_mapping
    client.send(first_response + server_name[:-1] + ", Press ^C to exit")
    user_name = None
    while True:
        request = client.recv(RECV_BUFFER_LIMIT)
        if not user_name:
            user_name = process_input(client, request.decode('utf-8'))
            user_name = user_name.rstrip()
            if user_name not in client_name_to_sock_mapping.keys():
                client_name_to_sock_mapping[user_name] = client
            else:
                msg = "Username not available".encode('ascii')
                client.send(msg)
        else:
            process_input(client, request.decode('utf-8'), user_name)

This is run from thread (2)

def send_compute_to_client():
    time.sleep(20)
    print("Sleep over")
    for _, client_sock in client_name_to_sock_mapping.iteritems():
        print("client = {}".format(client_sock))
        client_sock.sendall("COMPUTE 1,2,3")
        print("send completed = {}".format(client_sock))
        data = client_sock.recv(1024)
        print("Computed results from client {}".format(data))

Can someone please explain this behaviour?

Body:
I have faced similar problems in the past. That happens when in one thread you start a blocking action listening for a connection while in the other thread you send through the same socket.

If I understand it well, you always want to receive the response from the previously send data. So in order to solve it I would use locks to force that behaviour, so just create a class:

from threading import Lock

class ConnectionSession:
  def __init__(self, address, conn):
    self.ip = address[0]  # Optional info
    self.port = address[1] # Optional info
    self.conn = conn
    self.lock = Lock()

Here it goes how to create a ConnectionSession object properly when a listening socket is created:

address = ('127.0.0.1', 46140)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(address)
conn, addr = s.accept()
session = ConnectionSession(addr, conn)

And here it goes when a 'sending' connection is created:

address = ('127.0.0.1', 46140)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(address)
session = ConnectionSession(address, s)

Keep in mind that the created session instance is the one that needs to be shared among threads.

Afterwards, to send information through the shared socket you could do in each thread something like:

# Previous code
try:
    session.lock.acquire()
    session.conn.sendall("Hi there buddy!")
    # Do something if needed
    message = session.conn.recv(1024)
except Exception as e:
    print "Exception e=%s should be handled properly" % e
finally:
    if session.lock.locked():
        session.lock.release()
# Other code

Note that the finally block is important as it will free the locked connection whether if the action succeeded or not.

You can also wrap the previous code in a class, e.g: SocketManager with the following code in order to avoid having to explicitly acquire and release locks.

I hope it helps


问:
Subarray queries
So I was trying to solve this programming problem.

Given an array of numbers and some queries. Each query gives you three numbers a,b,c and asks you to answer sum of all elements from index a to index b (both included) that are less than or equal to c.

for example:

Given array: {2,4,6,1,5,1,6,4,5,4}

3 queries are to be answered:

2 4 4 -> ans=5 ie {4+1}

1 5 3 -> ans=3 ie {2+1}

4 5 1 -> ans=1

each value in the array is less than 10^5, the length of array and the number of queries could range upto 10^5

Here's what I did I used Mo's algorithm(Square root decomposition) to sort the queries, and created a Binary indexed tree to store the cumulative sum of the elements less than all the values from 1-10^5, and made an update moving from queries to queries. With this algorithm the overall complexity of my solution is O(q*sqrt(N)*log(N)) but it is not fast enough. I was looking for a better algorithm. I think square-root decomposition of queries wouldn't work. Is there any better algorithm to solve this problem?

I was wondering if some data-structure could solve this problem that I am unaware of?

答:
You can decompose it the other way around. Namely, build a tree of half-arrays (this is (n log n) space). Sort each subarray and build a cumulative sum array for it. Now your queries are (log2 n) each (log n to identify the subarrays and another log n to find the cumulative sum in each subarray).

For example, if your original array is

```<code>            5,10,2,7,16,4,8,9
</code>```

you first build this tree

```<code>            5,10,2,7,16,4,8,9
              /         \
      5,10,2,7           16,4,8,9
      /      \           /      \
    5,10     2,7      16,4      8,9
    / \      / \      / \       / \
   5   10   2   7   16   4     8   9
</code>```

then sort them all

```<code>           2,4,5,7,8,9,10,16
              /         \
      2,5,7,10           4,8,9,16
      /      \           /      \
    5,10     2,7      4,16      8,9
    / \      / \      / \       / \
   5   10   2   7   16   4     8   9
</code>```

Now if you want to answer query say (1,6,8) (indices are 0-based) you decompose the (1,6) interval into binary subintervals (1) (2,3) (4,5) (6) (there's no more than 2 log n of those) then find the answer for each one separately (0 for (1)={10}, 9 for (2,3)={2,7}, 4 for (4,5)={16,4}, 8 for (6)={8}) and sum them up.

Initial tree building can be done in (n log n) if you sort pairs (value, index) once and then just pass over the sorted array log n times (once for each tree level) and copy the values to their respective nodes.

Title: Subarray queries

Body:
You can decompose it the other way around. Namely, build a tree of half-arrays (this is (n log n) space). Sort each subarray and build a cumulative sum array for it. Now your queries are (log2 n) each (log n to identify the subarrays and another log n to find the cumulative sum in each subarray).

For example, if your original array is

            5,10,2,7,16,4,8,9

you first build this tree

            5,10,2,7,16,4,8,9
              /         \
      5,10,2,7           16,4,8,9
      /      \           /      \
    5,10     2,7      16,4      8,9
    / \      / \      / \       / \
   5   10   2   7   16   4     8   9

then sort them all

           2,4,5,7,8,9,10,16
              /         \
      2,5,7,10           4,8,9,16
      /      \           /      \
    5,10     2,7      4,16      8,9
    / \      / \      / \       / \
   5   10   2   7   16   4     8   9

Now if you want to answer query say (1,6,8) (indices are 0-based) you decompose the (1,6) interval into binary subintervals (1) (2,3) (4,5) (6) (there's no more than 2 log n of those) then find the answer for each one separately (0 for (1)={10}, 9 for (2,3)={2,7}, 4 for (4,5)={16,4}, 8 for (6)={8}) and sum them up.

Initial tree building can be done in (n log n) if you sort pairs (value, index) once and then just pass over the sorted array log n times (once for each tree level) and copy the values to their respective nodes.


问:
how to add zeros for integer variable
I'm very new to c# programming. I want to know how to add leading zeros for a integer type in c#.

ex:

int value = 23;

I want to use it like this ;

0023

Thanks in advance

答:
This is not a programming issue. Numbers have no leading zeroes.

There are two things here that you can do:

If it is a number, then format it on the way out.

If it is something like a code (article number etc.) - those are NOT NUMBERS.

The second point is important. Things like social security numbers, part numbers etc. are strings - with only numeric characters allowed. You never add or subtract them and you must be prepared for format changes. They are not integers or any other number form to start with.

Title: how to add zeros for integer variable


答:
Basically you want to add padding zeros.

string format specifier has a very simple method to this.

```<code>string valueAfterpadding;
int value = 23;
valueAfterpadding = value.ToString("D4");
Console.WriteLine(valueAfterpadding );
</code>```

this solve your problem. just google it.

Title: how to add zeros for integer variable

Body:
I'm very new to c# programming. I want to know how to add leading zeros for a integer type in c#.

ex:

int value = 23;

I want to use it like this ;

0023

Thanks in advance

Body:
Basically you want to add padding zeros.

string format specifier has a very simple method to this.

string valueAfterpadding;
int value = 23;
valueAfterpadding = value.ToString("D4");
Console.WriteLine(valueAfterpadding );

this solve your problem. just google it.