问:
Was there a a time when PHP's rand() function was used as an exploit?
Does anybody know if there was a time or event where somebody used rand()'s weakness in order to predict exploit it? Something like generating tokens or cheating in video games?

Since prior to PHP 7, rand() was very easy to crack. In fact here is some C code, credit to Peter Selinger, that predicts the values given a seed:

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

#define MAX 1000
#define seed 1

main() {
  int r[MAX];
  int i;

  r[0] = seed;
  for (i=1; i<31; i++) {
    r[i] = (16807LL * r[i-1]) % 2147483647;
    if (r[i] < 0) {
      r[i] += 2147483647;
    }
  }
  for (i=31; i<34; i++) {
    r[i] = r[i-31];
  }
  for (i=34; i<344; i++) {
    r[i] = r[i-31] + r[i-3];
  }
  for (i=344; i<MAX; i++) {
    r[i] = r[i-31] + r[i-3];
    printf("%d\n", ((unsigned int)r[i]) >> 1);
  }
}
</code>```

So once again, was there a time when this weakness was used in order to predict the next random number and exploit something?

Thanks!

答:
Before PHP 7, PHP use Linear Congruential Generator algorithm to generate a random number or in short LCG. The algorithm works as follow:

```<code> next_random = (previous_random * a + c) % m
 previous_random = next_random
</code>```

When you first make a random, obviously, there is no previous_random number. That's why we provide seed. So, seed is just a first previous_random value.

Now, we know the algorithm, but we need to know what the value of a, c, and m that PHP use. I believe that each version of PHP use different value for those. But let say we do not know those value, how do we guess this value. In my case, I am using PHP 5.6.15 Windows.

```<code>srand(0);
var_dump(rand());  // 12345
var_dump(rand());  // 5758
</code>```

So, m = getrandmax () + 1. Since our seed is 0, so our c = 12345. To get  value a, we can use simple loop to guess a.

```<code>$m  = getrandmax () + 1;
for($a = 0; $a < $m; $a++)
   if ((($a * 12345 + 12345) % $m) == 5758)
       var_dump($a);  // in my case, 20077
</code>```

or you can get value a like this

```<code>srand(0); rand(); // 12345
srand(1); rand(); // 32422
// so a = 32422 - 12345 = 20077
</code>```

Now, I am able to write the same random function as my current PHP version.

```<code>class visal_rnd
{
    function __construct($seed = 0) {
        $this->seed = $seed;
    }

    function rnd() {
        $this->seed = ($this->seed * 20077 + 12345) % 32768;
        return $this->seed;
    }
}
</code>```

However

I was able to predict my own PHP version because I have so much knowledge about my current environment, I know a few previous random, I know the seed. If the attacker has almost zero knowledge, it would not be easy to attack.

Mersenne Twister

PHP 7.0+, by default, use Mersenne Twister. There are more parameters to be guessed than Linear Congruential Generator. So, it requires more knowledge.

Is Linear Congruential Generator Bad?

Depends on how much information you have exposed to the public. If you generate only one random number and attacker has no knowledge of a, previous_random, c and m. It is impossible for attackers to predict the next random number.

Body:
Does anybody know if there was a time or event where somebody used rand()'s weakness in order to predict exploit it? Something like generating tokens or cheating in video games?

Since prior to PHP 7, rand() was very easy to crack. In fact here is some C code, credit to Peter Selinger, that predicts the values given a seed:

#include <stdio.h>

#define MAX 1000
#define seed 1

main() {
  int r[MAX];
  int i;

  r[0] = seed;
  for (i=1; i<31; i++) {
    r[i] = (16807LL * r[i-1]) % 2147483647;
    if (r[i] < 0) {
      r[i] += 2147483647;
    }
  }
  for (i=31; i<34; i++) {
    r[i] = r[i-31];
  }
  for (i=34; i<344; i++) {
    r[i] = r[i-31] + r[i-3];
  }
  for (i=344; i<MAX; i++) {
    r[i] = r[i-31] + r[i-3];
    printf("%d\n", ((unsigned int)r[i]) >> 1);
  }
}

So once again, was there a time when this weakness was used in order to predict the next random number and exploit something?

Thanks!

Body:
Before PHP 7, PHP use Linear Congruential Generator algorithm to generate a random number or in short LCG. The algorithm works as follow:

 next_random = (previous_random * a + c) % m
 previous_random = next_random

When you first make a random, obviously, there is no previous_random number. That's why we provide seed. So, seed is just a first previous_random value.

Now, we know the algorithm, but we need to know what the value of a, c, and m that PHP use. I believe that each version of PHP use different value for those. But let say we do not know those value, how do we guess this value. In my case, I am using PHP 5.6.15 Windows.

srand(0);
var_dump(rand());  // 12345
var_dump(rand());  // 5758

So, m = getrandmax () + 1. Since our seed is 0, so our c = 12345. To get  value a, we can use simple loop to guess a.

$m  = getrandmax () + 1;
for($a = 0; $a < $m; $a++)
   if ((($a * 12345 + 12345) % $m) == 5758)
       var_dump($a);  // in my case, 20077

or you can get value a like this

srand(0); rand(); // 12345
srand(1); rand(); // 32422
// so a = 32422 - 12345 = 20077

Now, I am able to write the same random function as my current PHP version.

class visal_rnd
{
    function __construct($seed = 0) {
        $this->seed = $seed;
    }

    function rnd() {
        $this->seed = ($this->seed * 20077 + 12345) % 32768;
        return $this->seed;
    }
}

However

I was able to predict my own PHP version because I have so much knowledge about my current environment, I know a few previous random, I know the seed. If the attacker has almost zero knowledge, it would not be easy to attack.

Mersenne Twister

PHP 7.0+, by default, use Mersenne Twister. There are more parameters to be guessed than Linear Congruential Generator. So, it requires more knowledge.

Is Linear Congruential Generator Bad?

Depends on how much information you have exposed to the public. If you generate only one random number and attacker has no knowledge of a, previous_random, c and m. It is impossible for attackers to predict the next random number.


来源: stackexchange

问:
What are the side-affects of ensuring every control created has a handle in .NET?
In the past, I've suffered from a freezing issue that was the result of a Control being used to marshall calls on the UI thread before a handle has been created for that control. (See Kim Greenlee's blog for more info).

Using this method - implemented recursively - I ensure all controls that are created in our application have handles when they are constructed. Specifically, this is done after the designer call to initialise the GUI for the control.

My question is:

Q - Aside from performance, are there any other reasons not to ensure all controls have handles in this way?

I ask as we're experiencing an issue with an Infragistics control which is placed inside and Infragistics Panel. When the user modifies the size of this panel the size of the contained Infragistics control does not resize correctly even though it's Dock property is set to Dock.Fill. There is also an issue by which the tooltips that appear in this Control are no longer displayed next to the mouse. Both these issues are resolved if both the container and containing controls do not ensure they have handles created for themselves and all their child controls.

I hope someone here will be able to answer my question. Brownie points for anyone who can shed some light on to why I may be seeing this issue too! =) But I think this question would be more for the Infragistics team.

Cheers!

答:
Okay, I've solved the specific issue I was having. It was not an issue with the Infragistics components. I was simply forcing the creation of the handles at the incorrect time...

I was forcing the handle creating in the construct of each custom Control/Form - after the InitializeComponent() call. This is fine for Forms, but a Control will most likely not have been placed in a parent Control/Form by this stage. It is obviously bad to be forcing the creation of a handle when the Control has no parent to "hold on" to it.

So I've changed my rule of thumb for implementing this to:

For Forms, force creation of handles after ALL child controls have been added, for the Form itself and any child Controls. I typically continue to do this in the Construct of the Form after the InitializeComponent() call.

For Controls, force creation of handles after the Control has been constructed and added to it's parent Contol/Form, for the new Control and all its child Controls (if any).

So I presume if you ensure you use this functionality correctly, the only drawback is a potential performance issue (which I haven't really noticed to be honest).

I'd welcome a formal description of the cons of using this functionality, and a more technical description of how forcing the creation of handles for a Control before it is placed in it's parent Control causes problems, as my description is a bit brief...

Roo

ContentLicense: CC BY-SA 2.5


问:
Docker for Mac Container to Host Networking - Consul Health Checks Connection Refused
I have a HTTP health check in my service, exposed on localhost:35000/health. At the moment it always returns 200 OK. The configuration for the health check is done programmatically via the HTTP API rather than with a service config, but in essence, it is:

```<code>set id: service-id
set name: health check
set notes: consul does a GET to '/health' every 30 seconds
set http: http://127.0.0.1:35000/health
set interval: 30s
</code>```

When I run consul in dev mode (consul agent -dev -ui) on my host machine directly the health check passes without any problem. However, when I run consul in a docker container, the health check fails with:

```<code>2017/07/08 09:33:28 [WARN] agent: http request failed 'http://127.0.0.1:35000/health': Get http://127.0.0.1:35000/health: dial tcp 127.0.0.1:35000: getsockopt: connection refused
</code>```

The docker container launches consul, as far as I am aware, in exaclty the same state as the host version:

```<code>version: '2'
services:
  consul-dev:
    image: "consul:latest"
    container_name: "net-sci_discovery-service_consul-dev"
    hostname: "consul-dev"
    ports:
      - "8400:8400"
      - "8500:8500"
      - "8600:8600"
    volumes:
      - ./etc/consul.d:/etc/consul.d
    command: "agent -dev -ui -client=0.0.0.0 -config-dir=/etc/consul.d"
