问:
Spring threads in web app
I am writing server for MMO browser game, and I need to make few threads.
They will be running all the time with some sleep time.
Is it good idea, to use spring threads like this?

```<code>@Component
@Scope("prototype")
public class PrintTask2 implements Runnable{

String name;

public void setName(String name){
    this.name = name;
}

@Override
public void run() {

    System.out.println(name + " is running");

    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println(name + " is running");

}
</code>```

}

with task executor implemented as bean?

```<code><bean id="taskExecutor"
       class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
    <property name="corePoolSize" value="5" />
    <property name="maxPoolSize" value="10" />
    <property name="WaitForTasksToCompleteOnShutdown" value="true" />
</bean>
</code>```

Also, threads are started in singleton also defined as a bean.

What can be wrong in my approach?

答:
You can use @Scheduled(fixedDelay = 5000) to execute a method periodic. Remember to set @EnableScheduling for class containing your main method.

There are two options for the @Scheduled annotation - fixedDelayand fixedRate.

fixedDelay will continuously execute your method with a delay of X miliseconds after the last execution has finished.

fixedRate will continuously execute your method with at a fixed date. So every X milisecond this method will be executed regardless if the last execution has finished.

You can also use @Async if you want to process a bunch of objects all at once. Once again, you need to add @EnableAsync to your class with your main method.

Example

```<code>//Remember to set @EnableScheduling
//in the class containing your main method
@SpringBootApplication
@EnableScheduling
@EnableAsync
public class Application {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class);
    }
}

@Component
public class ScheduledTasks {

List<YourObject> myObjects;

    //This method will run every 5 second.
    @Scheduled(fixedDelay = 5000)
    public void yourMethodName() {
        //This will process all of your objects all at once using treads
        for(YourObject yo : myObjects){
            yo.process();
        }
    }
}

public class YourObject {

    Integer someTest = 0;

    @Async
    public void process() {
       someTest++;
    }
}
</code>```

Bonus
You can get rid of your XML configuration for the pool size by extending AsyncConfigurerSupport and override getAsyncExecutor. More information about this approach can be found at the below links

I suggest that you take a look at:

https://spring.io/guides/gs/scheduling-tasks/

https://spring.io/guides/gs/async-method/

Title: Spring threads in web app

Body:
I am writing server for MMO browser game, and I need to make few threads.
They will be running all the time with some sleep time.
Is it good idea, to use spring threads like this?

@Component
@Scope("prototype")
public class PrintTask2 implements Runnable{

String name;

public void setName(String name){
    this.name = name;
}

@Override
public void run() {

    System.out.println(name + " is running");

    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println(name + " is running");

}

}

with task executor implemented as bean?

<bean id="taskExecutor"
       class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
    <property name="corePoolSize" value="5" />
    <property name="maxPoolSize" value="10" />
    <property name="WaitForTasksToCompleteOnShutdown" value="true" />
</bean>

Also, threads are started in singleton also defined as a bean.

What can be wrong in my approach?

Body:
You can use @Scheduled(fixedDelay = 5000) to execute a method periodic. Remember to set @EnableScheduling for class containing your main method.

There are two options for the @Scheduled annotation - fixedDelayand fixedRate.

fixedDelay will continuously execute your method with a delay of X miliseconds after the last execution has finished.

fixedRate will continuously execute your method with at a fixed date. So every X milisecond this method will be executed regardless if the last execution has finished.

You can also use @Async if you want to process a bunch of objects all at once. Once again, you need to add @EnableAsync to your class with your main method.

Example

//Remember to set @EnableScheduling
//in the class containing your main method
@SpringBootApplication
@EnableScheduling
@EnableAsync
public class Application {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class);
    }
}

@Component
public class ScheduledTasks {

List<YourObject> myObjects;

    //This method will run every 5 second.
    @Scheduled(fixedDelay = 5000)
    public void yourMethodName() {
        //This will process all of your objects all at once using treads
        for(YourObject yo : myObjects){
            yo.process();
        }
    }
}

public class YourObject {

    Integer someTest = 0;

    @Async
    public void process() {
       someTest++;
    }
}

Bonus
You can get rid of your XML configuration for the pool size by extending AsyncConfigurerSupport and override getAsyncExecutor. More information about this approach can be found at the below links

I suggest that you take a look at:

https://spring.io/guides/gs/scheduling-tasks/

https://spring.io/guides/gs/async-method/


来源: stackexchange

问:
Python class--Super variable
The below piece of code is giving me a error for some reason, Can someone tell me what would be the problem..

Basically, I create 2 classes Point & Circle..THe circle is trying to inherit the Point class.

```<code>Code:

class Point():

    x = 0.0
    y = 0.0

    def __init__(self, x, y):
        self.x = x
        self.y = y
        print("Point constructor")

    def ToString(self):
        return "{X:" + str(self.x) + ",Y:" + str(self.y) + "}"

class Circle(Point):
    radius = 0.0

    def __init__(self, x, y, radius):
        super(Point,self).__init__(x,y)
        self.radius = radius
        print("Circle constructor")

    def ToString(self):
        return super().ToString() + \
               ",{RADIUS=" + str(self.radius) + "}"

if __name__=='__main__':
        newpoint = Point(10,20)
        newcircle = Circle(10,20,0)
</code>```

Error:

```<code>C:\Python27>python Point.py
Point constructor
Traceback (most recent call last):
  File "Point.py", line 29, in <module>
    newcircle = Circle(10,20,0)
  File "Point.py", line 18, in __init__
    super().__init__(x,y)
TypeError: super() takes at least 1 argument (0 given)
</code>```

答:
```<code>class Point(object):

x = 0.0
y = 0.0

def __init__(self, x, y):
    self.x = x
    self.y = y
    print("Point constructor")

def ToString(self):
    return "{X:" + str(self.x) + ",Y:" + str(self.y) + "}"

class Circle(Point,object):
radius = 0.0

def __init__(self, x, y, radius):
    super(Circle,self).__init__(x,y)
    self.radius = radius
    print("Circle constructor")

def ToString(self):
    return super(Circle, self).ToString() + \
           ",{RADIUS=" + str(self.radius) + "}"

if __name__=='__main__':
    newpoint = Point(10,20)
    newcircle = Circle(10,20,0)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Python class--Super variable

Body:
The below piece of code is giving me a error for some reason, Can someone tell me what would be the problem..

Basically, I create 2 classes Point & Circle..THe circle is trying to inherit the Point class.

Code:

class Point():

    x = 0.0
    y = 0.0

    def __init__(self, x, y):
        self.x = x
        self.y = y
        print("Point constructor")

    def ToString(self):
        return "{X:" + str(self.x) + ",Y:" + str(self.y) + "}"

class Circle(Point):
    radius = 0.0

    def __init__(self, x, y, radius):
        super(Point,self).__init__(x,y)
        self.radius = radius
        print("Circle constructor")

    def ToString(self):
        return super().ToString() + \
               ",{RADIUS=" + str(self.radius) + "}"

if __name__=='__main__':
        newpoint = Point(10,20)
        newcircle = Circle(10,20,0)

Error:

C:\Python27>python Point.py
Point constructor
Traceback (most recent call last):
  File "Point.py", line 29, in <module>
    newcircle = Circle(10,20,0)
  File "Point.py", line 18, in __init__
    super().__init__(x,y)
TypeError: super() takes at least 1 argument (0 given)


问:
Sending special character for a web-api project
Hi all enthusiastics programmers.
I am making a get call from a C# client towards a web-api Project
The code looks like below

```<code>    private const string Url = "http://localhost:61809/";
    public ItemService()
    {

        _httpClient.DefaultRequestHeaders.Accept.Clear();
        _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    }

public async Task<IEnumerable<Item>> GetItemsAsync(string searchString)
    {
        List<Items>  = null;
        string path = @"api/item/" + searchString;
        HttpResponseMessage response = await _httpClient.GetAsync(Url+path).ConfigureAwait(false);
        if (response.IsSuccessStatusCode)
        {
            items = await response.Content.ReadAsAsync<List<Item>>().ConfigureAwait(false);
        }
        return items;
    }
</code>```

Everything works but if a look after a item whcih contains the character # it fails. If i looks for the item i.e Mastering C# it fails. I have debugged this on the backend side also and the content on the backend doesn't contain the character #. The content is Mastering C which of course fails.
The same occurs if i sent the request from Postman
What can i do to get it works? Some special encoding or configuration of the backend code?

答:
Yes, you do need to encode it. I'm in the process of writing a library that does this correctly, but it's not released yet.

In the meantime, you can use percent encoding as such:

```<code>public class UrlEncoding
{
  public static Encoding Utf8EncodingWithoutBom { get; } = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);

  public static string PercentEncodePathSegment(string value)
  {
    var bytes = Utf8EncodingWithoutBom.GetBytes(value);
    var sb = new StringBuilder(bytes.Length);
    foreach (var ch in bytes)
    {
      if (ch == '-' || ch == '.' || ch == '_' || ch == '~' ||
          (ch >= '0' && ch <= '9') ||
          (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'Z') ||
          ch == '!' || ch == '$' || ch == '&' || ch == '\'' ||
          ch == '(' || ch == ')' || ch == '*' || ch == '+' ||
          ch == ',' || ch == ';' || ch == '=' ||
          ch == ':' || ch == '@')
      {
        sb.Append((char)ch);
      }
      else
      {
        sb.Append("%" + ch.ToString("X2", CultureInfo.InvariantCulture));
      }
    }
    return sb.ToString();
  }
}
</code>```

Body:
Hi all enthusiastics programmers.
I am making a get call from a C# client towards a web-api Project
The code looks like below

    private const string Url = "http://localhost:61809/";
    public ItemService()
    {

        _httpClient.DefaultRequestHeaders.Accept.Clear();
        _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    }

public async Task<IEnumerable<Item>> GetItemsAsync(string searchString)
    {
        List<Items>  = null;
        string path = @"api/item/" + searchString;
        HttpResponseMessage response = await _httpClient.GetAsync(Url+path).ConfigureAwait(false);
        if (response.IsSuccessStatusCode)
        {
            items = await response.Content.ReadAsAsync<List<Item>>().ConfigureAwait(false);
        }
        return items;
    }

Everything works but if a look after a item whcih contains the character # it fails. If i looks for the item i.e Mastering C# it fails. I have debugged this on the backend side also and the content on the backend doesn't contain the character #. The content is Mastering C which of course fails.
The same occurs if i sent the request from Postman
What can i do to get it works? Some special encoding or configuration of the backend code?

Body:
Yes, you do need to encode it. I'm in the process of writing a library that does this correctly, but it's not released yet.

In the meantime, you can use percent encoding as such:

public class UrlEncoding
{
  public static Encoding Utf8EncodingWithoutBom { get; } = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);

  public static string PercentEncodePathSegment(string value)
  {
    var bytes = Utf8EncodingWithoutBom.GetBytes(value);
    var sb = new StringBuilder(bytes.Length);
    foreach (var ch in bytes)
    {
      if (ch == '-' || ch == '.' || ch == '_' || ch == '~' ||
          (ch >= '0' && ch <= '9') ||
          (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'Z') ||
          ch == '!' || ch == '$' || ch == '&' || ch == '\'' ||
          ch == '(' || ch == ')' || ch == '*' || ch == '+' ||
          ch == ',' || ch == ';' || ch == '=' ||
          ch == ':' || ch == '@')
      {
        sb.Append((char)ch);
      }
      else
      {
        sb.Append("%" + ch.ToString("X2", CultureInfo.InvariantCulture));
      }
    }
    return sb.ToString();
  }
}


问:
Removing right bar button item from navigation item
I have added a right bar button item in my navigation item and want to remove this on some condition. This is what I am doing:

```<code>self.navigationItem.rightBarButtonItem = nil;
</code>```

But not getting the desired behavior.

I want to hide it but do not find any method for it.

答:
It worked for me with the following code:</p>

```<code>self.navigationItem?.rightBarButtonItem = nil
navigationBar.items = [self.navigationItem!]
</code>```

Body:
I have added a right bar button item in my navigation item and want to remove this on some condition. This is what I am doing:

self.navigationItem.rightBarButtonItem = nil;

But not getting the desired behavior.

I want to hide it but do not find any method for it.

Body:
It worked for me with the following code:

self.navigationItem?.rightBarButtonItem = nil
navigationBar.items = [self.navigationItem!]


问:
How to ssh+expect to login and su to another user on remote machine?
I'm from local machine, ssh to remote machine, and sudo su to admin user. I don't wish to quit from ssh, I wish to stay on remote machine, so I tried:

```<code>$cat
#!/usr/bin/expect
spawn "/usr/bin/ssh myself@myremotebox -t \"/usr/bin/sudo su admin\""
expect "Password: " {send "mypassword\r"}

