问:
Access97: INSERT INTO if not exists
I need to do a very simple task: execute an INSERT INTO query only if the record doesn't exist in the table.
I found a lot of hints out there but none of them work in SQL Access97.

Example:

```<code>IF NOT EXISTS ( SELECT 1 FROM Users WHERE FirstName = 'John' AND LastName = 'Smith' )
BEGIN
    INSERT INTO Users (FirstName, LastName) VALUES ('John', 'Smith')
END
</code>```

this won't work because IF NOT EXISTS is not valid.

What is the right way to do this in one SQL clause?

答:
You can build that into an insert . ..  select:

```<code>INSERT INTO Users (FirstName, LastName)
    SELECT TOP 1 'John', 'Smith'
    FROM Users
    WHERE NOT EXISTS ( SELECT 1 FROM Users WHERE FirstName = 'John' AND LastName = 'Smith' );
</code>```

Title: Access97: INSERT INTO if not exists

Body:
I need to do a very simple task: execute an INSERT INTO query only if the record doesn't exist in the table.
I found a lot of hints out there but none of them work in SQL Access97.

Example:

IF NOT EXISTS ( SELECT 1 FROM Users WHERE FirstName = 'John' AND LastName = 'Smith' )
BEGIN
    INSERT INTO Users (FirstName, LastName) VALUES ('John', 'Smith')
END

this won't work because IF NOT EXISTS is not valid.

What is the right way to do this in one SQL clause?

Body:
You can build that into an insert . ..  select:

INSERT INTO Users (FirstName, LastName)
    SELECT TOP 1 'John', 'Smith'
    FROM Users
    WHERE NOT EXISTS ( SELECT 1 FROM Users WHERE FirstName = 'John' AND LastName = 'Smith' );


来源: stackexchange

问:
How to retrieve all certificates in your X509Store
I am using the following code to retrieve all certificates in my PC from an asp.net webapp. The certificates collection is empty, and I can't understand why.

I tried impersonating my own user account and I didn't succeed as well. What am I doing wrong?

```<code>var store = new X509Store(StoreLocation.CurrentUser); //StoreLocation.LocalMachine fails too
var certificates = store.Certificates;
foreach (var certificate in certificates)
{
    var friendlyName = certificate.FriendlyName;
    Console.WriteLine(friendlyName);
}

//original problem: fetch a single certificate by its subject name
X509Certificate2 clientCertificate = CertificateUtility.GetCertificate(StoreName.My, StoreLocation.CurrentUser,  "CN=mypc.domainname"); //returns null :(
</code>```

答:
Add this line of code to the second line and see how it works:

```<code>store.Open(OpenFlags.ReadOnly);
</code>```

and then this at the bottom :):

```<code>store.Close();
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am using the following code to retrieve all certificates in my PC from an asp.net webapp. The certificates collection is empty, and I can't understand why.

I tried impersonating my own user account and I didn't succeed as well. What am I doing wrong?

var store = new X509Store(StoreLocation.CurrentUser); //StoreLocation.LocalMachine fails too
var certificates = store.Certificates;
foreach (var certificate in certificates)
{
    var friendlyName = certificate.FriendlyName;
    Console.WriteLine(friendlyName);
}

//original problem: fetch a single certificate by its subject name
X509Certificate2 clientCertificate = CertificateUtility.GetCertificate(StoreName.My, StoreLocation.CurrentUser,  "CN=mypc.domainname"); //returns null :(

Body:
Add this line of code to the second line and see how it works:

store.Open(OpenFlags.ReadOnly);

and then this at the bottom :):

store.Close();


问:
AWS Elastic Beanstalk - switching environment variables between environments
I am using Elastic Beanstalk's aws:elasticbeanstalk:application:environment namespace to configure my environment with env vars. How can I set different values for different environments (e.g. development versus production)?

Development:

option_settings:
  aws:elasticbeanstalk:application:environment:
    REDIS_HOST: localhost
```

<h3>Production:</h3>

<pre class="lang-yaml prettyprint-override"><code>option_settings:
  aws:elasticbeanstalk:application:environment:
    REDIS_HOST: prod.redis.server.com
</code>```

答:
How it's changed depends on your deployment method.

One option you can use is to set a bogus value in your .config file:

```<code>option_settings:
  aws:elasticbeanstalk:application:environment:
    REDIS_HOST: change me