</code>```

I'm guessing the problem is that consul is trying to do the GET request to the containers loopback interface rather than what I am intending, which is for the loopback interface of the host. Is that a correct assumption? More importantly, what do I need to do to correct the problem?

答:
So it transpires that there was a bug in some previous versions of macOS that prevented use of the docker0 network. Whilst the bug is fixed in newer versions, Docker support extends to older versions and so Docker for Mac doesn't currently support docker0. See this discussion for details.

The workaround is to create an alias to the loopback interface on the host machine, set the service to listen on either that alias or 0.0.0.0, and configure Consul to send the health check GET request to the alias.

To set the alias (choose a private IP address that's not being used for anything else; I chose a class A address but that's irrelevant):

```<code>sudo ifconfig lo0 alias 10.200.10.1/24
</code>```

To remove the alias:

```<code>sudo ifconfig lo0 -alias 10.200.10.1
</code>```

From the service definition above, the HTTP line should now read:

```<code>set http: http://10.200.10.1:35000/health
</code>```

And the HTTP server listening for the health check requests also needs to be listening on either 10.200.10.2 or 0.0.0.0. This latter option is suggested in the discussion but I've only tried it with the alias.

I've updated the title of the question to more accurately reflect the problem, now I know the solution. Hope it helps somebody else too.

ContentLicense: CC BY-SA 3.0

Body:
I have a HTTP health check in my service, exposed on localhost:35000/health. At the moment it always returns 200 OK. The configuration for the health check is done programmatically via the HTTP API rather than with a service config, but in essence, it is:

set id: service-id
set name: health check
set notes: consul does a GET to '/health' every 30 seconds
set http: http://127.0.0.1:35000/health
set interval: 30s

When I run consul in dev mode (consul agent -dev -ui) on my host machine directly the health check passes without any problem. However, when I run consul in a docker container, the health check fails with:

2017/07/08 09:33:28 [WARN] agent: http request failed 'http://127.0.0.1:35000/health': Get http://127.0.0.1:35000/health: dial tcp 127.0.0.1:35000: getsockopt: connection refused

The docker container launches consul, as far as I am aware, in exaclty the same state as the host version:

version: '2'
services:
  consul-dev:
    image: "consul:latest"
    container_name: "net-sci_discovery-service_consul-dev"
    hostname: "consul-dev"
    ports:
      - "8400:8400"
      - "8500:8500"
      - "8600:8600"
    volumes:
      - ./etc/consul.d:/etc/consul.d
    command: "agent -dev -ui -client=0.0.0.0 -config-dir=/etc/consul.d"

I'm guessing the problem is that consul is trying to do the GET request to the containers loopback interface rather than what I am intending, which is for the loopback interface of the host. Is that a correct assumption? More importantly, what do I need to do to correct the problem?

Body:
So it transpires that there was a bug in some previous versions of macOS that prevented use of the docker0 network. Whilst the bug is fixed in newer versions, Docker support extends to older versions and so Docker for Mac doesn't currently support docker0. See this discussion for details.

The workaround is to create an alias to the loopback interface on the host machine, set the service to listen on either that alias or 0.0.0.0, and configure Consul to send the health check GET request to the alias.

To set the alias (choose a private IP address that's not being used for anything else; I chose a class A address but that's irrelevant):

sudo ifconfig lo0 alias 10.200.10.1/24

To remove the alias:

sudo ifconfig lo0 -alias 10.200.10.1

From the service definition above, the HTTP line should now read:

set http: http://10.200.10.1:35000/health

And the HTTP server listening for the health check requests also needs to be listening on either 10.200.10.2 or 0.0.0.0. This latter option is suggested in the discussion but I've only tried it with the alias.

I've updated the title of the question to more accurately reflect the problem, now I know the solution. Hope it helps somebody else too.


问:
Problems with curl requests for RESTful API - Laravel 5.4
I am trying to create a RESTful application using Laravel (I am beginner). It is a login-based app with creating a post and creating a comment to a post.(only authenticated users can write a post or comment). I made the functionality to create post and I tested  it with curl request that looks like this:

```<code>$ curl --data "title=test&body=test" http://127.0.0.1:8000/api/post?api_token=dLE6IofaGHmG1CWU6b6jWUE9h4161G8FJ3719CjZkTRbkH4orIvT5aGGNhWt
</code>```

It is working and everything is fine. I also created the routes in api.php for login/logout/register. And I want to test them via curl requests. So I am trying to test it with some requests like:

```<code>$ curl --data "name=test&email=test@gmail.com&password=test&password_confirmation=test" http://127.0.0.1:8000/api/register
</code>```

And they all redirect me to login. Can you tell me where I am wrong?

Thanks in advance.

答:
routes/api.php does not use the StartSession middleware and since logins use sessions, it will always prompt you to login on each request.

You have a few options

1) move your API routes into routes/web.php
so your API uses sessions.

This is not the best design however as APIs should be stateless to follow good REST design principles, but it will solve your login problem.

2) Look into Laravel Passport as a commenter above suggested.

This would be the preferred method, especially if you plan on consuming your API from multiple platforms.

Body:
I am trying to create a RESTful application using Laravel (I am beginner). It is a login-based app with creating a post and creating a comment to a post.(only authenticated users can write a post or comment). I made the functionality to create post and I tested  it with curl request that looks like this:

$ curl --data "title=test&body=test" http://127.0.0.1:8000/api/post?api_token=dLE6IofaGHmG1CWU6b6jWUE9h4161G8FJ3719CjZkTRbkH4orIvT5aGGNhWt

It is working and everything is fine. I also created the routes in api.php for login/logout/register. And I want to test them via curl requests. So I am trying to test it with some requests like:

$ curl --data "name=test&email=test@gmail.com&password=test&password_confirmation=test" http://127.0.0.1:8000/api/register

And they all redirect me to login. Can you tell me where I am wrong?

Thanks in advance.


问:
How to route requests to MVC controllers to an application tier
My team is reviewing security on a 2-tier ASP MVC application and has decided to introduce an service tier to prevent the website connecting directly to the database. I'm looking for ways to avoid a large rewrite of the application.

Is there a framework to route all controller calls to a service? Microsoft have a similar framework to introduce an intermediary for WCF services. Is there anything similar for MVC?

https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/routing-service

答:
I'm trying to introduce another physical tier so that if the web server is compromised. . .

Cool.  You can solve that problem without changing the applciation at all using a Reverse Proxy.  Like

IIS Application Request Routing

Or, for internet-facing or cloud applications Azure Web Application Gateway / Web Application Firewall


问:
Configure pretty url iis 7.5
I want to use pretty url on my application. I'm using Yii 1.1 (Php framework) and IIS 7.5

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>

<directoryBrowse enabled="false" />

    <rewrite>
        <rules>
        <rule name="Hide Yii Index" stopProcessing="true">
            <match url="." ignoreCase="false" />
            <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
            </conditions>
                <action type="Rewrite" url="index.php" appendQueryString="true" />
        </rule>
        </rules>
    </rewrite>

</system.webServer>
</configuration>
</code>```

I have configure my IIS rewrite rule like this. But isn't work. Someone knows why?

答:
I think you insert below code in web.config

```<code> <serverVariables>
      <set name="REQUEST_URI" value="{UNENCODED_URL}"  replace="true" />
 </serverVariables>
</code>```

and result :

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="WordPress Rule" stopProcessing="true">
                    <match url=".*" />
                    <conditions>
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="index.php" />
                    <serverVariables>
                        <set name="REQUEST_URI" value="{UNENCODED_URL}" replace="true" />
                    </serverVariables>
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>
</code>```

This problem occurs mostly in Persian and Arabic Language
and mostly use in wordpress website

Title: Configure pretty url iis 7.5

Body:
I want to use pretty url on my application. I'm using Yii 1.1 (Php framework) and IIS 7.5

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>

<directoryBrowse enabled="false" />

    <rewrite>
        <rules>
        <rule name="Hide Yii Index" stopProcessing="true">
            <match url="." ignoreCase="false" />
            <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
            </conditions>
                <action type="Rewrite" url="index.php" appendQueryString="true" />
        </rule>
        </rules>
    </rewrite>

</system.webServer>
</configuration>

I have configure my IIS rewrite rule like this. But isn't work. Someone knows why?

Body:
I think you insert below code in web.config

 <serverVariables>
      <set name="REQUEST_URI" value="{UNENCODED_URL}"  replace="true" />
 </serverVariables>

and result :

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="WordPress Rule" stopProcessing="true">
                    <match url=".*" />
                    <conditions>
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="index.php" />
                    <serverVariables>
                        <set name="REQUEST_URI" value="{UNENCODED_URL}" replace="true" />
                    </serverVariables>
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

This problem occurs mostly in Persian and Arabic Language
and mostly use in wordpress website


问:
Store one decimal digit
I have a problem which concern with large number of small integers (actually decimal digits). What is the space efficient way to store such a data?

Is it good idea to use std::bitset<4> to store one decimal digit?

答:
Is it good idea to use std::bitset<4> to store one decimal digit?

Yes, in principle that's a good idea. It's a well known optimization and called BCD encoding.

(actually decimal digits). What is the space efficient way to store such a data?

You can compact the decimal digit representation by using one nibble of the occupied byte. Also math might be applied optimized, vs. ASCII representation of digits or such.

The std::bitset<4> won't serve that well for compacting the data.

std::bitset<4> will still occupy a full byte.

An alternative data structure I could think of is a bitfield

```<code>// Maybe #pragma pack(push(1))
struct TwoBCDDecimalDigits {
    uint8_t digit1 : 4;
    uint8_t digit2 : 4;
};
// Maybe #pragma pack(pop)
</code>```

There is even a library available, to convert this format to a normalized numerical format supported at your target CPU architecture:

XBCD_Math

Another way I could think of is to write your own class:

```<code>class BCDEncodedNumber {
    enum class Sign_t : char {
        plus = '+' ,
        minus = '-'
    };
    std::vector<uint8_t> doubleDigitsArray;
public:
    BCDEncodedNumber() = default;
    BCDEncodedNumber(int num) {
        AddDigits(num); // Implements math operation + against the
                        // current BCD representation stored in
                        // doubleDigitsArray.
    }
};
</code>```

Title: Store one decimal digit

Body:
Is it good idea to use std::bitset<4> to store one decimal digit?

Yes, in principle that's a good idea. It's a well known optimization and called BCD encoding.

(actually decimal digits). What is the space efficient way to store such a data?

You can compact the decimal digit representation by using one nibble of the occupied byte. Also math might be applied optimized, vs. ASCII representation of digits or such.

The std::bitset<4> won't serve that well for compacting the data.

std::bitset<4> will still occupy a full byte.

An alternative data structure I could think of is a bitfield

// Maybe #pragma pack(push(1))
struct TwoBCDDecimalDigits {
    uint8_t digit1 : 4;
    uint8_t digit2 : 4;
};
// Maybe #pragma pack(pop)

There is even a library available, to convert this format to a normalized numerical format supported at your target CPU architecture:

XBCD_Math

Another way I could think of is to write your own class:

class BCDEncodedNumber {
    enum class Sign_t : char {
        plus = '+' ,
        minus = '-'
    };
    std::vector<uint8_t> doubleDigitsArray;
public:
    BCDEncodedNumber() = default;
    BCDEncodedNumber(int num) {
        AddDigits(num); // Implements math operation + against the
                        // current BCD representation stored in
                        // doubleDigitsArray.
    }
};


问:
displaying other form inside DetailView in django
I have the detail view of "part" in views.py

```<code>class part_detail_view(DetailView):
    model = part_list
    context_object_name = 'part_detail'
    template_name = 'part_detail.html'

    def get_context_data(self, **kwargs):
        context = super(part_detail_view, self).get_context_data(**kwargs)
        context['my_list'] = populate_nav_bar()
        return context