$./myssh.exp
spawn /usr/bin/ssh myself@myremotebox -t "/usr/bin/sudo su admin"
couldn't execute "/usr/bin/ssh myself@myremotebox -t "/usr/bin/sudo su admin"": no such file or directory
    while executing
"spawn "/usr/bin/ssh myself@myremotebox -t \"/usr/bin/sudo su admin\"""
    (file "./myssh.exp" line 2)
</code>```

Seems I 've got syntax error. I tried to add/remove the "\" inside and outisde my spawn statement, neither works. How to fix it?

Thanks!

答:
Should be:</p>

```<code>spawn /usr/bin/ssh -t myself@myremotebox "/usr/bin/sudo su admin"
expect "Password: " { send "mypassword\r" }
interact
</code>```

Body:
I'm from local machine, ssh to remote machine, and sudo su to admin user. I don't wish to quit from ssh, I wish to stay on remote machine, so I tried:

$cat
#!/usr/bin/expect
spawn "/usr/bin/ssh myself@myremotebox -t \"/usr/bin/sudo su admin\""
expect "Password: " {send "mypassword\r"}

$./myssh.exp
spawn /usr/bin/ssh myself@myremotebox -t "/usr/bin/sudo su admin"
couldn't execute "/usr/bin/ssh myself@myremotebox -t "/usr/bin/sudo su admin"": no such file or directory
    while executing
"spawn "/usr/bin/ssh myself@myremotebox -t \"/usr/bin/sudo su admin\"""
    (file "./myssh.exp" line 2)

Seems I 've got syntax error. I tried to add/remove the "\" inside and outisde my spawn statement, neither works. How to fix it?

Thanks!

Body:
Should be:

spawn /usr/bin/ssh -t myself@myremotebox "/usr/bin/sudo su admin"
expect "Password: " { send "mypassword\r" }
interact


问:
htaccess rewrite combining lines
I have 3 rewrite lines in htaccess on a site and would like to know If I can combine them.

Here are the 3 lines:

```<code>RewriteRule ([0-9]+)-folder/  http://www.example.com/folder/ [L,R=301]
RewriteRule folder/([0-9]+)-  http://www.example.com/folder/ [L,R=301]
RewriteRule folder/(.*)/([0-9]+)-  http://www.example.com/folder/$1/ [L,R=301]
</code>```

Basicly, the top 2 lines would need to take effect BEFORE the 3rd line.  It is also possible that the top 2 lines need to take effect WITHOUT the 3rd line being used (when the 3rd line doesn't apply).

I think that sums it up.

Thanks for your help!

EDIT: Forgot to say... line 1 OR line 2 will apply.  Now both at the same time.

答:
Use below rule for first two lines use second rule as it is,</p>

```<code>RewriteRule ((([0-9]+)-folder/)|(folder/([0-9]+)-)) /folder [L,R=301]
</code>```

Title: htaccess rewrite combining lines

Body:
I have 3 rewrite lines in htaccess on a site and would like to know If I can combine them.

Here are the 3 lines:

RewriteRule ([0-9]+)-folder/  http://www.example.com/folder/ [L,R=301]
RewriteRule folder/([0-9]+)-  http://www.example.com/folder/ [L,R=301]
RewriteRule folder/(.*)/([0-9]+)-  http://www.example.com/folder/$1/ [L,R=301]

Basicly, the top 2 lines would need to take effect BEFORE the 3rd line.  It is also possible that the top 2 lines need to take effect WITHOUT the 3rd line being used (when the 3rd line doesn't apply).

I think that sums it up.

Thanks for your help!

EDIT: Forgot to say... line 1 OR line 2 will apply.  Now both at the same time.

Body:
Use below rule for first two lines use second rule as it is,

RewriteRule ((([0-9]+)-folder/)|(folder/([0-9]+)-)) /folder [L,R=301]


问:
fulltext queries using prefix
I'm trying to use ArangoDB to do a fulltext query for names, and I would like to be able to search by initial, e.g. searching for "John J. Doe" or "J. Doe" would both return John James Doe. I set the index minLength: 1 and I'm trying to use the prefix tag for the search, e.g. "prefix:J,Doe". Unfortunately this makes the searches unusably slow (5 seconds for a single search over 1.6M records). Should this be working faster or is it the expected behavior with prefix: queries of length 1?

答:
ArangoDB utilises the ICU tokenizer to split words on their boundaries.
You can inpsect its work in arangosh using the SYS_SPLIT_WORDS_ICU command:

```<code>SYS_SPLIT_WORDS_ICU()
usage: SplitWordlist(<value>, minLength, [<maxLength>, [<lowerCase>]])
</code>```

So for your your case you may try to:

```<code>SYS_SPLIT_WORDS_ICU('John J. Doe', 1)
[
  "John",
  " ",
  "J",
  ".",
  " ",
  "Doe"
]
</code>```

which is probably the cause for the high cpu utilization. A minimum length of 3 seems to be a good compromise.
If you need certain features, you have to prepare a special search field in your application which prepares your text for the index.

Title: fulltext queries using prefix

Body:
ArangoDB utilises the ICU tokenizer to split words on their boundaries.
You can inpsect its work in arangosh using the SYS_SPLIT_WORDS_ICU command:

SYS_SPLIT_WORDS_ICU()
usage: SplitWordlist(<value>, minLength, [<maxLength>, [<lowerCase>]])

So for your your case you may try to:

SYS_SPLIT_WORDS_ICU('John J. Doe', 1)
[
  "John",
  " ",
  "J",
  ".",
  " ",
  "Doe"
]

which is probably the cause for the high cpu utilization. A minimum length of 3 seems to be a good compromise.
If you need certain features, you have to prepare a special search field in your application which prepares your text for the index.


问:
Blocked HTTP redirect due to missing preflight request in Chrome
We are currently building an Angular application backed with a RESTful API. The app tries to fetch a user's information with the following request URL: http://example.com:1337/api/users/1. This resource responses with a HTTP 301 (Moved Permanently) and sets the location header where the resource has been moved to, e.g. Location=http://another-hostname.com:8088/new/users/1.
Angular's HTTP client or rather the browser is handling this response automatically and redirects to this new location.

Sadly, in Chrome we get the following error message:

```<code>XMLHttpRequest cannot load http://example.com:1337/api/users/1. Redirect from 'http://example.com:1337/api/users/1' to 'http://another-hostname.com:8088/new/users/1' has been blocked by CORS policy: Request requires preflight, which is disallowed to follow cross-origin redirect.
</code>```

Chrome skips a preflight request (CORS) before calling the GET to the new resource. We tested this with Firefox and there it is working quite well. Firefox issues a new preflight request and the GET request afterwards will be handled successfully.

So, I'm wondering what's the correct behavior here. Has anyone made a similar experience with 30x responses?

Is there a possibility to disable the automatic browser (or Angular HTTP client) redirect handling? So that we can handle the new GET manually with a brand new this.http.get(...).

Thanks for any advice,

Michael

答:
Chrome skips a preflight request (CORS) before calling the GET to the new resource. We tested this with Firefox and there it is working quite well. Firefox issues a new preflight request and the GET request afterwards will be handled successfully.

You can find a discussion about that with additional workarounds and a link to the corresponding section of the W3C Recommendations for CORS here: https://stackoverflow.com/a/39728229/4282127.

Chrome should support preflight requests at redirects (3xx) since version 57. So updating to the latest Chrome version should solve at least the problem of missing preflight requests.

Body:
We are currently building an Angular application backed with a RESTful API. The app tries to fetch a user's information with the following request URL: http://example.com:1337/api/users/1. This resource responses with a HTTP 301 (Moved Permanently) and sets the location header where the resource has been moved to, e.g. Location=http://another-hostname.com:8088/new/users/1.
Angular's HTTP client or rather the browser is handling this response automatically and redirects to this new location.

Sadly, in Chrome we get the following error message:

XMLHttpRequest cannot load http://example.com:1337/api/users/1. Redirect from 'http://example.com:1337/api/users/1' to 'http://another-hostname.com:8088/new/users/1' has been blocked by CORS policy: Request requires preflight, which is disallowed to follow cross-origin redirect.

Chrome skips a preflight request (CORS) before calling the GET to the new resource. We tested this with Firefox and there it is working quite well. Firefox issues a new preflight request and the GET request afterwards will be handled successfully.

So, I'm wondering what's the correct behavior here. Has anyone made a similar experience with 30x responses?

Is there a possibility to disable the automatic browser (or Angular HTTP client) redirect handling? So that we can handle the new GET manually with a brand new this.http.get(...).

Thanks for any advice,

Michael


问:
Python Skips Numbers
I'm writing a program that's supposed to determine the square root of a number by brute force. However, certain numbers(same every time).

Here is the code:

```<code>toCalc = 3

guess = toCalc
toCalc = round(toCalc, 2)
while 1+1==2:

        print "Trying ", guess, "..."
        calc = guess * guess
        calc = round(calc, 2)
        print calc
        guess = guess - 0.01
        if calc == toCalc:
                break
</code>```

And here is the output:

```<code>Trying  1.22 ...
1.49
Trying  1.21 ...
1.46
Trying  1.2 ...
1.44
Trying  1.19 ...
1.42
Trying  1.18 ...
1.39
Trying  1.17 ...
1.37
Trying  1.16 ...
1.35
Trying  1.15 ...
1.32
Trying  1.14 ...
1.3
Trying  1.13 ...
1.28
Trying  1.12 ...
1.25
Trying  1.11 ...
1.23
Trying  1.1 ...
1.21
Trying  1.09 ...
1.19
Trying  1.08 ...
1.17
Trying  1.07 ...
1.14
Trying  1.06 ...
1.12
Trying  1.05 ...
1.1
Trying  1.04 ...
1.08
Trying  1.03 ...
1.06
Trying  1.02 ...
1.04
Trying  1.01 ...
1.02
Trying  1.0 ...
1.0
Trying  0.99 ...
0.98
Trying  0.98 ...
0.96
Trying  0.97 ...
0.94
Trying  0.96 ...
0.92
Trying  0.95 ...
0.9
Trying  0.94 ...
0.88
Trying  0.93 ...
0.86
Trying  0.92 ...
0.85
Trying  0.91 ...
0.83
</code>```

The number under "Trying" is calc and the number after "Trying" is guess.

答:
Here's a shorter alternative. It only needs 5 steps to calculate 11 correct decimals of sqrt(3), thanks to Newton's iteration :

```<code>to_calc = 3
guess = to_calc
epsilon = 1e-13