</code>```

Then, after deployment, modify the variable either using the AWS Management Console or using the EB CLI:

```<code>eb setenv REDIS_HOST=prod.redis.server.com
</code>```

If you are using CloudFormation to deploy your EB application, you can feed the value as part of the OptionSettings field in your CloudFormation template:

```<code>    "EBConfigurationTemplate" : {
        "Type" : "AWS::ElasticBeanstalk::ConfigurationTemplate",
        "Properties" : {
            "ApplicationName" : {
                "Ref" : "EBApplication"
            },
            "Description"     : "Configuration Template",
            "OptionSettings"  : [
                {
                    "Namespace" : "aws:elasticbeanstalk:application:environment",
                    "OptionName" : "REDIS_HOST",
                    "Value"      : {
                        "Ref" : "RedisHostInputParameter"
                    }
                },
            ]
</code>```

There are probably other methods too, but they will depend on the method of deployment.

ContentLicense: CC BY-SA 4.0

Body:
I am using Elastic Beanstalk's aws:elasticbeanstalk:application:environment namespace to configure my environment with env vars. How can I set different values for different environments (e.g. development versus production)?

Development:

option_settings:
  aws:elasticbeanstalk:application:environment:
    REDIS_HOST: localhost

Production:

option_settings:
  aws:elasticbeanstalk:application:environment:
    REDIS_HOST: prod.redis.server.com

Body:
How it's changed depends on your deployment method.

One option you can use is to set a bogus value in your .config file:

option_settings:
  aws:elasticbeanstalk:application:environment:
    REDIS_HOST: change me

Then, after deployment, modify the variable either using the AWS Management Console or using the EB CLI:

eb setenv REDIS_HOST=prod.redis.server.com

If you are using CloudFormation to deploy your EB application, you can feed the value as part of the OptionSettings field in your CloudFormation template:

    "EBConfigurationTemplate" : {
        "Type" : "AWS::ElasticBeanstalk::ConfigurationTemplate",
        "Properties" : {
            "ApplicationName" : {
                "Ref" : "EBApplication"
            },
            "Description"     : "Configuration Template",
            "OptionSettings"  : [
                {
                    "Namespace" : "aws:elasticbeanstalk:application:environment",
                    "OptionName" : "REDIS_HOST",
                    "Value"      : {
                        "Ref" : "RedisHostInputParameter"
                    }
                },
            ]

There are probably other methods too, but they will depend on the method of deployment.

ContentLicense: CC BY-SA 3.0


问:
Reason: CORS header ‘Access-Control-Allow-Origin’ missing even though explictly specificed in java resource
I am testing my backend (Java using Jersey on tomcat server) and frontend (Angular 4 using webpack to serve) on two different ports, thus I am getting a cors access control origin block. For my get methods everything works fine and any data requested is found on the UI. Now I am testing my POST method and I keep getting the same message in the title.

My post method should persist the data sent to it and return a response with the location of the new persisted entity.

```<code>@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response persistAccountLocation(AccountLocation entity) throws URISyntaxException {

    accountLocationService.persist(entity);

    JsonObject object = Json.createObjectBuilder()
            .add("location", "api/v1/accounts_locations/"+entity.getLocation_id()).build();

    return Response.status(Response.Status.CREATED)// 201
            .entity("Location created")
            .header("Access-Control-Allow-Origin","*")
            .header("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE")
            .allow("OPTIONS")
            .entity(object.toString()).build();
}
</code>```

In my network tab in firefox browser I only see OPTIONS with 200 status

```<code>Host: localhost:8081
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: POST
Access-Control-Request-Headers: access-control-allow-origin,content-type
Origin: http://localhost:4200
Connection: keep-alive
</code>```

but after that the post is never happens. I am assuming CORS blocks it at that point. Is there somewhere else I should be allowing access control besides the resource class? I have read that typical all CORS configuration is done on server side. Totally lost. Any feedback appreciated

EDIT

```<code>public class CORSResponseFilter
implements ContainerResponseFilter {

    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
            throws IOException {

        MultivaluedMap<String, Object> headers = responseContext.getHeaders();

        headers.add("Access-Control-Allow-Origin", "*");
        headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS");
        headers.add("Access-Control-Allow-Headers", "X-Requested-With, Content-Type,");
    }

}
</code>```

I have made a a filter with slight adjustments and registered it to my app

```<code>public class JaxRsApplication extends ResourceConfig{
    public JaxRsApplication() {

        //  register application resources - unmapped resources will throw exception
        register(AccountLocationResource.class);

        register(CORSResponseFilter.class);
    }
</code>```

答:
Quite a good answer is provided in How to handle CORS using JAX-RS with Jersey stackoverflow question.

You have given a link to Jersey 1, but please make sure what version you are using.

This way you will not have to write

```<code>        .header("Access-Control-Allow-Origin","*")
        .header("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE")
        .allow("OPTIONS")
</code>```

for every request. Filter will apply the options for you.

One more thing I have noticed

```<code>return Response.status(Response.Status.CREATED)// 201
        .entity("Location created") // <- entity() call here
        .header("Access-Control-Allow-Origin","*")
        .header("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE")
        .allow("OPTIONS")
        .entity(object.toString()).build(); // <- one more entity() call here (not sure what effect it may have)
</code>```

Body:
I am testing my backend (Java using Jersey on tomcat server) and frontend (Angular 4 using webpack to serve) on two different ports, thus I am getting a cors access control origin block. For my get methods everything works fine and any data requested is found on the UI. Now I am testing my POST method and I keep getting the same message in the title.

My post method should persist the data sent to it and return a response with the location of the new persisted entity.

@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response persistAccountLocation(AccountLocation entity) throws URISyntaxException {

    accountLocationService.persist(entity);

    JsonObject object = Json.createObjectBuilder()
            .add("location", "api/v1/accounts_locations/"+entity.getLocation_id()).build();

    return Response.status(Response.Status.CREATED)// 201
            .entity("Location created")
            .header("Access-Control-Allow-Origin","*")
            .header("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE")
            .allow("OPTIONS")
            .entity(object.toString()).build();
}

In my network tab in firefox browser I only see OPTIONS with 200 status

Host: localhost:8081
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: POST
Access-Control-Request-Headers: access-control-allow-origin,content-type
Origin: http://localhost:4200
Connection: keep-alive

but after that the post is never happens. I am assuming CORS blocks it at that point. Is there somewhere else I should be allowing access control besides the resource class? I have read that typical all CORS configuration is done on server side. Totally lost. Any feedback appreciated

EDIT

public class CORSResponseFilter
implements ContainerResponseFilter {

    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
            throws IOException {

        MultivaluedMap<String, Object> headers = responseContext.getHeaders();

        headers.add("Access-Control-Allow-Origin", "*");
        headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS");
        headers.add("Access-Control-Allow-Headers", "X-Requested-With, Content-Type,");
    }

}

I have made a a filter with slight adjustments and registered it to my app

public class JaxRsApplication extends ResourceConfig{
    public JaxRsApplication() {

        //  register application resources - unmapped resources will throw exception
        register(AccountLocationResource.class);

        register(CORSResponseFilter.class);
    }

Body:
Quite a good answer is provided in How to handle CORS using JAX-RS with Jersey stackoverflow question.

You have given a link to Jersey 1, but please make sure what version you are using.

This way you will not have to write

        .header("Access-Control-Allow-Origin","*")
        .header("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE")
        .allow("OPTIONS")

for every request. Filter will apply the options for you.

One more thing I have noticed

return Response.status(Response.Status.CREATED)// 201
        .entity("Location created") // <- entity() call here
        .header("Access-Control-Allow-Origin","*")
        .header("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE")
        .allow("OPTIONS")
        .entity(object.toString()).build(); // <- one more entity() call here (not sure what effect it may have)


问:
Can not figure out how get certain inputs to work?
I am making a post fix calculator and i can not figure out how to do functions without having an equal sign. For example " a = 3 5 + " will print 8 , but " 3 5 + " will make the program crash. Here is what i have so far</p>

```<code>if (values.peek().matches("[a-z]") || values.search("=") > -1 )
{
    String a = values.pop();
    values.pop();
    double answer = compute(values);
    memory.put(a, answer);
    var.add(a);
    System.out.println("   " + answer);
}
else
{
    double answer = compute(values);
    System.out.println(answer);
}
</code>```

答:
I guess your parsing of input has some problem. If you want to split the input by space, try this way:

```<code>String str = " 3 5 + ";
String[] splited = str.split("\\s+");
</code>```

Inspired by the first answer of this question:

Body:
I am making a post fix calculator and i can not figure out how to do functions without having an equal sign. For example " a = 3 5 + " will print 8 , but " 3 5 + " will make the program crash. Here is what i have so far

if (values.peek().matches("[a-z]") || values.search("=") > -1 )
{
    String a = values.pop();
    values.pop();
    double answer = compute(values);
    memory.put(a, answer);
    var.add(a);
    System.out.println("   " + answer);
}
else
{
    double answer = compute(values);
    System.out.println(answer);
}

Body:
I guess your parsing of input has some problem. If you want to split the input by space, try this way:

String str = " 3 5 + ";
String[] splited = str.split("\\s+");

Inspired by the first answer of this question:


问:
How to pivot dynamic array using PHP or SQL directly?
I have the following PHP array. It store the information of a certain item, the store id and the price for that store. This array will be dynamic, so later more store_ids will be added.

```<code>array (size=6)
0 =>
    array (size=3)
      'item_id' => '1'
      'store_id' => '1'
      'price' => '74.99'
1 =>
    array (size=3)
      'item_id' => '2'
      'store_id' => '1'
      'price' => '35.99'
2 =>
    array (size=3)
      'item_id' => '3'
      'store_id' => '1'
      'price' => '89.99'
3 =>
    array (size=3)
      'item_id' => '1'
      'store_id' => '2'
      'price' => '69.99'
4 =>
    array (size=3)
      'item_id' => '2'
      'store_id' => '2'
      'price' => '39.99'
5 =>
    array (size=3)
      'item_id' => '3'
      'store_id' => '2'
      'price' => '95.99'
</code>```

This is the result I want to get, I want to group them by the item_id and store every price each item has at every store. All the items will be available in all the store_ids.

```<code>array (size=3)
0 =>
    array (size=3)
      'item_id' => '1'
      (price for store_id 1) => '74.99'
      (price for store_id 2) => '69.99'
1 =>
    array (size=3)
      'item_id' => '2'
      (price for store_id 1) => '35.99'
      (price for store_id 2) => '39.99'
2 =>
    array (size=3)
      'item_id' => '3'
      (price for store_id 1) => '89.99'
      (price for store_id 2) => '95.99'
</code>```

I was trying to do this directly from the query but I am using mysql and didn't find a solution for that.
I know I need to loop through the array but I have no clue about the process needed to achieve this. Any help or suggestion is appreciated. Thanks!

答:
Not the best nor the most optimized code, but gives the expected result:

```<code>//$arr = ...
$output = array();
foreach($arr as $item){
    if(in_array($item['item_id'], array_column($output, 'item_id'))){
        // add store to already existing item
        $key = array_search($item['item_id'], array_column($arr, 'item_id'));
        $output[$key]['store_id_' . $item['store_id']] = $item['price'];
    }else{
        // add new item with store
        $tmp = array(
            'item_id' => $item['item_id'],
            'store_id_' . $item['store_id'] => $item['price'],
        );
        $output[] = $tmp;
    }
}
</code>```

You can check it out.

Body:
I have the following PHP array. It store the information of a certain item, the store id and the price for that store. This array will be dynamic, so later more store_ids will be added.

array (size=6)
0 =>
    array (size=3)
      'item_id' => '1'
      'store_id' => '1'
      'price' => '74.99'
1 =>
    array (size=3)
      'item_id' => '2'
      'store_id' => '1'
      'price' => '35.99'
2 =>
    array (size=3)
      'item_id' => '3'
      'store_id' => '1'
      'price' => '89.99'
3 =>
    array (size=3)
      'item_id' => '1'
      'store_id' => '2'
      'price' => '69.99'
4 =>
    array (size=3)
      'item_id' => '2'
      'store_id' => '2'
      'price' => '39.99'
5 =>
    array (size=3)
      'item_id' => '3'
      'store_id' => '2'
      'price' => '95.99'

This is the result I want to get, I want to group them by the item_id and store every price each item has at every store. All the items will be available in all the store_ids.

array (size=3)
0 =>
    array (size=3)
      'item_id' => '1'
      (price for store_id 1) => '74.99'
      (price for store_id 2) => '69.99'
1 =>
    array (size=3)
      'item_id' => '2'
      (price for store_id 1) => '35.99'
      (price for store_id 2) => '39.99'
2 =>
    array (size=3)
      'item_id' => '3'
      (price for store_id 1) => '89.99'
      (price for store_id 2) => '95.99'

I was trying to do this directly from the query but I am using mysql and didn't find a solution for that.
I know I need to loop through the array but I have no clue about the process needed to achieve this. Any help or suggestion is appreciated. Thanks!

Body:
Not the best nor the most optimized code, but gives the expected result:

//$arr = ...
$output = array();
foreach($arr as $item){
    if(in_array($item['item_id'], array_column($output, 'item_id'))){
        // add store to already existing item
        $key = array_search($item['item_id'], array_column($arr, 'item_id'));
        $output[$key]['store_id_' . $item['store_id']] = $item['price'];
    }else{
        // add new item with store
        $tmp = array(
            'item_id' => $item['item_id'],
            'store_id_' . $item['store_id'] => $item['price'],
        );
        $output[] = $tmp;
    }
}

You can check it out.


问:
Set SQL Server 'Maximum server memory in (MB)' using Powershell
I'm currently automating a VM and using a Powershell script to install SQL Server 2017.

I need to be able to script the Maximum server memory as well. Is this possible through the current configuration settings or will I need to create a custom script? If a custom script is required what would I need to do.

答:
By using sqlps module it's possible to address this task the next way:</p>

```<code>Import-Module Sqlps
$sql16 = ls 'SQLSERVER:\SQL\(local)'|? InstanceName -eq 'SQL16'
$sql16.Configuration.MaxServerMemory.RunValue
$sql16.Configuration.MaxServerMemory.ConfigValue = [Math]::Floor($sql16.Configuration.MaxServerMemory.RunValue * 1.5)
$sql16.Alter()
$sql16.Configuration.MaxServerMemory.RunValue
</code>```

Body:
By using sqlps module it's possible to address this task the next way:

Import-Module Sqlps
$sql16 = ls 'SQLSERVER:\SQL\(local)'|? InstanceName -eq 'SQL16'
$sql16.Configuration.MaxServerMemory.RunValue
$sql16.Configuration.MaxServerMemory.ConfigValue = [Math]::Floor($sql16.Configuration.MaxServerMemory.RunValue * 1.5)
$sql16.Alter()
$sql16.Configuration.MaxServerMemory.RunValue


问:
Does the location background mode work in swift when the app is terminated?
Right now, I'm trying to implement the location background mode for my app. When the user location is updated, I'm going to schedule a notification (eventually I'll schedule them conditionally, but for right now I'm just scheduling them so I know it works). I have the following code:

```<code> func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.first {
        currentLocation = location
    }
    if UIApplication.shared.applicationState == .background {
    // if the app is in the background
         let notif = UNMutableNotificationContent()
    notif.title = "Location was updated"
    var message = " "
    notif.body = message
    let identifier = String(arc4random())
    var dc = DateComponents()
    var date = Date()
    date = Calendar.current.date(byAdding: .second, value: 3, to: date)!
    dc.hour = Calendar.current.component(.hour, from: date)
    dc.minute = Calendar.current.component(.minute, from: date)
    dc.second = Calendar.current.component(.second, from: date)
    let notifTrigger = UNCalendarNotificationTrigger(dateMatching: dc, repeats: false)
    let request = UNNotificationRequest(identifier: identifier, content: notif, trigger: notifTrigger)
    UNUserNotificationCenter.current().add(request, withCompletionHandler: { error in
        if error != nil {
            print(error!)
        } else {
            print("Notification scheduled!")
        }
    })
</code>```

This works great when the app is in the background, but when the app gets terminated, my function isn't called, and the notifications aren't getting delivered. My question is: Is this possible with Swift? Or does the locationManager function I'm using only work if the app is backgrounded, but not terminated?

Side note: I've tried taking out if UIApplication.shared.applicationState == .background and it does not fix the problem

答: That's possible. Move the app so that location updates gets triggered. Check with accuracy as 100m and move your device or use simulator simulation for location. I am assuming that you have already given Use Location Always Permission</p>

Body:
Right now, I'm trying to implement the location background mode for my app. When the user location is updated, I'm going to schedule a notification (eventually I'll schedule them conditionally, but for right now I'm just scheduling them so I know it works). I have the following code:

 func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.first {
        currentLocation = location
    }
    if UIApplication.shared.applicationState == .background {
    // if the app is in the background
         let notif = UNMutableNotificationContent()
    notif.title = "Location was updated"
    var message = " "
    notif.body = message
    let identifier = String(arc4random())
    var dc = DateComponents()
    var date = Date()
    date = Calendar.current.date(byAdding: .second, value: 3, to: date)!
    dc.hour = Calendar.current.component(.hour, from: date)
    dc.minute = Calendar.current.component(.minute, from: date)
    dc.second = Calendar.current.component(.second, from: date)
    let notifTrigger = UNCalendarNotificationTrigger(dateMatching: dc, repeats: false)
    let request = UNNotificationRequest(identifier: identifier, content: notif, trigger: notifTrigger)
    UNUserNotificationCenter.current().add(request, withCompletionHandler: { error in
        if error != nil {
            print(error!)
        } else {
            print("Notification scheduled!")
        }
    })

This works great when the app is in the background, but when the app gets terminated, my function isn't called, and the notifications aren't getting delivered. My question is: Is this possible with Swift? Or does the locationManager function I'm using only work if the app is backgrounded, but not terminated?

Side note: I've tried taking out if UIApplication.shared.applicationState == .background and it does not fix the problem


问:
How do I split the definition of a long string over multiple lines?
I have a very long query. I would like to split it in several lines in Python. A way to do it in JavaScript would be using several sentences and joining them with a + operator (I know, maybe it's not the most efficient way to do it, but I'm not really concerned about performance in this stage, just code readability). Example:

var long_string = 'some text not important. just garbage to' +
                      'illustrate my example';
```
<p>I tried doing something similar in Python, but it didn't work, so I used <code>\</code> to split the long string. However, I'm not sure if this is the only/best/pythonicest way of doing it. It looks awkward.
Actual code:</p>
<pre class="lang-py prettyprint-override"><code>query = 'SELECT action.descr as "action", '\
    'role.id as role_id,'\
    'role.descr as role'\
    'FROM '\
    'public.role_action_def,'\
    'public.role,'\
    'public.record_def, '\
    'public.action'\
    'WHERE role.id = role_action_def.role_id AND'\
    'record_def.id = role_action_def.def_id AND'\
    'action.id = role_action_def.action_id AND'\
    'role_action_def.account_id = ' + account_id + ' AND'\
    'record_def.account_id=' + account_id + ' AND'\
    'def_id=' + def_id
</code>```

答:
I personally find the following to be the best (simple, safe and Pythonic) way to write raw SQL queries in Python, especially when using Python's sqlite3 module:

```<code>query = '''
    SELECT
        action.descr as action,
        role.id as role_id,
        role.descr as role
    FROM
        public.role_action_def,
        public.role,
        public.record_def,
        public.action
    WHERE
        role.id = role_action_def.role_id
        AND record_def.id = role_action_def.def_id
        AND action.id = role_action_def.action_id
        AND role_action_def.account_id = ?
        AND record_def.account_id = ?
        AND def_id = ?
'''
vars = (account_id, account_id, def_id)   # a tuple of query variables
cursor.execute(query, vars)   # using Python's sqlite3 module
</code>```

Pros

Neat and simple code (Pythonic!)

Safe from SQL injection

Compatible with both Python 2 and Python 3 (it's Pythonic after all)

No string concatenation required

No need to ensure that the right-most character of each line is a space

Cons

Since variables in the query are replaced by the ? placeholder, it may become a little difficult to keep track of which ? is to be substituted by which Python variable when there are lots of them in the query.

Body:
I have a very long query. I would like to split it in several lines in Python. A way to do it in JavaScript would be using several sentences and joining them with a + operator (I know, maybe it's not the most efficient way to do it, but I'm not really concerned about performance in this stage, just code readability). Example:

var long_string = 'some text not important. just garbage to' +
                      'illustrate my example';

I tried doing something similar in Python, but it didn't work, so I used \ to split the long string. However, I'm not sure if this is the only/best/pythonicest way of doing it. It looks awkward.
Actual code:

query = 'SELECT action.descr as "action", '\
    'role.id as role_id,'\
    'role.descr as role'\
    'FROM '\
    'public.role_action_def,'\
    'public.role,'\
    'public.record_def, '\
    'public.action'\
    'WHERE role.id = role_action_def.role_id AND'\
    'record_def.id = role_action_def.def_id AND'\
    'action.id = role_action_def.action_id AND'\
    'role_action_def.account_id = ' + account_id + ' AND'\
    'record_def.account_id=' + account_id + ' AND'\
    'def_id=' + def_id

Body:
I personally find the following to be the best (simple, safe and Pythonic) way to write raw SQL queries in Python, especially when using Python's sqlite3 module:

query = '''
    SELECT
        action.descr as action,
        role.id as role_id,
        role.descr as role
    FROM
        public.role_action_def,
        public.role,
        public.record_def,
        public.action
    WHERE
        role.id = role_action_def.role_id
        AND record_def.id = role_action_def.def_id
        AND action.id = role_action_def.action_id
        AND role_action_def.account_id = ?
        AND record_def.account_id = ?
        AND def_id = ?
'''
vars = (account_id, account_id, def_id)   # a tuple of query variables
cursor.execute(query, vars)   # using Python's sqlite3 module

Pros

Neat and simple code (Pythonic!)

Safe from SQL injection

Compatible with both Python 2 and Python 3 (it's Pythonic after all)

No string concatenation required

No need to ensure that the right-most character of each line is a space

Cons

Since variables in the query are replaced by the ? placeholder, it may become a little difficult to keep track of which ? is to be substituted by which Python variable when there are lots of them in the query.


问:
Calculating the sum of values from a text file?
im trying to find the sum of the cost of all my books in my libary system from a file, could someone say where im going wrong atm. It would be great help

```<code>int sum = 0;
    File Fileobject = new File ("E:\\text files for java\\BooksToImport.txt");

    try {
        Scanner fileReader  = new Scanner (Fileobject);

        // Read and display each line of the file

        while(fileReader.hasNext())
        {
            sum+= fileReader.nextInt ( );
            line = fileReader.nextLine();
            System.out.println(line);
            System.out.println(sum);
        }
            fileReader.close();
</code>```

This is my data im reading:

```<code>The_Hunger_Games - Suzanne_Collins - 5 - Scholastic_Press - 9781921988752

OOP_programming - Graham_Winter - 32.50 – Oreilly - 0471974555

Harry_potter - Jk_Rowling - 10 - Bloomsbury- 9788700631625
</code>```

This is the errors im getting:

```<code>Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at c3500948JavaProjectAssignement1.c3500948.main(c3500948.java:80)
</code>```

答:
Scanner.next*() reads a stream until the next delimiter (the default is defined in Character.isWhitespace).  When you call nextInt() it reads the next delimiter and then attempts to parse it as an int, if it is not then you get an InputMixmatchException.  You can define your own delimiter like this (using an escaped regegex for <space>-<space>):

```<code>new Scanner(input).useDelimiter("\\s-\\s");
</code>```

Then you would need to call .next() to skip over the parts of each line that you aren't parsing.

Now that last line of your example shows a hyphen directly following the publisher (without space).  This fix might require more work over more data (such as book titles with hyphens in them).  Hopefully, this gets you unstuck.

Body:
im trying to find the sum of the cost of all my books in my libary system from a file, could someone say where im going wrong atm. It would be great help

int sum = 0;
    File Fileobject = new File ("E:\\text files for java\\BooksToImport.txt");

    try {
        Scanner fileReader  = new Scanner (Fileobject);

        // Read and display each line of the file

        while(fileReader.hasNext())
        {
            sum+= fileReader.nextInt ( );
            line = fileReader.nextLine();
            System.out.println(line);
            System.out.println(sum);
        }
            fileReader.close();

This is my data im reading:

The_Hunger_Games - Suzanne_Collins - 5 - Scholastic_Press - 9781921988752

OOP_programming - Graham_Winter - 32.50 – Oreilly - 0471974555

Harry_potter - Jk_Rowling - 10 - Bloomsbury- 9788700631625

This is the errors im getting:

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at c3500948JavaProjectAssignement1.c3500948.main(c3500948.java:80)

Body:
Scanner.next*() reads a stream until the next delimiter (the default is defined in Character.isWhitespace).  When you call nextInt() it reads the next delimiter and then attempts to parse it as an int, if it is not then you get an InputMixmatchException.  You can define your own delimiter like this (using an escaped regegex for <space>-<space>):

new Scanner(input).useDelimiter("\\s-\\s");

Then you would need to call .next() to skip over the parts of each line that you aren't parsing.

Now that last line of your example shows a hyphen directly following the publisher (without space).  This fix might require more work over more data (such as book titles with hyphens in them).  Hopefully, this gets you unstuck.


问:
Why is '[f x[1]]' ungrammatical while '[1 + x[1]]' is?
For an Array x, the following are grammatical expressions:

puts x[1]

[puts(x[1])]

[1 + x[1]]

but this:

[puts x[1]]

fails to parse with:

```<code>syntax error, unexpected tIDENTIFIER, expecting keyword_do or '{' or '('
</code>```

Why can't the parser figure out this syntax?

答:
In Ruby you can often, but not always omit the parentheses around method calls. You've found a case where you can't. Sometimes there's too much ambiguity for Ruby to understand exactly what you want and you must be more specific.

The valid notation here is:

```<code>[puts(x[1])]
</code>```

Though as puts always returns nil, this is really an odd thing to do.

Body:
For an Array x, the following are grammatical expressions:

puts x[1]

[puts(x[1])]

[1 + x[1]]

but this:

[puts x[1]]

fails to parse with:

syntax error, unexpected tIDENTIFIER, expecting keyword_do or '{' or '('

Why can't the parser figure out this syntax?

Body:
In Ruby you can often, but not always omit the parentheses around method calls. You've found a case where you can't. Sometimes there's too much ambiguity for Ruby to understand exactly what you want and you must be more specific.

The valid notation here is:

[puts(x[1])]

Though as puts always returns nil, this is really an odd thing to do.


问:
Bean Validation - JSR-303 DuplicateItemCheck for a list in java
Is there any standard bean validation annotation to check duplicate item in a collection in java.
or Anyone implemented custom validation to check duplicate in a list using bean validation.

for example

```<code>

    public class MySecurityRequest{
        private Date dob;

        @DuplicateNotAllowed
        private List securityQuestions;
    }

    public class SecurityQuestion{
      private String question;
      private String answer;
    }

</code>```

Here i need to make sure that, questions are not repeated in the list.
Are one faced this similar issue?

答: Use a Set. And override and implement hashcode() and equals() methods on your SecurityQuestion class to help the Set identify duplicates. </p>

Body:
Is there any standard bean validation annotation to check duplicate item in a collection in java.
or Anyone implemented custom validation to check duplicate in a list using bean validation.

for example

    public class MySecurityRequest{
        private Date dob;

        @DuplicateNotAllowed
        private List securityQuestions;
    }

    public class SecurityQuestion{
      private String question;
      private String answer;
    }

Here i need to make sure that, questions are not repeated in the list.
Are one faced this similar issue?


问:
Filtering instances by IAM role in boto3?
Is there a way to filter instances by IAM role?
Basically I want a script that terminates all the instances that I've launched, but doesn't touch instances launched with other IAM roles.</p>

答:
Method 1:

If it is just a one-time activity, you can consider using aws-cli itself.

Use the below aws-cli command to list all instances with a particular IAM Role.

```<code>aws ec2 describe-instances --region us-east-1 --query 'Reservations[*].Instances[?IamInstanceProfile.Arn==`<Enter you Instance Profile ARN here>`].{InstanceId: InstanceId}' --output text
</code>```

Replace <Enter you Instance Profile ARN here> with the Instance Profile Arn.

NOTE:
You must enter the Instance Profile Arn and NOT the Role ARN.

Instance Profile Arn will be of the form:

arn:aws:iam::xxxxxxxxxxxx:instance-profile/Profile-ASDNSDLKJ

You can then pass the list of Instance-id's returned above to the terminate-instance cli command. The instance-ids must be separated by spaces.

aws ec2 terminate-instances --instance-ids i-1234567890abcdef0 i-1234567890jkefpq1

Method 2:

```<code>import boto3

client = boto3.client('ec2',region_name='us-east-1')
response = client.describe_instances(
    Filters=[
        {
            'Name': 'iam-instance-profile.arn',
            'Values': [
                'arn:aws:iam::1234567890:instance-profile/MyProfile-ASDNSDLKJ',
            ]
        },
    ]
)
terminate_instance_list = []
for resp in response['Reservations']:
  for inst in resp['Instances']:
    #print inst['InstanceId']
    terminate_instance_list.append(inst['InstanceId'])

#print(terminate_instance_list)
if terminate_instance_list:
    response = client.terminate_instances(
        InstanceIds=terminate_instance_list
    )
    print(response)
</code>```

Body:
Method 1:

If it is just a one-time activity, you can consider using aws-cli itself.

Use the below aws-cli command to list all instances with a particular IAM Role.

aws ec2 describe-instances --region us-east-1 --query 'Reservations[*].Instances[?IamInstanceProfile.Arn==`<Enter you Instance Profile ARN here>`].{InstanceId: InstanceId}' --output text

Replace <Enter you Instance Profile ARN here> with the Instance Profile Arn.

NOTE:
You must enter the Instance Profile Arn and NOT the Role ARN.

Instance Profile Arn will be of the form:

arn:aws:iam::xxxxxxxxxxxx:instance-profile/Profile-ASDNSDLKJ

You can then pass the list of Instance-id's returned above to the terminate-instance cli command. The instance-ids must be separated by spaces.

aws ec2 terminate-instances --instance-ids i-1234567890abcdef0 i-1234567890jkefpq1

Method 2:

import boto3

client = boto3.client('ec2',region_name='us-east-1')
response = client.describe_instances(
    Filters=[
        {
            'Name': 'iam-instance-profile.arn',
            'Values': [
                'arn:aws:iam::1234567890:instance-profile/MyProfile-ASDNSDLKJ',
            ]
        },
    ]
)
terminate_instance_list = []
for resp in response['Reservations']:
  for inst in resp['Instances']:
    #print inst['InstanceId']
    terminate_instance_list.append(inst['InstanceId'])

#print(terminate_instance_list)
if terminate_instance_list:
    response = client.terminate_instances(
        InstanceIds=terminate_instance_list
    )
    print(response)


问:
How to publish a component written in typescript consumable as a global, commonjs, or typescript module
I have written a simple component in typescript which has a dependency on d3. I would like to publish this component on npm and have it be usable as a global, a commonjs module, or a typescript module. The component looks something like this:

```<code>/// <reference types="d3" />
class MyAwesomeComponent {
  data(data: IMyDataFormat) {
    // set data, etc.
  }
  render() {
    // do stuff with d3
  }
}
interface IMyDataFormat {
  // keys/types
}
</code>```

My tsconfig.json file currently looks like this:

```<code>{
  "compilerOptions": {
    "module": "none",
    "target": "es5",
    "noImplicitAny": true,
    "removeComments": true,
    "preserveConstEnums": true,
    "declaration": true,
    "outFile": "./dist/index.js",
    "sourceMap": true
  },
  "include": [
    "./src/**/*.ts"
  ]
}
</code>```

When I run tsc with this config, I get a file which works in the global context, so this would work for a consumer:

```<code><script src="./d3.js"></script>
<script src="./my-awesome-component.js"></script>
<script>
  var chart = new MyAwesomeComponent();
  chart.data([/* ... */]);
  chart.render();
</script>
</code>```

How do I set up my project (e.g. with alternate tsconfig files or small changes to the source files etc) so that it is consumable in a commonJS environment (i.e. webpack or browserify), as well as in a typescript project environment?

Here is what I am expecting to work for the commonJS environment:

```<code>const MyAwesomeComponent = require('my-awesome-component');
// this would also be fine:
const MyAwesomeComponent = require('my-awesome-component').MyAwesomeComponent;
</code>```

Here is what I am expecting to work for the TypeScript environment:

```<code>import {MyAwesomeComponent, IMyDataFormat} from 'my-awesome-component';
</code>```

Thanks!

答:
I have published a boilerplate example to npmjs.org.

The package is called stackoverflow-47210046.

I have also created a GitHub repository with the source.

The main documentation with some steps are available there but here a few remarks too:

Make sure you have added "dom" to the libraries in the tsconfig.json to include them during the compilation. (This is not required in general, but the question was about consuming d3 in a boilerplate TS package.)

Add "main": "lib/index" to the package.json. You can see, it points to the compiled output and has no file extension.

Adde "typings": "lib/index" to the package.json.

Although the lib output folder is not added to version control, that will be available on npmjs.org.

The tests will be executed with ts-node so the tsc compilation can be omitted.

If you want to run your test in watch mode, execute npm run test -- -w.

If you want to run your tsc compiler in watch mode, execute npm run build -- -w.

I hope this helps, if you have any questions, just post it here, or submit a new issue on GitHub.

Cheers.

Body:
I have written a simple component in typescript which has a dependency on d3. I would like to publish this component on npm and have it be usable as a global, a commonjs module, or a typescript module. The component looks something like this:

/// <reference types="d3" />
class MyAwesomeComponent {
  data(data: IMyDataFormat) {
    // set data, etc.
  }
  render() {
    // do stuff with d3
  }
}
interface IMyDataFormat {
  // keys/types
}

My tsconfig.json file currently looks like this:

{
  "compilerOptions": {
    "module": "none",
    "target": "es5",
    "noImplicitAny": true,
    "removeComments": true,
    "preserveConstEnums": true,
    "declaration": true,
    "outFile": "./dist/index.js",
    "sourceMap": true
  },
  "include": [
    "./src/**/*.ts"
  ]
}

When I run tsc with this config, I get a file which works in the global context, so this would work for a consumer:

How do I set up my project (e.g. with alternate tsconfig files or small changes to the source files etc) so that it is consumable in a commonJS environment (i.e. webpack or browserify), as well as in a typescript project environment?

Here is what I am expecting to work for the commonJS environment:

const MyAwesomeComponent = require('my-awesome-component');
// this would also be fine:
const MyAwesomeComponent = require('my-awesome-component').MyAwesomeComponent;

Here is what I am expecting to work for the TypeScript environment:

import {MyAwesomeComponent, IMyDataFormat} from 'my-awesome-component';

Thanks!


问:
How get data back out of a (PHP) shell script
I'm running a PHP script in a larger shell script by doing

```<code>php -f $filename > `basename $filename .php`.html
</code>```

Now I would like to let the script tell me which file extension to use for the output file name. I tried

```<code>export AW_FILENAME_SUFFIX=".html"
php -f $filename > `basename $filename .php`$AW_FILENAME_SUFFIX
</code>```

and a putenv("AW_FILENAME_SUFFIX=.txt") in the script itself, but it seems that only changes the environment the PHP command and its subprocesses run in, not the one of the calling script.

Is there another way to get data out of my script besides the output that I can use for metadata like that, or writing to a second file?

I will run several scripts, which AFAIK means I can't really source them into mine, that might give me duplicate function errors.

答:
You can do the writing in your PHP script. So that is:

```<code><?php
$ext = '.txt';
$filename = $argv[1].$ext;
ob_start();
    // my script
$data = ob_get_clean();
file_put_contents($data, $filename);
</code>```

and then from the shell you can call like:

```<code>php -f $scriptname $dumpfile
</code>```

Body:
I'm running a PHP script in a larger shell script by doing

php -f $filename > `basename $filename .php`.html

Now I would like to let the script tell me which file extension to use for the output file name. I tried

export AW_FILENAME_SUFFIX=".html"
php -f $filename > `basename $filename .php`$AW_FILENAME_SUFFIX

and a putenv("AW_FILENAME_SUFFIX=.txt") in the script itself, but it seems that only changes the environment the PHP command and its subprocesses run in, not the one of the calling script.

Is there another way to get data out of my script besides the output that I can use for metadata like that, or writing to a second file?

I will run several scripts, which AFAIK means I can't really source them into mine, that might give me duplicate function errors.

Body:
You can do the writing in your PHP script. So that is:

<?php
$ext = '.txt';
$filename = $argv[1].$ext;
ob_start();
    // my script
$data = ob_get_clean();
file_put_contents($data, $filename);

and then from the shell you can call like:

php -f $scriptname $dumpfile


问:
is it possible to access value from a model databasetable in the application.html.erb?
im trying to make a app

with users
this users can join multiple groups - every group has the same menu on the page
their group page is accessable about group/1 or group/2

so i wanted to put the the menu in the application.html.erb, with lnks depending on the group.id - but i dont know how to acces this id in the application.html.erb

答:
The correct approach would be to set this in ApplicationController via before_filter and just use it as an instance variable in views.

So in controller set something like @links = some logic where you calculate your links based on current user.

In view you do something like:

```<code><ul>
  <%- for link in @links -%>
    <li><%= link.title =>
  <%- end -%.
</ul>
</code>```

Of course, you set your @links in ApplicationController only if you want your links to be available to all your controllers/views, which I think you do.

Rails Cells could also be used here http://cells.rubyforge.org/

Body:
The correct approach would be to set this in ApplicationController via before_filter and just use it as an instance variable in views.

So in controller set something like @links = some logic where you calculate your links based on current user.

In view you do something like:

<ul>
  <%- for link in @links -%>
    <li><%= link.title =>
  <%- end -%.
</ul>

Of course, you set your @links in ApplicationController only if you want your links to be available to all your controllers/views, which I think you do.

Rails Cells could also be used here http://cells.rubyforge.org/


问:
Spring Boot Program cannot find main class
I have a program which runs as a Spring boot App in eclipse. The program was running fine. Then i did the following:

Right click on project ->  Run As -> Maven Test .

This was accidental. When i then tried to run the program as a spring boot app again, it threw the following error below.

Error: Could not find or load main class com.bt.collab.alu.api.webapp.Application

How do i point the application back to my main class?
Thanks

答:
deleting old jars from .m2 and updating maven project should be primary step.
In most of the cases it resolves the issue.The reason for this issue is mostly corrupted old jars</p>


问:
ios saving and retrieving NSNumber from NSUserdefaults
I've searched but I can't find a good explanation as to why I'm still not getting the right value from my saved Integer.

This is how I saved my event Id.

```<code>NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setInteger:eventSelected.eventId forKey:@"currentEvent"];
</code>```

This is how I'm trying to retrieve it.

```<code>NSLog(@"user dfault %@", [NSNumber numberWithUnsignedInt:[[[NSUserDefaults standardUserDefaults] objectForKey:@"currentEvent"] unsignedIntegerValue]]);
</code>```

I'm gettin gthis.

user dfault 123581200

Also, to note, event if I did intValue instead of unsignedIntegerValue , it would still give me a random id number. was wondering what I'm doing wrong.

答:
```<code>NSNumber *number;
</code>```

store:

```<code>[[NSUserDefaults standardUserDefaults] setValue:number forKey:@"Number"];
</code>```

retrieving:

```<code>number = [NSNumber numberWithInteger:[[NSUserDefaults standardUserDefaults] integerForKey:@"Number"]];
</code>```

Body:
I've searched but I can't find a good explanation as to why I'm still not getting the right value from my saved Integer.

This is how I saved my event Id.

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setInteger:eventSelected.eventId forKey:@"currentEvent"];

This is how I'm trying to retrieve it.

NSLog(@"user dfault %@", [NSNumber numberWithUnsignedInt:[[[NSUserDefaults standardUserDefaults] objectForKey:@"currentEvent"] unsignedIntegerValue]]);

I'm gettin gthis.

user dfault 123581200

Also, to note, event if I did intValue instead of unsignedIntegerValue , it would still give me a random id number. was wondering what I'm doing wrong.

Body:
NSNumber *number;

store:

[[NSUserDefaults standardUserDefaults] setValue:number forKey:@"Number"];

retrieving:

number = [NSNumber numberWithInteger:[[NSUserDefaults standardUserDefaults] integerForKey:@"Number"]];


问:
Javascript file not including inside html page
I'm trying to use JQuery inside a ASP.NET MVC practice project but the site.js file not working or including inside html page. If I write JQuery code inside script tag in html then it's working fine, Even I have included some other files like Bootstrap and site.css that also working only problem with site.js file.

Site.js

```<code>$(document).ready(function () {
    alert("Hello 1");
});

$(window).load(function () {
    alert("Hello 2");
});
</code>```

_Layout.cshtml

Including snippet

```<code><script src="~/lib/jquery/dist/jquery.min.js" type="text/javascript"></script>
<script src="~/js/site.js" type="text/javascript"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js" type="text/javascript"></script>
</code>```

答:
your source is starting from lib and js folder. if  your js folder is in your content folder than please use content after tilt sign</p>

```<code><script src="~/Content/lib/jquery/dist/jquery.min.js" type="text/javascript"></script>
</code>```

Body:
I'm trying to use JQuery inside a ASP.NET MVC practice project but the site.js file not working or including inside html page. If I write JQuery code inside script tag in html then it's working fine, Even I have included some other files like Bootstrap and site.css that also working only problem with site.js file.

Site.js

$(document).ready(function () {
    alert("Hello 1");
});

$(window).load(function () {
    alert("Hello 2");
});

_Layout.cshtml

Including snippet

Body:
your source is starting from lib and js folder. if  your js folder is in your content folder than please use content after tilt sign

<script src="~/Content/lib/jquery/dist/jquery.min.js" type="text/javascript"></script>


问:
How to create a column that present the delta if it's greater than a specific number from two columns that each one of them is from a different table
I have two tables,

table1:

```<code>  ID  |  Value1  |  Value2
----------------------------
   1  |   152    |   187
   2  |   348    |   457
   3  |   214    |   192
</code>```

table2:

```<code>  ID  |  Value1  |  Value2
----------------------------
   1  |   196    |   242
   2  |   233    |   132
   3  |   451    |   121
</code>```

I want to create a query to select or create a new temporary table that will contains the id and the values columns if the delta between them is greater than 50,

so it should be:

```<code>if table1.Value1 - table2.Value1 >= 50 or table2.Value1 - table1.Value1 >= 50
</code>```

Then I want the delta value to be presented as Value1 and the same for Value2,

Your help would be appreciated,

Thank you.

答:
I suppose you want something like this:

```<code>select t1.*, t2.*
from t1 join
     t2
     on t1.id = t2.id
where abs(t1.value1 - t2.value1) >= 50;
</code>```

With this, you should be able to add in the difference in the SELECT and any similar conditions you also want on value2.

Body:
I have two tables,

table1:

  ID  |  Value1  |  Value2
----------------------------
   1  |   152    |   187
   2  |   348    |   457
   3  |   214    |   192

table2:

  ID  |  Value1  |  Value2
----------------------------
   1  |   196    |   242
   2  |   233    |   132
   3  |   451    |   121

I want to create a query to select or create a new temporary table that will contains the id and the values columns if the delta between them is greater than 50,

so it should be:

if table1.Value1 - table2.Value1 >= 50 or table2.Value1 - table1.Value1 >= 50

Then I want the delta value to be presented as Value1 and the same for Value2,

Your help would be appreciated,

Thank you.

Body:
I suppose you want something like this:

select t1.*, t2.*
from t1 join
     t2
     on t1.id = t2.id
where abs(t1.value1 - t2.value1) >= 50;

With this, you should be able to add in the difference in the SELECT and any similar conditions you also want on value2.


问:
Assertion Failure in UICollectionViewData validateLayoutInRect on ios7
Assertion Failure in UICollectionViewData validateLayoutInRect on iOS7.

I am trying to delete all UICollectionView items, one by one, using a for loop; I posted my code below. I delete the UICollectionView items using deleteItemsAtIndexPaths. It's working perfectly on iOS6, but crashes in iOS7 with this exception:

Assertion Failure in UICollectionViewData validateLayoutInRect

I delete the object from collectionArray then self.collectionView, one by one, using indexPath. When I delete the 4th object its raises Assertion failure on iOS7. Here I am using performBatchUpdates.

Please help me get the proper result in iOS7. Share proper code.
Thanks in advance.

```<code>try  {
    for (int i=count-1; i>=0; i--)  {
        [self.collectionView performBatchUpdates:^(void){
            [collectionArray removeObjectAtIndex:i]; // First delete the item from you model
            [self.collectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:i inSection:0]]];
        } completion:nil];
        [self.collectionView reloadData];
    }
}
@catch (NSException *exception) {
}
@finally {
}
</code>```

答:
In my case following delegate was missing:</p>

```<code>func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
</code>```

Body:
Assertion Failure in UICollectionViewData validateLayoutInRect on iOS7.

I am trying to delete all UICollectionView items, one by one, using a for loop; I posted my code below. I delete the UICollectionView items using deleteItemsAtIndexPaths. It's working perfectly on iOS6, but crashes in iOS7 with this exception:

Assertion Failure in UICollectionViewData validateLayoutInRect

I delete the object from collectionArray then self.collectionView, one by one, using indexPath. When I delete the 4th object its raises Assertion failure on iOS7. Here I am using performBatchUpdates.

Please help me get the proper result in iOS7. Share proper code.
Thanks in advance.

try  {
    for (int i=count-1; i>=0; i--)  {
        [self.collectionView performBatchUpdates:^(void){
            [collectionArray removeObjectAtIndex:i]; // First delete the item from you model
            [self.collectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:i inSection:0]]];
        } completion:nil];
        [self.collectionView reloadData];
    }
}
@catch (NSException *exception) {
}
@finally {
}

Body:
In my case following delegate was missing:

func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }


问:
For-loop with string possible?
I need something like this. Is it possible in Java?</p>

```<code>    for(String i = "A"; i < "Z"; i++) {

        System.out.println(i);
    }
</code>```

答:
You can do it by:</p>

```<code>for (char alphabet = 'A'; alphabet <= 'Z'; alphabet++) {
    System.out.println(alphabet);
}
</code>```

Title: For-loop with string possible?

Body:
I need something like this. Is it possible in Java?

    for(String i = "A"; i < "Z"; i++) {

        System.out.println(i);
    }

Body:
You can do it by:

for (char alphabet = 'A'; alphabet <= 'Z'; alphabet++) {
    System.out.println(alphabet);
}


问:
Angular 5 + NodeJS+ MongoDB - How to implement voice/speech recording and playback
I am creating an Angular 5 application, with a nodejs and mongodb backend.

A feature needs to be implemented to allow a user to record their speech on a page. Later the speech will need to be played back on a different page, therefore it should be saved.

What can i use to record a users voice via their microphone in the browser?.

How do i store this recording? e.g in a mongodb?

答:
I developed the same functionality half year ago. Except it was .NET on the backend and Angular 1.x on the frontend. I've used getUserMedia on the client with the help of the following articles:

http://typedarray.org/from-microphone-to-wav-with-getusermedia-and-web-audio/

http://typedarray.org/from-microphone-to-wav-to-server/

There's big chunks of code which you will need to adopt for your specific case.
In general I'd suggest to getUserMedia on the client, then convert in to wav on the client and upload this Blob to the server. Then you can save this file on the server and store path to it in MongoDB. I believe this will be the most efficient way. Another option will be to convert this wav to base64 and store in DB as string, but it's not the best idea, since this will be dramatically big string.


问:
How would I toggle an animation at runtime in React Native using Lottie?
I'm trying to create a save button (basically to bookmark a screen) that toggles animation whether a user taps the button to "save" an item or remove the "save". Tapping the button should call one of the animations whether it's the "on" animation or the "off" animation.

Unfortunately besides iOS I can't find any documentation on toggling an animation on a button in React Native. Any ideas would be appreciated.

Here's the component:

```<code>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
    StyleSheet,
    TouchableOpacity
} from 'react-native';
import _ from 'lodash';

import { connect } from 'react-redux';
import { toggleSaved } from '../../actions';
import Animation from 'lottie-react-native';

import onAnimation from '../animations/heart_On.json';
import offAnimation from '../animations/heart_Off.json';

class SaveButton extends Component {
    isSaved = () => {
        let item = this.props.item;
        if (_.find(this.props.saved, function(i) { return i.type == item.type && i.id == item.id; })) {
            return true;
        } else {
            return false;
        }
    }

    toggleSaved = (saved, item) => {
        const { dispatch } = this.props;
        dispatch(toggleSaved(saved, item));
        this.animation.play();
    }

    render() {
        return (
            <TouchableOpacity
                onPress={ () => this.toggleSaved(this.props.saved, this.props.item) }
            >
                <Animation
                    ref={ animation => {
                        this.animation = animation;
                    } }
                    style={ styles.icon }
                    loop={ false }
                    source={ this.isSaved() ? onAnimation: offAnimation }
                />
            </TouchableOpacity>
        );
    }
}

SaveButton.propTypes = {
    dispatch: PropTypes.func.isRequired,
    saved: PropTypes.array.isRequired,
    item: PropTypes.object.isRequired
};

const styles = StyleSheet.create({
    icon: {
        width: 30,
        height: 30,
        marginTop: 5,
        marginRight: 10
    }
});

function mapStateToProps(state) {
    const { saved } = state.saved;

    return {
        saved
    };
}

export default connect(mapStateToProps)(SaveButton);
</code>```

答:
I'd suggest you to have two separate animation elements and then, depending on the state, show or hide (and of course .play()) them accordingly.

So (code in half-pseudo to get the idea):

state prop like isSaved, which defines which animation is currently on stage,

when saving (or removing) toggle the state to show correct animation and call the this.refToCorrectAnimation.play().

```<code>constructor(props) {
  super(props);
  this.state = {
    isSaved: false,
  };
}

isSavedVisible() {
  return (this.state.isSaved) ? { display: 'flex' } : { display: 'none' };
}

isRemovedVisible() {
  return (!this.state.isSaved) ? { display: 'flex' } : { display: 'none' };
}

toggleSaved(...) {
  if (this.state.isSaved) {
    this.isSavedAnimation.play();
  } else {
    this.isRemovedAnimation.play();
}

render() {
  return (
    <TouchableOpacity onPress={() => this.toggleSaved()} ...>
      <Animation style={this.isSavedVisible()} ref={(animation) = this.isSavedAnimation = animation} ... />
      <Animation style={this.isRemovedVisible()} ref={(animation) = this.isRemovedAnimation = animation} ... />
    </TouchableOpacity>
  )
}
</code>```

Body:
I'm trying to create a save button (basically to bookmark a screen) that toggles animation whether a user taps the button to "save" an item or remove the "save". Tapping the button should call one of the animations whether it's the "on" animation or the "off" animation.

Unfortunately besides iOS I can't find any documentation on toggling an animation on a button in React Native. Any ideas would be appreciated.

Here's the component:

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
    StyleSheet,
    TouchableOpacity
} from 'react-native';
import _ from 'lodash';

import { connect } from 'react-redux';
import { toggleSaved } from '../../actions';
import Animation from 'lottie-react-native';

import onAnimation from '../animations/heart_On.json';
import offAnimation from '../animations/heart_Off.json';

class SaveButton extends Component {
    isSaved = () => {
        let item = this.props.item;
        if (_.find(this.props.saved, function(i) { return i.type == item.type && i.id == item.id; })) {
            return true;
        } else {
            return false;
        }
    }

    toggleSaved = (saved, item) => {
        const { dispatch } = this.props;
        dispatch(toggleSaved(saved, item));
        this.animation.play();
    }

    render() {
        return (
            <TouchableOpacity
                onPress={ () => this.toggleSaved(this.props.saved, this.props.item) }
            >
                <Animation
                    ref={ animation => {
                        this.animation = animation;
                    } }
                    style={ styles.icon }
                    loop={ false }
                    source={ this.isSaved() ? onAnimation: offAnimation }
                />
            </TouchableOpacity>
        );
    }
}

SaveButton.propTypes = {
    dispatch: PropTypes.func.isRequired,
    saved: PropTypes.array.isRequired,
    item: PropTypes.object.isRequired
};

const styles = StyleSheet.create({
    icon: {
        width: 30,
        height: 30,
        marginTop: 5,
        marginRight: 10
    }
});

function mapStateToProps(state) {
    const { saved } = state.saved;

    return {
        saved
    };
}

export default connect(mapStateToProps)(SaveButton);

Body:
I'd suggest you to have two separate animation elements and then, depending on the state, show or hide (and of course .play()) them accordingly.

So (code in half-pseudo to get the idea):

state prop like isSaved, which defines which animation is currently on stage,

when saving (or removing) toggle the state to show correct animation and call the this.refToCorrectAnimation.play().

constructor(props) {
  super(props);
  this.state = {
    isSaved: false,
  };
}

isSavedVisible() {
  return (this.state.isSaved) ? { display: 'flex' } : { display: 'none' };
}

isRemovedVisible() {
  return (!this.state.isSaved) ? { display: 'flex' } : { display: 'none' };
}

toggleSaved(...) {
  if (this.state.isSaved) {
    this.isSavedAnimation.play();
  } else {
    this.isRemovedAnimation.play();
}

render() {
  return (
    <TouchableOpacity onPress={() => this.toggleSaved()} ...>
      <Animation style={this.isSavedVisible()} ref={(animation) = this.isSavedAnimation = animation} ... />
      <Animation style={this.isRemovedVisible()} ref={(animation) = this.isRemovedAnimation = animation} ... />
    </TouchableOpacity>
  )
}


问:
merge arrays and convert to JSON string
I have two arrays consist of strings
["25","36","32"] and ["GradeA", "GradeB", "GradeC"]

I want to merge them all together and want to produce JSON string something like this:

{"GradeA" : "25", "GradeB" : "36", "GradeC": "32"}

How do I do this in js?

答:
Try like this</p>

```<code>var keys =["GradeA", "GradeB", "GradeC"];
var values= ["25","36","32"];
var obj = {};
for(var i=0; i< keys.length; i++){
    if(values.length>i+1){
         obj[keys[i]] = values[i];
     }else{
         obj[keys[i]] = null;
     }
}
console.log(obj);
</code>```

Title: merge arrays and convert to JSON string

Body:
Try like this

var keys =["GradeA", "GradeB", "GradeC"];
var values= ["25","36","32"];
var obj = {};
for(var i=0; i< keys.length; i++){
    if(values.length>i+1){
         obj[keys[i]] = values[i];
     }else{
         obj[keys[i]] = null;
     }
}
console.log(obj);


问:
Version mismatch between H2O and R package, where to get the right one?
I am using H2O (basic version) and it works well. I want to try Deep Water for GPU support. So, I carefully followed the instruction on;
https://www.h2o.ai/deep-water/#try
to install Deep Water. However, it failed to run and showed this error:

Error in h2o.init(nthreads = -1, port = 54323, startH2O = FALSE) :
        Version mismatch! H2O is running version 3.15.0.393 but h2o-R package is version 3.13.0.369.
               Install the matching h2o-R version from - http://h2o-release.s3.amazonaws.com/h2o/(HEAD detached at c46596cad)

Where do I get the right version?

答:
you can force the Connection

h2o.init(ip=Cluster_ip, port = Cluster_port,

strict_version_check = FALSE,

startH2O = FALSE)


问:
Use two different AWS resources hosted in two different regions in AWS Lambda?
I want to use my "Dynamodb DocumentClient" which is hosted in 'us-west-2' region and SES which is hosted in 'us-west-1' region, in one lambda function. How can I do it?</p>

答:
When you initialize an AWS SDK client you can specify the region for the client to use, like this:</p>

```<code>var ses = new AWS.SES({region: 'us-west-1'});
var documentClient = new AWS.DynamoDB.DocumentClient({region: 'us-west-2'})
</code>```

Body:
When you initialize an AWS SDK client you can specify the region for the client to use, like this:

var ses = new AWS.SES({region: 'us-west-1'});
var documentClient = new AWS.DynamoDB.DocumentClient({region: 'us-west-2'})


问:
Making a new list with tuples based on strings in the list
```<code>L = ["5", "0 1", "0 2", "1 3", "2 3", "2 4", "3 4"]
</code>```

Each number represents a person. So, there are five people from 0 to 4 in the list. L[0] always shows how many people are in the list.

```<code>L1 = [(0,[1,2]), (1, [3]), (2, [3,4]), (3, [4])]
</code>```

The person "0" is paired with 1 and 2. So, it has a list of 1, 2 in a tuple. My approach to get the result above is to compare the first character in L[1] to the end of the list. If the first letter in L[1] matches with the first letter in L[2], it bundles the second letter in L[2] with the second letter in L[1]. Finally, the new list is paired with 0 in a tuple. By the way, I cannot come up with such thing that can check the first letter in strings. I am not sure if this approach is right or not.

I am struggling to make such list L1 above. Could anyone let me know if my approach to this question is right? If it is wrong, please briefly give me a hint to solve this.

答:
Here is an itertools.groupy solution. (The commented out line also considers reverse pairs.)

```<code>import itertools as it
import operator as op

def L1(L):
    # split pairs
    L = [p.split() for p in L[1:]]
    # convert to int
    L = [(int(P1), int(P2)) for P1, P2 in L]
    LL = sorted(L)
#    # add reversed and sort
#    LL = sorted(L + [P[::-1] for P in L])
    # group by first element
    res = it.groupby(LL, op.itemgetter(0))
    # make proper lists
    return [(k, [P[1] for P in v]) for k, v in res]
</code>```

Output (for the example L):

```<code>[(0, [1, 2]), (1, [3]), (2, [3, 4]), (3, [4])]
</code>```

Body:
L = ["5", "0 1", "0 2", "1 3", "2 3", "2 4", "3 4"]

Each number represents a person. So, there are five people from 0 to 4 in the list. L[0] always shows how many people are in the list.

L1 = [(0,[1,2]), (1, [3]), (2, [3,4]), (3, [4])]

The person "0" is paired with 1 and 2. So, it has a list of 1, 2 in a tuple. My approach to get the result above is to compare the first character in L[1] to the end of the list. If the first letter in L[1] matches with the first letter in L[2], it bundles the second letter in L[2] with the second letter in L[1]. Finally, the new list is paired with 0 in a tuple. By the way, I cannot come up with such thing that can check the first letter in strings. I am not sure if this approach is right or not.

I am struggling to make such list L1 above. Could anyone let me know if my approach to this question is right? If it is wrong, please briefly give me a hint to solve this.

Body:
Here is an itertools.groupy solution. (The commented out line also considers reverse pairs.)

import itertools as it
import operator as op

def L1(L):
    # split pairs
    L = [p.split() for p in L[1:]]
    # convert to int
    L = [(int(P1), int(P2)) for P1, P2 in L]
    LL = sorted(L)
#    # add reversed and sort
#    LL = sorted(L + [P[::-1] for P in L])
    # group by first element
    res = it.groupby(LL, op.itemgetter(0))
    # make proper lists
    return [(k, [P[1] for P in v]) for k, v in res]

Output (for the example L):

[(0, [1, 2]), (1, [3]), (2, [3, 4]), (3, [4])]


问:
Symfony EntityType - How to use custom layout?
In my Symfony 3.x project, I have 3 entities:

Project

Property

Category

Assumptions:

Each Project has multiple Properties.

Each Property has one Category.

Each Property might have parent Property.

I would like to render Symfony form for Project entity. I'm using EntityType field for properties. However, instead of displaying them in one, long list, I would like to divide them in columns, with Categories as headers.

Regular way of displaying EntityType field:

What I would like to get:

How do I do that? - Without using dirty hacks in entities or views.

答:
So the only way I found it working was:

In Repository class (pulling list of all properties with child properties and categories):

```<code>$this->getEntityManager()
    ->createQueryBuilder()
    ->select('t, category, children')
    ->join('t.category', 'category')
    ->leftJoin('t.children', 'children')
    ->where('t.parent IS NULL')
    ->orderBy('category.sortOrder', 'ASC')
    ->addOrderBy('t.sortOrder', 'ASC')
    ->addOrderBy('t.name', 'ASC');

$entities = $query->getResult();

$options = [];
/** @var Property $entity */
foreach ($entities as $entity) {
    $options[$entity->getCategory()->getName()][] = $entity;
}
</code>```

In Entity class (pulling the list of IDs of selected properties, to preselect checkboxes in the view file):

```<code>public function getPropertyIds() {
    $properties = $this->getProperties();

    $propertyIds = [];
    foreach ($properties as $property) {
        $propertyIds[] = $property->getId();
    }

    return $propertyIds;
}
</code>```

Edition form class, so the data can be validated:

```<code>$builder
    ->add(
        'properties',
        EntityType::class,
        [
            'label' => 'Properties',
            'class' => Property::class,
            'choice_label' => 'name',
            'placeholder' => '',
            'expanded' => true,
            'multiple' => true,
            'required' => false,
        ]
    );
</code>```

And finally, the view file:

```<code>{% for categoryName, items in properties %}
    <h2>{{ categoryName }}</h2>

    <ul>
        {% for property in items %}
            <li>
                <input type="checkbox"
                       name="{{ form.properties.vars.full_name }}[]"
                       value="{{ property.id }}"
                       id="{{ form.properties.vars.id }}_{{ property.id }}">
                <label for="{{ form.properties.vars.id }}_{{ property.id }}">
                    {{ property.name }}
                </label>
            </li>
        {% endfor %}
    </ul>
{% endfor %}

{% do form.properties.setRendered %}
</code>```

(I omitted the "checked" and "children" part in the view)

However this solution is not ideal in my point of view. I would rather to get rid of manually generating <input...> in the view - I would rather want to use some helper functions.

Anyway, this is some kind of low-level solution to my problem. Hope that helps.

Body:
So the only way I found it working was:

In Repository class (pulling list of all properties with child properties and categories):

$this->getEntityManager()
    ->createQueryBuilder()
    ->select('t, category, children')
    ->join('t.category', 'category')
    ->leftJoin('t.children', 'children')
    ->where('t.parent IS NULL')
    ->orderBy('category.sortOrder', 'ASC')
    ->addOrderBy('t.sortOrder', 'ASC')
    ->addOrderBy('t.name', 'ASC');

$entities = $query->getResult();

$options = [];
/** @var Property $entity */
foreach ($entities as $entity) {
    $options[$entity->getCategory()->getName()][] = $entity;
}

In Entity class (pulling the list of IDs of selected properties, to preselect checkboxes in the view file):

public function getPropertyIds() {
    $properties = $this->getProperties();

    $propertyIds = [];
    foreach ($properties as $property) {
        $propertyIds[] = $property->getId();
    }

    return $propertyIds;
}

Edition form class, so the data can be validated:

$builder
    ->add(
        'properties',
        EntityType::class,
        [
            'label' => 'Properties',
            'class' => Property::class,
            'choice_label' => 'name',
            'placeholder' => '',
            'expanded' => true,
            'multiple' => true,
            'required' => false,
        ]
    );

And finally, the view file:

{% for categoryName, items in properties %}
    <h2>{{ categoryName }}</h2>

    <ul>
        {% for property in items %}
            <li>
                <input type="checkbox"
                       name="{{ form.properties.vars.full_name }}[]"
                       value="{{ property.id }}"
                       id="{{ form.properties.vars.id }}_{{ property.id }}">
                <label for="{{ form.properties.vars.id }}_{{ property.id }}">
                    {{ property.name }}
                </label>
            </li>
        {% endfor %}
    </ul>
{% endfor %}

{% do form.properties.setRendered %}

(I omitted the "checked" and "children" part in the view)

However this solution is not ideal in my point of view. I would rather to get rid of manually generating <input...> in the view - I would rather want to use some helper functions.

Anyway, this is some kind of low-level solution to my problem. Hope that helps.


问:
Regex infitine capture groups after a specific string
I have a bot that takes a number of different commands and I'm trying scale it's ability to take arguments for all these commands.

This is the syntax:

```<code>!action db_table mandatory_arg arg1 arg2 arg3...
</code>```

Right now I have this functional but un-scalable regex for processing commands:

```<code>^!(\S*)\s?(\S*)\s?(\S*)\s?(\S*)\s?(\S*)\s?(\S*)\s?(\S*)\s?(\S*)$
</code>```

It works, but it's not great and it's obviously limited to how many \S* I add in there.

So how can I match an unlimited number of arguments in the following string?

```<code>!dont match this match1 match2 match3 match4 etc...
</code>```

I've tried using a lookbehind but it only works for the first match. I've also tried making it [^ignore] the first part completely but again, this only works for the first argument since the others are also looking for that specific ignore.

Finally, I also gave \K a shot but it didn't work out.

```<code>!\w+\s\w+\s\w+\s\K(\S*)*
</code>```

答:
Actually, there's no regex needed here, just use split():

```<code>cmds = ['!action db_table mandatory_arg arg1 arg2 arg3...',
        '!dont match this match1 match2 match3 match4 etc...',
        'this one not']

new_cmds = [args[3:]
            for cmd in cmds
            for args in [cmd.split()]
            if cmd.startswith('!')]

print(new_cmds)
# [['arg1', 'arg2', 'arg3...'],
#  ['match1', 'match2', 'match3', 'match4', 'etc...']]
</code>```

Body:
I have a bot that takes a number of different commands and I'm trying scale it's ability to take arguments for all these commands.

This is the syntax:

!action db_table mandatory_arg arg1 arg2 arg3...

Right now I have this functional but un-scalable regex for processing commands:

^!(\S*)\s?(\S*)\s?(\S*)\s?(\S*)\s?(\S*)\s?(\S*)\s?(\S*)\s?(\S*)$

It works, but it's not great and it's obviously limited to how many \S* I add in there.

So how can I match an unlimited number of arguments in the following string?

!dont match this match1 match2 match3 match4 etc...

I've tried using a lookbehind but it only works for the first match. I've also tried making it [^ignore] the first part completely but again, this only works for the first argument since the others are also looking for that specific ignore.

Finally, I also gave \K a shot but it didn't work out.

!\w+\s\w+\s\w+\s\K(\S*)*

Body:
Actually, there's no regex needed here, just use split():

cmds = ['!action db_table mandatory_arg arg1 arg2 arg3...',
        '!dont match this match1 match2 match3 match4 etc...',
        'this one not']

new_cmds = [args[3:]
            for cmd in cmds
            for args in [cmd.split()]
            if cmd.startswith('!')]

print(new_cmds)
# [['arg1', 'arg2', 'arg3...'],
#  ['match1', 'match2', 'match3', 'match4', 'etc...']]


问:
ASP.NET MVC - Easy way to temporarily require authorisation for whole site except one page
I am building a site with a mixture of public and member-only pages.  The login system works fine as it is.

However I'd like to launch a closed, invite-only preview and temporarily require visitors log in for all actions except the welcome page.

Currently I have [Authorize] attributes on certain action methods.  I could add additional attributes to the other action methods too, but this feels a bit hacky and will make it harder to remove them correctly later when I want to revert to having more open content.

So, how can I effectively add a site-wide authorisation requirement?  Recall that I want the single /Home/Index route to remain public as well, so that people I've invited can read some information before activating their invites.

答:
You could customize the Authorize attribute and have your list of users for private beta need to pass some logic within.  Just remove the customization when you go public.

Stack Overflow answer on how to customize the Authorize attribute

Look at the answer containing AuthorizeOwnerAttribute too.


问:
Is using a case statement in my ruby on rails example ok?
I have a built a little online tool using rails. The app has no database.
(I know I should have used another simpler framework, like Sinatra for Ruby).
So I need to capture selected car model from the interface and use its power, speed, and dimensions properties
Is it ok to use case statement, like the code below:

```<code>class Car
def get_car_properties (dropdown_selection)
    info = {}
    info=Hash.new{2}
    case dropdown_selection
        when 'Mazda 3'
             info = { speed: 'fast', power: 'real strong', dimensions: '4X3X3'}
        when 'Lancer 81'
             info = { speed: 'slow', power: 'real weak', dimensions: '2X2X2'}
         else
             info={}

    end
    return info
end
end

selected_car=Car.new()
puts selected_car.get_car_properties('Mazda 3')
</code>```

For simplifications, I have not used the exact scenario. Also note that my case statement is about 30 options big and the hash 10 symbols.

答:
Big case statements are a code smell, meaning they are a hint that there may be an opportunity to improve your code.

In this case, while your app does not have a database, you still have data. The reason why your code looks messy right now is that you have not separated that data from your program logic.

I would recommend storing the data about each car in a hash, and then treat that hash as if it were your database.

class Car
  CAR_INFO = {
    'Mazda 3' => {
      speed: 'fast',
      power: 'real strong',
      dimensions: '4X3X3'
    },
    'Lancer 81' => {
      speed: 'slow',
      power: 'real weak',
      dimensions: '2X2X2'
    },
    # etc
  }

  def get_car_properties (dropdown_selection)
    CAR_INFO.fetch(dropdown_selection, {})
  end
end

selected_car=Car.new()
puts selected_car.get_car_properties('Mazda 3')
```

Why is this better? For one thing, the hash is pure data. It's clear that there's no additional control logic hiding somewhere in one of the branches of your case statement. You can now tell at a glance exactly what get_car_properties is doing - it's looking up the selection in a data structure, and returning an empty hash if nothing is found. You may wish to move CAR_INFO into a separate file, or perhaps into a proper database later on - get_car_properties won't change much in either of those cases.

Body:
I have a built a little online tool using rails. The app has no database.
(I know I should have used another simpler framework, like Sinatra for Ruby).
So I need to capture selected car model from the interface and use its power, speed, and dimensions properties
Is it ok to use case statement, like the code below:

class Car
def get_car_properties (dropdown_selection)
    info = {}
    info=Hash.new{2}
    case dropdown_selection
        when 'Mazda 3'
             info = { speed: 'fast', power: 'real strong', dimensions: '4X3X3'}
        when 'Lancer 81'
             info = { speed: 'slow', power: 'real weak', dimensions: '2X2X2'}
         else
             info={}

    end
    return info
end
end

selected_car=Car.new()
puts selected_car.get_car_properties('Mazda 3')

For simplifications, I have not used the exact scenario. Also note that my case statement is about 30 options big and the hash 10 symbols.

Body:
Big case statements are a code smell, meaning they are a hint that there may be an opportunity to improve your code.

In this case, while your app does not have a database, you still have data. The reason why your code looks messy right now is that you have not separated that data from your program logic.

I would recommend storing the data about each car in a hash, and then treat that hash as if it were your database.

class Car
  CAR_INFO = {
    'Mazda 3' => {
      speed: 'fast',
      power: 'real strong',
      dimensions: '4X3X3'
    },
    'Lancer 81' => {
      speed: 'slow',
      power: 'real weak',
      dimensions: '2X2X2'
    },
    # etc
  }

  def get_car_properties (dropdown_selection)
    CAR_INFO.fetch(dropdown_selection, {})
  end
end

selected_car=Car.new()
puts selected_car.get_car_properties('Mazda 3')

Why is this better? For one thing, the hash is pure data. It's clear that there's no additional control logic hiding somewhere in one of the branches of your case statement. You can now tell at a glance exactly what get_car_properties is doing - it's looking up the selection in a data structure, and returning an empty hash if nothing is found. You may wish to move CAR_INFO into a separate file, or perhaps into a proper database later on - get_car_properties won't change much in either of those cases.


问:
group numbers in an array by step value changes
i have an array like [101, 107, 106, 199, 204, 205, 207, 306, 310, 312, 312, 314, 317, 318, 380, 377, 379, 382, 466, 469, 471, 472, 557, 559, 562, 566, 569...]

In this array, after a few integers, there will be a step change in value.(like between [101,107,106] and [199,204,...])
Or put it in another way, the array is made up of groups of integers, each group with values centered around an unknown mean.
But i won't know how many groups are there in total ,and the number of integers in each is uncertain.

How could i group those integers in each step change into different arrays.

Thanks

答:
You could try this: Determine the difference for each pair of consecutive numbers, and from those determine the average difference.

```<code>nums = [101, 107, 106, 199, 204, 205, 207, 306, 310, 312, 312, 314, 317, 318,
        380, 377, 379, 382, 466, 469, 471, 472, 557, 559, 562, 566, 569]
pairs = list(zip(nums, nums[1:]))
diffs = [abs(x-y) for x, y in pairs]
avg_diff = sum(diffs) / len(diffs)  # ~ 18.31
</code>```

Now, you can group the numbers by whether the difference to the previous number is lower or higher than that average:

```<code>groups = [[nums[0]]]          # first group already has first number
for (x, y), d in zip(pairs, diffs):
    if d < avg_diff:
        groups[-1].append(y)  # add to last group
    else:
        groups.append([y])    # start new group
</code>```

Or if you prefer one-liners spanning three lines, this one might be for you:

```<code>groups = [functools.reduce(lambda A, b: A+(b[1],) if A else b, group, None)
          for key, group in itertools.groupby(zip(nums, nums[1:]),
                  key=lambda t: abs(t[0]-t[1]) < 18.3) if key]
</code>```

Result for your example is this:

```<code>[[101, 107, 106],
 [199, 204, 205, 207],
 [306, 310, 312, 312, 314, 317, 318],
 [380, 377, 379, 382],
 [466, 469, 471, 472],
 [557, 559, 562, 566, 569]]
</code>```

Of course, this breaks down if there are groups with vastly different group-internal differences, as in [1, 4, 2, 5, 1042, 1230, 920, 3, 2, 5]. If that is the case, you might try the relative difference of numbers instead, e.g. max(x,y)/min(x,y) instead of abs(x-y).

Body:
You could try this: Determine the difference for each pair of consecutive numbers, and from those determine the average difference.

nums = [101, 107, 106, 199, 204, 205, 207, 306, 310, 312, 312, 314, 317, 318,
        380, 377, 379, 382, 466, 469, 471, 472, 557, 559, 562, 566, 569]
pairs = list(zip(nums, nums[1:]))
diffs = [abs(x-y) for x, y in pairs]
avg_diff = sum(diffs) / len(diffs)  # ~ 18.31

Now, you can group the numbers by whether the difference to the previous number is lower or higher than that average:

groups = [[nums[0]]]          # first group already has first number
for (x, y), d in zip(pairs, diffs):
    if d < avg_diff:
        groups[-1].append(y)  # add to last group
    else:
        groups.append([y])    # start new group

Or if you prefer one-liners spanning three lines, this one might be for you:

groups = [functools.reduce(lambda A, b: A+(b[1],) if A else b, group, None)
          for key, group in itertools.groupby(zip(nums, nums[1:]),
                  key=lambda t: abs(t[0]-t[1]) < 18.3) if key]

Result for your example is this:

[[101, 107, 106],
 [199, 204, 205, 207],
 [306, 310, 312, 312, 314, 317, 318],
 [380, 377, 379, 382],
 [466, 469, 471, 472],
 [557, 559, 562, 566, 569]]

Of course, this breaks down if there are groups with vastly different group-internal differences, as in [1, 4, 2, 5, 1042, 1230, 920, 3, 2, 5]. If that is the case, you might try the relative difference of numbers instead, e.g. max(x,y)/min(x,y) instead of abs(x-y).


问:
Auto rotating code works on iPhone but not on iPad
This is the code that only works on the iphone.
I am making a universal app that runs on both devices, so it it the identical app.</p>

```<code>**//Automatically rotates the view to landscape
    let orientation: UIDeviceOrientation = UIDevice.current.orientation
    //If landscape right the rotate right
    if orientation == UIDeviceOrientation.landscapeLeft
    {
        UIView.animate(withDuration: 0.5, animations:
            {
                () -> Void in
                let value = UIInterfaceOrientation.landscapeRight.rawValue
                UIDevice.current.setValue(value, forKey: "orientation")
        })

    }
    else
    {
        UIView.animate(withDuration: 0.5, animations:
            {
                () -> Void in
                let value = UIInterfaceOrientation.landscapeLeft.rawValue
                UIDevice.current.setValue(value, forKey: "orientation")
        })

    }**
</code>```

答:
Here's one possibility for you to check...

In the project's settings, under the General tab for a build target, there's the Deployment Info section where you select the "Devices" option (that you probably have on "Universal"). Below that is the Device Orientation selection. There's one, um, interesting feature here.

If you check some orientations when Devices is on Universal, it only applies the setting to the iPhone version. If you toggle the Devices selection to iPad, the options will likely be different. What you need to do is switch the selection to iPhone, apply the orientations you want there, switch it to iPad, apply orientations again, and then finally set Devices to Universal.

I have a hunch (not tested with your code) that if you try to apply an orientation that is not supported here, your code will do nothing.

Body:
This is the code that only works on the iphone.
I am making a universal app that runs on both devices, so it it the identical app.

**//Automatically rotates the view to landscape
    let orientation: UIDeviceOrientation = UIDevice.current.orientation
    //If landscape right the rotate right
    if orientation == UIDeviceOrientation.landscapeLeft
    {
        UIView.animate(withDuration: 0.5, animations:
            {
                () -> Void in
                let value = UIInterfaceOrientation.landscapeRight.rawValue
                UIDevice.current.setValue(value, forKey: "orientation")
        })

    }
    else
    {
        UIView.animate(withDuration: 0.5, animations:
            {
                () -> Void in
                let value = UIInterfaceOrientation.landscapeLeft.rawValue
                UIDevice.current.setValue(value, forKey: "orientation")
        })

    }**


问:
Java - Do object references get destroyed when the creating class is closed?
Say i have a class, which loads a file and then calls another method to do something to that file. For example, counting the words in the file.

Within class CountWords, a number of objects/collections are created in order to get the number of words. The method runs, the number of words is found, and then this is returned to the calling class.

My question is, do all the objects/collection created in the CountWords class get "destroyed" when control is returned to the calling class or do they remain in the memory? If the latter, would i have to set each object to null before exiting the class to mark them for collection?

答:
We don't need to set the objects to null after coming out the function . For this Java have garbage Collector ,  which runs on the Java Virtual Machine which gets rid of objects which are not being used by a Java application anymore. It is a form of automatic memory management.

For example :

```<code>for (int i =0 ; i<10 ; i++) {
    String s = String.valueOf(i)
}
</code>```

In the above code, the integer s is being created on each iteration of the for loop. This means that in every iteration, a little bit of memory is being allocated to make a integer object.

Going back to the code, we can see that once a single iteration is executed, in the next iteration, the integer object that was created in the previous iteration is not being used anymore -- that object is now considered "garbage".

Eventually, we'll start getting a lot of garbage, and memory will be used for objects which aren't being used anymore. If this keeps going on, eventually the Java Virtual Machine will run out of space to make new objects.

That's where the garbage collector steps in.

The garbage collector will look for objects which aren't being used anymore, and gets rid of them, freeing up the memory so other new objects can use that piece of memory.

Automatic memory management schemes like garbage collection makes it so the programmer does not have to worry so much about memory management issues, so he or she can focus more on developing the applications they need to develop.

Body:
We don't need to set the objects to null after coming out the function . For this Java have garbage Collector ,  which runs on the Java Virtual Machine which gets rid of objects which are not being used by a Java application anymore. It is a form of automatic memory management.

For example :

for (int i =0 ; i<10 ; i++) {
    String s = String.valueOf(i)
}

In the above code, the integer s is being created on each iteration of the for loop. This means that in every iteration, a little bit of memory is being allocated to make a integer object.

Going back to the code, we can see that once a single iteration is executed, in the next iteration, the integer object that was created in the previous iteration is not being used anymore -- that object is now considered "garbage".

Eventually, we'll start getting a lot of garbage, and memory will be used for objects which aren't being used anymore. If this keeps going on, eventually the Java Virtual Machine will run out of space to make new objects.

That's where the garbage collector steps in.

The garbage collector will look for objects which aren't being used anymore, and gets rid of them, freeing up the memory so other new objects can use that piece of memory.

Automatic memory management schemes like garbage collection makes it so the programmer does not have to worry so much about memory management issues, so he or she can focus more on developing the applications they need to develop.


问:
Xcode 8 source control broken
I came across strange issue with source control (git) on Xcode 8.

While removing some old, already merged to master branches the popup appeared stating Couldn’t communicate with a helper application.

The branches were removed but another issue came up, so when commiting I have something like this:

Repository View seem to be ok:

Project View should look somewhat the same but is kinda weird:

I can commit but when trying to remove a branch the warning popup still appears.
I've searched for solution, found this one:
xcode 7.2 couldn’t communicate with a helper application
but when I check in Terminal with xcrun git config --global user.email and xcrun git config --global user.name it gives me the proper values.

I use SourceTree as well and it works flawlessly without any warnings.

All other projects are ok - no warnings and no weird Project View.

Update:

All other projects have normal Project View but apparently the warning popup Couldn’t communicate with a helper application appears when I try to remove a branch.

Any help would appreciated.

答: Installing Xcode 9 and updating project solved the problem</p>

Title: Xcode 8 source control broken


问:
For a small MongoDB collection, is it safe to design as if it's all in memory?
There are many uses of MongoDB for which I would like to treat a collection as if it's in memory.   For example, for a collection of user Session objects (for a website).  Prior to using MongoDB, I would store such data in a memcached server, etc.  But, it seems silly to have to run both memcached+MongoDB for cases like this.

Is it reasonably safe to assume that for a small-sized (small ~= 1% of total system RAM) collection of frequently accessed data, that the collection is essentially always held in-memory?  I'm always going to be doing direct lookup by _id, and have no indexes on the data.

Would it help this assumption if the Session collection were held in its own database?  I ask because of the nature of MongoDB's buffer cache based memory mapping scheme.

答:
MongoDB doesn't do DB storage memory management itself but relies on OS virtual memory manager. So it's very dependent on OS. The VMM can load the whole DB in memory, even if it 99% of its size, or it can page it all out because other applications are demanding RAM. So it also depends on usage patterns.

Any decent VMM will try to keep MRU data in memory whenever possible, so your Session collection will likely be always in memory no matter whether it's in separate database or not - it's split into pages (usually of 4k size).

You can always check paging status with mongostat utility. It has page fault counter which represents number of accesses to pages that were not in memory and had to be loaded from file.