</code>```

but inside this URL I also want to display another form "CreateView" of the stock model so that from the same page I can display the form to add stock of the part and add the stock. This was done easily in function based view but I am not sure how to do this in class based view.

答:
You must create your form explicitly in forms.py:

```<code># forms.py
class ParForm(forms.ModelForm):
    class Meta:
        model = Part  # Your Part model
        fields = '__all__'
</code>```

Then just inject the form into the context in get_context_data():

```<code># views.py
class PartDetailView(DetailView):
    ...

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['part_form'] = PartForm()  # Your part form
        return context
</code>```

Then render the form in template:

```<code>...
<form method="post" action="{% url 'create_part' %}">
    {{ part_form }}
    <button type="submit">Submit</button>
</form>
...
</code>```

where create_part is the url of your CreateView.

Body:
I have the detail view of "part" in views.py

class part_detail_view(DetailView):
    model = part_list
    context_object_name = 'part_detail'
    template_name = 'part_detail.html'

    def get_context_data(self, **kwargs):
        context = super(part_detail_view, self).get_context_data(**kwargs)
        context['my_list'] = populate_nav_bar()
        return context

but inside this URL I also want to display another form "CreateView" of the stock model so that from the same page I can display the form to add stock of the part and add the stock. This was done easily in function based view but I am not sure how to do this in class based view.

Body:
You must create your form explicitly in forms.py:

# forms.py
class ParForm(forms.ModelForm):
    class Meta:
        model = Part  # Your Part model
        fields = '__all__'

Then just inject the form into the context in get_context_data():

# views.py
class PartDetailView(DetailView):
    ...

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['part_form'] = PartForm()  # Your part form
        return context

Then render the form in template:

...
<form method="post" action="{% url 'create_part' %}">
    {{ part_form }}
    <button type="submit">Submit</button>
</form>
...

where create_part is the url of your CreateView.

ContentLicense: CC BY-SA 4.0


问:
Providing alternative images if Adobe Flash isn't available
Are there any ways providing an alternate GIF/PNG image, in case the user has no Adobe Flash installed and/or deactivated.
I’ve found recommendations, like the following from W3C, which determine via JavaScript the existence of Adobe Flash on the client: W3C Providing alternative images

Honestly, I would prefer a non JS technique. I’m thinking of some XHTML tag, equivalent to . (like <noobject> if the object (in our case Flash) can’t be displayed/loaded).

The reason for needing this separation is the following:
The bank I’m working for will preferably display their banners in Flash format. In case it isn’t possible a simple image should be shown.
In the past it was solved very likely in the way mentioned before. We’re currently working on a design refresh and that’s where I stumbled upon this piece of code which makes me wonder if it’s really the most elegant and compatible way of doing so.

Another idea that strikes me: Is it actually possible to load Flash-objects in a JavaScript disabled environment?

答:
Actually having flash installed but javascript turned off is a valid scenario. This should work across most browsers:</p>

```<code><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="800" height="600" id="flashContent">
  <param name="movie" value="flash.swf" />
  <!--[if !IE]>-->
    <object type="application/x-shockwave-flash" data="flash.swf" width="800" height="600">
  <!--<![endif]-->
      <img src="(...)" alt="Put your alternate content here" />
  <!--[if !IE]>-->
    </object>
  <!--<![endif]-->
</object>
</code>```

OwnerDisplayName: Gerhard Dinhof

Body:
Actually having flash installed but javascript turned off is a valid scenario. This should work across most browsers:

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="800" height="600" id="flashContent">
  <param name="movie" value="flash.swf" />
  <!--[if !IE]>-->
    <object type="application/x-shockwave-flash" data="flash.swf" width="800" height="600">
  <!--<![endif]-->
      <img src="(...)" alt="Put your alternate content here" />
  <!--[if !IE]>-->
    </object>
  <!--<![endif]-->
</object>

OwnerDisplayName: Kristian J.


问:
How to access iPhone application directory and store image files there
I want to know whether I can access the directory where my application is installed.
Also I want to create a sub directory in the same directory to store all the images I capture in my application. I further want to view the images using iPhone's default image viewer. Can this be done?</p>

答:
You can get the Document folder of the app

```<code>NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
</code>```

You can create Folder and files using NSFileManger. You can store files in document folder or even you can store it in temp folder.

OwnerDisplayName: Neo

Body:
You can get the Document folder of the app

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder

You can create Folder and files using NSFileManger. You can store files in document folder or even you can store it in temp folder.


问:
Bootstrap 4: Vertical align image in a circle button
I have a circle button that needs to have a plus image in the center of it. The thing is, I can't seem to vertical align that image without resorting to messing with margins.

Is there an easier, Bootstrap-y way of doing this?

Here's my code:

.btn-circle {
  background-color: blue;
  height: 60px;
  width: 60px;
  border-radius: 50%;
}

/* the button is supposed to be a circle, but for some reason it's not showing up like that in this snippet */```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<img src="https://res.cloudinary.com/dt9b7pad3/image/upload/v1499509391/58a2031e6af142ce619ba2a2_plus-symbol_y6vqca.svg" height="20"></code>```

答:
.btn-circle {
  background-color: blue;
  height: 60px;
  width: 60px;
  border-radius: 50%;
  display: flex;
    align-items: center;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">

        <img style="height: 30px;padding-left:15px;" src="https://res.cloudinary.com/dt9b7pad3/image/upload/v1499509391/58a2031e6af142ce619ba2a2_plus-symbol_y6vqca.svg" class="" height="20">

</div></code>```

Body:
I have a circle button that needs to have a plus image in the center of it. The thing is, I can't seem to vertical align that image without resorting to messing with margins.

Is there an easier, Bootstrap-y way of doing this?

Here's my code:

.btn-circle {
  background-color: blue;
  height: 60px;
  width: 60px;
  border-radius: 50%;
}

/* the button is supposed to be a circle, but for some reason it's not showing up like that in this snippet */

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

Body:
.btn-circle {
  background-color: blue;
  height: 60px;
  width: 60px;
  border-radius: 50%;
  display: flex;
    align-items: center;

}

<div class="container">
    <a class="btn btn-circle mr-3 d-flex justify-content-center align-items-center" data-toggle="collapse" href="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
        <img style="height: 30px;padding-left:15px;" src="https://res.cloudinary.com/dt9b7pad3/image/upload/v1499509391/58a2031e6af142ce619ba2a2_plus-symbol_y6vqca.svg" class="" height="20">
    </a>
</div>


问:
Why is my ruby case statement not working?
What's wrong with that?
Yes, I could make an if else statement, but I wanna do that with case statements.

In my Controller

```<code>query_limit = case current_user
                when nil
                  return 5
                when is_admin?
                  return 200
                when has_role?('registered')
                  return 20
                else
                  return 5
              end

NoMethodError (undefined method `is_admin?' for #<V1::MyController:123123123>):
</code>```

puts query_limit # is always ELSE when I do this:

```<code> query_limit = case current_user
                    when nil
                      return 5
                    when current_user.is_admin?
                      return 200
                    when current_user.has_role?('registered')
                      return 20
                    else
                      return 5
                  end
</code>```

Model User

```<code>class User
  def is_admin?
    self.has_role?('administrator')
  end

  def has_role?(the_role)
    self.roles.any? {|role| role.slug == the_role}
  end
end
</code>```

答:
The way case works is it doesn't call whatever method you wanted to put in the when clause. Instead it uses === on the when clause passing the case-ed thingy as argument.

In other words:

```<code>case user
when admin? then 42
end
</code>```

Isn't

```<code>42 if user.admin?
</code>```

But

```<code>42 if admin? === user
</code>```

And as you don't have an admin? method in the controller, you get a NoMethodError.

Just rewrite it with simple if - elsif instead.

Body:
What's wrong with that?
Yes, I could make an if else statement, but I wanna do that with case statements.

In my Controller

query_limit = case current_user
                when nil
                  return 5
                when is_admin?
                  return 200
                when has_role?('registered')
                  return 20
                else
                  return 5
              end

NoMethodError (undefined method `is_admin?' for #<V1::MyController:123123123>):

puts query_limit # is always ELSE when I do this:

 query_limit = case current_user
                    when nil
                      return 5
                    when current_user.is_admin?
                      return 200
                    when current_user.has_role?('registered')
                      return 20
                    else
                      return 5
                  end

Model User

class User
  def is_admin?
    self.has_role?('administrator')
  end

  def has_role?(the_role)
    self.roles.any? {|role| role.slug == the_role}
  end
end

Body:
The way case works is it doesn't call whatever method you wanted to put in the when clause. Instead it uses === on the when clause passing the case-ed thingy as argument.

In other words:

case user
when admin? then 42
end

Isn't

42 if user.admin?

But

42 if admin? === user

And as you don't have an admin? method in the controller, you get a NoMethodError.

Just rewrite it with simple if - elsif instead.


问:
Data grid row filter return less than
when i run this to filter my xml file it returns all rows even those higher than the given amount.

```<code>DataSet ds = new DataSet();

ds.ReadXml("Database.xml");

string filter = "";
filter = "Dayvisited <= '20'";

DataView dv = new DataView(ds.Tables[0]);
dv.RowFilter = filter;
dataGridView2.DataSource = dv;
dataGridView2.Columns[4].Visible = false;
</code>```

this is my xml

```<code><root>
  <place>
    <Name />
    <Location />
    <Info />
    <Dayvisited />
    <userdata />
  </place>
  <place>
    <Name>home</Name>
    <Location>x-292 z 277</Location>
    <Info>home</Info>
    <Dayvisited>100</Dayvisited>
    <userdata>u</userdata>
  </place>
  <place>
    <Name>base</Name>
    <Location>x868 z986</Location>
    <Info>stuff</Info>
    <Dayvisited>20</Dayvisited>
    <userdata>u</userdata>
  </place>
  <place>
    <Name>town</Name>
    <Location>x 990 z-2485</Location>
    <Info>gas station</Info>
    <Dayvisited>12</Dayvisited>
    <userdata>u</userdata>
  </place>
  <place>
    <Name>crossing</Name>
    <Location>x 90 z-2998</Location>
    <Info>working stiff</Info>
    <Dayvisited>11</Dayvisited>
    <userdata>u</userdata>
  </place>
  <place>
    <Name>home</Name>
    <Location>x-280 z 277</Location>
    <Info>home and more stuff</Info>
    <Dayvisited>125</Dayvisited>
    <userdata>u</userdata>
  </place>
</root>
</code>```

how can i make it return only those with Dayvisited less than 20 to the data grid?. i thought using textbox for the value was confusing something so i changed it to just use 20 and it still does it and i dont know why.

how i add user input to the file