while abs(guess**2 > to_calc) > epsilon:
    guess = 0.5*(guess + to_calc / guess)

print(guess)
# 1.73205080757
print(guess**2)
# 3.0
</code>```

Title: Python Skips Numbers

Body:
I'm writing a program that's supposed to determine the square root of a number by brute force. However, certain numbers(same every time).

Here is the code:

toCalc = 3

guess = toCalc
toCalc = round(toCalc, 2)
while 1+1==2:

        print "Trying ", guess, "..."
        calc = guess * guess
        calc = round(calc, 2)
        print calc
        guess = guess - 0.01
        if calc == toCalc:
                break

And here is the output:

Trying  1.22 ...
1.49
Trying  1.21 ...
1.46
Trying  1.2 ...
1.44
Trying  1.19 ...
1.42
Trying  1.18 ...
1.39
Trying  1.17 ...
1.37
Trying  1.16 ...
1.35
Trying  1.15 ...
1.32
Trying  1.14 ...
1.3
Trying  1.13 ...
1.28
Trying  1.12 ...
1.25
Trying  1.11 ...
1.23
Trying  1.1 ...
1.21
Trying  1.09 ...
1.19
Trying  1.08 ...
1.17
Trying  1.07 ...
1.14
Trying  1.06 ...
1.12
Trying  1.05 ...
1.1
Trying  1.04 ...
1.08
Trying  1.03 ...
1.06
Trying  1.02 ...
1.04
Trying  1.01 ...
1.02
Trying  1.0 ...
1.0
Trying  0.99 ...
0.98
Trying  0.98 ...
0.96
Trying  0.97 ...
0.94
Trying  0.96 ...
0.92
Trying  0.95 ...
0.9
Trying  0.94 ...
0.88
Trying  0.93 ...
0.86
Trying  0.92 ...
0.85
Trying  0.91 ...
0.83

The number under "Trying" is calc and the number after "Trying" is guess.

Body:
Here's a shorter alternative. It only needs 5 steps to calculate 11 correct decimals of sqrt(3), thanks to Newton's iteration :

to_calc = 3
guess = to_calc
epsilon = 1e-13

while abs(guess**2 > to_calc) > epsilon:
    guess = 0.5*(guess + to_calc / guess)

print(guess)
# 1.73205080757
print(guess**2)
# 3.0


问:
Generating string in code when one of a group of properties change
I am seeking advice on how to be notified when one of many properties change.

For example, lets say I want to bind a control's text to a FullAddress property in my WPF ViewModel that I can calculate on the fly whenever one of a set of properties changes, such as StreetNumber, StreetName, Suburb, PostCode etc.

I am thinking that I need to bind my displaying control to the FullAddress property, but how do I have it automatically update whenever one of the dependent properties changes? Can I bind the property's codebehind to multiple other properties on the same ViewModel? If so how? Is there a better way?

答:
try something like this:</p>

```<code>public class Address : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private string address1;
    public string Address1
    {
        get { return address1; }
        set
        {
            address1 = value;
            OnPropertyChanged("Address1");
            OnPropertyChanged("FullAddress");
        }
    }

    private string address2;
    public string Address2
    {
        get { return address2; }
        set
        {
            address2 = value;
            OnPropertyChanged("Address2");
            OnPropertyChanged("FullAddress");
        }
    }

    private string town;
    public string Town
    {
        get { return town; }
        set
        {
            town = value;
            OnPropertyChanged("Town");
            OnPropertyChanged("FullAddress");
        }
    }

    public string FullAddress
    {
        get { return string.Format("{0}, {1}, {2}", address1, address2, town);  }
    }

    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}
</code>```

Body:
try something like this:

public class Address : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private string address1;
    public string Address1
    {
        get { return address1; }
        set
        {
            address1 = value;
            OnPropertyChanged("Address1");
            OnPropertyChanged("FullAddress");
        }
    }

    private string address2;
    public string Address2
    {
        get { return address2; }
        set
        {
            address2 = value;
            OnPropertyChanged("Address2");
            OnPropertyChanged("FullAddress");
        }
    }

    private string town;
    public string Town
    {
        get { return town; }
        set
        {
            town = value;
            OnPropertyChanged("Town");
            OnPropertyChanged("FullAddress");
        }
    }

    public string FullAddress
    {
        get { return string.Format("{0}, {1}, {2}", address1, address2, town);  }
    }

    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

ContentLicense: CC BY-SA 2.5


问:
Secure way to pass image id to php file
Hello guys I'm working on a little picture upload site. I found a problem which can be exploitet I'll show you.

I do use a foreach to display every image so 1 image in html looks like this:

```<code><a href="edit.php?id=ID_OF_PIC"><img src="IMG_PATH"></a>
</code>```

The things written in caps are just examples but there are working values. In edit.php the id is used to update the pictures name. But if I'm a sneaky smart hacker I can change the id in the href and like this I can change another post. So how/where can I save/hide the id so that nobody can change it?

答: @Qirel found a simple solution. Actually ist not very hard to do this. In my example I just have to check if the user who edits the image is the owner of the image.</p>

Title: Secure way to pass image id to php file

Body:
Hello guys I'm working on a little picture upload site. I found a problem which can be exploitet I'll show you.

I do use a foreach to display every image so 1 image in html looks like this:

The things written in caps are just examples but there are working values. In edit.php the id is used to update the pictures name. But if I'm a sneaky smart hacker I can change the id in the href and like this I can change another post. So how/where can I save/hide the id so that nobody can change it?


问:
Setting a web table scraper by Msxml2.ServerXMLHTTP.6.0 on Excel VBA
I need to do a web data scraper.

I need to login to the site: user, password, click login button

Click a second button

Wait for page to load, here is the Table in question. The table is a call log and adds new content dynamically, so it is always refreshing.

I want to exclude a form from the table content and limit the rows pasted to Excel.

I make it work by InternetExplorer.Application code but I need to switch to MSXML2.XMLHTTP code because it is very slow.

Working InternetExplorer.Application Version:

```<code> Sub extractTablesData()
 'we define the essential variables

 Dim IE As Object, obj As Object
 Dim r As Integer, c As Integer, t As Integer
 Dim elemCollection As Object

 'add the "Microsoft Internet Controls" reference in your VBA Project indirectly
 Set IE = CreateObject("InternetExplorer.Application")

 With IE
 .Silent = True
 .Visible = True
 .navigate ("https://www.clickphone.ro")

 ' we ensure that the web page downloads completely before we fill the form automatically
 While IE.readyState <> 4
 DoEvents
 Wend
Application.Wait Now + TimeValue("00:00:03")
Set HTMLDoc = IE.document
 HTMLDoc.all.user.Value = "user or email" 'Enter your email/user id here
 HTMLDoc.all.pass.Value = "xXXxXXXxxXXXxx" 'Enter your password here
 'Login Button Click
 With IE.document

    Set elems = .getElementsByTagName("a")
    For Each e In elems

        If (e.getAttribute("class") = "orange_button") Then
            e.Click
            Exit For
        End If

    Next e

End With

 'Needed Table page Button Click https://www.clickphone.ro/account/istoric_apel_in.html
 While IE.readyState <> 4
 DoEvents
 Wend
Set iedoc = IE.document

Set elems = iedoc.getElementsByClassName("black")(12)
    elems.Click

 ' again ensuring that the web page loads completely before we start scraping data
 While IE.readyState <> 4
 DoEvents
 Wend
 Application.Wait Now + TimeValue("00:00:05")
 Set iedoc = IE.document

'Clearing any unnecessary or old data in Sheet1

 ThisWorkbook.Sheets("Sheet1").Range("A1:K1000").ClearContents

'Scrapping Data and past to Sheet1
 Set elemCollection = IE.document.getElementsByTagName("table")

    For t = 0 To (elemCollection.Length - 1)
        For r = 0 To (elemCollection(t).Rows.Length - 1)
            For c = 0 To (elemCollection(t).Rows(r).Cells.Length - 1)
                ThisWorkbook.Worksheets(1).Cells(r + 1, c + 1) = elemCollection(t).Rows(r).Cells(c).innerText
            Next c
        Next r
    Next t

 End With

 ' cleaning up memory
 Set IE = Nothing

 End Sub
</code>```

This is my attempt of MSXMLHTTP:

```<code>Option Explicit
 'reference to Microsoft Internet Controls
 'reference to Microsoft HTML Object Library

Sub Web_Table_Option_One()
Dim xml    As Object
Dim html   As Object
Dim objTable As Object
Dim result As String
Dim lRow As Long
Dim lngTable As Long
Dim lngRow As Long
Dim lngCol As Long
Dim ActRw As Long

Set xml = CreateObject("MSXML2.XMLHTTP.6.0")

Set html = CreateObject("htmlFile")

With xml
.Open "POST", "https://www.clickphone.ro/login.html", False
.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
.send "userName=USER&password=XXXXxxxxXxxxxXXX"
.Open "GET", "https://www.clickphone.ro/account/istoric_apel_in.html", False
.setRequestHeader "Content-type", "text/xml"
.send
End With

html.body.innerHTML = xml.responseText

Set objTable = html.getElementsByTagName("table")
 For lngTable = 0 To objTable.Length - 1
        For lngRow = 0 To objTable(lngTable).Rows.Length - 1
            For lngCol = 0 To objTable(lngTable).Rows(lngRow).Cells.Length - 1
                ThisWorkbook.Sheets("Sheet2").Cells(ActRw + lngRow + 1, lngCol + 1) = objTable(lngTable).Rows(lngRow).Cells(lngCol).innerText
            Next lngCol
        Next lngRow
        ActRw = ActRw + objTable(lngTable).Rows.Length + 1
    Next lngTable
End Sub
</code>```

HTML source code:

For user,pass,login button:

```<code><form action="/login.html" id="toploginform" name="toploginform" method="post">
                                                                      <script>
                                            function processLoginForm(){
                                                with (document.toploginform) {
                                                    if (user.value=="Email"){alert('Email/Parola incorecte!'); return false}
                                                    document.getElementById('toploginform').submit();
                                                }
                                            }
                                        </script>

                                                                            <fieldset>
                                            <input name="userlogin" type="hidden" id="userlogin" value="true" />
                                            <span class="text">
                                            <input name="user" type="text" onFocus="if(this.value=='Email'){this.value=''}" onBlur="if(this.value==''){this.value='Email'}" value="Email">
                                            </span> <span class="text">
                                            <input name="pass" type="password" onFocus="if(this.value=='Password'){this.value=''}" onBlur="if(this.value==''){this.value='Password'}" value="Password">
                                            </span>
                                            <input name="authcode" type="hidden" id="authcode" value="false" />
                                            <span><a href="#" class="orange_button" onClick="return processLoginForm()">Login</a></span>
                                             <span class="links"><a href="/login~parola.html">Am uitat parola</a><br/>
                                                <input class="css-checkbox" id="checkbox2" type="checkbox" name="rememberpass" value="da" />
                                                <label for="checkbox2" name="checkbox2_lbl" class="css-label lite-orange-check">Retin datele?</label>
                                        </span>
                                        </fieldset>
                                                                </form>
