问:
Laravel DI coupling differences
What is the difference in class coupling if you use these 3 types of usages:

Case 1

```<code>use UserRepository

...

UserRepository::getUser();
</code>```

Case 2

```<code>App::make('UserRepository')->getUser();
</code>```

Case 3

```<code>public function __construct(UserRepository $userRepository)
{
    $this->userRepository = $userRepository;
}
...
$this->userRepository->getUser();
</code>```

Is there any reason to prefer one over the other?

EDIT

I feel as though the constructor option is the best way to go, but I find myself in question when I need to include 3 services and 3 repositories in the controller which then very soon escalates to 6 parameters in constructor.

EDIT - Case 4

What about when you're using a facade instead?

EDIT - Case 5

What about when you specify it as \UserRepository?

答:
First of all, the idea of the Repository is to have an Interface (UserRepositoryInterface) and classes that implement it (MySQLUserRepository, RedisUserRepository). It gives you a quick way to change the storage of users through your DI container by calling an interface:

```<code>public function __construct(UserRepositoryInterface $userRepository)
{
    $this->userRepository = $userRepository;
}
</code>```

And changing it to any implementation in the DI container.

Let's say you have a Controller with 10 actions.

Case 1 Is not the OOP way, because the call doesn't go through the DI container at all.

Case 2 is actually OK, but you'll have to call the App facade in every action. It's not really beautiful.

Case 3 gives you only one place to create/change/configure the class.

E.g. you need to do something like:

```<code>public function __construct(UserRepository $userRepository)
{
    $this->userRepository = $userRepository;
    $this->userRepository->excludeAdmins();
}
</code>```

A lot of repositories in constructor is actually ok, however if the code fills gross to you, you can extract it to a Service class.

UPDATE
By Service class I mean a class that doesn't extends anything and contains the business logic.

Further reading: https://m.dotdev.co/design-pattern-service-layer-with-laravel-5-740ff0a7b65f

Case 4. Facades, in my opinion, are suitable for something more global. Why would you want to populate each repository with a facade? Too time consuming.

Case 5. Didn't get the question. You mean put it to the root namespace? What does it change?

Title: Laravel DI coupling differences

Body:
What is the difference in class coupling if you use these 3 types of usages:

Case 1

use UserRepository

...

UserRepository::getUser();

Case 2

App::make('UserRepository')->getUser();

Case 3

public function __construct(UserRepository $userRepository)
{
    $this->userRepository = $userRepository;
}
...
$this->userRepository->getUser();

Is there any reason to prefer one over the other?

EDIT

I feel as though the constructor option is the best way to go, but I find myself in question when I need to include 3 services and 3 repositories in the controller which then very soon escalates to 6 parameters in constructor.

EDIT - Case 4

What about when you're using a facade instead?

EDIT - Case 5

What about when you specify it as \UserRepository?

Body:
First of all, the idea of the Repository is to have an Interface (UserRepositoryInterface) and classes that implement it (MySQLUserRepository, RedisUserRepository). It gives you a quick way to change the storage of users through your DI container by calling an interface:

public function __construct(UserRepositoryInterface $userRepository)
{
    $this->userRepository = $userRepository;
}

And changing it to any implementation in the DI container.

Let's say you have a Controller with 10 actions.

Case 1 Is not the OOP way, because the call doesn't go through the DI container at all.

Case 2 is actually OK, but you'll have to call the App facade in every action. It's not really beautiful.

Case 3 gives you only one place to create/change/configure the class.

E.g. you need to do something like:

public function __construct(UserRepository $userRepository)
{
    $this->userRepository = $userRepository;
    $this->userRepository->excludeAdmins();
}

A lot of repositories in constructor is actually ok, however if the code fills gross to you, you can extract it to a Service class.

UPDATE
By Service class I mean a class that doesn't extends anything and contains the business logic.

Further reading: https://m.dotdev.co/design-pattern-service-layer-with-laravel-5-740ff0a7b65f

Case 4. Facades, in my opinion, are suitable for something more global. Why would you want to populate each repository with a facade? Too time consuming.

Case 5. Didn't get the question. You mean put it to the root namespace? What does it change?


来源: stackexchange

问:
How to use jquery in a function
So I want to hide an input in a function. Here's what I already have:

function doGetWord() {
  var word = F.gword.value;
  var wLength = word.length;
  for (var i = 0; i < wLength; i++) {
    document.getElementById("dword").innerHTML += "_ "
  }

  $(document).ready(function() {
    $("input.cclick").click(function() {
      $("input.cword").hide();
    });
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form name="F">
  <input type="text" name="gword" class="cword">
  <!--<input type="text" name="t" class="in2">-->
  <input type="button" name="b" value="do" onclick="doGetWord()" class="cclick">
  <div id="dword"></div>
</form></code>```

But it doesn't seem to hide it.

Thanks in advance.

答:
But it doesn't seem to hide it.

You are binding a document.ready event inside a function, much after this event has been fired already. So these lines are unlikely to be reached

```<code>  $("input.cclick").click(function(){
        $("input.cword").hide();
  });
</code>```

Simply put this

```<code>$("input.cword").hide();
</code>```

without wrapping it in document.ready and click event

```<code>function doGetWord(){
    var word = F.gword.value;
    var wLength = word.length;
    for(var i = 0; i < wLength; i++){
        document.getElementById("dword").innerHTML += "_ "
    }
    $("input.cword").hide();
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to use jquery in a function

Body:
So I want to hide an input in a function. Here's what I already have:

function doGetWord() {
  var word = F.gword.value;
  var wLength = word.length;
  for (var i = 0; i < wLength; i++) {
    document.getElementById("dword").innerHTML += "_ "
  }

  $(document).ready(function() {
    $("input.cclick").click(function() {
      $("input.cword").hide();
    });
  });
}

<form name="F">
  <input type="text" name="gword" class="cword">

  <input type="button" name="b" value="do" onclick="doGetWord()" class="cclick">

</form>

But it doesn't seem to hide it.

Thanks in advance.

Body:
But it doesn't seem to hide it.

You are binding a document.ready event inside a function, much after this event has been fired already. So these lines are unlikely to be reached

  $("input.cclick").click(function(){
        $("input.cword").hide();
  });

Simply put this

$("input.cword").hide();

without wrapping it in document.ready and click event

function doGetWord(){
    var word = F.gword.value;
    var wLength = word.length;
    for(var i = 0; i < wLength; i++){
        document.getElementById("dword").innerHTML += "_ "
    }
    $("input.cword").hide();
}


问:
Removing rows with same foreign key but with different values
I have a table with similar structure to the following:

I am looking for a way to remove all rows where role_id = 4, in cases where there is already a row with the same context_id and user_id and where the role_id = 3.

for example this row should be removed:

Since there is already a row with the same context_id, user_id and where the role_id = 3

答:
Do a DELETE self join:

```<code>DELETE t1
FROM yourTable t1
INNER JOIN yourTable t2
    ON t1.context_id = t2.context_id AND
       t1.user_id = t2.user_id AND
       t2.role_id = 3
WHERE
    t1.role_id = 4;
</code>```

This matches rows from your table under the following conditions:

the context_id matches to another context_id, and the user_id also matches

the left side record has role_id of 4 and the right side record has role_id of 3

Body:
Do a DELETE self join:

DELETE t1
FROM yourTable t1
INNER JOIN yourTable t2
    ON t1.context_id = t2.context_id AND
       t1.user_id = t2.user_id AND
       t2.role_id = 3
WHERE
    t1.role_id = 4;

This matches rows from your table under the following conditions:

the context_id matches to another context_id, and the user_id also matches

the left side record has role_id of 4 and the right side record has role_id of 3


问:
Python - Update Dictionary With User Input
For this part of my program, I need to write code that will allow the user to update the dictionary. The key is the employee ID, and the updatable fields are their name, department, and title. So that when the updated record is viewed it would display the new name, title, and department. Where Employees is the dictionary. This is what i have so far:

```<code>while Choice == '2':

    dict_key = input('Enter the employee ID of the employee to change the record: ')

    if dict_key in Employees:
        n = 3
        print('Enter the new Name, Department, and Title')
        for i in range(n):
            updates = input().split(' ')

        Employees[dict_key] = updates[0][1][2]
        print('\n')
    else:
        print('ERROR: That record does not exist!')
        print('\n')

    Continue = input('Press 1 to update another employee record or 2 to exit: ')
    print('\n')

    if Continue == '2':
        print('*' * 80)
        break
</code>```

When running this code i get the following error:

```<code>Traceback (most recent call last):
line 43, in <module>
  Employees[dict_key] = updates[0][1][2]
IndexError: string index out of range
</code>```

Desired output for ex:
If employee ID 1234 = John,IT,Programmer
and the updates were: John Doe, IT, Manager.

Employee ID 1234 should = John Doe,IT,Manager after the update entries.

Edit
I was trying to program this in a way where the user could enter the updates individually (name first, title second..) and update the dictionary for the key value (1234) with all three inputs to get my desired output.

Sorry if my code is a mess, I am learning python at the moment. Also sorry if my post is a mess, first time here as well.

答:
Wow, I feel a bit dumb. But I managed to figure out my problem. After reading the comments my light bulb came on. I made an empty list, and appended each input to the list. To allow for the three separate inputs.

```<code>updates = []

        updates.append(input('Enter the new name: '))
        updates.append(input('Enter the new department: '))
        updates.append(input('Enter the new Title: '))
</code>```

I also updated this portion to:

```<code>Employees[dict_key] = updates
</code>```

And now my output is as follows after updating:

```<code>['John Doe', 'IT', 'Manager']
</code>```

Thank y'all for the feedback! I don't know why I did not think of that earlier.

Body:
For this part of my program, I need to write code that will allow the user to update the dictionary. The key is the employee ID, and the updatable fields are their name, department, and title. So that when the updated record is viewed it would display the new name, title, and department. Where Employees is the dictionary. This is what i have so far:

while Choice == '2':

    dict_key = input('Enter the employee ID of the employee to change the record: ')

    if dict_key in Employees:
        n = 3
        print('Enter the new Name, Department, and Title')
        for i in range(n):
            updates = input().split(' ')

        Employees[dict_key] = updates[0][1][2]
        print('\n')
    else:
        print('ERROR: That record does not exist!')
        print('\n')

    Continue = input('Press 1 to update another employee record or 2 to exit: ')
    print('\n')

    if Continue == '2':
        print('*' * 80)
        break

When running this code i get the following error:

Traceback (most recent call last):
line 43, in <module>
  Employees[dict_key] = updates[0][1][2]
IndexError: string index out of range

Desired output for ex:
If employee ID 1234 = John,IT,Programmer
and the updates were: John Doe, IT, Manager.

Employee ID 1234 should = John Doe,IT,Manager after the update entries.

Edit
I was trying to program this in a way where the user could enter the updates individually (name first, title second..) and update the dictionary for the key value (1234) with all three inputs to get my desired output.

Sorry if my code is a mess, I am learning python at the moment. Also sorry if my post is a mess, first time here as well.

Body:
Wow, I feel a bit dumb. But I managed to figure out my problem. After reading the comments my light bulb came on. I made an empty list, and appended each input to the list. To allow for the three separate inputs.

updates = []

        updates.append(input('Enter the new name: '))
        updates.append(input('Enter the new department: '))
        updates.append(input('Enter the new Title: '))

I also updated this portion to:

Employees[dict_key] = updates

And now my output is as follows after updating:

['John Doe', 'IT', 'Manager']

Thank y'all for the feedback! I don't know why I did not think of that earlier.


问:
Cannot resolve rxjava2 with gradle 3.0
Hare is my app gradle:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.atumanin.testandroidannotations"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.1.18"

        javaCompileOptions {
            annotationProcessorOptions {
                includeCompileClasspath true
            }
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'io.reactivex.rxjava2:rxjava:2.1.6'
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
}
</code>```

and this is my project gradle:

```<code>buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

If I try to build project, I get error:

```<code>Could not resolve io.reactivex.rxjava2:rxjava:2.1.6.
</code>```

and

```<code>Could not resolve io.reactivex.rxjava2:rxandroid:2.0.1.
</code>```

I tried to clean, to rebuild the project and to invalidate cache. Nothing helps. I also tried to use compile instead of implementation. I also tried different versions of both libraries, also without success.

答:
I found the solution. The issue was my proxy, it blocks https and I need to use the http version of repository. So instead of:

```<code>repositories {
        jcenter()
    }
</code>```

I use now:

```<code>repositories {
        jcenter {
            url "http://jcenter.bintray.com/"
        }
    }
</code>```

and it compiles now.

Title: Cannot resolve rxjava2 with gradle 3.0

Body:
Hare is my app gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.atumanin.testandroidannotations"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.1.18"

        javaCompileOptions {
            annotationProcessorOptions {
                includeCompileClasspath true
            }
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'io.reactivex.rxjava2:rxjava:2.1.6'
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
}

and this is my project gradle:

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

If I try to build project, I get error:

Could not resolve io.reactivex.rxjava2:rxjava:2.1.6.

and

Could not resolve io.reactivex.rxjava2:rxandroid:2.0.1.

I tried to clean, to rebuild the project and to invalidate cache. Nothing helps. I also tried to use compile instead of implementation. I also tried different versions of both libraries, also without success.

Body:
I found the solution. The issue was my proxy, it blocks https and I need to use the http version of repository. So instead of:

repositories {
        jcenter()
    }

I use now:

repositories {
        jcenter {
            url "http://jcenter.bintray.com/"
        }
    }

and it compiles now.


问:
How to use custom annotation at collection type level in spring mvc
I have added my custom annotation and it's constraint validator to validate list inputs on PersonForm but when it comes to test an exception fires it deals with data binding
My request sent throw ajax call + form.serialize();

PersonForm:

```<code>private Long id;

@NotEmpty
private String firstName;

@NotEmpty
private String lastName;

@Email(message = "profile.email.email")
private String email;

private List<@ResourceConstraint String> resource;

// all setters/getters ....
</code>```

Annotation

```<code>@Documented
@Constraint(validatedBy = ResourceValidator.class)
@Target({ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@NotEmpty
public @interface ResourceConstraint {

    String message() default "resource not Valid";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}
</code>```

Constraint validator

```<code>public class ResourceValidator implements ConstraintValidator<ResourceConstraint, String> {

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        boolean result = false;
            if(Enums.getIfPresent(Resource.class, value.toUpperCase()).isPresent()) {
                    result = true;
            }
        return result;
    }

}
</code>```

Controller

```<code>@PostMapping(path = "/applay/profile/{id}", produces = "application/json;charset=UTF-8")
public @ResponseBody JsonResponseBean applayProfile(@PathVariable Long id, @Valid PersonForm form, BindingResult result, Locale locale) throws BusinessException {
    JsonResponseBean jsonResponse = new JsonResponseBean();
    Person current = new Person();

    if (!result.hasErrors()) {
        ...

    } else {
        ...
    }

    return jsonResponse;
}
</code>```

exception

```<code>java.lang.IllegalStateException: JSR-303 validated property 'resource[1].<list element>' does not have a corresponding accessor for Spring data binding - check your DataBinder's configuration (bean property versus direct field access)
    at org.springframework.validation.beanvalidation.SpringValidatorAdapter.processConstraintViolations(SpringValidatorAdapter.java:162)
    at org.springframework.validation.beanvalidation.SpringValidatorAdapter.validate(SpringValidatorAdapter.java:117)
    at org.springframework.validation.DataBinder.validate(DataBinder.java:891)
    at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.validateIfApplicable(ModelAttributeMethodProcessor.java:168)
    at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:115)
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)

Caused by: org.springframework.beans.NotReadablePropertyException: Invalid property 'resource[1].<list element>' of bean class [com.domain.project.forms.PersonForm]: Bean property 'resource[1].<list element>' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
    at org.springframework.beans.AbstractNestablePropertyAccessor.getPropertyValue(AbstractNestablePropertyAccessor.java:633)
    at org.springframework.beans.AbstractNestablePropertyAccessor.getPropertyValue(AbstractNestablePropertyAccessor.java:624)
    at org.springframework.validation.AbstractPropertyBindingResult.getActualFieldValue(AbstractPropertyBindingResult.java:99)
    at org.springframework.validation.AbstractBindingResult.getRawFieldValue(AbstractBindingResult.java:283)
    at org.springframework.validation.beanvalidation.SpringValidatorAdapter.getRejectedValue(SpringValidatorAdapter.java:268)
    at org.springframework.validation.beanvalidation.SpringValidatorAdapter.processConstraintViolations(SpringValidatorAdapter.java:148)
    ... 40 common frames omitted
</code>```

how to right bind the custom validator process
All setters and getters of PersonForm are implemented
according to hibernate doc i do not need any thing more than applying the constraint

dependencies (Gradle)

```<code>    compile group: 'javax.validation', name: 'validation-api', version: '2.0.0.Final'
    compile group: 'org.hibernate.validator', name: 'hibernate-validator', version: '6.0.2.Final'
...
</code>```

答:
I got it, to get rid with this error upgrade to</p>

```<code>spring Version      = '5.0.1.RELEASE'
hibernate Version   = '5.2.12.Final'

with
compile group: 'javax.validation', name: 'validation-api', version: '2.0.0.Final'
compile group: 'org.hibernate.validator', name: 'hibernate-validator', version: '6.0.4.Final'
</code>```

Body:
I have added my custom annotation and it's constraint validator to validate list inputs on PersonForm but when it comes to test an exception fires it deals with data binding
My request sent throw ajax call + form.serialize();

PersonForm:

private Long id;

@NotEmpty
private String firstName;

@NotEmpty
private String lastName;

@Email(message = "profile.email.email")
private String email;

private List<@ResourceConstraint String> resource;

// all setters/getters ....

Annotation

@Documented
@Constraint(validatedBy = ResourceValidator.class)
@Target({ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@NotEmpty
public @interface ResourceConstraint {

    String message() default "resource not Valid";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

Constraint validator

public class ResourceValidator implements ConstraintValidator<ResourceConstraint, String> {

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        boolean result = false;
            if(Enums.getIfPresent(Resource.class, value.toUpperCase()).isPresent()) {
                    result = true;
            }
        return result;
    }

}

Controller

@PostMapping(path = "/applay/profile/{id}", produces = "application/json;charset=UTF-8")
public @ResponseBody JsonResponseBean applayProfile(@PathVariable Long id, @Valid PersonForm form, BindingResult result, Locale locale) throws BusinessException {
    JsonResponseBean jsonResponse = new JsonResponseBean();
    Person current = new Person();

    if (!result.hasErrors()) {
        ...

    } else {
        ...
    }

    return jsonResponse;
}

exception

java.lang.IllegalStateException: JSR-303 validated property 'resource[1].<list element>' does not have a corresponding accessor for Spring data binding - check your DataBinder's configuration (bean property versus direct field access)
    at org.springframework.validation.beanvalidation.SpringValidatorAdapter.processConstraintViolations(SpringValidatorAdapter.java:162)
    at org.springframework.validation.beanvalidation.SpringValidatorAdapter.validate(SpringValidatorAdapter.java:117)
    at org.springframework.validation.DataBinder.validate(DataBinder.java:891)
    at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.validateIfApplicable(ModelAttributeMethodProcessor.java:168)
    at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:115)
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)

Caused by: org.springframework.beans.NotReadablePropertyException: Invalid property 'resource[1].<list element>' of bean class [com.domain.project.forms.PersonForm]: Bean property 'resource[1].<list element>' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
    at org.springframework.beans.AbstractNestablePropertyAccessor.getPropertyValue(AbstractNestablePropertyAccessor.java:633)
    at org.springframework.beans.AbstractNestablePropertyAccessor.getPropertyValue(AbstractNestablePropertyAccessor.java:624)
    at org.springframework.validation.AbstractPropertyBindingResult.getActualFieldValue(AbstractPropertyBindingResult.java:99)
    at org.springframework.validation.AbstractBindingResult.getRawFieldValue(AbstractBindingResult.java:283)
    at org.springframework.validation.beanvalidation.SpringValidatorAdapter.getRejectedValue(SpringValidatorAdapter.java:268)
    at org.springframework.validation.beanvalidation.SpringValidatorAdapter.processConstraintViolations(SpringValidatorAdapter.java:148)
    ... 40 common frames omitted

how to right bind the custom validator process
All setters and getters of PersonForm are implemented
according to hibernate doc i do not need any thing more than applying the constraint

dependencies (Gradle)

    compile group: 'javax.validation', name: 'validation-api', version: '2.0.0.Final'
    compile group: 'org.hibernate.validator', name: 'hibernate-validator', version: '6.0.2.Final'
...

Body:
I got it, to get rid with this error upgrade to

spring Version      = '5.0.1.RELEASE'
hibernate Version   = '5.2.12.Final'

with
compile group: 'javax.validation', name: 'validation-api', version: '2.0.0.Final'
compile group: 'org.hibernate.validator', name: 'hibernate-validator', version: '6.0.4.Final'


问:
Check if the user is authenticated on not secured route
I'm trying to build a simple login using symofny/security package in Silex, but I have a small problem with authentication checking.

The structure:

```<code>/
/login
/admin
    /login_check
    /logout
</code>```

In order to get to the /admin route user needs to be authenticated, if he's not, he gets redirected to /login form, which then, as recommended, is asking admin/login_check for authentication (that's all provided by symofny's security firewalls).

The firewalls configuration:

```<code>'security.firewalls' => array(
    'login' => array(
        'pattern' => '^/login$',
    ),
    'admin' => array(
        'pattern' => '^/admin',
        'http' => true,
        'form' => array(
            'login_path' => '/login',
            'check_path' => '/admin/login'
        ),
        'logout' => array(
            'logout_path' => '/admin/logout',
            'invalidate_session' => true
        ),
        'users' => ...
    ),
)
</code>```

Everything works fine, but the user can enter the /login route even-though he's already authenticated, which is not that bad, but I'd like to avoid it. I tired to check the user authentication status, but I guess it does not work as I'm checking it on /login controller, which is not in "secured" area of the website.

Here's the code:

```<code>public function index(Request $request, Application $app)
{
    if ($app['security.authorization_checker']->isGranted('ROLE_ADMIN')) {
        return $app->redirect($app['url_generator']->generate('admin'));
    }
    return $app['twig']->render('login/index.twig', array(
        'error'         => $app['security.last_error']($request),
        'last_username' => $app['session']->get('_security.last_username'),
    ));
}
</code>```

That throws an error: The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL. So, the question, is there any way to do this using symfony/security natively (without any walk-arounds)? or is it somehow possible to create the /login route inside secured area with possibility to access it even-though the user is not logged in (e.g. make an exception for GET request) which would solve the problem?

UPDATE

I've also added the firewall configuration for /login page with an option anonymous: true, which resulted in not throwing an error anymore, but yet, when I'm logged in on the /admin route, method isGranted('ROLE_ADMIN') results in true, whereas on /login route it results in false (I'm still logged in there).

答:
You can easily understand the behavior of the security component by dumping the current token.

```<code>public function index(Request $request, Application $app)
{
    var_dump($application['security.token_storage']->getToken());
}
</code>```

When you don't set anonymous option for login page (by default it is false):

```<code>null
</code>```

When you set anonymous option for login page to true:

```<code>object(Symfony\Component\Security\Core\Authentication\Token\AnonymousToken)
    private 'secret' => string 'login' (length=5)
    private 'user' (Symfony\Component\Security\Core\Authentication\Token\AbstractToken) => string 'anon.' (length=5)
    private 'roles' (Symfony\Component\Security\Core\Authentication\Token\AbstractToken) =>
        array (size=0)
            empty
    private 'authenticated' (Symfony\Component\Security\Core\Authentication\Token\AbstractToken) => boolean true
    private 'attributes' (Symfony\Component\Security\Core\Authentication\Token\AbstractToken) =>
        array (size=0)
           empty
</code>```

Following example describes why you are getting error in your initial code example.

How to share security token?

To share security token between multiple firewalls you have to set the same Firewall Context.

SecurityServiceProvider registers context listener for protected firewall you have declared with pattern security.context_listener.<name>. In your example it is registered as security.context_listener.admin. Thus context you want to use is named admin.

Also a firewall context key is stored in session, so every firewall using it must set its stateless option to false.

What is more, to invoke authentication on login page the anonymous option must be set to true

```<code>'security.firewalls' => array(
    'login' => array(
        'context' => 'admin',
        'stateless' => false,
        'anonymous' => true,
        'pattern' => '^/login$',
    ),
    'admin' => array(
        'context' => 'admin',
        'stateless' => false,
        'pattern' => '^/admin',
        'http' => true,
        'form' => array(
            'login_path' => '/login',
            'check_path' => '/admin/login'
        ),
        'logout' => array(
            'logout_path' => '/admin/logout',
            'invalidate_session' => true
        ),
        'users' => ...
    ),
)
</code>```

After the change, if you are logged in on admin panel and login page you will get an instance of Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken as a token and
Symfony\Component\Security\Core\Authentication\Token\AnonymousToken if you are not logged in.

Because of that, you can safely check permission using $app['security.authorization_checker']->isGranted('ROLE_ADMIN') and get the same results on both firewalls.

Body:
I'm trying to build a simple login using symofny/security package in Silex, but I have a small problem with authentication checking.

The structure:

/
/login
/admin
    /login_check
    /logout

In order to get to the /admin route user needs to be authenticated, if he's not, he gets redirected to /login form, which then, as recommended, is asking admin/login_check for authentication (that's all provided by symofny's security firewalls).

The firewalls configuration:

'security.firewalls' => array(
    'login' => array(
        'pattern' => '^/login$',
    ),
    'admin' => array(
        'pattern' => '^/admin',
        'http' => true,
        'form' => array(
            'login_path' => '/login',
            'check_path' => '/admin/login'
        ),
        'logout' => array(
            'logout_path' => '/admin/logout',
            'invalidate_session' => true
        ),
        'users' => ...
    ),
)

Everything works fine, but the user can enter the /login route even-though he's already authenticated, which is not that bad, but I'd like to avoid it. I tired to check the user authentication status, but I guess it does not work as I'm checking it on /login controller, which is not in "secured" area of the website.

Here's the code:

public function index(Request $request, Application $app)
{
    if ($app['security.authorization_checker']->isGranted('ROLE_ADMIN')) {
        return $app->redirect($app['url_generator']->generate('admin'));
    }
    return $app['twig']->render('login/index.twig', array(
        'error'         => $app['security.last_error']($request),
        'last_username' => $app['session']->get('_security.last_username'),
    ));
}

That throws an error: The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL. So, the question, is there any way to do this using symfony/security natively (without any walk-arounds)? or is it somehow possible to create the /login route inside secured area with possibility to access it even-though the user is not logged in (e.g. make an exception for GET request) which would solve the problem?

UPDATE

I've also added the firewall configuration for /login page with an option anonymous: true, which resulted in not throwing an error anymore, but yet, when I'm logged in on the /admin route, method isGranted('ROLE_ADMIN') results in true, whereas on /login route it results in false (I'm still logged in there).

Body:
You can easily understand the behavior of the security component by dumping the current token.

public function index(Request $request, Application $app)
{
    var_dump($application['security.token_storage']->getToken());
}

When you don't set anonymous option for login page (by default it is false):

null

When you set anonymous option for login page to true:

object(Symfony\Component\Security\Core\Authentication\Token\AnonymousToken)
    private 'secret' => string 'login' (length=5)
    private 'user' (Symfony\Component\Security\Core\Authentication\Token\AbstractToken) => string 'anon.' (length=5)
    private 'roles' (Symfony\Component\Security\Core\Authentication\Token\AbstractToken) =>
        array (size=0)
            empty
    private 'authenticated' (Symfony\Component\Security\Core\Authentication\Token\AbstractToken) => boolean true
    private 'attributes' (Symfony\Component\Security\Core\Authentication\Token\AbstractToken) =>
        array (size=0)
           empty

Following example describes why you are getting error in your initial code example.

How to share security token?

To share security token between multiple firewalls you have to set the same Firewall Context.

SecurityServiceProvider registers context listener for protected firewall you have declared with pattern security.context_listener.<name>. In your example it is registered as security.context_listener.admin. Thus context you want to use is named admin.

Also a firewall context key is stored in session, so every firewall using it must set its stateless option to false.

What is more, to invoke authentication on login page the anonymous option must be set to true

'security.firewalls' => array(
    'login' => array(
        'context' => 'admin',
        'stateless' => false,
        'anonymous' => true,
        'pattern' => '^/login$',
    ),
    'admin' => array(
        'context' => 'admin',
        'stateless' => false,
        'pattern' => '^/admin',
        'http' => true,
        'form' => array(
            'login_path' => '/login',
            'check_path' => '/admin/login'
        ),
        'logout' => array(
            'logout_path' => '/admin/logout',
            'invalidate_session' => true
        ),
        'users' => ...
    ),
)

After the change, if you are logged in on admin panel and login page you will get an instance of Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken as a token and
Symfony\Component\Security\Core\Authentication\Token\AnonymousToken if you are not logged in.

Because of that, you can safely check permission using $app['security.authorization_checker']->isGranted('ROLE_ADMIN') and get the same results on both firewalls.


问:
DatePickerDialog not Displaying Last Week
I have implemented DatePickerDialog in my app and I am having the following issues with Lollipop only.

Code Snippet:

```<code>void setDate(final EditText ed) {
    Calendar mcurrentTime = Calendar.getInstance();
    int day = mcurrentTime.get(Calendar.DAY_OF_MONTH);
    int month = mcurrentTime.get(Calendar.MONTH);
    int year = mcurrentTime.get(Calendar.YEAR);
    DatePickerDialog mTimePicker;
    mTimePicker = new DatePickerDialog(getContext(), new OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int selectedYear, int monthOfYear, int dayOfMonth) {
            // TODO Auto-generated method stub
            monthOfYear += 1;
            ed.setText(selectedYear + "-" + monthOfYear + "-" + dayOfMonth);
        }
    }, year, month, day);
    //mTimePicker.setTitle("Select Date:");
    mTimePicker.show();
}
</code>```

I am not able to select date of last week and on pressing next it's displaying next month.

Has anyone run into a problem like this? Does anyone have a solution?

Any help is appreciated, thank you.

答:
I'm seeing the same issue as well.

It has nothing to do with min or max dates set on the datepicker...

It seems to be an issue arising from the screen size being small and thus the datepicker cuts off the last week of the month(or more if the screen in really small) and the 'days' area is not scrollable(up/down)... scrolling left/right will take you to the previous/next month...

My idea for a fix would be to make the 'days' area of the datepicker vertically scrollable but as this is a default android widget I am not sure how to go about doing this -_-

P.S. I know this is not an answer but my rep prevents me from making a comment thus this is the only option open to me...

Body:
I have implemented DatePickerDialog in my app and I am having the following issues with Lollipop only.

Code Snippet:

void setDate(final EditText ed) {
    Calendar mcurrentTime = Calendar.getInstance();
    int day = mcurrentTime.get(Calendar.DAY_OF_MONTH);
    int month = mcurrentTime.get(Calendar.MONTH);
    int year = mcurrentTime.get(Calendar.YEAR);
    DatePickerDialog mTimePicker;
    mTimePicker = new DatePickerDialog(getContext(), new OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int selectedYear, int monthOfYear, int dayOfMonth) {
            // TODO Auto-generated method stub
            monthOfYear += 1;
            ed.setText(selectedYear + "-" + monthOfYear + "-" + dayOfMonth);
        }
    }, year, month, day);
    //mTimePicker.setTitle("Select Date:");
    mTimePicker.show();
}

I am not able to select date of last week and on pressing next it's displaying next month.

Has anyone run into a problem like this? Does anyone have a solution?

Any help is appreciated, thank you.


答:
Your code is almost valid you've just to remove the inline event onclick="doGetWord()" since you attach it already form the JS side and call you function on click, then adjust the braces to separate the ready function form the doGetWord function, like :

function doGetWord() {
  var word = F.gword.value;
  var wLength = word.length;
  for (var i = 0; i < wLength; i++) {
    document.getElementById("dword").innerHTML += "_ "
  }

  $("input.cword").hide();
}

$(document).ready(function() {
  $("input.cclick").on('click', doGetWord);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form name="F">
  <input type="text" name="gword" class="cword">
  <!--<input type="text" name="t" class="in2">-->
  <input type="button" name="b" value="do" class="cclick">
  <div id="dword"></div>
</form></code>```

Title: How to use jquery in a function

Body:
Your code is almost valid you've just to remove the inline event onclick="doGetWord()" since you attach it already form the JS side and call you function on click, then adjust the braces to separate the ready function form the doGetWord function, like :

function doGetWord() {
  var word = F.gword.value;
  var wLength = word.length;
  for (var i = 0; i < wLength; i++) {
    document.getElementById("dword").innerHTML += "_ "
  }

  $("input.cword").hide();
}

$(document).ready(function() {
  $("input.cclick").on('click', doGetWord);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form name="F">
  <input type="text" name="gword" class="cword">
  <!--<input type="text" name="t" class="in2">-->
  <input type="button" name="b" value="do" class="cclick">
  <div id="dword"></div>
</form>


问:
How to define tiles definition for a specific view
So my tiles definition looks like following and I would like to know how I can manage it to show a specific template on a specific view:
I want that the default template ist "commonPage" and for e.g. "/monitor1" return value I want the emptyTemplate to be applicated.</p>

```<code><tiles-definitions>
  <definition name="commonPage" template="/WEB-INF/tiles/layouts/topmenulayout.jsp">
    <put-attribute name="header" value="/WEB-INF/tiles/jsp/header.jsp" />
    <put-attribute name="menu" value="/WEB-INF/views/menu.jsp" />
    <put-attribute name="footer" value="/WEB-INF/tiles/jsp/footer.jsp" />
  </definition>

  <definition name="emptyPage" template="/WEB-INF/tiles/layouts/emptylayout.jsp">
  </definition>

  <!-- Views ending in "Dialog" have no header, menu or      -->
  <!-- footer. Useful for creating jQuery popup dialogs.     -->
  <definition name="*/*Dialog" template="/WEB-INF/views/{1}/{2}Dialog.jsp" />
  <definition name="*Dialog" template="/WEB-INF/views/{1}Dialog.jsp" />

  <!-- All other views get the header, menu and footer tiles. -->
  <!-- I want commonPage as default template, and e.g. for "/Monitor1" return value I want the emptyLayout       -->

  <definition name="*" extends="commonPage">
    <put-attribute name="body" value="/WEB-INF/views/{1}.jsp" />
  </definition>
</tiles-definitions>
</code>```

答:
It was pretty easy to solve it.
I added the following definition and it worked the way I wanted it to be:

```<code><definition name="*Monitor1" extends="emptyPage">
</code>```

Body:
So my tiles definition looks like following and I would like to know how I can manage it to show a specific template on a specific view:
I want that the default template ist "commonPage" and for e.g. "/monitor1" return value I want the emptyTemplate to be applicated.

<tiles-definitions>
  <definition name="commonPage" template="/WEB-INF/tiles/layouts/topmenulayout.jsp">
    <put-attribute name="header" value="/WEB-INF/tiles/jsp/header.jsp" />
    <put-attribute name="menu" value="/WEB-INF/views/menu.jsp" />
    <put-attribute name="footer" value="/WEB-INF/tiles/jsp/footer.jsp" />
  </definition>

  <definition name="emptyPage" template="/WEB-INF/tiles/layouts/emptylayout.jsp">
  </definition>

  <definition name="*/*Dialog" template="/WEB-INF/views/{1}/{2}Dialog.jsp" />
  <definition name="*Dialog" template="/WEB-INF/views/{1}Dialog.jsp" />

  <definition name="*" extends="commonPage">
    <put-attribute name="body" value="/WEB-INF/views/{1}.jsp" />
  </definition>
</tiles-definitions>

Body:
It was pretty easy to solve it.
I added the following definition and it worked the way I wanted it to be:

<definition name="*Monitor1" extends="emptyPage">


问:
JS function split not working letters uppercase
Example 1:

```<code>var string_1 = "My name is Tom Jelly";
var param = string_1.split('Tom');
console.log(param);
</code>```

["My name is ", " Jelly"]

Example 2:

```<code>var string_2 = "My name is tom Jelly";
var param = string_2.split('Tom');
console.log(param);
</code>```

["My name is tom Jelly"]

How can I get the result as Example 1?

答:
You can use regexp as a separator with i flag (case insensitive):

```<code>string_2.split(/Tom/i);
</code>```

Body:
Example 1:

var string_1 = "My name is Tom Jelly";
var param = string_1.split('Tom');
console.log(param);

["My name is ", " Jelly"]

Example 2:

var string_2 = "My name is tom Jelly";
var param = string_2.split('Tom');
console.log(param);

["My name is tom Jelly"]

How can I get the result as Example 1?

Body:
You can use regexp as a separator with i flag (case insensitive):

string_2.split(/Tom/i);


问:
how do I use the Rails.logger from javascript
I nside a html.erb, I want to use the logger</p>

```<code><script type="text/javascript">
  $j(function(){

    $j('#AddQuestion').click(function(){
     //Send and http transaction to the server to get the address
      $j('#dialog').dialog(
        {buttons:{OK:function (event) {
                say('You clicked the ' + $(event.target).text() + ' button' );
              },  No:function (event) {
                say('You clicked the ' + $(event.target).text() + ' button' );
              }
                }
         });

      $j('#dialog').dialog('open');

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

答:
```<code># controllers/logs_controller.rb
class LogsController < ApplicationController
  def create
    logger.debug params['message']
    render :nothing => true
  end
end

# config/routes.rb
map.logs "logs", :controller => 'logs', :action => 'create', :conditions => {:method => :post}

# js
$.post('/logs', {message: 'Your log message'})
</code>```

ContentLicense: CC BY-SA 2.5


问:
Pin Annotation as Subview on map
Here's what i'm expect :

as I know, annotationView cannot contain view. Anyone help me. thanks alot.

答: Take a look at this. Is pretty old and in ObjC but you can reuse the logic and adapt it for your use-case</p>

Title: Pin Annotation as Subview on map


问:
Openstack Not able to connect to using rest api
I have a local install on openstack on my virtual box. I am trying to use the lib cloud api to connnect and get a list of images,flavours etc.

Below is the code that I am trying to execute

```<code>    from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver

# Authentication information so you can authenticate to DreamCompute
# copy the details from the OpenStack RC file
# https://dashboard.dreamcompute.com/project/access_and_security/api_access/openrc/

auth_username = 'admin'
auth_password = 'f882e2f4eaad434c'
TENANT_NAME = 'admin'
project_name = 'admin'
auth_url = 'http://192.168.56.101:5000/v3/tokens'
region_name = 'RegionOne'

provider = get_driver(Provider.OPENSTACK)
conn = provider(auth_username,
                auth_password,
                ex_force_auth_url=auth_url,
                ex_force_auth_version='2.0_password',
                ex_tenant_name=project_name,
                ex_force_service_type='compute',
                ex_force_service_name='compute',
                ex_force_base_url='http://192.168.56.101:8774/v2.1/29a8949bc3a04bfead0654be8e552017')

# Get the image that we want to use by its id
# NOTE: the image_id may change. See the documentation to find
# all the images available to your user
image_id = '4525d442-e9f4-4d19-889f-49ab03be93df'
image = conn.get_image(image_id)

# Get the flavor that we want to use by its id
flavor_id = '100'
flavor = conn.ex_get_size(flavor_id)

# Create the node with the name “PracticeInstance”
# and the size and image we chose above
instance = conn.create_node(name='PracticeInstance', image=image, size=flavor)
</code>```

When I run the above code I am getting below error:

```<code>C:\Python dev\website\music\openstack>python openstack.py
Traceback (most recent call last):
  File "openstack.py", line 30, in <module>
    image = conn.get_image(image_id)
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\compute\drivers\openstack.py", line 2028, in get_image
    '/images/%s' % (image_id,)).object['image'])
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\openstack.py", line 223, in request
    raw=raw)
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\base.py", line 536, in request
    action = self.morph_action_hook(action)
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\openstack.py", line 290, in morph_action_hook
    self._populate_hosts_and_request_paths()
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\openstack.py", line 324, in _populate_hosts_and_request_paths
    osa = osa.authenticate(**kwargs)  # may throw InvalidCreds
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\openstack_identity.py", line 855, in authenticate
    return self._authenticate_2_0_with_password()
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\openstack_identity.py", line 880, in _authenticate_2_0_with_password
    return self._authenticate_2_0_with_body(reqbody)
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\openstack_identity.py", line 885, in _authenticate_2_0_with_body
    method='POST')
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\base.py", line 637, in request
    response = responseCls(**kwargs)
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\base.py", line 157, in __init__
    message=self.parse_error())
libcloud.common.exceptions.BaseHTTPError: {"error": {"message": "The resource could not be found.", "code": 404, "title": "Not Found"}}
</code>```

I have checked the logs in my server at /var/log/keystone and it does not give any error so I am guessing that I am able to login.

Also there are many examples which show that after the above steps I should be able to get list of images/flavors/servers.

Not sure why i am not able to connect. Can someone please help me with this.

答:
I think you should modify the auth_url and provider arguments.
As following argument set is worked at my environment.

```<code>auth_username = 'admin'
auth_password = 'f882e2f4eaad434c'
TENANT_NAME = 'admin'
project_name = 'admin'
auth_url = 'http://192.168.56.101:5000'
region_name = 'RegionOne'

provider = get_driver(Provider.OPENSTACK)
conn = provider(auth_username,
                auth_password,
                ex_force_auth_url=auth_url,
                ex_force_auth_version='2.0_password',
                ex_tenant_name=project_name)
</code>```

Updated 2017.11.16

@user8040338 Your error message is the first clue,
The resource could not be found. and status code 404, the most cause of its message and status code is wrong rest api url format.

Firstly, you need to check keystone v2.0 rest api format.
At the same time, you check again Libcloud reference.
For instance, the argument ex_force_auth_version had been specified the api version 2.0_password (v2), but auth_url variable formed the url including  the version resource /v3, it was wrong version and usage of API with the libcloud API argument you specified. auth_url should be a base URL from API usage.

The similar processes about each argument of API should be conducted repeatedly until solving issues.

Body:
I have a local install on openstack on my virtual box. I am trying to use the lib cloud api to connnect and get a list of images,flavours etc.

Below is the code that I am trying to execute

    from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver

# Authentication information so you can authenticate to DreamCompute
# copy the details from the OpenStack RC file
# https://dashboard.dreamcompute.com/project/access_and_security/api_access/openrc/

auth_username = 'admin'
auth_password = 'f882e2f4eaad434c'
TENANT_NAME = 'admin'
project_name = 'admin'
auth_url = 'http://192.168.56.101:5000/v3/tokens'
region_name = 'RegionOne'

provider = get_driver(Provider.OPENSTACK)
conn = provider(auth_username,
                auth_password,
                ex_force_auth_url=auth_url,
                ex_force_auth_version='2.0_password',
                ex_tenant_name=project_name,
                ex_force_service_type='compute',
                ex_force_service_name='compute',
                ex_force_base_url='http://192.168.56.101:8774/v2.1/29a8949bc3a04bfead0654be8e552017')

# Get the image that we want to use by its id
# NOTE: the image_id may change. See the documentation to find
# all the images available to your user
image_id = '4525d442-e9f4-4d19-889f-49ab03be93df'
image = conn.get_image(image_id)

# Get the flavor that we want to use by its id
flavor_id = '100'
flavor = conn.ex_get_size(flavor_id)

# Create the node with the name “PracticeInstance”
# and the size and image we chose above
instance = conn.create_node(name='PracticeInstance', image=image, size=flavor)

When I run the above code I am getting below error:

C:\Python dev\website\music\openstack>python openstack.py
Traceback (most recent call last):
  File "openstack.py", line 30, in <module>
    image = conn.get_image(image_id)
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\compute\drivers\openstack.py", line 2028, in get_image
    '/images/%s' % (image_id,)).object['image'])
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\openstack.py", line 223, in request
    raw=raw)
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\base.py", line 536, in request
    action = self.morph_action_hook(action)
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\openstack.py", line 290, in morph_action_hook
    self._populate_hosts_and_request_paths()
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\openstack.py", line 324, in _populate_hosts_and_request_paths
    osa = osa.authenticate(**kwargs)  # may throw InvalidCreds
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\openstack_identity.py", line 855, in authenticate
    return self._authenticate_2_0_with_password()
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\openstack_identity.py", line 880, in _authenticate_2_0_with_password
    return self._authenticate_2_0_with_body(reqbody)
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\openstack_identity.py", line 885, in _authenticate_2_0_with_body
    method='POST')
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\base.py", line 637, in request
    response = responseCls(**kwargs)
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\base.py", line 157, in __init__
    message=self.parse_error())
libcloud.common.exceptions.BaseHTTPError: {"error": {"message": "The resource could not be found.", "code": 404, "title": "Not Found"}}

I have checked the logs in my server at /var/log/keystone and it does not give any error so I am guessing that I am able to login.

Also there are many examples which show that after the above steps I should be able to get list of images/flavors/servers.

Not sure why i am not able to connect. Can someone please help me with this.

Body:
I think you should modify the auth_url and provider arguments.
As following argument set is worked at my environment.

auth_username = 'admin'
auth_password = 'f882e2f4eaad434c'
TENANT_NAME = 'admin'
project_name = 'admin'
auth_url = 'http://192.168.56.101:5000'
region_name = 'RegionOne'

provider = get_driver(Provider.OPENSTACK)
conn = provider(auth_username,
                auth_password,
                ex_force_auth_url=auth_url,
                ex_force_auth_version='2.0_password',
                ex_tenant_name=project_name)

Updated 2017.11.16

@user8040338 Your error message is the first clue,
The resource could not be found. and status code 404, the most cause of its message and status code is wrong rest api url format.

Firstly, you need to check keystone v2.0 rest api format.
At the same time, you check again Libcloud reference.
For instance, the argument ex_force_auth_version had been specified the api version 2.0_password (v2), but auth_url variable formed the url including  the version resource /v3, it was wrong version and usage of API with the libcloud API argument you specified. auth_url should be a base URL from API usage.

The similar processes about each argument of API should be conducted repeatedly until solving issues.


问:
How to execute npm script using grunt-run?
I have a npm task in my package.json file as follows to execute jest testing:

```<code>  "scripts": {
    "test-jest": "jest",
    "jest-coverage": "jest --coverage"
  },
  "jest": {
    "testEnvironment": "jsdom"
  },
</code>```

I want to execute this task npm run test-jest using grunt. I installed grunt-run for the same and added the run task, but how do I invoke this npm task there?

```<code>    run: {
        options: {
          // Task-specific options go here.
        },
        your_target: {
          cmd: 'node'
        }
      }
</code>```

答:
Configure your Gruntfile.js similar to the example shown in the docs.

Set the value for the cmd to npm.

Set run and test-jest in the args Array.

Gruntfile.js

module.exports = function (grunt) {

  grunt.loadNpmTasks('grunt-run');

  grunt.initConfig({
    run: {
      options: {
        // ...
      },
      npm_test_jest: {
        cmd: 'npm',
        args: [
          'run',
          'test-jest',
          '--silent'
        ]
      }
    }
  });

  grunt.registerTask('default', [ 'run:npm_test_jest' ]);

};
```

<p><strong>Running</strong></p>

<p>Running <code>$ grunt</code> via your CLI using the configuration shown above will invoke the <code>npm run test-jest</code> command.</p>

<p>Note: Adding <code>--silent</code> (or it's shorthand equivalent <code>-s</code>) to the <code>args</code> Array simply helps avoids the additional npm log to the console.</p>

<hr>

<p><strong>EDIT:</strong></p>

<p><strong>Cross Platform</strong></p>

<p>Using the <code>grunt-run</code> solution shown above failed on Windows OS when running via <code>cmd.exe</code>. The following error was thrown:</p>

<blockquote>
  <p><code>Error: spawn npm ENOENT Warning: non-zero exit code -4058 Use --force to continue.</code></p>
</blockquote>

<p>For a cross-platform solution consider installing and utlizing grunt-shell to invoke the <code>npm run test-jest</code> instead.</p>

<p><code>npm i -D grunt-shell</code></p>

<p><strong>Gruntfile.js</strong></p>

<pre class="lang-js prettyprint-override"><code>module.exports = function (grunt) {

  require('load-grunt-tasks')(grunt); // <-- uses `load-grunt-tasks`

  grunt.initConfig({
    shell: {
      npm_test_jest: {
        command: 'npm run test-jest --silent',
      }
    }
  });

  grunt.registerTask('default', [ 'shell:npm_test_jest' ]);

};
</code>```

Notes

grunt-shell requires load-grunt-tasks for loading the Task instead of the typical grunt.loadNpmTasks(...), so you'll need to install that too:

npm i -D load-grunt-tasks

For older version of Windows I had to install an older version of grunt-shell, namely version 1.3.0, so I recommend installing an earlier version.

npm i -D grunt-shell@1.3.0

EDIT 2

grunt-run does seem to work on Windows if you use the exec key instead of the cmd and args keys...

For cross platform purposes... I found it necessary to specify the command as a single string using the exec key as per the documentation that reads:

If you would like to specify your command as a single string, useful
  for specifying multiple commands in one task, use the exec: key

Gruntfile.js

module.exports = function (grunt) {

  grunt.loadNpmTasks('grunt-run');

  grunt.initConfig({
    run: {
      options: {
        // ...
      },
      npm_test_jest: {
        exec: 'npm run test-jest --silent' // <-- use the exec key.
      }
    }
  });

  grunt.registerTask('default', [ 'run:npm_test_jest' ]);

};
```

Body:
I have a npm task in my package.json file as follows to execute jest testing:

  "scripts": {
    "test-jest": "jest",
    "jest-coverage": "jest --coverage"
  },
  "jest": {
    "testEnvironment": "jsdom"
  },

I want to execute this task npm run test-jest using grunt. I installed grunt-run for the same and added the run task, but how do I invoke this npm task there?

    run: {
        options: {
          // Task-specific options go here.
        },
        your_target: {
          cmd: 'node'
        }
      }

Body:
Configure your Gruntfile.js similar to the example shown in the docs.

Set the value for the cmd to npm.

Set run and test-jest in the args Array.

Gruntfile.js

module.exports = function (grunt) {

  grunt.loadNpmTasks('grunt-run');

  grunt.initConfig({
    run: {
      options: {
        // ...
      },
      npm_test_jest: {
        cmd: 'npm',
        args: [
          'run',
          'test-jest',
          '--silent'
        ]
      }
    }
  });

  grunt.registerTask('default', [ 'run:npm_test_jest' ]);

};

Running

Running $ grunt via your CLI using the configuration shown above will invoke the npm run test-jest command.

Note: Adding --silent (or it's shorthand equivalent -s) to the args Array simply helps avoids the additional npm log to the console.

EDIT:

Cross Platform

Using the grunt-run solution shown above failed on Windows OS when running via cmd.exe. The following error was thrown:

Error: spawn npm ENOENT Warning: non-zero exit code -4058 Use --force to continue.

For a cross-platform solution consider installing and utlizing grunt-shell to invoke the npm run test-jest instead.

npm i -D grunt-shell

Gruntfile.js

module.exports = function (grunt) {

  require('load-grunt-tasks')(grunt); // <-- uses `load-grunt-tasks`

  grunt.initConfig({
    shell: {
      npm_test_jest: {
        command: 'npm run test-jest --silent',
      }
    }
  });

  grunt.registerTask('default', [ 'shell:npm_test_jest' ]);

};

Notes

grunt-shell requires load-grunt-tasks for loading the Task instead of the typical grunt.loadNpmTasks(...), so you'll need to install that too:

npm i -D load-grunt-tasks

For older version of Windows I had to install an older version of grunt-shell, namely version 1.3.0, so I recommend installing an earlier version.

npm i -D grunt-shell@1.3.0

EDIT 2

grunt-run does seem to work on Windows if you use the exec key instead of the cmd and args keys...

For cross platform purposes... I found it necessary to specify the command as a single string using the exec key as per the documentation that reads:

If you would like to specify your command as a single string, useful
  for specifying multiple commands in one task, use the exec: key

Gruntfile.js

module.exports = function (grunt) {

  grunt.loadNpmTasks('grunt-run');

  grunt.initConfig({
    run: {
      options: {
        // ...
      },
      npm_test_jest: {
        exec: 'npm run test-jest --silent' // <-- use the exec key.
      }
    }
  });

  grunt.registerTask('default', [ 'run:npm_test_jest' ]);

};


问:
VBA String to Integer without rounding
I want to convert a String into Integer and keep the decimal places.

I tried multiple things like Foramat and CInt but all of them end up rounding my value.

My Code is:

```<code>Dim posZ As Integer
Dim TestZ As Integer
Dim strTestZ As String
Dim TestZold As Integer

For i = 1 To tllength
  posZ = InStr(tlmold(i), "Z=")
  strTestZ = Mid(tlmold(i), posZ + 2, 5)

  TestZ = Format(strTestZ, "0.0000")

   If TestZold = TestZ Or (TestZold - TestZ) > 0.02 Or (TestZ - TestZold) > 0.02 Then
   countLip = countLip + 1
   End If
 TestZold = TestZ
Next I
</code>```

e.g. the first value of strTestZ in the array tlmold() would be 0.085, 2nd would be 0.097.

And I want to compare them..

Thanks in Advance

答:
"I want to convert a String into Integer and keep the decimal places." - not possible, Integer is "Ganz Zahl".

However, I think that this is not your problem. I notice that you are from Germany, thus you are obviously experiencing a problem with the comma separator, which is a comma in Germany. In USA and the VBEditor it is a dot. Thus, you have to convert a bit your input to what is expected. Replace() is the way to do it.

See for yourself:

```<code>Public Sub TestMe()

    Dim inputA          As String
    Dim convertedNumber As Double

    inputA = "0.085"
    convertedNumber = CDbl(inputA)
    Debug.Print convertedNumber

    inputA = Replace(inputA, ".", ",")
    convertedNumber = CDbl(inputA)
    Debug.Print convertedNumber

End Sub
</code>```

The first time you print you would get 85 and the second time, you would get 0,085, as expected.

Title: VBA String to Integer without rounding

Body:
I want to convert a String into Integer and keep the decimal places.

I tried multiple things like Foramat and CInt but all of them end up rounding my value.

My Code is:

Dim posZ As Integer
Dim TestZ As Integer
Dim strTestZ As String
Dim TestZold As Integer

For i = 1 To tllength
  posZ = InStr(tlmold(i), "Z=")
  strTestZ = Mid(tlmold(i), posZ + 2, 5)

  TestZ = Format(strTestZ, "0.0000")

   If TestZold = TestZ Or (TestZold - TestZ) > 0.02 Or (TestZ - TestZold) > 0.02 Then
   countLip = countLip + 1
   End If
 TestZold = TestZ
Next I

e.g. the first value of strTestZ in the array tlmold() would be 0.085, 2nd would be 0.097.

And I want to compare them..

Thanks in Advance

Body:
"I want to convert a String into Integer and keep the decimal places." - not possible, Integer is "Ganz Zahl".

However, I think that this is not your problem. I notice that you are from Germany, thus you are obviously experiencing a problem with the comma separator, which is a comma in Germany. In USA and the VBEditor it is a dot. Thus, you have to convert a bit your input to what is expected. Replace() is the way to do it.

See for yourself:

Public Sub TestMe()

    Dim inputA          As String
    Dim convertedNumber As Double

    inputA = "0.085"
    convertedNumber = CDbl(inputA)
    Debug.Print convertedNumber

    inputA = Replace(inputA, ".", ",")
    convertedNumber = CDbl(inputA)
    Debug.Print convertedNumber

End Sub

The first time you print you would get 85 and the second time, you would get 0,085, as expected.


问:
extract data from a json file in python
I have been try to find the best way to search a particular value and extract the data. I am new and hope i have worded this correctly. </p>

```<code>    {"family": {
    "name": "Mary",
    "age": "32",
    "sex": "female",
    "kids": [
      {
        "name": "jim",
        "age": "10",
        "sex": "male",
        "dob_year": "2007",
        "ssn": "123-23-1234"
      },
      {
        "name": "jill",
        "age": "6",
        "sex": "female",
        "dob_year": "2011",
        "ssn": "123-23-1235"
      }]}}
</code>```

<p>if i needed to search "ssn" containing "1234" and return the "name" "jim" what would be the best way to go about achieving this?  </p>

答:
I'd rather like to provide a common method handling this case, the until method which is based on python functional programming, using this, you can find your target(provide a default value if not found), and you can decouple your filter criteria and candidates easily.

```<code>json_str = """
{"family": {
    "name": "Mary",
    "age": "32",
    "sex": "female",
    "kids": [
      {
        "name": "jim",
        "age": "10",
        "sex": "male",
        "dob_year": "2007",
        "ssn": "123-23-1234"
      },
      {
        "name": "jill",
        "age": "6",
        "sex": "female",
        "dob_year": "2011",
        "ssn": "123-23-1235"
      }]}}
"""
</code>```

load the data to a python dict object

```<code>import json
data = json.loads(json_str)
</code>```

Now here's the until part:

```<code>def until(terminate, iterator, default=None):
    try:
        i = next(iterator)
        if terminate(i):
            return i
        return until(terminate, iterator, default)
    except StopIteration:
        return default

ssn_target = '1234'

target_kid = until(lambda kid: ssn_target in kid['ssn'], iter(data['family']['kids']))

if target_kid is not None:
    print(target_kid['name'])
else:
    print('Opps! not found')
</code>```

Note that:

Python has a rather small limit to how many recursive calls can be made (typically ~1000), so the iterable list shouldn't be tooo long.

Title: extract data from a json file in python

Body:
I have been try to find the best way to search a particular value and extract the data. I am new and hope i have worded this correctly.

    {"family": {
    "name": "Mary",
    "age": "32",
    "sex": "female",
    "kids": [
      {
        "name": "jim",
        "age": "10",
        "sex": "male",
        "dob_year": "2007",
        "ssn": "123-23-1234"
      },
      {
        "name": "jill",
        "age": "6",
        "sex": "female",
        "dob_year": "2011",
        "ssn": "123-23-1235"
      }]}}

if i needed to search "ssn" containing "1234" and return the "name" "jim" what would be the best way to go about achieving this?

Body:
I'd rather like to provide a common method handling this case, the until method which is based on python functional programming, using this, you can find your target(provide a default value if not found), and you can decouple your filter criteria and candidates easily.

json_str = """
{"family": {
    "name": "Mary",
    "age": "32",
    "sex": "female",
    "kids": [
      {
        "name": "jim",
        "age": "10",
        "sex": "male",
        "dob_year": "2007",
        "ssn": "123-23-1234"
      },
      {
        "name": "jill",
        "age": "6",
        "sex": "female",
        "dob_year": "2011",
        "ssn": "123-23-1235"
      }]}}
"""

load the data to a python dict object

import json
data = json.loads(json_str)

Now here's the until part:

def until(terminate, iterator, default=None):
    try:
        i = next(iterator)
        if terminate(i):
            return i
        return until(terminate, iterator, default)
    except StopIteration:
        return default

ssn_target = '1234'

target_kid = until(lambda kid: ssn_target in kid['ssn'], iter(data['family']['kids']))

if target_kid is not None:
    print(target_kid['name'])
else:
    print('Opps! not found')

Note that:

Python has a rather small limit to how many recursive calls can be made (typically ~1000), so the iterable list shouldn't be tooo long.


问:
How to display Previous and Next instead of "<<" and ">>" codeigniter calendar library
I want to show my calendar page with previous and next month link with PREVIOUS and NEXT title instead of << and >>.</p>

答:
I Found the answer about this,</p>

```<code>$prefs = array("template" => array(
         'heading_previous_cell' => '<th><a href="{previous_url}">Previous</a></th>',
         'heading_next_cell' => '<th><a href="{next_url}">Next</a></th>',
    )
);

$this->load->library('calendar', $prefs);

$this->calendar->generate($this->uri->segment(3), $this->uri->segment(4));
</code>```

Body:
I Found the answer about this,

$prefs = array("template" => array(
         'heading_previous_cell' => '<th><a href="{previous_url}">Previous</a></th>',
         'heading_next_cell' => '<th><a href="{next_url}">Next</a></th>',
    )
);

$this->load->library('calendar', $prefs);

$this->calendar->generate($this->uri->segment(3), $this->uri->segment(4));


问:
Java: duplicate method signature in nested class
Hopefully this question hasn't already been asked. I've had a look around but haven't found a similar post.

Experimenting in Java I've noticed that there is no restriction on having duplicate method signatures in a nested class, which seems counter-intuitive.

For example, if I create class A containing a method with the signature int x() and later add a nested class B containing an identical method, the compiler seems to have no problem with it. My initial assumption was that it would complain that x is already defined. Perhaps I'm missing something obvious that explains why this is allowed?

```<code>class A {
    int x() {
        return 1;
    }

    class B {
        int x() {
            return 2;
        }
    }
}
</code>```

Subsequently, is there any way to access class A's method x from within the scope of class B, or is it permanently hidden by the method x of the local scope?

Edit: I appreciate that the core of the question is the same as this post, however, I was more interested in understanding why this behaviour is allowed as it wasn't immediately clear to me.

答:
For example, if I create class A containing a method with the signature int x() and later add a nested class B containing an identical method, the compiler seems to have no problem with it. My initial assumption was that it would complain that x is already defined. Perhaps I'm missing something obvious that explains why this is allowed?

When you define something in a nest scope which is otherwise in an outer scope, this is hiding.
What is important is that -: The version of a method that is executed will NOT be determined by the object that is used to invoke it. In fact it will be determined by the type of reference variable used to invoke the method

Subsequently, is there any way to access class A's method x from within the scope of class B, or is it permanently hidden by the method x of the local scope?

So as it is clear from above we can access it using class name, eg A.x

Hope this helps!!

Body:
Hopefully this question hasn't already been asked. I've had a look around but haven't found a similar post.

Experimenting in Java I've noticed that there is no restriction on having duplicate method signatures in a nested class, which seems counter-intuitive.

For example, if I create class A containing a method with the signature int x() and later add a nested class B containing an identical method, the compiler seems to have no problem with it. My initial assumption was that it would complain that x is already defined. Perhaps I'm missing something obvious that explains why this is allowed?

class A {
    int x() {
        return 1;
    }

    class B {
        int x() {
            return 2;
        }
    }
}

Subsequently, is there any way to access class A's method x from within the scope of class B, or is it permanently hidden by the method x of the local scope?

Edit: I appreciate that the core of the question is the same as this post, however, I was more interested in understanding why this behaviour is allowed as it wasn't immediately clear to me.


问:
Create async version of sync method
I'm currently writing an component where I already have a synchronous method to download files from a server. Here's the signature:

```<code>public Stream DownloadFile(IData data)
</code>```

Now I wanted to have an async version of this method and tried this:

```<code> public async Task<Stream> DownloadFileAsync(IData data)
 {
    Stream stream = null;
    await Task.Run(() =>
    {
      DownloadFile(data);
    });
    return stream;
 }
</code>```

But resharper is showing me a squiggle line under return stream; "expression is always null". Can somebody tell me what is wrong with my code?

What I want to do is run the DownloadFile method in background and return controlflow to the caller.

EDIT: here is the DownloadFile method:

```<code>var ms = new MemoryStream();

  using (var dtService = new DataTransferService(mConnectionInfo))
  {
    int bytesRead;
    do
    {
      var buffer = new byte[data.ChunkSize];
      bytesRead = dtService.Read(data, buffer);

      if (bytesRead == 0)
      {
        break;
      }

      data.Offset += bytesRead;
      ms.Write(buffer, 0, buffer.Length);
    } while (bytesRead > 0);
  }

  return ms;
</code>```

Thanks

答:
You forgot to actually assign the stream variable:</p>

```<code>public async Task<Stream> DownloadFileAsync(IData data)
 {
    Stream stream = null;
    await Task.Run(() =>
    {
      // VVV
      stream = DownloadFile(data);
    });
    return stream;
 }
</code>```

Title: Create async version of sync method

Body:
I'm currently writing an component where I already have a synchronous method to download files from a server. Here's the signature:

public Stream DownloadFile(IData data)

Now I wanted to have an async version of this method and tried this:

 public async Task<Stream> DownloadFileAsync(IData data)
 {
    Stream stream = null;
    await Task.Run(() =>
    {
      DownloadFile(data);
    });
    return stream;
 }

But resharper is showing me a squiggle line under return stream; "expression is always null". Can somebody tell me what is wrong with my code?

What I want to do is run the DownloadFile method in background and return controlflow to the caller.

EDIT: here is the DownloadFile method:

var ms = new MemoryStream();

  using (var dtService = new DataTransferService(mConnectionInfo))
  {
    int bytesRead;
    do
    {
      var buffer = new byte[data.ChunkSize];
      bytesRead = dtService.Read(data, buffer);

      if (bytesRead == 0)
      {
        break;
      }

      data.Offset += bytesRead;
      ms.Write(buffer, 0, buffer.Length);
    } while (bytesRead > 0);
  }

  return ms;

Thanks

Body:
You forgot to actually assign the stream variable:

public async Task<Stream> DownloadFileAsync(IData data)
 {
    Stream stream = null;
    await Task.Run(() =>
    {
      // VVV
      stream = DownloadFile(data);
    });
    return stream;
 }


问:
Passing argument 4 of 'obj_setProperty' from incompatible pointer type
I am getting the above compiler error in XCode, and I cannot work out what's going on.

```<code>#import <UIKit/UIKit.h>

// #import "HeaderPanelViewController.h"
#import "HTTPClientCommunicator.h"
#import "WebSocket.h"

@class HeaderPanelViewController;

@protocol ServerDateTimeUpdating
-(void)serverDateTimeHasBeenUpdatedWithDate:(NSString *) dateString andTime:(NSString *) timeString;
@end

@interface SmartWardPTAppDelegate : NSObject <UIApplicationDelegate, WebSocketDelegate> {

}

@property (nonatomic, retain) id<ServerDateTimeUpdating> *serverDateTimeDelegate;
....
@end
</code>```

Then in this line

```<code>@synthesize serverDateTimeDelegate;
</code>```

in ApplicationDelegate.m I am getting the error "Passing argument 4 of 'obj_setProperty' from incompatible pointer type". I did a bit of research and found that 'retain' only works on class types, which is fair enough. If I actually remove the 'retain' from the line

```<code>@property (nonatomic, retain) id<ServerDateTimeUpdating> *serverDateTimeDelegate;
</code>```

it does compile without complaints. However, I think, that's the wrong thing to do. Surely my 'id' is a class type and surely it should be retained in the setter. BTW, here is the declaration of my HeaderPanelViewController which implements the aforementioned protocol:

```<code> @interface HeaderPanelViewController : UIViewController<ServerDateTimeUpdating> {

 }

...
@end
</code>```

Also, if I actually do remove the retain I get a problem later down the track when I actually call the setter to register my HeaderPanelViewController as the delegate:

```<code>// Register this instance as the delegate for ServerDateTimeUpdating
// Retrieve the ApplicationDelegate...
ApplicationDelegate *applicationDelegate = (ApplicationDelegate *) [UIApplication sharedApplication].delegate;
// ...and register this instance
applicationDelegate.serverDateTimeDelegate = self;
</code>```

The last line causes the XCode error message "Passing argument 1 of 'setServerDateTimeDelegate' from incompatible pointer type".

答:
Your problem is the property declaration:

```<code>@property (nonatomic, retain) id<ServerDateTimeUpdating> *serverDateTimeDelegate;
</code>```

If you command-double click "id", you'll see it defined as:

```<code>typedef struct objc_object {
  Class isa;
} *id;
</code>```

In other words, id is already an object reference.  Therefore, the * right before serverDateTimeDelegate is unnecessary and wrong.  Having it there means a pointer to an object reference, when you really just want an object reference.

Body:
I am getting the above compiler error in XCode, and I cannot work out what's going on.

#import <UIKit/UIKit.h>

// #import "HeaderPanelViewController.h"
#import "HTTPClientCommunicator.h"
#import "WebSocket.h"

@class HeaderPanelViewController;

@protocol ServerDateTimeUpdating
-(void)serverDateTimeHasBeenUpdatedWithDate:(NSString *) dateString andTime:(NSString *) timeString;
@end

@interface SmartWardPTAppDelegate : NSObject <UIApplicationDelegate, WebSocketDelegate> {

}

@property (nonatomic, retain) id<ServerDateTimeUpdating> *serverDateTimeDelegate;
....
@end

Then in this line

@synthesize serverDateTimeDelegate;

in ApplicationDelegate.m I am getting the error "Passing argument 4 of 'obj_setProperty' from incompatible pointer type". I did a bit of research and found that 'retain' only works on class types, which is fair enough. If I actually remove the 'retain' from the line

@property (nonatomic, retain) id<ServerDateTimeUpdating> *serverDateTimeDelegate;

it does compile without complaints. However, I think, that's the wrong thing to do. Surely my 'id' is a class type and surely it should be retained in the setter. BTW, here is the declaration of my HeaderPanelViewController which implements the aforementioned protocol:

 @interface HeaderPanelViewController : UIViewController<ServerDateTimeUpdating> {

 }

...
@end

Also, if I actually do remove the retain I get a problem later down the track when I actually call the setter to register my HeaderPanelViewController as the delegate:

// Register this instance as the delegate for ServerDateTimeUpdating
// Retrieve the ApplicationDelegate...
ApplicationDelegate *applicationDelegate = (ApplicationDelegate *) [UIApplication sharedApplication].delegate;
// ...and register this instance
applicationDelegate.serverDateTimeDelegate = self;

The last line causes the XCode error message "Passing argument 1 of 'setServerDateTimeDelegate' from incompatible pointer type".

Body:
Your problem is the property declaration:

@property (nonatomic, retain) id<ServerDateTimeUpdating> *serverDateTimeDelegate;

If you command-double click "id", you'll see it defined as:

typedef struct objc_object {
  Class isa;
} *id;

In other words, id is already an object reference.  Therefore, the * right before serverDateTimeDelegate is unnecessary and wrong.  Having it there means a pointer to an object reference, when you really just want an object reference.


问:
Can I run multiple TCP Listeners sharing a single port but different URIs
Is it possible to run multiple instances of a TCP Listener on the same port but with different listener URIs? E.g.

```<code>tcp://localhost:555/MyService1
tcp://localhost:555/MyService2
</code>```

Context is Windows and .NET

答:
At the application level it is possible, IIS SERVER with multiple web apps which are all on 80/443 ports is just one example.

But this can be done only at the application level.

So, it can be one listener should give all the packets to the application and from there will routed
to different sub applications.

Hope it helps :)

Body:
Is it possible to run multiple instances of a TCP Listener on the same port but with different listener URIs? E.g.

tcp://localhost:555/MyService1
tcp://localhost:555/MyService2

Context is Windows and .NET


问:
How to refresh android mpchart graph without refreshing whole activity
Hello i am using android MPAndroidChart library in my project. I want to refresh chart without refreshing activity page.

Thanks in advance.

答:
Where ever upon button click or spinner selection you need to update your graph just call a method:</p>

```<code>chartView.notifyDataSetChanged();
chartView.invalidate();
</code>```

Body:
Where ever upon button click or spinner selection you need to update your graph just call a method:

chartView.notifyDataSetChanged();
chartView.invalidate();


问:
PostgreSQL: append element to jsonb array only if element is unique
I created a PostgreSQL (v10.0) as follows.

```<code>CREATE TABLE test (id INT, animals jsonb)

INSERT INTO test VALUES
   (1, '["[monkeys, 10]", "[hamsters, 7]", "[foxes, 3]"]'),
   (2, '["[monkeys, 10]", "[hamsters, 7]", "[foxes, 3]"]')
</code>```

Then I append a new animal as follows:

```<code>UPDATE test
SET animals = animals || '["[hamsters, 7]"]'::jsonb
WHERE id = 1;
</code>```

However, I want to append the element only if the element is not yet in the array.

答:
you can just use additional WHERE clause:

```<code>UPDATE test
SET animals = animals || '["[hamsters, 7]"]'::jsonb
WHERE id = 1 AND animals ~ '"\[hamsters, \d\]"'
</code>```

Here I don't use jsonb, but rather just regular expression. to avoid nesting array and because "[hamsters, 7]" itself won't be array anyway - just a string, so I compare with string operators...

Body:
I created a PostgreSQL (v10.0) as follows.

CREATE TABLE test (id INT, animals jsonb)

INSERT INTO test VALUES
   (1, '["[monkeys, 10]", "[hamsters, 7]", "[foxes, 3]"]'),
   (2, '["[monkeys, 10]", "[hamsters, 7]", "[foxes, 3]"]')

Then I append a new animal as follows:

UPDATE test
SET animals = animals || '["[hamsters, 7]"]'::jsonb
WHERE id = 1;

However, I want to append the element only if the element is not yet in the array.

Body:
you can just use additional WHERE clause:

UPDATE test
SET animals = animals || '["[hamsters, 7]"]'::jsonb
WHERE id = 1 AND animals ~ '"\[hamsters, \d\]"'

Here I don't use jsonb, but rather just regular expression. to avoid nesting array and because "[hamsters, 7]" itself won't be array anyway - just a string, so I compare with string operators...


问:
ReactJS & Firebase - Ordering data
I have a React app querying Firebase with the following code:

```<code>const usersRef = firebase.database().ref('users').orderByChild('totalSubs');

    usersRef.on('value', (snapshot) => {
      let users = snapshot.val();

      let newState = [];

      for (let user in users) {
        newState.push({
          id: user,
          displayName: users[user].displayName,
          totalSubs: users[user].totalSubs,
          userImg: users[user].userImg
      });

      }
      this.setState({
        users: newState
      });
    });
</code>```

My Firebase structure for 'users' can be seen here.

I have 3 different Google accounts that I'm testing with, which is why my name appears against each user.

I'd like to be able to display each user within my react app, in descending order of totalSubs, e.g. the user with the highest totalSubs at the top.

From other posts, I thought .orderByChild('totalSubs'); would order the data and allow this, but it doesn't work. Can anyone tell me what I'm missing?

答:
Your query is correct, but you need to adjust the method you're using to extract data from the returned DataSnapshot.

From the working with lists of data documentation:

Attaching a value observer to a list of data will return the entire list of data as a single snapshot which you can then loop over to access individual children.

Even when there is only a single match for the query, the snapshot is still a list; it just contains a single item. To access the item, you need to loop over the result:

```<code>ref.once('value', function(snapshot) {
  snapshot.forEach(function(childSnapshot) {
    var childKey = childSnapshot.key;
    var childData = childSnapshot.val();
    // ...
  });
});
</code>```

Therefore, with your example code, you'll need to make a couple of changes and iterate over the returned children using forEach:

```<code>const usersRef = firebase.database().ref('users').orderByChild('totalSubs');

usersRef.on('value', (snapshot) => {
    let newState = [];

    snapshot.forEach(function(childSnapshot) {
        newState.push({
            id: childSnapshot.key,
            displayName: childSnapshot.val().displayName,
            totalSubs: childSnapshot.val().totalSubs,
            userImg: childSnapshot.val().userImg
        });
    });

    this.setState({
        users: newState
    });
});
</code>```

Title: ReactJS & Firebase - Ordering data

Body:
I have a React app querying Firebase with the following code:

const usersRef = firebase.database().ref('users').orderByChild('totalSubs');

    usersRef.on('value', (snapshot) => {
      let users = snapshot.val();

      let newState = [];

      for (let user in users) {
        newState.push({
          id: user,
          displayName: users[user].displayName,
          totalSubs: users[user].totalSubs,
          userImg: users[user].userImg
      });

      }
      this.setState({
        users: newState
      });
    });

My Firebase structure for 'users' can be seen here.

I have 3 different Google accounts that I'm testing with, which is why my name appears against each user.

I'd like to be able to display each user within my react app, in descending order of totalSubs, e.g. the user with the highest totalSubs at the top.

From other posts, I thought .orderByChild('totalSubs'); would order the data and allow this, but it doesn't work. Can anyone tell me what I'm missing?

Body:
Your query is correct, but you need to adjust the method you're using to extract data from the returned DataSnapshot.

From the working with lists of data documentation:

Attaching a value observer to a list of data will return the entire list of data as a single snapshot which you can then loop over to access individual children.

Even when there is only a single match for the query, the snapshot is still a list; it just contains a single item. To access the item, you need to loop over the result:

ref.once('value', function(snapshot) {
  snapshot.forEach(function(childSnapshot) {
    var childKey = childSnapshot.key;
    var childData = childSnapshot.val();
    // ...
  });
});

Therefore, with your example code, you'll need to make a couple of changes and iterate over the returned children using forEach:

const usersRef = firebase.database().ref('users').orderByChild('totalSubs');

usersRef.on('value', (snapshot) => {
    let newState = [];

    snapshot.forEach(function(childSnapshot) {
        newState.push({
            id: childSnapshot.key,
            displayName: childSnapshot.val().displayName,
            totalSubs: childSnapshot.val().totalSubs,
            userImg: childSnapshot.val().userImg
        });
    });

    this.setState({
        users: newState
    });
});


答:
Because you return stream variable, and it's null :)

Just return your Task

```<code>public async Task<Stream> DownloadFileAsync(IData data)
{
    return await Task.Run(() => DownloadFile(data));
}
</code>```

Title: Create async version of sync method

Body:
Because you return stream variable, and it's null :)

Just return your Task

public async Task<Stream> DownloadFileAsync(IData data)
{
    return await Task.Run(() => DownloadFile(data));
}


问:
Rotate the image corresponding to the touch drag in iPhone
I want to rotate the image in clockwise or anticlockwise direction corresponding to the user touch drag with its speed. I think this can be done with some math and logic. What would a code sample for this look like?</p>

答:
If you're targeting iOS 3.2 or greater, you can use UIRotationGestureRecognizer. The code would look something like this:

In your setup method (viewDidLoad or init, etc,):

```<code>UIRotationGestureRecognizer *rotationGesture =
  [[UIRotationGestureRecognizer alloc] initWithTarget:self
                                               action:@selector(handleRotate:)];
rotationGesture.delegate = self;
[myImageView addGestureRecognizer:rotationGesture];
[rotationGesture release];
</code>```

The event handler:

```<code>- (void)handleRotate:(UIRotationGestureRecognizer *)recognizer {
  if(recognizer.state == UIGestureRecognizerStateBegan ||
     recognizer.state == UIGestureRecognizerStateChanged)
  {
    recognizer.view.transform = CGAffineTransformRotate(recognizer.view.transform,
                                                        recognizer.rotation);
    [recognizer setRotation:0];
  }
}
</code>```

I have some more examples of gesture recognizers (including the one above) on github.

Body:
If you're targeting iOS 3.2 or greater, you can use UIRotationGestureRecognizer. The code would look something like this:

In your setup method (viewDidLoad or init, etc,):

UIRotationGestureRecognizer *rotationGesture =
  [[UIRotationGestureRecognizer alloc] initWithTarget:self
                                               action:@selector(handleRotate:)];
rotationGesture.delegate = self;
[myImageView addGestureRecognizer:rotationGesture];
[rotationGesture release];

The event handler:

- (void)handleRotate:(UIRotationGestureRecognizer *)recognizer {
  if(recognizer.state == UIGestureRecognizerStateBegan ||
     recognizer.state == UIGestureRecognizerStateChanged)
  {
    recognizer.view.transform = CGAffineTransformRotate(recognizer.view.transform,
                                                        recognizer.rotation);
    [recognizer setRotation:0];
  }
}

I have some more examples of gesture recognizers (including the one above) on github.


问:
getting 0>=0 while running program
I run this code

```<code>public void loadtwo()
{
    try{
        String query="SELECT Grade.GradeName, [Group].GroupName, AcademicInfo.EntranceYear, Semester.SemesterName, AcademicRank.AcademicRankName, Others.OthersName, AcademicInfo.AcademicInfoID,AcademicInfo.Major, AcademicInfo.Department\n "+
                "FROM AcademicInfo INNER JOIN\n" +
                "AcademicRank ON AcademicInfo.AcademicRankID = AcademicRank.AcademicRankID INNER JOIN\n" +
                "Grade ON AcademicInfo.GradeID = Grade.GradeID INNER JOIN\n" +
                "[Group] ON AcademicInfo.GroupID = [Group].GroupID INNER JOIN\n" +
                "Others ON AcademicInfo.OthersID = Others.OthersID INNER JOIN\n" +
                "Semester ON AcademicInfo.SemesterID = Semester.SemesterID";
        DBlabprj.rs=DBlabprj.stmt.executeQuery(query);
        int i=0;
        while(DBlabprj.rs.next())
        {
            edutbl.setValueAt(DBlabprj.rs.getString("GradeName"),i,0);
            edutbl.setValueAt(DBlabprj.rs.getString("GroupName"),i,1);
            edutbl.setValueAt(DBlabprj.rs.getInt("EntranceYear"),i,2);
            edutbl.setValueAt(DBlabprj.rs.getString("SemesterName"),i,3);
            edutbl.setValueAt(DBlabprj.rs.getString("AcademicRankName"),i,4);
            edutbl.setValueAt(DBlabprj.rs.getString("OthersName"),i,5);
            edutbl.setValueAt(DBlabprj.rs.getInt("AcademicInfoID"),i,6);
            edutbl.setValueAt(DBlabprj.rs.getString("Major"),i,7);
            edutbl.setValueAt(DBlabprj.rs.getString("Department"),i,8);

            i++;
        }
    }
    catch(Exception e)
    {
        JOptionPane.showMessageDialog(rootPane,e.getMessage());
    }
}
</code>```

and I get this error:

0>=0

I can't understand what's wrong, when I remove the [] from Group I get this error:

Incorrect Syntax near the word 'Group'

答: The second error is due to the fact that group is a keyword for T-SQL , so you can try to alias the table with some other variable.</p>

Title: getting 0>=0 while running program

Body:
I run this code

public void loadtwo()
{
    try{
        String query="SELECT Grade.GradeName, [Group].GroupName, AcademicInfo.EntranceYear, Semester.SemesterName, AcademicRank.AcademicRankName, Others.OthersName, AcademicInfo.AcademicInfoID,AcademicInfo.Major, AcademicInfo.Department\n "+
                "FROM AcademicInfo INNER JOIN\n" +
                "AcademicRank ON AcademicInfo.AcademicRankID = AcademicRank.AcademicRankID INNER JOIN\n" +
                "Grade ON AcademicInfo.GradeID = Grade.GradeID INNER JOIN\n" +
                "[Group] ON AcademicInfo.GroupID = [Group].GroupID INNER JOIN\n" +
                "Others ON AcademicInfo.OthersID = Others.OthersID INNER JOIN\n" +
                "Semester ON AcademicInfo.SemesterID = Semester.SemesterID";
        DBlabprj.rs=DBlabprj.stmt.executeQuery(query);
        int i=0;
        while(DBlabprj.rs.next())
        {
            edutbl.setValueAt(DBlabprj.rs.getString("GradeName"),i,0);
            edutbl.setValueAt(DBlabprj.rs.getString("GroupName"),i,1);
            edutbl.setValueAt(DBlabprj.rs.getInt("EntranceYear"),i,2);
            edutbl.setValueAt(DBlabprj.rs.getString("SemesterName"),i,3);
            edutbl.setValueAt(DBlabprj.rs.getString("AcademicRankName"),i,4);
            edutbl.setValueAt(DBlabprj.rs.getString("OthersName"),i,5);
            edutbl.setValueAt(DBlabprj.rs.getInt("AcademicInfoID"),i,6);
            edutbl.setValueAt(DBlabprj.rs.getString("Major"),i,7);
            edutbl.setValueAt(DBlabprj.rs.getString("Department"),i,8);

            i++;
        }
    }
    catch(Exception e)
    {
        JOptionPane.showMessageDialog(rootPane,e.getMessage());
    }
}

and I get this error:

0>=0

I can't understand what's wrong, when I remove the [] from Group I get this error:

Incorrect Syntax near the word 'Group'