```<code>try
{

DataRow dr = ds.Tables[0].NewRow();
dr["Name"] = Nametb.Text;
dr["Location"] = Locationtb.Text;
dr["Info"] = Infotb.Text;
dr["Dayvisited"] = dayvisitcb.Text;
dr["userdata"] = "u";
ds.Tables[0].Rows.Add(dr);
ds.WriteXml("Database.xml");

}
catch (Exception)
{
throw;
}
</code>```

答:
The basic problem is that you read the value of DayVisited as a string. So a comparison of "100" < "20" turns out to be true in a string comparison. This leads to the row being included into the result.

In order to compare the value correctly, you have to convert it to an integer before:

```<code>filter = "Convert(Dayvisited, System.Int32) <= 20"
</code>```

However, as your XML file contains a row without data for DayVisited at the beginning, you have to prepare for invalid data. Thus you have to check the length of the string before to exclude the invalid row:

```<code>filter = "IIF(LEN(DayVisited) = 0, FALSE, Convert(Dayvisited, System.Int32) <= 20)"
</code>```

If you want to include the empty row in the result, change the FALSE to TRUE.

Title: Data grid row filter return less than

Body:
when i run this to filter my xml file it returns all rows even those higher than the given amount.

DataSet ds = new DataSet();

ds.ReadXml("Database.xml");

string filter = "";
filter = "Dayvisited <= '20'";

DataView dv = new DataView(ds.Tables[0]);
dv.RowFilter = filter;
dataGridView2.DataSource = dv;
dataGridView2.Columns[4].Visible = false;

this is my xml

<root>
  <place>
    <Name />
    <Location />
    <Info />
    <Dayvisited />
    <userdata />
  </place>
  <place>
    <Name>home</Name>
    <Location>x-292 z 277</Location>
    <Info>home</Info>
    <Dayvisited>100</Dayvisited>
    <userdata>u</userdata>
  </place>
  <place>
    <Name>base</Name>
    <Location>x868 z986</Location>
    <Info>stuff</Info>
    <Dayvisited>20</Dayvisited>
    <userdata>u</userdata>
  </place>
  <place>
    <Name>town</Name>
    <Location>x 990 z-2485</Location>
    <Info>gas station</Info>
    <Dayvisited>12</Dayvisited>
    <userdata>u</userdata>
  </place>
  <place>
    <Name>crossing</Name>
    <Location>x 90 z-2998</Location>
    <Info>working stiff</Info>
    <Dayvisited>11</Dayvisited>
    <userdata>u</userdata>
  </place>
  <place>
    <Name>home</Name>
    <Location>x-280 z 277</Location>
    <Info>home and more stuff</Info>
    <Dayvisited>125</Dayvisited>
    <userdata>u</userdata>
  </place>
</root>

how can i make it return only those with Dayvisited less than 20 to the data grid?. i thought using textbox for the value was confusing something so i changed it to just use 20 and it still does it and i dont know why.

how i add user input to the file

try
{

DataRow dr = ds.Tables[0].NewRow();
dr["Name"] = Nametb.Text;
dr["Location"] = Locationtb.Text;
dr["Info"] = Infotb.Text;
dr["Dayvisited"] = dayvisitcb.Text;
dr["userdata"] = "u";
ds.Tables[0].Rows.Add(dr);
ds.WriteXml("Database.xml");

}
catch (Exception)
{
throw;
}

Body:
The basic problem is that you read the value of DayVisited as a string. So a comparison of "100" < "20" turns out to be true in a string comparison. This leads to the row being included into the result.

In order to compare the value correctly, you have to convert it to an integer before:

filter = "Convert(Dayvisited, System.Int32) <= 20"

However, as your XML file contains a row without data for DayVisited at the beginning, you have to prepare for invalid data. Thus you have to check the length of the string before to exclude the invalid row:

filter = "IIF(LEN(DayVisited) = 0, FALSE, Convert(Dayvisited, System.Int32) <= 20)"

If you want to include the empty row in the result, change the FALSE to TRUE.


问:
Wpf binding update happens too late
I use MVVM. There is a slow command. I want to use a log to indicate where is the execution.
xaml:

```<code> <TextBlock Height="200" Text="{Binding Log.Content, UpdateSourceTrigger=PropertyChanged}"></TextBlock>
</code>```

code:

```<code>Log.addLine("Ledger initialized.");
// slow1 operation
Log.addLine("slow1 operation.");
</code>```

The textblock is only updated when the whole command is finished. Both message appears at the same time when the GUI is active.

答:
Try executing slow method (presumably blocking method) in async manner, something like this:</p>

```<code>Log.addLine("Ledger initialized.");
await Task.Run(() =>
{
    SlowMethod();
});
Log.addLine("slow1 operation.");
</code>```

Title: Wpf binding update happens too late

Body:
I use MVVM. There is a slow command. I want to use a log to indicate where is the execution.
xaml:

 <TextBlock Height="200" Text="{Binding Log.Content, UpdateSourceTrigger=PropertyChanged}"></TextBlock>

code:

Log.addLine("Ledger initialized.");
// slow1 operation
Log.addLine("slow1 operation.");

The textblock is only updated when the whole command is finished. Both message appears at the same time when the GUI is active.

Body:
Try executing slow method (presumably blocking method) in async manner, something like this:

Log.addLine("Ledger initialized.");
await Task.Run(() =>
{
    SlowMethod();
});
Log.addLine("slow1 operation.");


问:
Query returns no result (Delphi, Oracle, DBExpress)
I am trying to get the query result from the Oracle sql server and insert it in the StringGridShowPapers table.

I have SQLConnection1 (a DBExpress connection) set up and working, SQLDataSetPapers DataSet and a query SQLQueryPapers.

When I am running this procedure, the query seems to return nothing:

```<code>procedure TFormOperator.TabSheetShowPapersShow(Sender: TObject);
begin
    SQLQueryShowPapers.SQL.Text := 'SELECT * FROM papers';
    SQLQueryShowPapers.Open;
    SQLQueryShowPapers.First;

    if (NOT SQLQueryShowPapers.IsEmpty) then begin
        SQLQueryShowPapers.First;
        StringGridShowPapers.RowCount := 2;

        while (NOT SQLQueryShowPapers.EOF) do begin
            if (SQLQueryShowPapers.Fields[2].AsString = Frame11.ID) then begin
                with StringGridShowPapers do begin
                  Cells[0, (StringGridShowPapers.RowCount - 1)] :=
                    SQLQueryShowPapers.Fields[0].AsString;
                  Cells[1, (StringGridShowPapers.RowCount - 1)] :=
                    SQLQueryShowPapers.Fields[1].AsString;
                  Cells[2, (StringGridShowPapers.RowCount - 1)] :=
                    SQLQueryShowPapers.Fields[2].AsString;
                end;
                SQLQueryShowPapers.Next;
                StringGridShowPapers.RowCount := StringGridShowPapers.RowCount + 1;
            end;
        end;
    end;

end;
</code>```

Frame11.ID contains a string value  of a number.

Running the same query SELECT * FROM papers in oracle SQL Developer results a number of rows.

What could trigger the problem?

Thanks in advance!

Looks like i found the solution:

It looks like the some (global) variables and properties in Delphi are inaccessable or simply cleaned up after the procedure that assigns them is finished. So you may need to assign first form value to a global variable of second one (that you use this value in) in a runtime of the first form procedure.

答:
try this, the next operator is out of if block
I think something in your data doesn't let you cycle to be completed

```<code>procedure TFormOperator.TabSheetShowPapersShow(Sender: TObject);
begin
    SQLQueryShowPapers.SQL.Text := 'SELECT * FROM papers';
    SQLQueryShowPapers.Open;
    SQLQueryShowPapers.First;

    if (NOT SQLQueryShowPapers.IsEmpty) then begin
        SQLQueryShowPapers.First;
        StringGridShowPapers.RowCount := 2;

        while (NOT SQLQueryShowPapers.EOF) do begin
            if (SQLQueryShowPapers.Fields[2].AsString = Frame11.ID) then begin
                with StringGridShowPapers do begin
                  Cells[0, (StringGridShowPapers.RowCount - 1)] :=
                    SQLQueryShowPapers.Fields[0].AsString;
                  Cells[1, (StringGridShowPapers.RowCount - 1)] :=
                    SQLQueryShowPapers.Fields[1].AsString;
                  Cells[2, (StringGridShowPapers.RowCount - 1)] :=
                    SQLQueryShowPapers.Fields[2].AsString;
                end;
                StringGridShowPapers.RowCount := StringGridShowPapers.RowCount + 1;
            end;
             SQLQueryShowPapers.Next;
        end;
    end;

end;
</code>```

Body:
I am trying to get the query result from the Oracle sql server and insert it in the StringGridShowPapers table.

I have SQLConnection1 (a DBExpress connection) set up and working, SQLDataSetPapers DataSet and a query SQLQueryPapers.

When I am running this procedure, the query seems to return nothing:

procedure TFormOperator.TabSheetShowPapersShow(Sender: TObject);
begin
    SQLQueryShowPapers.SQL.Text := 'SELECT * FROM papers';
    SQLQueryShowPapers.Open;
    SQLQueryShowPapers.First;

    if (NOT SQLQueryShowPapers.IsEmpty) then begin
        SQLQueryShowPapers.First;
        StringGridShowPapers.RowCount := 2;

        while (NOT SQLQueryShowPapers.EOF) do begin
            if (SQLQueryShowPapers.Fields[2].AsString = Frame11.ID) then begin
                with StringGridShowPapers do begin
                  Cells[0, (StringGridShowPapers.RowCount - 1)] :=
                    SQLQueryShowPapers.Fields[0].AsString;
                  Cells[1, (StringGridShowPapers.RowCount - 1)] :=
                    SQLQueryShowPapers.Fields[1].AsString;
                  Cells[2, (StringGridShowPapers.RowCount - 1)] :=
                    SQLQueryShowPapers.Fields[2].AsString;
                end;
                SQLQueryShowPapers.Next;
                StringGridShowPapers.RowCount := StringGridShowPapers.RowCount + 1;
            end;
        end;
    end;

end;

Frame11.ID contains a string value  of a number.

Running the same query SELECT * FROM papers in oracle SQL Developer results a number of rows.

What could trigger the problem?

Thanks in advance!

Looks like i found the solution:

It looks like the some (global) variables and properties in Delphi are inaccessable or simply cleaned up after the procedure that assigns them is finished. So you may need to assign first form value to a global variable of second one (that you use this value in) in a runtime of the first form procedure.

Body:
try this, the next operator is out of if block
I think something in your data doesn't let you cycle to be completed