</code>```

Table page button:

```<code><br /> <img src="/images/sageata_orange.gif" width="7" height="8" /> <a class="black" href="/account/istoric_apel_in.html">Apeluri primite</a>
</code>```

Table source code:

```<code><table class="TabelDate" cellspacing="0">
  <thead>
    <tr>
      <th width="130">Data</th>
      <th>Sursa</th>
      <th>Destinatie</th>
      <th>Durata</th>
      <th class="ultima">Status</th>
    </tr>
  </thead>
  <tr class="u">    <td class="prima">19-03-2017 17:31:16</td><td><font color="green"><form name="form24-1489937476.41719" method="post" action="">0720145931 <a class="TipFB" href="#"><span class="tip"><span class="tipTitle">Suna inapoi la 0720145931</span><span class="tipBody">Click si serverul te va suna gratuit pe numarul tau 0371780434.<br />Dupa ce raspunzi se formeaza automat numarul 0720145931.</span><span class="tipArrow"></span></span><input type="image" name="btn_opentextbox" src="/images/phone_small.gif" value="Submit" /></a>    <input name="numartel" type="hidden" id="numartel" value="0720145931" /></form></font></td><td align="center"><font color="green">0371780444</font></td><td align="center"><font color="green">00:00:07</font></td>
            <td class="ultima" align="center"><font color="green">Apel preluat</font></td></tr>  <tr class="gri">    <td class="prima">19-03-2017 17:30:48</td><td><font color="green"><form name="form24-1489937448.41715" method="post" action="">0728409617 <a class="TipFB" href="#"><span class="tip"><span class="tipTitle">Suna inapoi la 0728409617</span><span class="tipBody">Click si serverul te va suna gratuit pe numarul tau 0371780434.<br />Dupa ce raspunzi se formeaza automat numarul 0728409617.</span><span class="tipArrow"></span></span><input type="image" name="btn_opentextbox" src="/images/phone_small.gif" value="Submit" /></a>    <input name="numartel" type="hidden" id="numartel" value="0728409617" /></form></font></td><td align="center"><font color="green">0371780655</font></td><td align="center"><font color="green">00:00:07</font></td>
</code>```

答:
Version 2.0 of my working code:

```<code>Option Explicit
 'reference to Microsoft Internet Controls
 'reference to Microsoft HTML Object Library

Sub CallLog()
Dim xml    As Object
Dim html   As Object
Dim objTable As Object
Dim result As String
Dim lRow As Long
Dim lngTable As Long
Dim lngRow As Long
Dim lngCol As Long
Dim ActRw As Long

Set xml = CreateObject("MSXML2.XMLHTTP.6.0")

Set html = CreateObject("htmlFile")

With xml
.Open "POST", "https://www.XXXXXX.xx/login.html", False
.setRequestHeader "Content-type", "application/x-www-form-urlencoded" 'send appropriate Headers
.send "userlogin=true&user=USERNAME&pass=PASSWORD&authcode=false" ' send login info
'MsgBox xml.responseText
.Open "GET", "https://www.XXXXXX.xx/account/callLog.html", False
.setRequestHeader "Content-type", "text/xml"
.send
End With

html.body.innerHTML = xml.responseText

Set objTable = html.getElementsByTagName("table")
ThisWorkbook.Sheets("LogClickPhone").Range("A2") = objTable(1).Rows(1).Cells(0).innerText
ThisWorkbook.Sheets("LogClickPhone").Range("B2") = objTable(1).Rows(1).Cells(1).innerText
ThisWorkbook.Sheets("LogClickPhone").Range("C2") = objTable(1).Rows(1).Cells(2).innerText
ThisWorkbook.Sheets("LogClickPhone").Range("D2") = objTable(1).Rows(1).Cells(3).innerText
ThisWorkbook.Sheets("LogClickPhone").Range("E2") = objTable(1).Rows(1).Cells(4).innerText
End Sub
</code>```

I manage to get only the row i need but it's very slow, it takes 38.5 Sec to complete. I think I will better to use MSXML2.DOMDocument.6.0 structure for getting the text i need. But i don't know how to do that.
Question:
How i can automate this code so it's running every 60 sec or so?
Tx

Body:
I need to do a web data scraper.

I need to login to the site: user, password, click login button

Click a second button

Wait for page to load, here is the Table in question. The table is a call log and adds new content dynamically, so it is always refreshing.

I want to exclude a form from the table content and limit the rows pasted to Excel.

I make it work by InternetExplorer.Application code but I need to switch to MSXML2.XMLHTTP code because it is very slow.

Working InternetExplorer.Application Version:

 Sub extractTablesData()
 'we define the essential variables

 Dim IE As Object, obj As Object
 Dim r As Integer, c As Integer, t As Integer
 Dim elemCollection As Object

 'add the "Microsoft Internet Controls" reference in your VBA Project indirectly
 Set IE = CreateObject("InternetExplorer.Application")

 With IE
 .Silent = True
 .Visible = True
 .navigate ("https://www.clickphone.ro")

 ' we ensure that the web page downloads completely before we fill the form automatically
 While IE.readyState <> 4
 DoEvents
 Wend
Application.Wait Now + TimeValue("00:00:03")
Set HTMLDoc = IE.document
 HTMLDoc.all.user.Value = "user or email" 'Enter your email/user id here
 HTMLDoc.all.pass.Value = "xXXxXXXxxXXXxx" 'Enter your password here
 'Login Button Click
 With IE.document

    Set elems = .getElementsByTagName("a")
    For Each e In elems

        If (e.getAttribute("class") = "orange_button") Then
            e.Click
            Exit For
        End If

    Next e

End With

 'Needed Table page Button Click https://www.clickphone.ro/account/istoric_apel_in.html
 While IE.readyState <> 4
 DoEvents
 Wend
Set iedoc = IE.document

Set elems = iedoc.getElementsByClassName("black")(12)
    elems.Click

 ' again ensuring that the web page loads completely before we start scraping data
 While IE.readyState <> 4
 DoEvents
 Wend
 Application.Wait Now + TimeValue("00:00:05")
 Set iedoc = IE.document

'Clearing any unnecessary or old data in Sheet1

 ThisWorkbook.Sheets("Sheet1").Range("A1:K1000").ClearContents

'Scrapping Data and past to Sheet1
 Set elemCollection = IE.document.getElementsByTagName("table")

    For t = 0 To (elemCollection.Length - 1)
        For r = 0 To (elemCollection(t).Rows.Length - 1)
            For c = 0 To (elemCollection(t).Rows(r).Cells.Length - 1)
                ThisWorkbook.Worksheets(1).Cells(r + 1, c + 1) = elemCollection(t).Rows(r).Cells(c).innerText
            Next c
        Next r
    Next t

 End With

 ' cleaning up memory
 Set IE = Nothing

 End Sub

This is my attempt of MSXMLHTTP:

Option Explicit
 'reference to Microsoft Internet Controls
 'reference to Microsoft HTML Object Library

Sub Web_Table_Option_One()
Dim xml    As Object
Dim html   As Object
Dim objTable As Object
Dim result As String
Dim lRow As Long
Dim lngTable As Long
Dim lngRow As Long
Dim lngCol As Long
Dim ActRw As Long

Set xml = CreateObject("MSXML2.XMLHTTP.6.0")

Set html = CreateObject("htmlFile")

With xml
.Open "POST", "https://www.clickphone.ro/login.html", False
.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
.send "userName=USER&password=XXXXxxxxXxxxxXXX"
.Open "GET", "https://www.clickphone.ro/account/istoric_apel_in.html", False
.setRequestHeader "Content-type", "text/xml"
.send
End With

html.body.innerHTML = xml.responseText

Set objTable = html.getElementsByTagName("table")
 For lngTable = 0 To objTable.Length - 1
        For lngRow = 0 To objTable(lngTable).Rows.Length - 1
            For lngCol = 0 To objTable(lngTable).Rows(lngRow).Cells.Length - 1
                ThisWorkbook.Sheets("Sheet2").Cells(ActRw + lngRow + 1, lngCol + 1) = objTable(lngTable).Rows(lngRow).Cells(lngCol).innerText
            Next lngCol
        Next lngRow
        ActRw = ActRw + objTable(lngTable).Rows.Length + 1
    Next lngTable
End Sub

HTML source code:

For user,pass,login button:

<form action="/login.html" id="toploginform" name="toploginform" method="post">

                                                                            <fieldset>
                                            <input name="userlogin" type="hidden" id="userlogin" value="true" />

                                            <input name="user" type="text" onFocus="if(this.value=='Email'){this.value=''}" onBlur="if(this.value==''){this.value='Email'}" value="Email">

                                            <input name="pass" type="password" onFocus="if(this.value=='Password'){this.value=''}" onBlur="if(this.value==''){this.value='Password'}" value="Password">

                                            <input name="authcode" type="hidden" id="authcode" value="false" />
                                            Login
                                             Am uitat parola

                                                <input class="css-checkbox" id="checkbox2" type="checkbox" name="rememberpass" value="da" />
                                                Retin datele?

                                        </fieldset>
                                                                </form>

Table page button:

  Apeluri primite

Table source code:

      Data
      Sursa
      Destinatie
      Durata
      Status

    19-03-2017 17:31:16	<form name="form24-1489937476.41719" method="post" action="">0720145931 Suna inapoi la 0720145931Click si serverul te va suna gratuit pe numarul tau 0371780434.
Dupa ce raspunzi se formeaza automat numarul 0720145931.<input type="image" name="btn_opentextbox" src="/images/phone_small.gif" value="Submit" />    <input name="numartel" type="hidden" id="numartel" value="0720145931" /></form>	0371780444	00:00:07
            Apel preluat

    19-03-2017 17:30:48	<form name="form24-1489937448.41715" method="post" action="">0728409617 Suna inapoi la 0728409617Click si serverul te va suna gratuit pe numarul tau 0371780434.
Dupa ce raspunzi se formeaza automat numarul 0728409617.<input type="image" name="btn_opentextbox" src="/images/phone_small.gif" value="Submit" />    <input name="numartel" type="hidden" id="numartel" value="0728409617" /></form>	0371780655	00:00:07

Body:
Version 2.0 of my working code:

Option Explicit
 'reference to Microsoft Internet Controls
 'reference to Microsoft HTML Object Library

Sub CallLog()
Dim xml    As Object
Dim html   As Object
Dim objTable As Object
Dim result As String
Dim lRow As Long
Dim lngTable As Long
Dim lngRow As Long
Dim lngCol As Long
Dim ActRw As Long

Set xml = CreateObject("MSXML2.XMLHTTP.6.0")

Set html = CreateObject("htmlFile")

With xml
.Open "POST", "https://www.XXXXXX.xx/login.html", False
.setRequestHeader "Content-type", "application/x-www-form-urlencoded" 'send appropriate Headers
.send "userlogin=true&user=USERNAME&pass=PASSWORD&authcode=false" ' send login info
'MsgBox xml.responseText
.Open "GET", "https://www.XXXXXX.xx/account/callLog.html", False
.setRequestHeader "Content-type", "text/xml"
.send
End With

html.body.innerHTML = xml.responseText

Set objTable = html.getElementsByTagName("table")
ThisWorkbook.Sheets("LogClickPhone").Range("A2") = objTable(1).Rows(1).Cells(0).innerText
ThisWorkbook.Sheets("LogClickPhone").Range("B2") = objTable(1).Rows(1).Cells(1).innerText
ThisWorkbook.Sheets("LogClickPhone").Range("C2") = objTable(1).Rows(1).Cells(2).innerText
ThisWorkbook.Sheets("LogClickPhone").Range("D2") = objTable(1).Rows(1).Cells(3).innerText
ThisWorkbook.Sheets("LogClickPhone").Range("E2") = objTable(1).Rows(1).Cells(4).innerText
End Sub

I manage to get only the row i need but it's very slow, it takes 38.5 Sec to complete. I think I will better to use MSXML2.DOMDocument.6.0 structure for getting the text i need. But i don't know how to do that.
Question:
How i can automate this code so it's running every 60 sec or so?
Tx


问:
Drop down list show all elements but disabled for selection
I have JSP page and drop down list programatically populated.
Now, under some circumstances that dropdown should be disabled, but user should be still able to see all of it's element, but can't actually select it, something like this: https://jsfiddle.net/nenadbulatovic/6g4pmmpv/1/

```<code><select>
  <option value="Select...">Select...</option>
  <option disabled value="volvo">Volvo</option>
  <option disabled value="saab">Saab</option>
  <option disabled value="mercedes">Mercedes</option>
  <option disabled value="audi">Audi</option>
</select>
</code>```

Obviously as there is condition I can't just put disable next option.

This is actual part of code (drop down) where I need that.

```<code><div class="row-fluid">
    <div class="span3">
      <label><%=Constants.REQUIRED%> <c:out value="${requestScope.RESOURCES_MAP.SITE_PARENT}"/>:</label>
        <select class="selectpicker" data-width="100px" id="siteParentNameSelect" style="width:250px;margin-bottom:0px;">
          <option value=''>${requestScope.RESOURCES_MAP[SELECT]}</option>
          <c:forEach var="siteParentName" items="${siteParentNameList}">
            <option value="${(pageContext.request, siteParentName.id)}" ${siteParentName.id == '0' ? 'selected = "selected" ' : ''}> ${siteParentName.name}</option>
          </c:forEach>
        </select>
    </div>
  </div>
</code>```

I should check if some condition like "enabledFlag" and then if it is true/false enable/disable its elements for selection.

EDIT: I can use only JSP/JSTL, JavaScript, JQuery

答:
You should use Angular ng-disabled directive:

```<code><select>
  <option value="Select...">Select...</option>
  <option ng-disabled=flag value="volvo">Volvo</option>
  <option ng-disabled=flag value="saab">Saab</option>
  <option ng-disabled=flag value="mercedes">Mercedes</option>
  <option ng-disabled=flag value="audi">Audi</option>
</select>
</code>```

For more info: https://www.w3schools.com/angular/ng_ng-disabled.asp

EDIT:

Unfortunatelly, I am not quite familiar with JSTL, but can't you do something like this?

```<code><option value="mercedes" <c:if test="${flag}"><c:out value="disabled='disabled'"/></c:if>">
</code>```

Body:
I have JSP page and drop down list programatically populated.
Now, under some circumstances that dropdown should be disabled, but user should be still able to see all of it's element, but can't actually select it, something like this: https://jsfiddle.net/nenadbulatovic/6g4pmmpv/1/

<select>
  <option value="Select...">Select...</option>
  <option disabled value="volvo">Volvo</option>
  <option disabled value="saab">Saab</option>
  <option disabled value="mercedes">Mercedes</option>
  <option disabled value="audi">Audi</option>
</select>

Obviously as there is condition I can't just put disable next option.

This is actual part of code (drop down) where I need that.

      <%=Constants.REQUIRED%> <c:out value="${requestScope.RESOURCES_MAP.SITE_PARENT}"/>:
        <select class="selectpicker" data-width="100px" id="siteParentNameSelect" style="width:250px;margin-bottom:0px;">
          <option value=''>${requestScope.RESOURCES_MAP[SELECT]}</option>
          <c:forEach var="siteParentName" items="${siteParentNameList}">
            <option value="${(pageContext.request, siteParentName.id)}" ${siteParentName.id == '0' ? 'selected = "selected" ' : ''}> ${siteParentName.name}</option>
          </c:forEach>
        </select>

I should check if some condition like "enabledFlag" and then if it is true/false enable/disable its elements for selection.

EDIT: I can use only JSP/JSTL, JavaScript, JQuery

Body:
You should use Angular ng-disabled directive:

<select>
  <option value="Select...">Select...</option>
  <option ng-disabled=flag value="volvo">Volvo</option>
  <option ng-disabled=flag value="saab">Saab</option>
  <option ng-disabled=flag value="mercedes">Mercedes</option>
  <option ng-disabled=flag value="audi">Audi</option>
</select>

For more info: https://www.w3schools.com/angular/ng_ng-disabled.asp

EDIT:

Unfortunatelly, I am not quite familiar with JSTL, but can't you do something like this?

<option value="mercedes" <c:if test="${flag}"><c:out value="disabled='disabled'"/></c:if>">


问:
how to make dots inherit the width of the image? (slick)
There is a block 225px. Inside you insert a picture large size (850px). And she goes outside.

It looks like this:

.content {display: inline-block;}

.column {float:right; width:225px;}

.slider {
  border: 1px solid;
  width: 220px;
  padding: 5px;
}

.single-slide img {
  width: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content">
    <div class="column">
      <div class="slider single-slide">
        <div><img src='https://s-media-cache-ak0.pinimg.com/736x/2c/d0/19/2cd0197c5eb8c1f84e81734f97e80cd3.jpg' /></div>
        <div>to place the center of the image</div>
      </div>
    </div>
  </div></code>```

Using slick slider. I want to add dots to control the slider.

When I add the dots they are placed in the middle of the block. It's okay, I understand. But I want to place them in the center of the picture. How to do it?

UPD: The image goes beyond the block, that's right! And I need to do to the dots were at the center of the image, not the block

答:
if you want to need image in box then change

.single-slide img { width: auto;}

to

```<code>.single-slide img { max-width: 100%;}
</code>```

Body:
There is a block 225px. Inside you insert a picture large size (850px). And she goes outside.

It looks like this:

.content {display: inline-block;}

.column {float:right; width:225px;}

.slider {
  border: 1px solid;
  width: 220px;
  padding: 5px;
}

.single-slide img {
  width: auto;
}

to place the center of the image

Using slick slider. I want to add dots to control the slider.

When I add the dots they are placed in the middle of the block. It's okay, I understand. But I want to place them in the center of the picture. How to do it?

UPD: The image goes beyond the block, that's right! And I need to do to the dots were at the center of the image, not the block

Body:
if you want to need image in box then change

.single-slide img { width: auto;}

to

.single-slide img { max-width: 100%;}


问:
Is there a way to change column name before fetching data?
Is there a way to change column name before fetching data in all the controllers I call that column from, for example I had 2 columns in my table "Section" : "Title" and "TitleEN"

If the current culture is "en", I want to fetch "TitleEn" data but in my code I'll only use "Title" like this:

```<code>      section.Where(p =>
      p.Title.ToUpper().Contains(searchword.ToUpper()));
</code>```

I was working on a project with only one language and then the client requested adding English. Unfortunately I made the wrong decision by adding language fields for every table having string fields.

Now I want to fix this because the project has a lot of code dealing only with fields without "En".

答:
I hope this will work </p>

```<code>var section = new List<Test>();
var result = section.Where(x => (System.Globalization.CultureInfo.CurrentCulture.Name.Equals("en")
                                            && x.TitleEn.ToUpper().Contains(searchword.ToUpper()))
                                     || (!System.Globalization.CultureInfo.CurrentCulture.Name.Equals("en")
                                     && x.Title.ToUpper().Contains(searchword.ToUpper())));
</code>```

Body:
Is there a way to change column name before fetching data in all the controllers I call that column from, for example I had 2 columns in my table "Section" : "Title" and "TitleEN"

If the current culture is "en", I want to fetch "TitleEn" data but in my code I'll only use "Title" like this:

      section.Where(p =>
      p.Title.ToUpper().Contains(searchword.ToUpper()));

I was working on a project with only one language and then the client requested adding English. Unfortunately I made the wrong decision by adding language fields for every table having string fields.

Now I want to fix this because the project has a lot of code dealing only with fields without "En".

Body:
I hope this will work

var section = new List<Test>();
var result = section.Where(x => (System.Globalization.CultureInfo.CurrentCulture.Name.Equals("en")
                                            && x.TitleEn.ToUpper().Contains(searchword.ToUpper()))
                                     || (!System.Globalization.CultureInfo.CurrentCulture.Name.Equals("en")
                                     && x.Title.ToUpper().Contains(searchword.ToUpper())));


问:
How to send '&' symbol in email subject/html body using mailgun API?
I have implemented mailgun API method to send emails throughout my site using classic ASP as said in this link. But when we try to send '&' symbol in the subject/text/htmlbody the text after '&' symbol are not sending in the email.

For example : If we try to send subject as "A&B Traders" but the email sent using the mailgun API will show the subject as "A".

Problem occurs due to we are sending the parameters using query string seperated by & to the mailgun API is there a way to bypass '&' symbol in the content and send in the query string value but it should be received as & in the email.

I searched a lot but can't able to find any solution in mailgun API documentation.

Sample code to send email :

```<code>Function SendMailSync(toAddress, fromAddress, subject, body, htmlBody)
Dim httpPostData
Dim mailGunMessageUrl
Const MAILGUN_BASE_URL = "https://api.mailgun.net/v3/{DOMAIN HERE}"
Const MAILGUN_API_KEY = "key-{API_KEY}"
httpPostData = "from=" & fromAddress
httpPostData = httpPostData & "&to=" & toAddress
httpPostData = httpPostData & "&subject=" & subject
httpPostData = httpPostData & "&text=" & body
httpPostData = httpPostData & "&html=" & htmlBody
set http = CreateObject("MSXML2.ServerXMLHTTP.6.0")
mailGunMessageUrl = MAILGUN_BASE_URL & "/messages"
http.Open "POST", mailGunMessageUrl, false, "api", MAILGUN_API_KEY
http.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
http.setRequestHeader "Authorization", "Basic AUTH_STRING"
http.Send httpPostdata
If http.status <> 200 Then
    Response.Write "An error occurred: " & http.responseText
End If
SendMailSync = http.responseText
Set http = Nothing
End Function
SendMailSync "adam@example.com", "No Reply noreply@example.com", "A&B Traders", "A&B Traders Welcomes You", ""
</code>```

答:
Modify the SendMailAsync() function so that you Server.UrlEncode() each value passed. For example with the subject, just change it to;

```<code>httpPostData = httpPostData & "&subject=" & Server.UrlEncode(subject)
</code>```

that way, when the URL is sent the subject query string parameter will look like;