procedure TFormOperator.TabSheetShowPapersShow(Sender: TObject);
begin
    SQLQueryShowPapers.SQL.Text := 'SELECT * FROM papers';
    SQLQueryShowPapers.Open;
    SQLQueryShowPapers.First;

    if (NOT SQLQueryShowPapers.IsEmpty) then begin
        SQLQueryShowPapers.First;
        StringGridShowPapers.RowCount := 2;

        while (NOT SQLQueryShowPapers.EOF) do begin
            if (SQLQueryShowPapers.Fields[2].AsString = Frame11.ID) then begin
                with StringGridShowPapers do begin
                  Cells[0, (StringGridShowPapers.RowCount - 1)] :=
                    SQLQueryShowPapers.Fields[0].AsString;
                  Cells[1, (StringGridShowPapers.RowCount - 1)] :=
                    SQLQueryShowPapers.Fields[1].AsString;
                  Cells[2, (StringGridShowPapers.RowCount - 1)] :=
                    SQLQueryShowPapers.Fields[2].AsString;
                end;
                StringGridShowPapers.RowCount := StringGridShowPapers.RowCount + 1;
            end;
             SQLQueryShowPapers.Next;
        end;
    end;

end;


问:
How to assign a column's value to a variable?
I want to set the BalanceAmount into a variable but it returns an empty value.

```<code>Declare BalAmt as int;
SET BalAmt = (SELECT BalanceAmount FROM mstragentrecharge);
SELECT BalAmt
</code>```

答:
If this code is from function or procedure, then try below

```<code>Declare BalAmt as int;

SELECT BalanceAmount into BalAmt  FROM mstragentrecharge);

SELECT BalAmt
</code>```

Or, for simple query:

```<code>SET @BalAmt  := '';
SELECT @BalAmt  := `BalanceAmount ` FROM mstragentrecharge limit 1;
SELECT @BalAmt FROM mstragentrecharge;
</code>```

Body:
I want to set the BalanceAmount into a variable but it returns an empty value.

Declare BalAmt as int;
SET BalAmt = (SELECT BalanceAmount FROM mstragentrecharge);
SELECT BalAmt

Body:
If this code is from function or procedure, then try below

Declare BalAmt as int;

SELECT BalanceAmount into BalAmt  FROM mstragentrecharge);

SELECT BalAmt

Or, for simple query:

SET @BalAmt  := '';
SELECT @BalAmt  := `BalanceAmount ` FROM mstragentrecharge limit 1;
SELECT @BalAmt FROM mstragentrecharge;


问:
Pip - Fatal error in launcher: Unable to create process using '"'
I installed python 3.5.1 via ampps and it's working. However, when i try to use pip, i get the following message:

```<code>Fatal error in launcher: Unable to create process using '"'
</code>```

I already reinstalled ampps into a path which doesn't include any whitespaces. Note that the "python -m pip" workaround doesn't work for me too, since i get the following message everytime i use it:

```<code>C:\Users\MyUserName\Desktop\Ampps\python\python.exe: Error while finding spec for 'pip.__main__' (<class 'ImportError'>: No module named 'queue'); 'pip' is a package and cannot be directly executed
</code>```

How do i get pip to work properly? I hope, there is a way to use the pip command itself without the preceding python command.

EDIT: This is what happens, if i try to run python -c "import pip.__main__":

```<code>Traceback (most recent call last):
  File "C:\Users\MyUserName\Desktop\Ampps\python\lib\site-packages\pip\compat\__init__.py", line 11, in <module>
    from logging.config import dictConfig as logging_dictConfig
  File "C:\Users\MyUserName\Desktop\Ampps\python\lib\logging\config.py", line 30, in <module>
    import logging.handlers
  File "C:\Users\MyUserName\Desktop\Ampps\python\lib\logging\handlers.py", line 28, in <module>
    import queue
ImportError: No module named 'queue'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\MyUserName\Desktop\Ampps\python\lib\site-packages\pip\__init__.py", line 13, in <module>
    from pip.utils import get_installed_distributions, get_prog
  File "C:\Users\MyUserName\Desktop\Ampps\python\lib\site-packages\pip\utils\__init__.py", line 18, in <module>
    from pip.compat import console_to_str, stdlib_pkgs
  File "C:\Users\MyUserName\Desktop\Ampps\python\lib\site-packages\pip\compat\__init__.py", line 13, in <module>
    from pip.compat.dictconfig import dictConfig as logging_dictConfig
  File "C:\Users\MyUserName\Desktop\Ampps\python\lib\site-packages\pip\compat\dictconfig.py", line 22, in <module>
    import logging.handlers
  File "C:\Users\MyUserName\Desktop\Ampps\python\lib\logging\handlers.py", line 28, in <module>
    import queue
ImportError: No module named 'queue'
</code>```

答: One more very basic and simple solution. Run the related python version's installation file (setup file) and click repair mode. It hardly takes one-two minutes and everything works perfectly after that :)</p>

Body:
I installed python 3.5.1 via ampps and it's working. However, when i try to use pip, i get the following message:

Fatal error in launcher: Unable to create process using '"'

I already reinstalled ampps into a path which doesn't include any whitespaces. Note that the "python -m pip" workaround doesn't work for me too, since i get the following message everytime i use it:

C:\Users\MyUserName\Desktop\Ampps\python\python.exe: Error while finding spec for 'pip.__main__' (<class 'ImportError'>: No module named 'queue'); 'pip' is a package and cannot be directly executed

How do i get pip to work properly? I hope, there is a way to use the pip command itself without the preceding python command.

EDIT: This is what happens, if i try to run python -c "import pip.__main__":

Traceback (most recent call last):
  File "C:\Users\MyUserName\Desktop\Ampps\python\lib\site-packages\pip\compat\__init__.py", line 11, in <module>
    from logging.config import dictConfig as logging_dictConfig
  File "C:\Users\MyUserName\Desktop\Ampps\python\lib\logging\config.py", line 30, in <module>
    import logging.handlers
  File "C:\Users\MyUserName\Desktop\Ampps\python\lib\logging\handlers.py", line 28, in <module>
    import queue
ImportError: No module named 'queue'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\MyUserName\Desktop\Ampps\python\lib\site-packages\pip\__init__.py", line 13, in <module>
    from pip.utils import get_installed_distributions, get_prog
  File "C:\Users\MyUserName\Desktop\Ampps\python\lib\site-packages\pip\utils\__init__.py", line 18, in <module>
    from pip.compat import console_to_str, stdlib_pkgs
  File "C:\Users\MyUserName\Desktop\Ampps\python\lib\site-packages\pip\compat\__init__.py", line 13, in <module>
    from pip.compat.dictconfig import dictConfig as logging_dictConfig
  File "C:\Users\MyUserName\Desktop\Ampps\python\lib\site-packages\pip\compat\dictconfig.py", line 22, in <module>
    import logging.handlers
  File "C:\Users\MyUserName\Desktop\Ampps\python\lib\logging\handlers.py", line 28, in <module>
    import queue
ImportError: No module named 'queue'


问:
How to hide connection string, user name, pw when using source control?
I'm working on a small side-project and I'm using connection strings and also api keys and values that should not be seen or used by other people. I use a public GitHub account for source control. What is the usual method for using source control when these values are in plain text in web.config?

Do I need to remove the values manually before checking in code?

答:
What I find works is to check in a version of the file with blanked or dummy values and then to run:

```<code>git update-index --assume-unchanged [fileName]
</code>```

Git will then stop monitoring changes to that file allowing you to put the real config info into it without fear of checking it in.

If you later make changes that you DO want to check in you can run:

```<code>git update-index --no-assume-unchanged [fileName]
</code>```

Body:
What I find works is to check in a version of the file with blanked or dummy values and then to run:

git update-index --assume-unchanged [fileName]

Git will then stop monitoring changes to that file allowing you to put the real config info into it without fear of checking it in.

If you later make changes that you DO want to check in you can run:

git update-index --no-assume-unchanged [fileName]


问:
Run tests before sbt dist in sbt-native-packager
I don't wanna create any deployable without running tests. Is there anyway in sbt-native-packager / sbt where I could run sbt test in inside sbt dist, which would fail when any test fails?</p>

答:
There are multiple ways to achieve this.

Create a command alias

This is my recommended approach as it is very explicit, easy to understand and extend. In your build.sbt add

```<code>addCommandAlias("buildDist", ";  compile ; test ; dist")
</code>```

Now you can call sbt buildDist

Depend on test

You can add dependencies between tasks. In your build.sbt

```<code>dist := (dist dependsOn test).value
</code>```

This will add the test task as a dependency

Cheers,
Muki

Body:
There are multiple ways to achieve this.

Create a command alias

This is my recommended approach as it is very explicit, easy to understand and extend. In your build.sbt add

addCommandAlias("buildDist", ";  compile ; test ; dist")

Now you can call sbt buildDist

Depend on test

You can add dependencies between tasks. In your build.sbt

dist := (dist dependsOn test).value

This will add the test task as a dependency

Cheers,
Muki


问:
Countdown timer in gridview asp.net
I have a project table with start date and end date. I want to show a countdown in gridview in asp.net to when the project will end and when it comes to let it display a message 'Project Ended'.</p>

答:
I suppose you want to display the number of days remaining for the project
You can do this in RowDataBound event:</p>

```<code>protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataRowView rowView = (DataRowView)e.Row.DataItem;
                DateTime startDate = rowView["startDate"];
                DateTime endDate = rowView["endDate"];
                int daysRemaining = (endDate - startDate).TotalDays;
                if (daysRemaining > 0)
                   e.row.Cells[your column].Text = daysRemaining.ToString();
                else
                   e.row.Cells[your column].Text = "PROJECT ENDED";
             }
          }
</code>```

Title: Countdown timer in gridview asp.net

Body:
I suppose you want to display the number of days remaining for the project
You can do this in RowDataBound event:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataRowView rowView = (DataRowView)e.Row.DataItem;
                DateTime startDate = rowView["startDate"];
                DateTime endDate = rowView["endDate"];
                int daysRemaining = (endDate - startDate).TotalDays;
                if (daysRemaining > 0)
                   e.row.Cells[your column].Text = daysRemaining.ToString();
                else
                   e.row.Cells[your column].Text = "PROJECT ENDED";
             }
          }


答:
You could write it this way, which is basically a disguised if/elsif:

```<code>query_limit = case
                when current_user.nil?
                  return 5
                when current_user.is_admin?
                  return 200
                when current_user.has_role?('registered')
                  return 20
                else
                  return 5
                end
</code>```

Title: Why is my ruby case statement not working?

Body:
You could write it this way, which is basically a disguised if/elsif:

query_limit = case
                when current_user.nil?
                  return 5
                when current_user.is_admin?
                  return 200
                when current_user.has_role?('registered')
                  return 20
                else
                  return 5
                end


答:
Depending on how space-efficient it has to be and how efficient the retrieval should be, I see two possibilities:

Since a vector of std::bitset<4> is (as far as I know) stored in an unpacked setting (each bitset is stored in a memory word, either 32 or 64 bit), you should probably at least use a packed representation like using a 64 bit word to store 16 digits:

```<code>store (if the digit was not stored before):
block |= digit << 4 * index
load:
digit = (block >> 4 * index) & 0xF
reset:
block &= ~(0xF << 4 * index);
</code>```

A vector of these 64 bit words (uint64_t) together with some access methods should be easy to implement.

If your space requirements are even tighter, you could e.g. try packing 3 digits in 10 bits (at most 1024) using divisions and modulo, which would be a lot less time-efficient. Also the alignment with 64 bit words is much more difficult, so I would only recommend this if you need to get the final 16% improvement, at most you can get something like 3.3 bits per digit.

Title: Store one decimal digit

Body:
I have a problem which concern with large number of small integers (actually decimal digits). What is the space efficient way to store such a data?

Is it good idea to use std::bitset<4> to store one decimal digit?

Body:
Depending on how space-efficient it has to be and how efficient the retrieval should be, I see two possibilities:

Since a vector of std::bitset<4> is (as far as I know) stored in an unpacked setting (each bitset is stored in a memory word, either 32 or 64 bit), you should probably at least use a packed representation like using a 64 bit word to store 16 digits:

store (if the digit was not stored before):
block |= digit << 4 * index
load:
digit = (block >> 4 * index) & 0xF
reset:
block &= ~(0xF << 4 * index);

A vector of these 64 bit words (uint64_t) together with some access methods should be easy to implement.

If your space requirements are even tighter, you could e.g. try packing 3 digits in 10 bits (at most 1024) using divisions and modulo, which would be a lot less time-efficient. Also the alignment with 64 bit words is much more difficult, so I would only recommend this if you need to get the final 16% improvement, at most you can get something like 3.3 bits per digit.


问:
Nice way of doing dual column validation
I'm using Rails 3 for this one.  I've got a collections model, a user model and an intermediate subscription model.  This way a user can subscribe to multiple collections, with a particular role.  However, I don't want a user to be able to subscribe to the same collection twice.

So in my Subscription model I've got something like:

```<code>validate :subscription_duplicates

def subscription_duplicates
  self.errors.add_to_base "This user is already subscribed" if Subscription.where(:user_id => self.user.id, :collection_id => self.collection.id)
end
</code>```

However this seems ugly.  Also, it breaks when I want to do something like the following in my collection controller:

```<code>def create
  @collection = Collection.new(params[:collection])
  @collection.subscriptions.build(:user => current_user, :role => Subscription::ROLES['owner'])
  @collection.save
  respond_with(@collection)
end
</code>```

When I do the build the subscription does not have an id so I get a "Called id for nil" error.

Thanks for any guidance!

答:
First of all, your create action should always test if the object was saved, and if not then handle that (usually by re-rendering the new/edit page and showing the errors to the user).

A standard sort of create action would look like this (for a @post in this case):

```<code>def create
  @post = Post.new(params[:post])
  @created = @post.save
  respond_to do |format|
    if @created
      flash[:notice] = 'Post was successfully created.'
      format.html { redirect_to @post }
      format.xml  { render :xml => @post, :status => :created, :location => @post }
      format.js
    else
      format.html { render :action => :new } #or edit or wherever you got here from
      format.xml  { render :xml => @post.errors, :status => :unprocessable_entity }
      format.js
    end
  end
end
</code>```

Shingara's approach to avoiding duplicates should work fine for you.

Body:
I'm using Rails 3 for this one.  I've got a collections model, a user model and an intermediate subscription model.  This way a user can subscribe to multiple collections, with a particular role.  However, I don't want a user to be able to subscribe to the same collection twice.

So in my Subscription model I've got something like:

validate :subscription_duplicates

def subscription_duplicates
  self.errors.add_to_base "This user is already subscribed" if Subscription.where(:user_id => self.user.id, :collection_id => self.collection.id)
end

However this seems ugly.  Also, it breaks when I want to do something like the following in my collection controller:

def create
  @collection = Collection.new(params[:collection])
  @collection.subscriptions.build(:user => current_user, :role => Subscription::ROLES['owner'])
  @collection.save
  respond_with(@collection)
end

When I do the build the subscription does not have an id so I get a "Called id for nil" error.

Thanks for any guidance!

Body:
First of all, your create action should always test if the object was saved, and if not then handle that (usually by re-rendering the new/edit page and showing the errors to the user).

A standard sort of create action would look like this (for a @post in this case):

def create
  @post = Post.new(params[:post])
  @created = @post.save
  respond_to do |format|
    if @created
      flash[:notice] = 'Post was successfully created.'
      format.html { redirect_to @post }
      format.xml  { render :xml => @post, :status => :created, :location => @post }
      format.js
    else
      format.html { render :action => :new } #or edit or wherever you got here from
      format.xml  { render :xml => @post.errors, :status => :unprocessable_entity }
      format.js
    end
  end
end

Shingara's approach to avoiding duplicates should work fine for you.


问:
A* Algorithm for very large graphs, any thoughts on caching shortcuts?
I'm writing a courier/logistics simulation on OpenStreetMap maps and have realised that the basic A* algorithm as pictured below is not going to be fast enough for large maps (like Greater London).

The green nodes correspond to ones that were put in the open set/priority queue and due to the huge number (the whole map is something like 1-2 million), it takes 5 seconds or so to find the route pictured. Unfortunately 100ms per route is about my absolute limit.

Currently, the nodes are stored in both an adjacency list and also a spatial 100x100 2D array.

I'm looking for methods where I can trade off preprocessing time, space and if needed optimality of the route, for faster queries. The straight-line Haversine formula for the heuristic cost is the most expensive function according to the profiler - I have optimised my basic A* as much as I can.

For example, I was thinking if I chose an arbitrary node X from each quadrant of the 2D array and run A* between each, I can store the routes to disk for subsequent simulations. When querying, I can run A* search only in the quadrants, to get between the precomputed route and the X.

Is there a more refined version of what I've described above or perhaps a different method I should pursue. Many thanks!

For the record, here are some benchmark results for arbitrarily weighting the heuristic cost and computing the path between 10 pairs of randomly picked nodes:

```<code>Weight // AvgDist% // Time (ms)
1       1       1461.2
1.05    1       1327.2
1.1     1       900.7
1.2     1.019658848     196.4
1.3     1.027619169     53.6
1.4     1.044714394     33.6
1.5     1.063963413     25.5
1.6     1.071694171     24.1
1.7     1.084093229     24.3
1.8     1.092208509     22
1.9     1.109188175     22.5
2       1.122856792     18.2
2.2     1.131574742     16.9
2.4     1.139104895     15.4
2.6     1.140021962     16
2.8     1.14088128      15.5
3       1.156303676     16
4       1.20256964      13
5       1.19610861      12.9
</code>```

Surprisingly increasing the coefficient to 1.1 almost halved the execution time whilst keeping the same route.

答:
Old question, but yet:

Try to use different heaps that "binary heap". 'Best asymptotic complexity heap' is definetly Fibonacci Heap and it's wiki page got a nice overview:

https://en.wikipedia.org/wiki/Fibonacci_heap#Summary_of_running_times

Note that binary heap has simpler code and it's implemented over array and traversal of array is predictable, so modern CPU executes binary heap operations much faster.

However, given dataset big enough, other heaps will win over binary heap, because of their complexities...

This question seems like dataset big enough.

Body:
I'm writing a courier/logistics simulation on OpenStreetMap maps and have realised that the basic A* algorithm as pictured below is not going to be fast enough for large maps (like Greater London).

The green nodes correspond to ones that were put in the open set/priority queue and due to the huge number (the whole map is something like 1-2 million), it takes 5 seconds or so to find the route pictured. Unfortunately 100ms per route is about my absolute limit.

Currently, the nodes are stored in both an adjacency list and also a spatial 100x100 2D array.

I'm looking for methods where I can trade off preprocessing time, space and if needed optimality of the route, for faster queries. The straight-line Haversine formula for the heuristic cost is the most expensive function according to the profiler - I have optimised my basic A* as much as I can.

For example, I was thinking if I chose an arbitrary node X from each quadrant of the 2D array and run A* between each, I can store the routes to disk for subsequent simulations. When querying, I can run A* search only in the quadrants, to get between the precomputed route and the X.

Is there a more refined version of what I've described above or perhaps a different method I should pursue. Many thanks!

For the record, here are some benchmark results for arbitrarily weighting the heuristic cost and computing the path between 10 pairs of randomly picked nodes:

Weight // AvgDist% // Time (ms)
1       1       1461.2
1.05    1       1327.2
1.1     1       900.7
1.2     1.019658848     196.4
1.3     1.027619169     53.6
1.4     1.044714394     33.6
1.5     1.063963413     25.5
1.6     1.071694171     24.1
1.7     1.084093229     24.3
1.8     1.092208509     22
1.9     1.109188175     22.5
2       1.122856792     18.2
2.2     1.131574742     16.9
2.4     1.139104895     15.4
2.6     1.140021962     16
2.8     1.14088128      15.5
3       1.156303676     16
4       1.20256964      13
5       1.19610861      12.9

Surprisingly increasing the coefficient to 1.1 almost halved the execution time whilst keeping the same route.


问:
How to find the size of an int[]?
I have

```<code>int list[] = {1, 2, 3};
</code>```

How to I get the size of list?

I know that for a char array, we can use strlen(array) to find the size, or check with '\0' at the end of the array.

I tried sizeof(array) / sizeof(array[0]) as some answers said, but it only works in main? For example:

```<code>int size(int arr1[]){
    return sizeof(arr1) / sizeof(arr1[0]);
}

int main() {
    int list[] = {1, 2, 3};

    int size1 = sizeof(list) / sizeof(list[0]); // ok
    int size2 = size(list_1); // no
    // size1 and size2 are not the same
}
</code>```

Why?

答:
You have to use sizeof() function.

Code Snippet:

```<code>#include<bits/stdc++.h>
using namespace std;

int main()
{
      ios::sync_with_stdio(false);

      int arr[] ={5, 3, 6, 7};

      int size = sizeof(arr) / sizeof(arr[0]);
      cout<<size<<endl;

      return 0;
}
</code>```

Title: How to find the size of an int[]?

Body:
I have

int list[] = {1, 2, 3};

How to I get the size of list?

I know that for a char array, we can use strlen(array) to find the size, or check with '\0' at the end of the array.

I tried sizeof(array) / sizeof(array[0]) as some answers said, but it only works in main? For example:

int size(int arr1[]){
    return sizeof(arr1) / sizeof(arr1[0]);
}