&subject=A%26B%20Traders
```

If you want to test the approach yourself you can use an online URL decode / encode page like the URL Decoder/Encoder.

Whenever manually sending data via a Http Request you should URL encode all parameters so things like conflicts with special characters like ? and & etc don't happen. When you submit a standard form the Internet Browser does this as part of its process, which is why some may not be familiar with why it is required when sending manual requests.

Useful Links

RFC 3986 - Uniform Resource Identifier (URI): Generic Syntax - 2.2.  Reserved Characters

A: escaping ampersand in url (information about reserved characters).

Body:
I have implemented mailgun API method to send emails throughout my site using classic ASP as said in this link. But when we try to send '&' symbol in the subject/text/htmlbody the text after '&' symbol are not sending in the email.

For example : If we try to send subject as "A&B Traders" but the email sent using the mailgun API will show the subject as "A".

Problem occurs due to we are sending the parameters using query string seperated by & to the mailgun API is there a way to bypass '&' symbol in the content and send in the query string value but it should be received as & in the email.

I searched a lot but can't able to find any solution in mailgun API documentation.

Sample code to send email :

Function SendMailSync(toAddress, fromAddress, subject, body, htmlBody)
Dim httpPostData
Dim mailGunMessageUrl
Const MAILGUN_BASE_URL = "https://api.mailgun.net/v3/{DOMAIN HERE}"
Const MAILGUN_API_KEY = "key-{API_KEY}"
httpPostData = "from=" & fromAddress
httpPostData = httpPostData & "&to=" & toAddress
httpPostData = httpPostData & "&subject=" & subject
httpPostData = httpPostData & "&text=" & body
httpPostData = httpPostData & "&html=" & htmlBody
set http = CreateObject("MSXML2.ServerXMLHTTP.6.0")
mailGunMessageUrl = MAILGUN_BASE_URL & "/messages"
http.Open "POST", mailGunMessageUrl, false, "api", MAILGUN_API_KEY
http.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
http.setRequestHeader "Authorization", "Basic AUTH_STRING"
http.Send httpPostdata
If http.status <> 200 Then
    Response.Write "An error occurred: " & http.responseText
End If
SendMailSync = http.responseText
Set http = Nothing
End Function
SendMailSync "adam@example.com", "No Reply noreply@example.com", "A&B Traders", "A&B Traders Welcomes You", ""

Body:
Modify the SendMailAsync() function so that you Server.UrlEncode() each value passed. For example with the subject, just change it to;

httpPostData = httpPostData & "&subject=" & Server.UrlEncode(subject)

that way, when the URL is sent the subject query string parameter will look like;

&subject=A%26B%20Traders

If you want to test the approach yourself you can use an online URL decode / encode page like the URL Decoder/Encoder.

Whenever manually sending data via a Http Request you should URL encode all parameters so things like conflicts with special characters like ? and & etc don't happen. When you submit a standard form the Internet Browser does this as part of its process, which is why some may not be familiar with why it is required when sending manual requests.

Useful Links

RFC 3986 - Uniform Resource Identifier (URI): Generic Syntax - 2.2.  Reserved Characters

A: escaping ampersand in url (information about reserved characters).


问:
WatchKit + Swift 3.1: Cannot override 'handleAction' which has been marked unavailable
Prior to Swift 3.1, the following code did compile and work without any issues:

```<code>import WatchKit
import WatchConnectivity
import Foundation
import UserNotifications

class InterfaceController: WKInterfaceController, WCSessionDelegate {

    override func handleAction(withIdentifier identifier: String?, for notification: UNNotification) {

    // Do something

    }
}
</code>```

However, when compiling in Xcode 8.3 with Swift 3.1 and WatchKit version 3.0, I get the following compiler error:

Cannot override 'handleAction' which has been marked unavailable

Removing override from the code gives another compiler error:

Overriding declaration requires an 'override' keyword

According to the documentation, method handleAction with UNNotification is still a valid non-deprecated method of WKInterfaceController, so the code above should be valid and compilable. Setting the WatchKit version to 3.1 or 3.2 does not change anything.

Any ideas to get this working with Swift 3.1?

答:
TL;DR: you need to use "UNUserNotificationCenterDelegate"

You are 2 steps behind, and Apple's API Reference currently is one step behind.

The current online API Reference mentions:

Deprecated

Use handleAction(withIdentifier:for:) instead.

But this has been deprecated too, and if you open the WKInterfaceController class definition, you will find the following (line 238):

```<code>// deprecated
@available(watchOS 2.0, *)
@available(watchOS, deprecated: 3.0, message: "use UNUserNotificationCenterDelegate")
open func handleAction(withIdentifier identifier: String?, forRemoteNotification remoteNotification: [AnyHashable : Any])

@available(watchOS 2.0, *)
@available(watchOS, deprecated: 3.0, message: "use UNUserNotificationCenterDelegate")
open func handleAction(withIdentifier identifier: String?, for localNotification: UILocalNotification)
</code>```

As you can see, this is deprecated too, but it points in the right direction: "use UNUserNotificationCenterDelegate".
To put it differently, you could think from the API reference that you are using a method that is not deprecated, but it is.

This is related to the XCode update, I don't think it has anything to do with Swift 3.1.

Body:
Prior to Swift 3.1, the following code did compile and work without any issues:

import WatchKit
import WatchConnectivity
import Foundation
import UserNotifications

class InterfaceController: WKInterfaceController, WCSessionDelegate {

    override func handleAction(withIdentifier identifier: String?, for notification: UNNotification) {

    // Do something

    }
}

However, when compiling in Xcode 8.3 with Swift 3.1 and WatchKit version 3.0, I get the following compiler error:

Cannot override 'handleAction' which has been marked unavailable

Removing override from the code gives another compiler error:

Overriding declaration requires an 'override' keyword

According to the documentation, method handleAction with UNNotification is still a valid non-deprecated method of WKInterfaceController, so the code above should be valid and compilable. Setting the WatchKit version to 3.1 or 3.2 does not change anything.

Any ideas to get this working with Swift 3.1?

Body:
TL;DR: you need to use "UNUserNotificationCenterDelegate"

You are 2 steps behind, and Apple's API Reference currently is one step behind.

The current online API Reference mentions:

Deprecated

Use handleAction(withIdentifier:for:) instead.

But this has been deprecated too, and if you open the WKInterfaceController class definition, you will find the following (line 238):

// deprecated
@available(watchOS 2.0, *)
@available(watchOS, deprecated: 3.0, message: "use UNUserNotificationCenterDelegate")
open func handleAction(withIdentifier identifier: String?, forRemoteNotification remoteNotification: [AnyHashable : Any])

@available(watchOS 2.0, *)
@available(watchOS, deprecated: 3.0, message: "use UNUserNotificationCenterDelegate")
open func handleAction(withIdentifier identifier: String?, for localNotification: UILocalNotification)

As you can see, this is deprecated too, but it points in the right direction: "use UNUserNotificationCenterDelegate".
To put it differently, you could think from the API reference that you are using a method that is not deprecated, but it is.

This is related to the XCode update, I don't think it has anything to do with Swift 3.1.


问:
VBA Clear filters before merging files
I'm working on a spreadsheet automation process through VBA and had success so far, but I'm kinda stuck on a single element of it, namely clearing filters before copying.
This code is located in a module on a masterfile, and what it does is open every workbook in a folder (each file has a single sheet), copy all data from A2 to AJ(however many rows there are), paste it on the masterfile, then close the file and move to the next one in the folder, until all files have been merged into the master, one block of data directly below the previous one. It works perfectly. The issue is that in some cases, these files might have filtered columns, and everything that is filtered out will not be copied over. These files are sent from another department.
I did search SO and found different ways to clear filters, I even tried a code that worked on its own, but I just can't make them work on my code for some reason, maybe I'm placing them in a wrong spot or something? Also, is there anything that I should change to clean/optimize the code?

Thanks for your time and attention!

```<code>Option Explicit

Sub ExcelMerge()
    Dim wbkReports As Workbook
    Dim mergeObj As Object, dirObj As Object, filesObj As Object, everyObj As Object

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual

    Set mergeObj = CreateObject("Scripting.FileSystemObject")

    Set dirObj = mergeObj.Getfolder("C:\Users\Report")
    Set filesObj = dirObj.Files
For Each everyObj In filesObj
    Set wbkReports = Workbooks.Open(everyObj)

    Range("A2:AJ" & Range("A65536").End(xlUp).Row).Copy

    ThisWorkbook.Worksheets(1).Activate
    Range("A65536").End(xlUp).Offset(1, 0).PasteSpecial (xlPasteValues)
    Application.CutCopyMode = False
    wbkReports.Close
Next

    AddFormulas

    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
End Sub

Sub AddFormulas()
    Dim lastRow As Long, i As Long
    Dim ws As Worksheet

    Set ws = Sheets("Report")

    lastRow = ws.Range("A" & Rows.Count).End(xlUp).Row

With ws
    For i = 10 To lastRow
        If Len(Trim(.Range("A" & i).Value)) <> 0 Then _
        .Range("AK" & i).FormulaR1C1 = "formula here"
        .Range("AL" & i).FormulaR1C1 = "formula here"
        .Range("AM" & i).FormulaR1C1 = "formula here"
    Next i
End With
End Sub
</code>```

答:
Have a look at this. Also you should define which sheet you're using instead of just copying from Range("A2:AJ... as this could lead to errors with copying data from the wrong sheet. Also if you add SaveChanges:=False when you close the workbook down you'll prevent from making the unfiltering of ranges permanent

```<code>Sub ExcelMerge()
    Dim wbkReports As Workbook
    Dim ws As Worksheet
    Dim mergeObj As Object, dirObj As Object, filesObj As Object, everyObj As Object

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual

    Set mergeObj = CreateObject("Scripting.FileSystemObject")

    Set dirObj = mergeObj.Getfolder("C:\Users\Report")
    Set filesObj = dirObj.Files
    For Each everyObj In filesObj
        Set wbkReports = Workbooks.Open(everyObj)

        For Each ws In wbkReports.Worksheets
            If ws.AutoFilterMode Then ws.AutoFilter.ShowAllData
        Next ws

        Range("A2:AJ" & Range("A65536").End(xlUp).Row).Copy
        ThisWorkbook.Worksheets(1).Activate
        Range("A65536").End(xlUp).Offset(1, 0).PasteSpecial (xlPasteValues)
        Application.CutCopyMode = False
        ' Include savechanges:=False to not save the unfiltering of sheets
        wbkReports.Close savechanges:=False
    Next

    AddFormulas

    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
End Sub
</code>```

Title: VBA Clear filters before merging files

Body:
I'm working on a spreadsheet automation process through VBA and had success so far, but I'm kinda stuck on a single element of it, namely clearing filters before copying.
This code is located in a module on a masterfile, and what it does is open every workbook in a folder (each file has a single sheet), copy all data from A2 to AJ(however many rows there are), paste it on the masterfile, then close the file and move to the next one in the folder, until all files have been merged into the master, one block of data directly below the previous one. It works perfectly. The issue is that in some cases, these files might have filtered columns, and everything that is filtered out will not be copied over. These files are sent from another department.
I did search SO and found different ways to clear filters, I even tried a code that worked on its own, but I just can't make them work on my code for some reason, maybe I'm placing them in a wrong spot or something? Also, is there anything that I should change to clean/optimize the code?

Thanks for your time and attention!

Option Explicit

Sub ExcelMerge()
    Dim wbkReports As Workbook
    Dim mergeObj As Object, dirObj As Object, filesObj As Object, everyObj As Object

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual

    Set mergeObj = CreateObject("Scripting.FileSystemObject")

    Set dirObj = mergeObj.Getfolder("C:\Users\Report")
    Set filesObj = dirObj.Files
For Each everyObj In filesObj
    Set wbkReports = Workbooks.Open(everyObj)

    Range("A2:AJ" & Range("A65536").End(xlUp).Row).Copy

    ThisWorkbook.Worksheets(1).Activate
    Range("A65536").End(xlUp).Offset(1, 0).PasteSpecial (xlPasteValues)
    Application.CutCopyMode = False
    wbkReports.Close
Next

    AddFormulas

    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
End Sub

Sub AddFormulas()
    Dim lastRow As Long, i As Long
    Dim ws As Worksheet

    Set ws = Sheets("Report")

    lastRow = ws.Range("A" & Rows.Count).End(xlUp).Row

With ws
    For i = 10 To lastRow
        If Len(Trim(.Range("A" & i).Value)) <> 0 Then _
        .Range("AK" & i).FormulaR1C1 = "formula here"
        .Range("AL" & i).FormulaR1C1 = "formula here"
        .Range("AM" & i).FormulaR1C1 = "formula here"
    Next i
End With
End Sub

Body:
Have a look at this. Also you should define which sheet you're using instead of just copying from Range("A2:AJ... as this could lead to errors with copying data from the wrong sheet. Also if you add SaveChanges:=False when you close the workbook down you'll prevent from making the unfiltering of ranges permanent

Sub ExcelMerge()
    Dim wbkReports As Workbook
    Dim ws As Worksheet
    Dim mergeObj As Object, dirObj As Object, filesObj As Object, everyObj As Object

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual

    Set mergeObj = CreateObject("Scripting.FileSystemObject")

    Set dirObj = mergeObj.Getfolder("C:\Users\Report")
    Set filesObj = dirObj.Files
    For Each everyObj In filesObj
        Set wbkReports = Workbooks.Open(everyObj)

        For Each ws In wbkReports.Worksheets
            If ws.AutoFilterMode Then ws.AutoFilter.ShowAllData
        Next ws

        Range("A2:AJ" & Range("A65536").End(xlUp).Row).Copy
        ThisWorkbook.Worksheets(1).Activate
        Range("A65536").End(xlUp).Offset(1, 0).PasteSpecial (xlPasteValues)
        Application.CutCopyMode = False
        ' Include savechanges:=False to not save the unfiltering of sheets
        wbkReports.Close savechanges:=False
    Next

    AddFormulas

    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
End Sub


问:
How to make a dynamic method call?
There is a class containing many getters and setters :

```<code>@Entity
@Table(name = "valeur_indicateur")
public class ValeurIndicateur {

    @Id
    @SequenceGenerator(name="s_valeur_indicateur", sequenceName="s_valeur_indicateur", allocationSize=1)
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="s_valeur_indicateur")
    @Column(name = "val_indi_code")
    private Integer code;

    @ManyToOne
    @JoinColumn(name = "indi_code")
    private Indicateur indicateur;

    @ManyToOne
    @JoinColumn(name = "peri_mes_code")
    private PeriodiciteMesure periodicite_mesure;

    @Column(name = "val_indi_cible_1")
    private String cible_1;

    @Column(name = "val_indi_cible_2")
    private String cible_2;

    @Column(name = "val_indi_cible_3")
    private String cible_3;

    @Column(name = "val_indi_cible_4")
    private String cible_4;

    @Column(name = "val_indi_cible_5")
    private String cible_5;

    @Column(name = "val_indi_cible_6")
    private String cible_6;

    @Column(name = "val_indi_cible_7")
    private String cible_7;

    @Column(name = "val_indi_cible_8")
    private String cible_8;

    @Column(name = "val_indi_cible_9")
    private String cible_9;

    @Column(name = "val_indi_cible_10")
    private String cible_10;

    @Column(name = "val_indi_cible_11")
    private String cible_11;

    @Column(name = "val_indi_cible_12")
    private String cible_12;

    @Column(name = "val_indi_realise_1")
    private String realise_1;

    @Column(name = "val_indi_realise_2")
    private String realise_2;

    @Column(name = "val_indi_realise_3")
    private String realise_3;

    @Column(name = "val_indi_realise_4")
    private String realise_4;

    @Column(name = "val_indi_realise_5")
    private String realise_5;

    @Column(name = "val_indi_realise_6")
    private String realise_6;

    @Column(name = "val_indi_realise_7")
    private String realise_7;

    @Column(name = "val_indi_realise_8")
    private String realise_8;

    @Column(name = "val_indi_realise_9")
    private String realise_9;

    @Column(name = "val_indi_realise_10")
    private String realise_10;

    @Column(name = "val_indi_realise_11")
    private String realise_11;

    @Column(name = "val_indi_realise_12")
    private String realise_12;

    @Column(name = "val_indi_taux")
    private Integer taux;

    public ValeurIndicateur() {
        super();
        // TODO Auto-generated constructor stub
    }

    public ValeurIndicateur(Integer code) {
        super();
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public Indicateur getIndicateur() {
        return indicateur;
    }

    public void setIndicateur(Indicateur indicateur) {
        this.indicateur = indicateur;
    }

    public PeriodiciteMesure getPeriodicite_mesure() {
        return periodicite_mesure;
    }

    public void setPeriodicite_mesure(PeriodiciteMesure periodicite_mesure) {
        this.periodicite_mesure = periodicite_mesure;
    }

    public String getCible_1() {
        return cible_1;
    }

    public void setCible_1(String cible_1) {
        this.cible_1 = cible_1;
    }

    public String getCible_2() {
        return cible_2;
    }

    public void setCible_2(String cible_2) {
        this.cible_2 = cible_2;
    }

    public String getCible_3() {
        return cible_3;
    }

    public void setCible_3(String cible_3) {
        this.cible_3 = cible_3;
    }

    public String getCible_4() {
        return cible_4;
    }

    public void setCible_4(String cible_4) {
        this.cible_4 = cible_4;
    }

    public String getCible_5() {
        return cible_5;
    }

    public void setCible_5(String cible_5) {
        this.cible_5 = cible_5;
    }

    public String getCible_6() {
        return cible_6;
    }

    public void setCible_6(String cible_6) {
        this.cible_6 = cible_6;
    }

    public String getCible_7() {
        return cible_7;
    }

    public void setCible_7(String cible_7) {
        this.cible_7 = cible_7;
    }

    public String getCible_8() {
        return cible_8;
    }

    public void setCible_8(String cible_8) {
        this.cible_8 = cible_8;
    }

    public String getCible_9() {
        return cible_9;
    }

    public void setCible_9(String cible_9) {
        this.cible_9 = cible_9;
    }

    public String getCible_10() {
        return cible_10;
    }

    public void setCible_10(String cible_10) {
        this.cible_10 = cible_10;
    }

    public String getCible_11() {
        return cible_11;
    }

    public void setCible_11(String cible_11) {
        this.cible_11 = cible_11;
    }

    public String getCible_12() {
        return cible_12;
    }

    public void setCible_12(String cible_12) {
        this.cible_12 = cible_12;
    }

    public String getRealise_1() {
        return realise_1;
    }

    public void setRealise_1(String realise_1) {
        this.realise_1 = realise_1;
    }

    public String getRealise_2() {
        return realise_2;
    }

    public void setRealise_2(String realise_2) {
        this.realise_2 = realise_2;
    }

    public String getRealise_3() {
        return realise_3;
    }

    public void setRealise_3(String realise_3) {
        this.realise_3 = realise_3;
    }

    public String getRealise_4() {
        return realise_4;
    }

    public void setRealise_4(String realise_4) {
        this.realise_4 = realise_4;
    }

    public String getRealise_5() {
        return realise_5;
    }

    public void setRealise_5(String realise_5) {
        this.realise_5 = realise_5;
    }

    public String getRealise_6() {
        return realise_6;
    }

    public void setRealise_6(String realise_6) {
        this.realise_6 = realise_6;
    }

    public String getRealise_7() {
        return realise_7;
    }

    public void setRealise_7(String realise_7) {
        this.realise_7 = realise_7;
    }

    public String getRealise_8() {
        return realise_8;
    }

    public void setRealise_8(String realise_8) {
        this.realise_8 = realise_8;
    }

    public String getRealise_9() {
        return realise_9;
    }

    public void setRealise_9(String realise_9) {
        this.realise_9 = realise_9;
    }

    public String getRealise_10() {
        return realise_10;
    }

    public void setRealise_10(String realise_10) {
        this.realise_10 = realise_10;
    }

    public String getRealise_11() {
        return realise_11;
    }

    public void setRealise_11(String realise_11) {
        this.realise_11 = realise_11;
    }

    public String getRealise_12() {
        return realise_12;
    }

    public void setRealise_12(String realise_12) {
        this.realise_12 = realise_12;
    }

    public Integer getTaux() {
        return taux;
    }

    public void setTaux(Integer taux) {
        this.taux = taux;
    }

    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return code.toString();
    }

}
</code>```

I want to call the setters setCible_ from 1 to 12 :

```<code>@RequestMapping(value = "/insertIndicateur", method = RequestMethod.POST)
public ModelAndView insertIndicateur(@ModelAttribute("indicateur_formulaire") Indicateur indicateur,
                                    @RequestParam int f_objectif,
                                    @RequestParam int f_nature_indicateur,
                                    @RequestParam String f_periodicite_mesure,
                                    @RequestParam String f_type_sortie,
                                    @RequestParam String acteur_saisie,
                                    @RequestParam String acteur_verif,
                                    @RequestParam Map<String, String> params,
                                    HttpServletRequest request, HttpSession session) {

    indicateurDao.insert(indicateur, f_objectif, f_nature_indicateur, f_periodicite_mesure, f_type_sortie, acteur_saisie, acteur_verif);

    ValeurIndicateur valeurIndicateur = new ValeurIndicateur();

    switch(f_periodicite_mesure) {
        case "ANN":
            valeurIndicateur.setCible_1(params.get("val_indi_cible_1"));
            break;
        case "SEM":
            valeurIndicateur.setCible_1(params.get("val_indi_cible_1"));
            valeurIndicateur.setCible_2(params.get("val_indi_cible_2"));
            break;
        case "TRI":
            valeurIndicateur.setCible_1(params.get("val_indi_cible_1"));
            valeurIndicateur.setCible_2(params.get("val_indi_cible_2"));
            valeurIndicateur.setCible_3(params.get("val_indi_cible_3"));
            valeurIndicateur.setCible_4(params.get("val_indi_cible_4"));
            break;
        case "MEN":

            // here I want to loop from 1 to 12 and call dynamically valeurIndicateur.setCible_

            break;
    }

    valeurIndicateur.setIndicateur(indicateur);
    valeurIndicateur.setPeriodicite_mesure(periodiciteMesureDao.get(f_periodicite_mesure));

    valeurIndicateurDao.insert(valeurIndicateur);

    ModelAndView modelView = new ModelAndView("redirect:/elaboration/");

    return modelView;

}
</code>```

Is there a way to dynamically call them ?

答:
Dynamically boils down to use the reflection utilities.

So, yes; you can use reflection to invoke methods by name on your valeurIndicateur object. And of course, you can build those method names using a base string that gets some index appended to it.

But then, doing so comes with the usual "reflection bill"; as reflection impacts performance, and code readability/robustness in a (sometimes very) negative way.

In your case: I am wondering if you shouldn't rather look into reworking your whole model. Why are you explicitly using names like c1, c2, c3, ... in the first place? Wouldn't make much more sense to use some form of list/array instead?! Meaning: to me it seems as this question is a result of a bad design decision; and instead of fixing that real problem; you are asking "how do I mitigate the symptoms"?

Title: How to make a dynamic method call?

Body:
There is a class containing many getters and setters :

@Entity
@Table(name = "valeur_indicateur")
public class ValeurIndicateur {

    @Id
    @SequenceGenerator(name="s_valeur_indicateur", sequenceName="s_valeur_indicateur", allocationSize=1)
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="s_valeur_indicateur")
    @Column(name = "val_indi_code")
    private Integer code;

    @ManyToOne
    @JoinColumn(name = "indi_code")
    private Indicateur indicateur;

    @ManyToOne
    @JoinColumn(name = "peri_mes_code")
    private PeriodiciteMesure periodicite_mesure;

    @Column(name = "val_indi_cible_1")
    private String cible_1;

    @Column(name = "val_indi_cible_2")
    private String cible_2;

    @Column(name = "val_indi_cible_3")
    private String cible_3;

    @Column(name = "val_indi_cible_4")
    private String cible_4;

    @Column(name = "val_indi_cible_5")
    private String cible_5;

    @Column(name = "val_indi_cible_6")
    private String cible_6;

    @Column(name = "val_indi_cible_7")
    private String cible_7;

    @Column(name = "val_indi_cible_8")
    private String cible_8;

    @Column(name = "val_indi_cible_9")
    private String cible_9;

    @Column(name = "val_indi_cible_10")
    private String cible_10;

    @Column(name = "val_indi_cible_11")
    private String cible_11;

    @Column(name = "val_indi_cible_12")
    private String cible_12;

    @Column(name = "val_indi_realise_1")
    private String realise_1;

    @Column(name = "val_indi_realise_2")
    private String realise_2;

    @Column(name = "val_indi_realise_3")
    private String realise_3;

    @Column(name = "val_indi_realise_4")
    private String realise_4;

    @Column(name = "val_indi_realise_5")
    private String realise_5;

    @Column(name = "val_indi_realise_6")
    private String realise_6;

    @Column(name = "val_indi_realise_7")
    private String realise_7;

    @Column(name = "val_indi_realise_8")
    private String realise_8;

    @Column(name = "val_indi_realise_9")
    private String realise_9;

    @Column(name = "val_indi_realise_10")
    private String realise_10;

    @Column(name = "val_indi_realise_11")
    private String realise_11;

    @Column(name = "val_indi_realise_12")
    private String realise_12;

    @Column(name = "val_indi_taux")
    private Integer taux;

    public ValeurIndicateur() {
        super();
        // TODO Auto-generated constructor stub
    }

    public ValeurIndicateur(Integer code) {
        super();
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public Indicateur getIndicateur() {
        return indicateur;
    }

    public void setIndicateur(Indicateur indicateur) {
        this.indicateur = indicateur;
    }

    public PeriodiciteMesure getPeriodicite_mesure() {
        return periodicite_mesure;
    }

    public void setPeriodicite_mesure(PeriodiciteMesure periodicite_mesure) {
        this.periodicite_mesure = periodicite_mesure;
    }

    public String getCible_1() {
        return cible_1;
    }

    public void setCible_1(String cible_1) {
        this.cible_1 = cible_1;
    }

    public String getCible_2() {
        return cible_2;
    }

    public void setCible_2(String cible_2) {
        this.cible_2 = cible_2;
    }

    public String getCible_3() {
        return cible_3;
    }

    public void setCible_3(String cible_3) {
        this.cible_3 = cible_3;
    }

    public String getCible_4() {
        return cible_4;
    }

    public void setCible_4(String cible_4) {
        this.cible_4 = cible_4;
    }

    public String getCible_5() {
        return cible_5;
    }

    public void setCible_5(String cible_5) {
        this.cible_5 = cible_5;
    }

    public String getCible_6() {
        return cible_6;
    }

    public void setCible_6(String cible_6) {
        this.cible_6 = cible_6;
    }

    public String getCible_7() {
        return cible_7;
    }

    public void setCible_7(String cible_7) {
        this.cible_7 = cible_7;
    }

    public String getCible_8() {
        return cible_8;
    }

    public void setCible_8(String cible_8) {
        this.cible_8 = cible_8;
    }

    public String getCible_9() {
        return cible_9;
    }

    public void setCible_9(String cible_9) {
        this.cible_9 = cible_9;
    }

    public String getCible_10() {
        return cible_10;
    }

    public void setCible_10(String cible_10) {
        this.cible_10 = cible_10;
    }

    public String getCible_11() {
        return cible_11;
    }

    public void setCible_11(String cible_11) {
        this.cible_11 = cible_11;
    }

    public String getCible_12() {
        return cible_12;
    }

    public void setCible_12(String cible_12) {
        this.cible_12 = cible_12;
    }

    public String getRealise_1() {
        return realise_1;
    }

    public void setRealise_1(String realise_1) {
        this.realise_1 = realise_1;
    }

    public String getRealise_2() {
        return realise_2;
    }

    public void setRealise_2(String realise_2) {
        this.realise_2 = realise_2;
    }

    public String getRealise_3() {
        return realise_3;
    }

    public void setRealise_3(String realise_3) {
        this.realise_3 = realise_3;
    }

    public String getRealise_4() {
        return realise_4;
    }

    public void setRealise_4(String realise_4) {
        this.realise_4 = realise_4;
    }

    public String getRealise_5() {
        return realise_5;
    }

    public void setRealise_5(String realise_5) {
        this.realise_5 = realise_5;
    }

    public String getRealise_6() {
        return realise_6;
    }

    public void setRealise_6(String realise_6) {
        this.realise_6 = realise_6;
    }

    public String getRealise_7() {
        return realise_7;
    }

    public void setRealise_7(String realise_7) {
        this.realise_7 = realise_7;
    }

    public String getRealise_8() {
        return realise_8;
    }

    public void setRealise_8(String realise_8) {
        this.realise_8 = realise_8;
    }

    public String getRealise_9() {
        return realise_9;
    }

    public void setRealise_9(String realise_9) {
        this.realise_9 = realise_9;
    }

    public String getRealise_10() {
        return realise_10;
    }

    public void setRealise_10(String realise_10) {
        this.realise_10 = realise_10;
    }

    public String getRealise_11() {
        return realise_11;
    }

    public void setRealise_11(String realise_11) {
        this.realise_11 = realise_11;
    }

    public String getRealise_12() {
        return realise_12;
    }

    public void setRealise_12(String realise_12) {
        this.realise_12 = realise_12;
    }

    public Integer getTaux() {
        return taux;
    }

    public void setTaux(Integer taux) {
        this.taux = taux;
    }

    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return code.toString();
    }

}

I want to call the setters setCible_ from 1 to 12 :

@RequestMapping(value = "/insertIndicateur", method = RequestMethod.POST)
public ModelAndView insertIndicateur(@ModelAttribute("indicateur_formulaire") Indicateur indicateur,
                                    @RequestParam int f_objectif,
                                    @RequestParam int f_nature_indicateur,
                                    @RequestParam String f_periodicite_mesure,
                                    @RequestParam String f_type_sortie,
                                    @RequestParam String acteur_saisie,
                                    @RequestParam String acteur_verif,
                                    @RequestParam Map<String, String> params,
                                    HttpServletRequest request, HttpSession session) {

    indicateurDao.insert(indicateur, f_objectif, f_nature_indicateur, f_periodicite_mesure, f_type_sortie, acteur_saisie, acteur_verif);

    ValeurIndicateur valeurIndicateur = new ValeurIndicateur();

    switch(f_periodicite_mesure) {
        case "ANN":
            valeurIndicateur.setCible_1(params.get("val_indi_cible_1"));
            break;
        case "SEM":
            valeurIndicateur.setCible_1(params.get("val_indi_cible_1"));
            valeurIndicateur.setCible_2(params.get("val_indi_cible_2"));
            break;
        case "TRI":
            valeurIndicateur.setCible_1(params.get("val_indi_cible_1"));
            valeurIndicateur.setCible_2(params.get("val_indi_cible_2"));
            valeurIndicateur.setCible_3(params.get("val_indi_cible_3"));
            valeurIndicateur.setCible_4(params.get("val_indi_cible_4"));
            break;
        case "MEN":

            // here I want to loop from 1 to 12 and call dynamically valeurIndicateur.setCible_

            break;
    }

    valeurIndicateur.setIndicateur(indicateur);
    valeurIndicateur.setPeriodicite_mesure(periodiciteMesureDao.get(f_periodicite_mesure));

    valeurIndicateurDao.insert(valeurIndicateur);

    ModelAndView modelView = new ModelAndView("redirect:/elaboration/");

    return modelView;

}

Is there a way to dynamically call them ?


问:
Dynamic Web project in Eclipse Neon not including jars from Ear APP-INF/lib
I have a set of projects I am working on in eclipse. An ear with a number of jars in APP_INF/lib and several projects for the wars under the ear. They are all Dynamic web projects. In Kepler and Mars the jars in APP-INF/lib show up as a library in the war projects.

Now I am moving to Neon. I have pulled in the ear and one of the wars and the classes in the war won't compile because the jars from APP-INF/lib are not in the classpath of the war.

Did something change? Is there a settings change I need to make?

I even created a new dynamic web project. I added it the the ear as part of creation. But it too does not contain a library from the ear.

I am running the web app on JBOSS EAP 6.4

Neon.2 Release (4.6.2) Build id: 20161208-0600

答: I am not sure why it wasn't automatically included, but in the build path, I needed to add the Ear library.</p>


问:
Changing the background colour of label in QT
I have a main window and a label on it. This has to be displayed on full screen. A data will displayed on label. The background should be black and text needs to be white. I am receiving data like 1 or 2 or 3 via serial and I am fetching the related text of 1 or 2 or 3 from a file. I am also adjusting the text to fill the complete label. If the text is small, then its font size need to be increase and if it is large then it need to be small font size.

I am using stylesheet to make the background color of label to black and I am putting it after adjusting the font size of the text. Like below:

```<code>void MainWindow::SerialRead()
{
   //Reading the serial data
   //Reading the string from file
   //Adjusting the font size to fill the label

   //Changing color
   ui->label->setStyleSheet("QLabel{ background-color : black; color : white; }");
}
</code>```

So after this my outcome looks like this:

As you can see in the above image, there is white border which is of main window because we have not set the back color of main window (it is not clearly visible because webpage color is also white). I also want the color of main window to be black so that full screen is black and text is white. I also tried setting the stylesheet in main.c for main window like below:

```<code>int main(int argc, char *argv[])
{
  QApplication a(argc, argv);
  MainWindow app;
  //Chaning color
  app.setStyleSheet("QMainWindow {background-color : black;}");
  app.SerialInit();
  app.SerialWrite();
  app.showFullScreen();

  return a.exec();
}
</code>```

So it does changes the color of main window to black but the outcome looks like below:

As you can see it also changes the font size of the text which I do not want. How can I achieve this.?

答:
I am also new in qt , but I can suggest you to  first set a name of QMainWindow by setObjectName and then use style sheet as:

```<code>int main(int argc, char *argv[])
{
  QApplication a(argc, argv);
  MainWindow app;
  //Chaning color
  app.setStyleSheet("#MainWindowName{background-color : black;}");
  app.SerialInit();
  app.SerialWrite();
  app.showFullScreen();

  return a.exec();
}
</code>```

Hope it helps.

Body:
I have a main window and a label on it. This has to be displayed on full screen. A data will displayed on label. The background should be black and text needs to be white. I am receiving data like 1 or 2 or 3 via serial and I am fetching the related text of 1 or 2 or 3 from a file. I am also adjusting the text to fill the complete label. If the text is small, then its font size need to be increase and if it is large then it need to be small font size.

I am using stylesheet to make the background color of label to black and I am putting it after adjusting the font size of the text. Like below:

void MainWindow::SerialRead()
{
   //Reading the serial data
   //Reading the string from file
   //Adjusting the font size to fill the label

   //Changing color
   ui->label->setStyleSheet("QLabel{ background-color : black; color : white; }");
}

So after this my outcome looks like this:

As you can see in the above image, there is white border which is of main window because we have not set the back color of main window (it is not clearly visible because webpage color is also white). I also want the color of main window to be black so that full screen is black and text is white. I also tried setting the stylesheet in main.c for main window like below:

int main(int argc, char *argv[])
{
  QApplication a(argc, argv);
  MainWindow app;
  //Chaning color
  app.setStyleSheet("QMainWindow {background-color : black;}");
  app.SerialInit();
  app.SerialWrite();
  app.showFullScreen();

  return a.exec();
}

So it does changes the color of main window to black but the outcome looks like below:

As you can see it also changes the font size of the text which I do not want. How can I achieve this.?

Body:
I am also new in qt , but I can suggest you to  first set a name of QMainWindow by setObjectName and then use style sheet as:

int main(int argc, char *argv[])
{
  QApplication a(argc, argv);
  MainWindow app;
  //Chaning color
  app.setStyleSheet("#MainWindowName{background-color : black;}");
  app.SerialInit();
  app.SerialWrite();
  app.showFullScreen();

  return a.exec();
}

Hope it helps.