int main() {
    int list[] = {1, 2, 3};

    int size1 = sizeof(list) / sizeof(list[0]); // ok
    int size2 = size(list_1); // no
    // size1 and size2 are not the same
}

Why?

Body:
You have to use sizeof() function.

Code Snippet:

#include<bits/stdc++.h>
using namespace std;

int main()
{
      ios::sync_with_stdio(false);

      int arr[] ={5, 3, 6, 7};

      int size = sizeof(arr) / sizeof(arr[0]);
      cout<<size<<endl;

      return 0;
}


答:
According to the Ruby documentation:

Case statements consist of an optional condition, which is in the position of an argument to case, and zero or more when clauses. The first when clause to match the condition (or to evaluate to Boolean truth, if the condition is null) “wins”, and its code stanza is executed.

If you specify current_user as the case condition, then the first when expression that matches current_user will be executed. current_user.is_admin? returns a boolean value which will never be equal to current_user, so your second example will always take the else branch:

```<code>case current_user
  when nil  # current_user != nil, skip condition
    return 5
  when current_user.is_admin?  # current_user != current_user.is_admin?, skip condition
    return 200
  when current_user.has_role?('registered')  # and so on
    return 20
  else
    return 5
end
</code>```

Your first example is broken because there is no local is_admin? method defined. case does not know to call is_admin? on current_user in this case.

To fix your code, you can remove case condition. In this case the first when clause that evaluates to a truthy value will be chosen:

```<code>case  # no current_user here!
  when current_user.nil?  # current_user.nil? is false, skip condition
    return 5
  when current_user.is_admin?  # current_user.is_admin? is truthy, run this one!
    return 200
  when current_user.has_role?('registered')
    return 20
  else
    return 5
end
</code>```

Body:
What's wrong with that?
Yes, I could make an if else statement, but I wanna do that with case statements.

In my Controller

query_limit = case current_user
                when nil
                  return 5
                when is_admin?
                  return 200
                when has_role?('registered')
                  return 20
                else
                  return 5
              end

NoMethodError (undefined method `is_admin?' for #<V1::MyController:123123123>):

puts query_limit # is always ELSE when I do this:

 query_limit = case current_user
                    when nil
                      return 5
                    when current_user.is_admin?
                      return 200
                    when current_user.has_role?('registered')
                      return 20
                    else
                      return 5
                  end

Model User

class User
  def is_admin?
    self.has_role?('administrator')
  end

  def has_role?(the_role)
    self.roles.any? {|role| role.slug == the_role}
  end
end

Body:
According to the Ruby documentation:

Case statements consist of an optional condition, which is in the position of an argument to case, and zero or more when clauses. The first when clause to match the condition (or to evaluate to Boolean truth, if the condition is null) “wins”, and its code stanza is executed.

If you specify current_user as the case condition, then the first when expression that matches current_user will be executed. current_user.is_admin? returns a boolean value which will never be equal to current_user, so your second example will always take the else branch:

case current_user
  when nil  # current_user != nil, skip condition
    return 5
  when current_user.is_admin?  # current_user != current_user.is_admin?, skip condition
    return 200
  when current_user.has_role?('registered')  # and so on
    return 20
  else
    return 5
end

Your first example is broken because there is no local is_admin? method defined. case does not know to call is_admin? on current_user in this case.

To fix your code, you can remove case condition. In this case the first when clause that evaluates to a truthy value will be chosen:

case  # no current_user here!
  when current_user.nil?  # current_user.nil? is false, skip condition
    return 5
  when current_user.is_admin?  # current_user.is_admin? is truthy, run this one!
    return 200
  when current_user.has_role?('registered')
    return 20
  else
    return 5
end


问:
Java Overload resolution - Why m(cast, cast) instead of m(match, cast)
I'm pretty sure I can't be the first one to stumble over this but I can't find an answer. This is homework.

```<code>class Tier{}

class Fisch extends Tier{}

class Vogel extends Tier{}

class Huhn extends Vogel{}

class Spatz extends Vogel{}

class Karpfen extends Fisch{}

class Super{
    public void m(Tier t1, Tier t2){
        System.out.println("1");
    }

    public void m(Tier t, Fisch f){
        System.out.println("2");
    }

    public void m(Fisch f, Tier t){
        System.out.println("5");
    }
}

class Sub extends Super{
    public void m(Tier t1, Fisch t2){
        System.out.println("3");
    }

    public void m(Vogel v, Fisch f){
        System.out.println("4");
    }
}

public class TierTest{
    public static void main(String[] args) {
        Tier t1 = new Tier();
        Tier t2 = new Vogel();
        Fisch f = new Karpfen();
        Vogel v1 = new Vogel();
        Vogel v2 = new Spatz();
        Huhn h = new Huhn();
        Karpfen k = new Karpfen();

        Super sup1 = new Super();
        Super sup2 = new Sub();

        sup1.m(h, v2);
        sup2.m(v1, k);   //4 expected, got 3
        sup1.m(t1, t2);
        sup1.m(v1, k);
        sup1.m(v2, f);
        sup2.m(v1, f);  //4 expected, got 3
    }
}
</code>```

Both times a Vogel(bird) (declaration and runtime type) and some kind of fish. Why is m(Tier, Fisch) chosen over m(Vogel, Fisch) ?

The fist parameter would be a perfect match. The rest of this fits my intuition.

Sorry if I'm just too numb to find a similar question.

Have a nice weekend,
Stephan

答:
Here :

```<code>Vogel v1 = new Vogel();
Karpfen k = new Karpfen();
...
Super sup2 = new Sub();
...
sup2.m(v1, k);   //4 expected, got 3
</code>```

sup2 is declared with the Super class type.

The method chosen by the compiler relies on the class of the declared variable, not on the runtime instance.

So, the compilers looks for a method that matches in the Super class.

In Super class, these are the m() potential method candidates :

```<code>public void m(Tier t1, Tier t2){
    System.out.println("1");
}

public void m(Tier t, Fisch f){
    System.out.println("2");
}

public void m(Fisch f, Tier t){
    System.out.println("5");
}
</code>```

The compiler chooses the most specific method among other to match with v1 and k arguments declared types :

This method is selected :

```<code>public void m(Tier t, Fisch f){
    System.out.println("2");
}
</code>```

Now, at runtime, the method is invoked on the runtime object (polymorphism principle).

As the runtime class that the sup2 variable refers to is Sub, the overloaded method of Sub is invoked :

```<code>public void m(Tier t1, Fisch t2){
    System.out.println("3");
}
</code>```

And for this second invocation :

```<code>sup2.m(v1, f);  //4 expected, got 3
</code>```

It is exactly the same reasoning.

Body:
I'm pretty sure I can't be the first one to stumble over this but I can't find an answer. This is homework.

class Tier{}

class Fisch extends Tier{}

class Vogel extends Tier{}

class Huhn extends Vogel{}

class Spatz extends Vogel{}

class Karpfen extends Fisch{}

class Super{
    public void m(Tier t1, Tier t2){
        System.out.println("1");
    }

    public void m(Tier t, Fisch f){
        System.out.println("2");
    }

    public void m(Fisch f, Tier t){
        System.out.println("5");
    }
}

class Sub extends Super{
    public void m(Tier t1, Fisch t2){
        System.out.println("3");
    }

    public void m(Vogel v, Fisch f){
        System.out.println("4");
    }
}

public class TierTest{
    public static void main(String[] args) {
        Tier t1 = new Tier();
        Tier t2 = new Vogel();
        Fisch f = new Karpfen();
        Vogel v1 = new Vogel();
        Vogel v2 = new Spatz();
        Huhn h = new Huhn();
        Karpfen k = new Karpfen();

        Super sup1 = new Super();
        Super sup2 = new Sub();

        sup1.m(h, v2);
        sup2.m(v1, k);   //4 expected, got 3
        sup1.m(t1, t2);
        sup1.m(v1, k);
        sup1.m(v2, f);
        sup2.m(v1, f);  //4 expected, got 3
    }
}

Both times a Vogel(bird) (declaration and runtime type) and some kind of fish. Why is m(Tier, Fisch) chosen over m(Vogel, Fisch) ?

The fist parameter would be a perfect match. The rest of this fits my intuition.

Sorry if I'm just too numb to find a similar question.

Have a nice weekend,
Stephan

Body:
Here :

Vogel v1 = new Vogel();
Karpfen k = new Karpfen();
...
Super sup2 = new Sub();
...
sup2.m(v1, k);   //4 expected, got 3

sup2 is declared with the Super class type.

The method chosen by the compiler relies on the class of the declared variable, not on the runtime instance.

So, the compilers looks for a method that matches in the Super class.

In Super class, these are the m() potential method candidates :

public void m(Tier t1, Tier t2){
    System.out.println("1");
}

public void m(Tier t, Fisch f){
    System.out.println("2");
}

public void m(Fisch f, Tier t){
    System.out.println("5");
}

The compiler chooses the most specific method among other to match with v1 and k arguments declared types :

This method is selected :

public void m(Tier t, Fisch f){
    System.out.println("2");
}

Now, at runtime, the method is invoked on the runtime object (polymorphism principle).

As the runtime class that the sup2 variable refers to is Sub, the overloaded method of Sub is invoked :

public void m(Tier t1, Fisch t2){
    System.out.println("3");
}

And for this second invocation :

sup2.m(v1, f);  //4 expected, got 3

It is exactly the same reasoning.


问:
After assigning Elastic IP address, the EC2 instance is no longer accessible
I create a new Amazon EC2 instance, and it is successfully working. I assign an Elastic IP address and after that my instance is not reachable. I did lots of changes in the VPC, ENI and Elastic IP address, but my instance is not reachable by public DNS, also in any region no EC2 instance is reachable by public DNS.</p>

答:
Check the security groups attached to the instance and whitelist your IP for required ports in security rules.

Check the NACL rules attached to the instance and see if there are any deny rules which is blocking your traffic.

Check whether your instance is passing 2/2 Status checks, Stop and Start or reboot your instance accordingly to resolve the status check failures.

Go to Instance actions --> Network Settings and get the instance screenshot, check whether you are able to see login screen or not.

Finally if you can get the instance logs from the Instance actions --> Network Settings and view logs to see if there are any issues while booting up the instance.

Since you are already confirmed that the instance is in public subnet and has DNS resolution enabled, one of the above step will definitely resolve your issue.


问:
how to use redis to persist token using spring-security-oauth2
It is my first time developing an application with OAuth2 approach. I started based on certain tutorial and I am moving forward from this (http://websystique.com/spring-security/secure-spring-rest-api-using-oauth2/).

I will deploy the application to clustered WebSpheres so, as far as I understand in-memory will not work (... clients.inMemory().withClient ...).

I want to use Redis (my first use as well) and I am bit confused how to settup it in certain no-xml java config app.

I found certain similar question with xml but I am still with no north for a first try (Redis Token Store). Interesting, here, the question owner talked about about "Spring-Security OAuth i.e. 2.8.0 provides RedisTokenStore" but I found "2.0.12.RELEASE" as latest mvn release version.

That said, my straight question is: how can I adjust the code bellow to rely on Redis instead of in-memory?

Any comment on how to setup RedisTokenStore bellow will be appreciatted.

Additionally, if it is easy to add such additional comment, what is the difference between ".passwordEncoder" and ".secret"? The code bellow relies on ".secret" with hard-coded expression (fixed value) while I see few examples using jdbc with ".passwordEncoder filled in by springframework.security.crypto.bcrypt.BCryptPasswordEncoder" which seems to make more sense. Am I right when I guess either I use ".secret" or ".passwordEncoder"? Am I right when I think secret stands for fixed value and passwordEncoder for dinamic ones?

(example using ".passwordEncoder" and clients.jdbc https://github.com/spring-projects/spring-security-oauth/blob/master/tests/annotation/jdbc/src/main/java/demo/Application.java#L102)

```<code>@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    private static String REALM="MY_OAUTH_REALM";

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private UserApprovalHandler userApprovalHandler;

    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        clients.inMemory()
            .withClient("abc-trusted-client")
            .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
            .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
            .scopes("read", "write", "trust")
            .secret("abc-secret")
            .accessTokenValiditySeconds(120).//Access token is only valid for 2 minutes.
            refreshTokenValiditySeconds(600);//Refresh token is only valid for 10 minutes.
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore).userApprovalHandler(userApprovalHandler)
                .authenticationManager(authenticationManager);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.realm(REALM+"/client");
    }

}
</code>```

答:
Here,I set up a oauth2 authrizion [server]: https://github.com/zth390872451/oauth2-redis-mysql，If you were Chinese，you can read this blog .If not,I'm sorry about that!
This project of the github，I use the oauth-server as the authorization server,it use the redis to store the accesstoken，you just only use to configure the datasource and redis! Through  copy two class ,there: AuthAuthorizeConfig and DataStoreConfig ,you can use the redis to store token!</p>

Body:
It is my first time developing an application with OAuth2 approach. I started based on certain tutorial and I am moving forward from this (http://websystique.com/spring-security/secure-spring-rest-api-using-oauth2/).

I will deploy the application to clustered WebSpheres so, as far as I understand in-memory will not work (... clients.inMemory().withClient ...).

I want to use Redis (my first use as well) and I am bit confused how to settup it in certain no-xml java config app.

I found certain similar question with xml but I am still with no north for a first try (Redis Token Store). Interesting, here, the question owner talked about about "Spring-Security OAuth i.e. 2.8.0 provides RedisTokenStore" but I found "2.0.12.RELEASE" as latest mvn release version.

That said, my straight question is: how can I adjust the code bellow to rely on Redis instead of in-memory?

Any comment on how to setup RedisTokenStore bellow will be appreciatted.

Additionally, if it is easy to add such additional comment, what is the difference between ".passwordEncoder" and ".secret"? The code bellow relies on ".secret" with hard-coded expression (fixed value) while I see few examples using jdbc with ".passwordEncoder filled in by springframework.security.crypto.bcrypt.BCryptPasswordEncoder" which seems to make more sense. Am I right when I guess either I use ".secret" or ".passwordEncoder"? Am I right when I think secret stands for fixed value and passwordEncoder for dinamic ones?

(example using ".passwordEncoder" and clients.jdbc https://github.com/spring-projects/spring-security-oauth/blob/master/tests/annotation/jdbc/src/main/java/demo/Application.java#L102)

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    private static String REALM="MY_OAUTH_REALM";

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private UserApprovalHandler userApprovalHandler;

    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        clients.inMemory()
            .withClient("abc-trusted-client")
            .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
            .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
            .scopes("read", "write", "trust")
            .secret("abc-secret")
            .accessTokenValiditySeconds(120).//Access token is only valid for 2 minutes.
            refreshTokenValiditySeconds(600);//Refresh token is only valid for 10 minutes.
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore).userApprovalHandler(userApprovalHandler)
                .authenticationManager(authenticationManager);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.realm(REALM+"/client");
    }

}


问:
Open a webpage in python in default browser, in a specific named window
In Python, is there a way to open a specific url in the default browser, and specify the target name of the window to open it into?

I suppose you can do that using an automation framework such as selenium, but is there a solution which is not so "heavy"?

The html equivalent of this is a "a href" link with the target specified.

答:
Use webbrowser module:  </p>

```<code>import webbrowser

webbrowser.open_new(url)
</code>```

Body:
Use webbrowser module:

import webbrowser

webbrowser.open_new(url)


问:
BadMethodCallException in Builder.php line 2405: in laravel
I am new to laravel and facing an issue,I am calling a controller via ajax call ,it is calling controller but when controller is calling model it is giving
"BadMethodCallException in Builder.php line 2405:" error.Following is my code

AJAX:

```<code>$.ajax({
        url: "<?php echo url('master/add-car-to-db');?>",
        method : "post",

        data :  completeData ,
        success : function (data){
                    data=parse.JSON(data);
            if(data.success == 1){
                            window.location="<?php echo url('master/add-car-view');?>";

                        }
        },
        error:  function(data,status){
            alert(JSON.stringify(data));
        }
    });
</code>```

Controller:

```<code>public function postAddCarToDb(Request $request){
        $result = Master::addNewCar($request);
        echo $result;
        die;
         if ($result > 0) {
            echo json_encode(Array('success' => 1));
        } else {
            echo json_encode(Array('success' => 0));
        }
    }
</code>```

Model:

```<code>public static function addNewCar(Request $request){
return "success"
}
</code>```

Route:

```<code>Route::controller('master', 'MasterController');
</code>```

Thanks in advance

答:
Reverse routing is deprecated in laravel 5 so on.

```<code>Route::controller('master', 'MasterController');
</code>```

use

```<code>Route::post('master/add-car-to-db','MasterController@postAddCarToDb');
</code>```

then in Controller

if you still want to use reverse routing you can

```<code>$.ajax({
    url: "<?php echo   action(YourController@yourAction) ;?>",
    method : "post",

    data :  completeData ,
    success : function (data){
                data=parse.JSON(data);
        if(data.success == 1){
                        window.location="<?php echo url('master/add-car-view');?>";

                    }
    },
    error:  function(data,status){
        alert(JSON.stringify(data));
    }
});
</code>```

Body:
I am new to laravel and facing an issue,I am calling a controller via ajax call ,it is calling controller but when controller is calling model it is giving
"BadMethodCallException in Builder.php line 2405:" error.Following is my code

AJAX:

$.ajax({
        url: "<?php echo url('master/add-car-to-db');?>",
        method : "post",

        data :  completeData ,
        success : function (data){
                    data=parse.JSON(data);
            if(data.success == 1){
                            window.location="<?php echo url('master/add-car-view');?>";

                        }
        },
        error:  function(data,status){
            alert(JSON.stringify(data));
        }
    });

Controller:

public function postAddCarToDb(Request $request){
        $result = Master::addNewCar($request);
        echo $result;
        die;
         if ($result > 0) {
            echo json_encode(Array('success' => 1));
        } else {
            echo json_encode(Array('success' => 0));
        }
    }

Model:

public static function addNewCar(Request $request){
return "success"
}

Route:

Route::controller('master', 'MasterController');

Thanks in advance

Body:
Reverse routing is deprecated in laravel 5 so on.

Route::controller('master', 'MasterController');

use

Route::post('master/add-car-to-db','MasterController@postAddCarToDb');

then in Controller

if you still want to use reverse routing you can

$.ajax({
    url: "<?php echo   action(YourController@yourAction) ;?>",
    method : "post",

    data :  completeData ,
    success : function (data){
                data=parse.JSON(data);
        if(data.success == 1){
                        window.location="<?php echo url('master/add-car-view');?>";

                    }
    },
    error:  function(data,status){
        alert(JSON.stringify(data));
    }
});


问:
Fast way to compare items in list with each other for similarity in python
I am aware of the other questions about comparing items (strings) with each other, but I didn't fing any which will solve my problem.

I'm trying to do a text analysis of scientific papers (titles, keywords, abstracts). I want to count the occurrence of words in text. The code functions fine, but I've got problem with one part - comparing strings in list for similarity. There are lot of words like ex. "wetland" and "wetlands" and my code is comparing them for similarity and replacing them with the first one ("wetlands" become "wetland").

It works as I need but it's quite slow. So my question is if there is some better solution for this.

My code:

```<code>def similar_words(words_list):
    checked_words = []
    similar = words_list
    ind_a = 0
    num_words = len(words_list)
    print("from" + " " + str(num_words) + " " + "words")
    for similar[ind_a] in similar:
        if similar[ind_a] not in checked_words:
            ind_b = 0
            for word in similar:
                match = SequenceMatcher(None, similar[ind_a], similar[ind_b]).ratio()
                if match >= 0.85:
                    similar[ind_b] = similar[ind_a]
                ind_b += 1
            ind_a += 1
        checked_words.append(similar[ind_a])
        stdout.write("\r%d words solved" % ind_a)
        stdout.flush()
    stdout.write("\n")
    print("solved %d words for 85percent similarity" % num_words)
    return similar
</code>```

答: The Python Natural Language Toolkit has tools for stemming and lemmatization. It probably performs better than your code (and prevents a lot of "reinventing the wheel")

Body:
I am aware of the other questions about comparing items (strings) with each other, but I didn't fing any which will solve my problem.

I'm trying to do a text analysis of scientific papers (titles, keywords, abstracts). I want to count the occurrence of words in text. The code functions fine, but I've got problem with one part - comparing strings in list for similarity. There are lot of words like ex. "wetland" and "wetlands" and my code is comparing them for similarity and replacing them with the first one ("wetlands" become "wetland").

It works as I need but it's quite slow. So my question is if there is some better solution for this.

My code:

def similar_words(words_list):
    checked_words = []
    similar = words_list
    ind_a = 0
    num_words = len(words_list)
    print("from" + " " + str(num_words) + " " + "words")
    for similar[ind_a] in similar:
        if similar[ind_a] not in checked_words:
            ind_b = 0
            for word in similar:
                match = SequenceMatcher(None, similar[ind_a], similar[ind_b]).ratio()
                if match >= 0.85:
                    similar[ind_b] = similar[ind_a]
                ind_b += 1
            ind_a += 1
        checked_words.append(similar[ind_a])
        stdout.write("\r%d words solved" % ind_a)
        stdout.flush()
    stdout.write("\n")
    print("solved %d words for 85percent similarity" % num_words)
    return similar