问:
Dynamically creating divs using Jquery with JSON data
so basically what I am trying to do is I have a bunch of data in an external JSON file. This JSON file can be edited by authorised people at any time so the number of data will keep on changing. Therefore, using the data in that file, I need to dynamically create divs so that the number of divs that I have will match the amount of data there is in the JSON file. And in the divs, the JSON data will be shown. I've done my research and I found out that it could be done through Jquery and Ajax but I did not manage to find something that was similar to my situation. Pardon me because I am quite a newbie when it comes to web development

This is how the divs are if it was hard-coded.

```<code><div class="container" id="TestCi">
<h3>Files</h3>
<div class="row">
  <div class="col-md-102 col-sm-12">

    <div class="col-md-4 col-sm-4">
      <div class="well">
        <h5>3G</h5>
         <a href="https://example.com" target="_blank"><img data-toggle="tooltip" data-placement="left" title="Click to open data" src="images/3GQoS.jpg" height="100%" width="100%"/> </a>
      </div>
    </div>

    <div class="col-md-4 col-sm-4">
      <div class="well">
        <h5>4G</h5>
        <a href="https://example.com" target="_blank"><img data-toggle="tooltip" data-placement="left" title="Click to open data" src="images/4GQoS.jpg" height="100%" width="100%"/></a>
      </div>
    </div>

  <div class="col-md-4 col-sm-4">
    <div class="well">
      <h5>Lorem Ipsum</h5>
      <p>Integer eget tortor justo. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia.</p>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit Ut enim ad minim veniam, quis nostrud exercitation.</p>
    </div>
  </div>
</code>```

And this is my JSON file

```<code>[{"title":"3G","filePath":"https://example.com","imagePath":"images/3GQoS.jpg"}, {"title":"4G", "filePath":"https://example.com", "imagePath":"images/4GQoS.jpg"} ]
</code>```

Edit:
I need to read each item in the external JSON file and with each item, a div will be created and the data will be displayed in it. Here is an image of how the divs look like: Image

答:
you need to deserialize your JSON File first. after that, you loop through that each obj, and build divs. Then, you just .prepend() it into your target div

```<code>var JsonData = '[{"title":"3G","filePath":"https://example.com","imagePath":"images/3GQoS.jpg"}, {"title":"4G", "filePath":"https://example.com", "imagePath":"images/4GQoS.jpg"} ]';

var obj = JSON.parse( JsonData );

var tmp = '';
$.each( obj, function( key, value ) {
  tmp += '<div class="col-md-4 col-sm-4">';
  tmp += '    <div class="well">';
  tmp += '      <h5>' + value.title + '</h5>';
  tmp += '      <a href="' + value.filePath + '" target="_blank"><img data-toggle="tooltip" data-placement="left" title="Click to open data" src="' + value.imagePath + '" height="100%" width="100%"/></a>    ';
  tmp += '    </div>';
  tmp += '  </div>';
});

$('#main').prepend(tmp);
</code>```

demo : https://jsfiddle.net/vd2jaxtr/

Body:
so basically what I am trying to do is I have a bunch of data in an external JSON file. This JSON file can be edited by authorised people at any time so the number of data will keep on changing. Therefore, using the data in that file, I need to dynamically create divs so that the number of divs that I have will match the amount of data there is in the JSON file. And in the divs, the JSON data will be shown. I've done my research and I found out that it could be done through Jquery and Ajax but I did not manage to find something that was similar to my situation. Pardon me because I am quite a newbie when it comes to web development

This is how the divs are if it was hard-coded.

Files

3G

4G

Lorem Ipsum

Integer eget tortor justo. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia.

Lorem ipsum dolor sit amet, consectetur adipiscing elit Ut enim ad minim veniam, quis nostrud exercitation.

And this is my JSON file

[{"title":"3G","filePath":"https://example.com","imagePath":"images/3GQoS.jpg"}, {"title":"4G", "filePath":"https://example.com", "imagePath":"images/4GQoS.jpg"} ]

Edit:
I need to read each item in the external JSON file and with each item, a div will be created and the data will be displayed in it. Here is an image of how the divs look like: Image

Body:
you need to deserialize your JSON File first. after that, you loop through that each obj, and build divs. Then, you just .prepend() it into your target div

var JsonData = '[{"title":"3G","filePath":"https://example.com","imagePath":"images/3GQoS.jpg"}, {"title":"4G", "filePath":"https://example.com", "imagePath":"images/4GQoS.jpg"} ]';

var obj = JSON.parse( JsonData );

var tmp = '';
$.each( obj, function( key, value ) {
  tmp += '<div class="col-md-4 col-sm-4">';
  tmp += '    <div class="well">';
  tmp += '      <h5>' + value.title + '</h5>';
  tmp += '      <a href="' + value.filePath + '" target="_blank"><img data-toggle="tooltip" data-placement="left" title="Click to open data" src="' + value.imagePath + '" height="100%" width="100%"/></a>    ';
  tmp += '    </div>';
  tmp += '  </div>';
});

$('#main').prepend(tmp);

demo : https://jsfiddle.net/vd2jaxtr/


来源: stackexchange

问:
Linq mystery error in EF query
I have a UserProfile class

```<code> [Key]
    public int UserProfileId { get; set; }

    public string AppUserId { get; set; }

   ...code removed for brevity

    [Required]
    public NotificationMethod NotificationMethod { get; set; }

    public List<PrivateMessage> PrivateMessages { get; set; }

    public List<Machine> OwnedMachines { get; set; }

    public bool IsProfileComplete { get; set; }

    public byte[] Avatar { get; set; }
    public string AvatarUrl { get; set; }

    public string GetFullName()
    {
        return $"{FirstName} {LastName}";
    }
}
</code>```

I also have a PrivateMessage class

```<code> public class PrivateMessage
{
    [Key]
    public int Id { get; set; }

    public int MessageToUserId { get; set; }

    public int MessageFromUserId { get; set; }

    public DateTime DateSent { get; set; }
    public string Message { get; set; }
}
</code>```

I set up a simple test to pull the user profile out with various includes. The PrivateMessages always errors. Here is a sample method that errors.

```<code>public static UserProfile GetUserProfileIncluding(string appUserId)
    {
        using (RestorationContext)
        {
            //RestorationContext.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);

            return RestorationContext.MemberProfiles.Where(m => m.AppUserId == appUserId)
                  .Include(m=> m.PrivateMessages)
                  .FirstOrDefault();
        }
    }
</code>```

The error noted is

InnerException    {"Invalid column name 'UserProfile_UserProfileId'.\r\nInvalid column name 'UserProfile_UserProfileId'."}    System.Exception {System.Data.SqlClient.SqlException}

Which I don't understand, neither table has a column "UserProfile_UserProfileId"

If I use the property OwnedMachines instead of PrivateMessages, it works perfectly fine (well not really, its only pulling in 4 records when there are 6 that match but I can figure that out later).

```<code>public static UserProfile GetUserProfileIncluding(string appUserId)
    {
        using (RestorationContext)
        {

            return RestorationContext.MemberProfiles.Where(m => m.AppUserId == appUserId)
                  .Include(m=> m.OwnedMachines)
                  .FirstOrDefault();
        }
    }
</code>```

And you can see below, Machine is set up exactly like PrivateMessage, albeit it has two UserProfiles instead of one

```<code>public class Machine
{
    [Key]
    public int MachineId { get; set; }

    public int OwnerProfileId { get; set; }

    public int SerialNumber { get; set; }

    public string YearofManufacture { get; set; }

    public string ModelName { get; set; }

    public Manufacturer Manufacturer { get; set; }

    public DateTime DateAcquired { get; set; }
}
</code>```

I've spent far to much time on this now. Does it have something to do with the fact that I have two UserProfile Id int properties in PrivateMessage? (MessageToUserId & MessageFromUserId). I originally had these set as foreign keys with a UserProfile property in there as well like this

```<code>    [ForeignKey("MessageToProfile")]
    public int MessageToUserId { get; set; }

    public UserProfile MessageToProfile { get; set; }

    [ForeignKey("MessageFromProfile")]
    public int MessageFromUserId { get; set; }

    public UserProfile MessageFromProfile { get; set; }
</code>```

But I removed them thinking they may have been the source of the error, but apparently not.

UPDATE:
After a bunch more trial and error, it is apparent that the current method will always err as the method is looking for a navigable property which doesn't exist. Since I have the two int properties in PrivateMessage, when trying to include those in the UserProfile object, I will need to filter then by MessageToUserId and then include them. Not sure how to filter and include.

Using this method should work;

```<code>public static UserProfile GetProfileForLoggedInUser(string appUserId)
    {

        using (RestorationContext)
        {
            RestorationContext.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);

            var profile= RestorationContext.MemberProfiles.Include(m => m.OwnedMachines)
                                           .FirstOrDefault(m => m.AppUserId == appUserId);
            var pms = RestorationContext.PrivateMessages.Where(m => m.MessageToUserId == profile.UserProfileId).ToList();

            if (profile != null) profile.PrivateMessages = pms;

            return profile;
        }
    }
</code>```

But it gives the same invalid column error UserProfile_UserProfileID.

Here is the TSql

```<code>SELECT
[Extent1].[Id] AS [Id],
[Extent1].[MessageToUserId] AS [MessageToUserId],
[Extent1].[MessageFromUserId] AS [MessageFromUserId],
[Extent1].[DateSent] AS [DateSent],
[Extent1].[Message] AS [Message],
[Extent1].[UserProfile_UserProfileId] AS [UserProfile_UserProfileId]
FROM [RestorationContext].[PrivateMessages] AS [Extent1]
WHERE [Extent1].[MessageToUserId] = @p__linq__0
</code>```

Since this is just querying the PrivateMessage table WHY is it looking for that UserProfileId, it has nothing to do with this table. Here are the table properties from SSMS

Where is that UserProfileID crap coming from?

答:
Your Machine inclusion works because the Machine class has only one foreign key of UserProfile.

You have 2 foreign keys to the same table in PrivateMessage class, naturally, you would need 2 ICollection navigation properties in your UserProfile class. EntityFramework didn't know which foreign key to use in your PrivateMessage class for loading your ICollection<PrivateMessage> property in your UserProfile class.

```<code>public ICollection<PrivateMessage> FromPrivateMessages { get; set; }
public ICollection<PrivateMessage> ToPrivateMessages { get; set; }
</code>```

In your context class

```<code>protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<PrivateMessage>()
                .HasRequired(m => m.MessageFromProfile)
                .WithMany(t => t.FromPrivateMessages)
                .HasForeignKey(m => m.MessageFromUserId)
                .WillCascadeOnDelete(false);

    modelBuilder.Entity<PrivateMessage>()
                .HasRequired(m => m.MessageToProfile)
                .WithMany(t => t.ToPrivateMessages)
                .HasForeignKey(m => m.MessageToUserId)
                .WillCascadeOnDelete(false);
}
</code>```

UPDATE

EF uses convention over configuration, and by having navigation properties of UserProfile in your PrivateMessage class will imply a relationship and EF will try to find a foreign key in the form of <Navigation Property Name>_<Primary Key Name of Navigation Property type>, which gives you UserProfile_UserProfileId.

You should be wondering why UserProfile_UserProfileId instead of UserProfile_MessageToUserId or UserProfile_MessageFromUserId at this point. That's because of your foreign key attribute, telling EF to use the UserProfileId property in your UserProfile class.

What you can do now is, remove the foreign key attributes like this

```<code>public int MessageToUserId { get; set; }

public UserProfile MessageToProfile { get; set; }

public int MessageFromUserId { get; set; }

public UserProfile MessageFromProfile {get; set; }
</code>```

and add another ICollection and do the modelBuilder configuration like how I stated before the update.

ContentLicense: CC BY-SA 3.0

Title: Linq mystery error in EF query

Body:
I have a UserProfile class

 [Key]
    public int UserProfileId { get; set; }

    public string AppUserId { get; set; }

   ...code removed for brevity

    [Required]
    public NotificationMethod NotificationMethod { get; set; }

    public List<PrivateMessage> PrivateMessages { get; set; }

    public List<Machine> OwnedMachines { get; set; }

    public bool IsProfileComplete { get; set; }

    public byte[] Avatar { get; set; }
    public string AvatarUrl { get; set; }

    public string GetFullName()
    {
        return $"{FirstName} {LastName}";
    }
}

I also have a PrivateMessage class

 public class PrivateMessage
{
    [Key]
    public int Id { get; set; }

    public int MessageToUserId { get; set; }

    public int MessageFromUserId { get; set; }

    public DateTime DateSent { get; set; }
    public string Message { get; set; }
}

I set up a simple test to pull the user profile out with various includes. The PrivateMessages always errors. Here is a sample method that errors.

public static UserProfile GetUserProfileIncluding(string appUserId)
    {
        using (RestorationContext)
        {
            //RestorationContext.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);

            return RestorationContext.MemberProfiles.Where(m => m.AppUserId == appUserId)
                  .Include(m=> m.PrivateMessages)
                  .FirstOrDefault();
        }
    }

The error noted is

InnerException    {"Invalid column name 'UserProfile_UserProfileId'.\r\nInvalid column name 'UserProfile_UserProfileId'."}    System.Exception {System.Data.SqlClient.SqlException}

Which I don't understand, neither table has a column "UserProfile_UserProfileId"

If I use the property OwnedMachines instead of PrivateMessages, it works perfectly fine (well not really, its only pulling in 4 records when there are 6 that match but I can figure that out later).

public static UserProfile GetUserProfileIncluding(string appUserId)
    {
        using (RestorationContext)
        {

            return RestorationContext.MemberProfiles.Where(m => m.AppUserId == appUserId)
                  .Include(m=> m.OwnedMachines)
                  .FirstOrDefault();
        }
    }

And you can see below, Machine is set up exactly like PrivateMessage, albeit it has two UserProfiles instead of one

public class Machine
{
    [Key]
    public int MachineId { get; set; }

    public int OwnerProfileId { get; set; }

    public int SerialNumber { get; set; }

    public string YearofManufacture { get; set; }

    public string ModelName { get; set; }

    public Manufacturer Manufacturer { get; set; }

    public DateTime DateAcquired { get; set; }
}

I've spent far to much time on this now. Does it have something to do with the fact that I have two UserProfile Id int properties in PrivateMessage? (MessageToUserId & MessageFromUserId). I originally had these set as foreign keys with a UserProfile property in there as well like this

    [ForeignKey("MessageToProfile")]
    public int MessageToUserId { get; set; }

    public UserProfile MessageToProfile { get; set; }

    [ForeignKey("MessageFromProfile")]
    public int MessageFromUserId { get; set; }

    public UserProfile MessageFromProfile { get; set; }

But I removed them thinking they may have been the source of the error, but apparently not.

UPDATE:
After a bunch more trial and error, it is apparent that the current method will always err as the method is looking for a navigable property which doesn't exist. Since I have the two int properties in PrivateMessage, when trying to include those in the UserProfile object, I will need to filter then by MessageToUserId and then include them. Not sure how to filter and include.

Using this method should work;

public static UserProfile GetProfileForLoggedInUser(string appUserId)
    {

        using (RestorationContext)
        {
            RestorationContext.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);

            var profile= RestorationContext.MemberProfiles.Include(m => m.OwnedMachines)
                                           .FirstOrDefault(m => m.AppUserId == appUserId);
            var pms = RestorationContext.PrivateMessages.Where(m => m.MessageToUserId == profile.UserProfileId).ToList();

            if (profile != null) profile.PrivateMessages = pms;

            return profile;
        }
    }

But it gives the same invalid column error UserProfile_UserProfileID.

Here is the TSql

SELECT
[Extent1].[Id] AS [Id],
[Extent1].[MessageToUserId] AS [MessageToUserId],
[Extent1].[MessageFromUserId] AS [MessageFromUserId],
[Extent1].[DateSent] AS [DateSent],
[Extent1].[Message] AS [Message],
[Extent1].[UserProfile_UserProfileId] AS [UserProfile_UserProfileId]
FROM [RestorationContext].[PrivateMessages] AS [Extent1]
WHERE [Extent1].[MessageToUserId] = @p__linq__0

Since this is just querying the PrivateMessage table WHY is it looking for that UserProfileId, it has nothing to do with this table. Here are the table properties from SSMS

Where is that UserProfileID crap coming from?

Body:
Your Machine inclusion works because the Machine class has only one foreign key of UserProfile.

You have 2 foreign keys to the same table in PrivateMessage class, naturally, you would need 2 ICollection navigation properties in your UserProfile class. EntityFramework didn't know which foreign key to use in your PrivateMessage class for loading your ICollection<PrivateMessage> property in your UserProfile class.

public ICollection<PrivateMessage> FromPrivateMessages { get; set; }
public ICollection<PrivateMessage> ToPrivateMessages { get; set; }

In your context class

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<PrivateMessage>()
                .HasRequired(m => m.MessageFromProfile)
                .WithMany(t => t.FromPrivateMessages)
                .HasForeignKey(m => m.MessageFromUserId)
                .WillCascadeOnDelete(false);

    modelBuilder.Entity<PrivateMessage>()
                .HasRequired(m => m.MessageToProfile)
                .WithMany(t => t.ToPrivateMessages)
                .HasForeignKey(m => m.MessageToUserId)
                .WillCascadeOnDelete(false);
}

UPDATE

EF uses convention over configuration, and by having navigation properties of UserProfile in your PrivateMessage class will imply a relationship and EF will try to find a foreign key in the form of <Navigation Property Name>_<Primary Key Name of Navigation Property type>, which gives you UserProfile_UserProfileId.

You should be wondering why UserProfile_UserProfileId instead of UserProfile_MessageToUserId or UserProfile_MessageFromUserId at this point. That's because of your foreign key attribute, telling EF to use the UserProfileId property in your UserProfile class.

What you can do now is, remove the foreign key attributes like this

public int MessageToUserId { get; set; }

public UserProfile MessageToProfile { get; set; }

public int MessageFromUserId { get; set; }

public UserProfile MessageFromProfile {get; set; }

and add another ICollection and do the modelBuilder configuration like how I stated before the update.


问:
how to convert a list into a list of tuples?
Here's what I have in the text file:

1712 Albert
1703 Benny
1799 Henry
1735 Jessica
1722 Lucas
1701 Luke
1757 William
1777 Jenny
1783 Lucia
1764 Venus
1718 Felicitas
```

<p>Here's what I have done to read the file but I have no idea how to put them into a list of tuples</p>

```def readRecords(filepath):
    file = open('Students1.txt', 'r')
    filecontent = file.readlines()
    file.close()
    return filecontent
```

Here's what the output is supposed to be:

答:
You must iterate over the lines in the file you just read. Here's what you could do:</p>

```<code>def readRecords(filepath):
    file = open(filepath, 'r')  # You should use the filepath variable you've given
    filecontent = file.readlines()
    file.close()

    my_tuples = []
    for line in filecontent:  # For each line in the file...
        line = line.strip()  # Remove the newline character which you likely don't want
        my_tuples.append(int((line.split(' ')[0]), line.split(' ')[1]))  # Create a tuple of the two words separated by a space

    return my_tuples

print(readRecords('Students1.txt'))
</code>```

Body:
Here's what I have in the text file:

1712 Albert
1703 Benny
1799 Henry
1735 Jessica
1722 Lucas
1701 Luke
1757 William
1777 Jenny
1783 Lucia
1764 Venus
1718 Felicitas

Here's what I have done to read the file but I have no idea how to put them into a list of tuples

def readRecords(filepath):
    file = open('Students1.txt', 'r')
    filecontent = file.readlines()
    file.close()
    return filecontent

Here's what the output is supposed to be:

Body:
You must iterate over the lines in the file you just read. Here's what you could do:

def readRecords(filepath):
    file = open(filepath, 'r')  # You should use the filepath variable you've given
    filecontent = file.readlines()
    file.close()

    my_tuples = []
    for line in filecontent:  # For each line in the file...
        line = line.strip()  # Remove the newline character which you likely don't want
        my_tuples.append(int((line.split(' ')[0]), line.split(' ')[1]))  # Create a tuple of the two words separated by a space

    return my_tuples

print(readRecords('Students1.txt'))


问:
PHP Function for evaluating percentage change
I'm trying to build a function which evaluates two numbers and sees if there is a percentage change that happens.

```<code>// $live_data = data pulled from an API - ex: .000121231 or 2500.00
// $pervious_data = data pulled from a DB - ex: .0001231 or 11111.00
// $alert_data['value'] = data pulled from a DB - ex: 10 or -10

function percent_change_eval($data, $alert_data, $previous, $currency){
  $live_data = (float)$data[$currency][$alert_data['comparison']];
  $previous_data = (float)$previous[$alert_data['comparison']];
  $percent = round((($live_data) - ($previous_data)) / ($previous_data) * 100, 10);
  switch($alert_data['operator']) {
    case ">=":
        if($percent > $alert_data['value']){
            return TRUE;
        } else {
            return FALSE;
        }
        break 1;
    case "<=":
        if($percent < $alert_data['value']){
            return TRUE;
        } else {
            return FALSE;
        }
        break 1;
  }
}
</code>```

I've built the function but for some reason it keeps throwing true when it shouldn't. I'm assuming it has something to do with the numbers being either too big or too small or if one of the vars is null.

Any advice or help?

答:
Not an answer per se, but I hate switch cases. It took 16 lines of code!

I'd rewrite it using just two lines:

```<code>if($alert_data['operator'] == '>=') return $percent > $alert_data['value']);
if($alert_data['operator'] == '<=') return $percent < $alert_data['value']);
</code>```

Looks cleaner and much less place for making a mistake

Body:
I'm trying to build a function which evaluates two numbers and sees if there is a percentage change that happens.

// $live_data = data pulled from an API - ex: .000121231 or 2500.00
// $pervious_data = data pulled from a DB - ex: .0001231 or 11111.00
// $alert_data['value'] = data pulled from a DB - ex: 10 or -10

function percent_change_eval($data, $alert_data, $previous, $currency){
  $live_data = (float)$data[$currency][$alert_data['comparison']];
  $previous_data = (float)$previous[$alert_data['comparison']];
  $percent = round((($live_data) - ($previous_data)) / ($previous_data) * 100, 10);
  switch($alert_data['operator']) {
    case ">=":
        if($percent > $alert_data['value']){
            return TRUE;
        } else {
            return FALSE;
        }
        break 1;
    case "<=":
        if($percent < $alert_data['value']){
            return TRUE;
        } else {
            return FALSE;
        }
        break 1;
  }
}

I've built the function but for some reason it keeps throwing true when it shouldn't. I'm assuming it has something to do with the numbers being either too big or too small or if one of the vars is null.

Any advice or help?

Body:
Not an answer per se, but I hate switch cases. It took 16 lines of code!

I'd rewrite it using just two lines:

if($alert_data['operator'] == '>=') return $percent > $alert_data['value']);
if($alert_data['operator'] == '<=') return $percent < $alert_data['value']);

Looks cleaner and much less place for making a mistake


问:
swift function return multiple values
Below is a function that I am trying to create that will get the values in JSON data based on the key value entered. The problem I am having is I need Need to be able to use all the rates in another calculation. I am not sure how to get each rate saved to a global variable. At this point, the function is giving me an error - "Missing Return in a function expecting to return a string". Any ideas how to solve this problem </p>

```<code>   func getLenderData(selectedLenderKey: String) -> String
    {

        let url = ""
        var request = URLRequest(url: URL(string: url)!)
        request.httpMethod = "GET"

        let configuration = URLSessionConfiguration.default
        let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)

        let task = session.dataTask(with: request) { (data, response, error) in
            if error != nil {
                print("Error")
            }
            else{

                do{
                    //let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! NSArray
                    //print(fecthdata)

                    let swiftyJSON = try JSON(data:data!)
                    let lenderName = swiftyJSON["lenders"][selectedLenderKey]["financial_institution"].stringValue
                    let oneYear = swiftyJSON["lenders"][selectedLenderKey]["one_year"].stringValue
                    let twoYear = swiftyJSON["lenders"][selectedLenderKey]["two_year"].stringValue
                    let threeYear = swiftyJSON["lenders"][selectedLenderKey]["three_year"].stringValue
                    let fourYear = swiftyJSON["lenders"][selectedLenderKey]["four_year"].stringValue
                    let fiveYear = swiftyJSON["lenders"][selectedLenderKey]["five_year"].stringValue

                    print(lenderName)
                    print(oneYear)
                    print(twoYear)
                    print(threeYear)
                    print(fourYear)
                    print(fiveYear)

                }

                catch{
                    print("Error 2")
                }
            }

        }
        task.resume()
    }// end function
</code>```

答:
You could create a model and return that model:

```<code>struct Rates {
    let lenderName: String?
    let oneYear: String?
    let twoYear: String?
    let threeYear: String?
    let fourYear: String?
    let fiveYear: String?

    required init() {
        lenderName = nil
        oneYear = nil
        twoYear = nil
        threeYear = nil
        fourYear = nil
        fiveYear = nil
    }

    init(lenderName: String?, oneYear: String?, twoYear: String?, threeYear: String?, fourYear: String?, fiveYear: String?) {
        self.lenderName = lenderName
        self.oneYear = oneYear
        self.twoYear = twoYear
        self.threeYear = threeYear
        self.fourYear = fourYear
        self.fiveYear = fiveYear
    }
}
</code>```

Then return the model you created:

```<code>func getLenderData(selectedLenderKey: String, onCompletion: @escaping (Rates?) -> Void, onError: @escaping (NSError) -> Void) {
    let url = ""
    var request = URLRequest(url: URL(string: url)!)
    request.httpMethod = "GET"

    let configuration = URLSessionConfiguration.default
    let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)

    let task = session.dataTask(with: request) { (data, response, error) in
        if error != nil {
            print("Error")
        }
        else{

            do{
                //let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! NSArray
                //print(fecthdata)

                let swiftyJSON = try JSON(data:data!)
                let lenderName = swiftyJSON["lenders"][selectedLenderKey]["financial_institution"].stringValue
                let oneYear = swiftyJSON["lenders"][selectedLenderKey]["one_year"].stringValue
                let twoYear = swiftyJSON["lenders"][selectedLenderKey]["two_year"].stringValue
                let threeYear = swiftyJSON["lenders"][selectedLenderKey]["three_year"].stringValue
                let fourYear = swiftyJSON["lenders"][selectedLenderKey]["four_year"].stringValue
                let fiveYear = swiftyJSON["lenders"][selectedLenderKey]["five_year"].stringValue

                print(lenderName)
                print(oneYear)
                print(twoYear)
                print(threeYear)
                print(fourYear)
                print(fiveYear)

                let rate = Rates(lenderName: lenderName, oneYear: oneYear, twoYear: twoYear, threeYear: threeYear, fourYear: fourYear, fiveYear: fiveYear)
                onCompletion(rate)

            }

            catch{
                print("Error 2")
                onError(NSError(domain: "Some error description...", code: 0, userInfo: nil))
            }
        }

    }
    task.resume()
}// end function
</code>```

Now you can just use the return value as you want. To use it use the following code:

```<code>getLenderData(selectedLenderKey: "someVal", onCompletion: { (rate) in
   // you can use the rate here
   let oneYear = rate.oneYear
}, onError: { (error) in
    // Error
})
</code>```

Title: swift function return multiple values

Body:
Below is a function that I am trying to create that will get the values in JSON data based on the key value entered. The problem I am having is I need Need to be able to use all the rates in another calculation. I am not sure how to get each rate saved to a global variable. At this point, the function is giving me an error - "Missing Return in a function expecting to return a string". Any ideas how to solve this problem

   func getLenderData(selectedLenderKey: String) -> String
    {

        let url = ""
        var request = URLRequest(url: URL(string: url)!)
        request.httpMethod = "GET"

        let configuration = URLSessionConfiguration.default
        let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)

        let task = session.dataTask(with: request) { (data, response, error) in
            if error != nil {
                print("Error")
            }
            else{

                do{
                    //let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! NSArray
                    //print(fecthdata)

                    let swiftyJSON = try JSON(data:data!)
                    let lenderName = swiftyJSON["lenders"][selectedLenderKey]["financial_institution"].stringValue
                    let oneYear = swiftyJSON["lenders"][selectedLenderKey]["one_year"].stringValue
                    let twoYear = swiftyJSON["lenders"][selectedLenderKey]["two_year"].stringValue
                    let threeYear = swiftyJSON["lenders"][selectedLenderKey]["three_year"].stringValue
                    let fourYear = swiftyJSON["lenders"][selectedLenderKey]["four_year"].stringValue
                    let fiveYear = swiftyJSON["lenders"][selectedLenderKey]["five_year"].stringValue

                    print(lenderName)
                    print(oneYear)
                    print(twoYear)
                    print(threeYear)
                    print(fourYear)
                    print(fiveYear)

                }

                catch{
                    print("Error 2")
                }
            }

        }
        task.resume()
    }// end function

Body:
You could create a model and return that model:

struct Rates {
    let lenderName: String?
    let oneYear: String?
    let twoYear: String?
    let threeYear: String?
    let fourYear: String?
    let fiveYear: String?

    required init() {
        lenderName = nil
        oneYear = nil
        twoYear = nil
        threeYear = nil
        fourYear = nil
        fiveYear = nil
    }

    init(lenderName: String?, oneYear: String?, twoYear: String?, threeYear: String?, fourYear: String?, fiveYear: String?) {
        self.lenderName = lenderName
        self.oneYear = oneYear
        self.twoYear = twoYear
        self.threeYear = threeYear
        self.fourYear = fourYear
        self.fiveYear = fiveYear
    }
}

Then return the model you created:

func getLenderData(selectedLenderKey: String, onCompletion: @escaping (Rates?) -> Void, onError: @escaping (NSError) -> Void) {
    let url = ""
    var request = URLRequest(url: URL(string: url)!)
    request.httpMethod = "GET"

    let configuration = URLSessionConfiguration.default
    let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)

    let task = session.dataTask(with: request) { (data, response, error) in
        if error != nil {
            print("Error")
        }
        else{

            do{
                //let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! NSArray
                //print(fecthdata)

                let swiftyJSON = try JSON(data:data!)
                let lenderName = swiftyJSON["lenders"][selectedLenderKey]["financial_institution"].stringValue
                let oneYear = swiftyJSON["lenders"][selectedLenderKey]["one_year"].stringValue
                let twoYear = swiftyJSON["lenders"][selectedLenderKey]["two_year"].stringValue
                let threeYear = swiftyJSON["lenders"][selectedLenderKey]["three_year"].stringValue
                let fourYear = swiftyJSON["lenders"][selectedLenderKey]["four_year"].stringValue
                let fiveYear = swiftyJSON["lenders"][selectedLenderKey]["five_year"].stringValue

                print(lenderName)
                print(oneYear)
                print(twoYear)
                print(threeYear)
                print(fourYear)
                print(fiveYear)

                let rate = Rates(lenderName: lenderName, oneYear: oneYear, twoYear: twoYear, threeYear: threeYear, fourYear: fourYear, fiveYear: fiveYear)
                onCompletion(rate)

            }

            catch{
                print("Error 2")
                onError(NSError(domain: "Some error description...", code: 0, userInfo: nil))
            }
        }

    }
    task.resume()
}// end function

Now you can just use the return value as you want. To use it use the following code:

getLenderData(selectedLenderKey: "someVal", onCompletion: { (rate) in
   // you can use the rate here
   let oneYear = rate.oneYear
}, onError: { (error) in
    // Error
})


答:
```<code>def readRecords(filepath):
    result = []
    with open('Students1.txt', 'r') as f:  # close the file outside of `with`
        for line in f:  # Iterate over lines
            num, name = line.split()  # split line into two part
            num = int(num)  # convert number part to `int`
            result.append((num, name))
    return result
</code>```

NOTE: Don't use readlines() unless you need whole lines at once. You just need a line at a time; iterating a file is enough.

Title: how to convert a list into a list of tuples?

Body:
def readRecords(filepath):
    result = []
    with open('Students1.txt', 'r') as f:  # close the file outside of `with`
        for line in f:  # Iterate over lines
            num, name = line.split()  # split line into two part
            num = int(num)  # convert number part to `int`
            result.append((num, name))
    return result

NOTE: Don't use readlines() unless you need whole lines at once. You just need a line at a time; iterating a file is enough.


问:
How to start a python file while Windows starts?
I have a python file and I am running the file.

If Windows is shutdown and booted up again, how I can run that file every time Windows starts?

答:
In the following startup directory (at least this path exists on Windows XP):

```<code>C:\Documents and Settings\All Users\Start Menu\Programs\Startup
</code>```

put a shortcut to your python program. It should be executed every time your system starts up.

Body:
In the following startup directory (at least this path exists on Windows XP):

C:\Documents and Settings\All Users\Start Menu\Programs\Startup

put a shortcut to your python program. It should be executed every time your system starts up.

ContentLicense: CC BY-SA 2.5


问:
React Native Android app minimizes and shows Launcher3
I have a relatively simple React Native (Android) app that sits in a lobby. It consists of 4 simple screens that allow a user to select his/her name, select a location on a map, then restart the process.

After running for about 5 days with regular use, the app crashes... Well, it doesn't actually crash. We're using Crashlytics and we don't receive a crash report and the app doesn't actually close; it just goes to the Overview screen and shows Launcher3 (see image below).

I have no idea what could cause this error. Any idea what's causing this? Or at the very least, any suggestions on how I might go about debugging this?

Hardware: Alcatel 9015B (Marshmallow)

React Native: v0.42.3

Dependencies:

```<code>  "dependencies": {
    "prop-types": "^15.5.8",
    "react": "15.5.4",
    "react-native": "0.42.3",
    "react-native-fabric": "^0.4.1",
    "react-native-keep-awake": "2.0.4",
    "react-native-maps": "0.13.1",
    "react-navigation": "1.0.0-beta.9",
    "react-redux": "5.0.4",
    "redux": "3.6.0",
    "redux-thunk": "2.2.0"
  },
  "devDependencies": {
    "babel-jest": "20.0.0",
    "babel-plugin-module-resolver": "^2.7.0",
    "babel-preset-react-native": "1.9.1",
    "jest": "20.0.0",
    "react-test-renderer": "15.5.4"
  },
  "jest": {
    "preset": "react-native"
  }
</code>```

Update

It's looking increasingly likely that this is a memory issue. Here is a snippet from the logs around the time the problems started happening:

```<code>[1077527.452315] binder: release 15127:15138 transaction 80204186 in, still active
[1077527.452330] binder: send failed reply for transaction 80204186 to 15092:15126
[1077527.459627] binder: 15092: binder_alloc_buf, no vma
[1077527.459644] binder: 980:3503 transaction failed 29201, size 88-4
[1077527.493244] binder: release 15141:15141 transaction 80204387 out, still active
[1077527.562781] binder: 980:5223 transaction failed 29189, size 1940-8
[1077527.562797] binder: send failed reply for transaction 80204387, target dead
[1077528.120965] lowmemorykiller: Killing 'e.process.gapps' (15171), adj 0,
[1077528.120965]    to free 37840kB on behalf of 'kswapd0' (111) because
[1077528.120965]    cache 13264kB is below limit 61440kB for oom_score_adj 0
[1077528.120965]    Free memory is 9376kB above reserved.
[1077528.120965]    Free CMA is 10300kB
[1077528.120965]    Total reserve is 21676kB
[1077528.120965]    Total free pages is 22100kB
[1077528.120965]    Total file cache is 136564kB
[1077528.120965]    Slab Reclaimable is 9452kB
[1077528.120965]    Slab UnReclaimable is 535236kB
[1077528.120965]    Total Slab is 544688kB
[1077528.120965]    GFP mask is 0xd0
[1077528.153006] lowmemorykiller: Killing '.gms.persistent' (15158), adj 0,
[1077528.153006]    to free 36220kB on behalf of 'kswapd0' (111) because
[1077528.153006]    cache 13016kB is below limit 61440kB for oom_score_adj 0
[1077528.153006]    Free memory is 9452kB above reserved.
[1077528.153006]    Free CMA is 10300kB
[1077528.153006]    Total reserve is 21676kB
[1077528.153006]    Total free pages is 27744kB
[1077528.153006]    Total file cache is 136788kB
[1077528.153006]    Slab Reclaimable is 9452kB
[1077528.153006]    Slab UnReclaimable is 535236kB
[1077528.153006]    Total Slab is 544688kB
[1077528.153006]    GFP mask is 0xd0
[1077528.179007] binder: 15158: binder_alloc_buf, no vma
[1077528.179024] binder: 980:994 transaction failed 29201, size 88-4
[1077531.534580] CHG: get_prop_capacity: soc samples[0] = 100
[1077531.534597] CHG: get_prop_capacity: soc samples[1] = 100
[1077531.534608] CHG: get_prop_capacity: soc samples[2] = 100
[1077531.534618] CHG: get_prop_capacity: soc samples[3] = 100
[1077531.537690] BMS_DEBUG 107535      16:28:30     4177573    100%    266C
[1077531.544665] CHG: get_prop_capacity: soc samples[0] = 100
[1077531.544680] CHG: get_prop_capacity: soc samples[1] = 100
[1077531.544691] CHG: get_prop_capacity: soc samples[2] = 100
[1077531.544700] CHG: get_prop_capacity: soc samples[3] = 100
[1077531.548164] CHG: get_prop_capacity: soc samples[0] = 100
[1077531.548178] CHG: get_prop_capacity: soc samples[1] = 100
[1077531.548188] CHG: get_prop_capacity: soc samples[2] = 100
[1077531.548197] CHG: get_prop_capacity: soc samples[3] = 100
[1077537.472422] type=1400 audit(1496766516.553:45833): avc: denied { search } for pid=2370 comm="ndroid.systemui" name="15206" dev="proc" ino=12174739 scontext=u:r:platform_app:s0:c512,c768 tcontext=u:r:system_app:s0 tclass=dir permissive=0
[1077537.472735] type=1400 audit(1496766516.553:45834): avc: denied { search } for pid=2370 comm="ndroid.systemui" name="15206" dev="proc" ino=12174739 scontext=u:r:platform_app:s0:c512,c768 tcontext=u:r:system_app:s0 tclass=dir permissive=0
[1077537.472999] type=1400 audit(1496766516.553:45835): avc: denied { search } for pid=2370 comm="ndroid.systemui" name="15206" dev="proc" ino=12174739 scontext=u:r:platform_app:s0:c512,c768 tcontext=u:r:system_app:s0 tclass=dir permissive=0
[1077541.017542] init: Service 'atfwd' (pid 9821) exited with status 255
[1077541.017582] init: Service 'atfwd' (pid 9821) killing any children in process group
[1077541.018827] init: Starting service 'atfwd'...
</code>```

答: Few days back i faced the similar issue i resolved it by simply deleting node_modules and then installed the fresh node_modules or if you are running yarn then please run yarn upgrade.

Body:
I have a relatively simple React Native (Android) app that sits in a lobby. It consists of 4 simple screens that allow a user to select his/her name, select a location on a map, then restart the process.

After running for about 5 days with regular use, the app crashes... Well, it doesn't actually crash. We're using Crashlytics and we don't receive a crash report and the app doesn't actually close; it just goes to the Overview screen and shows Launcher3 (see image below).

I have no idea what could cause this error. Any idea what's causing this? Or at the very least, any suggestions on how I might go about debugging this?

Hardware: Alcatel 9015B (Marshmallow)

React Native: v0.42.3

Dependencies:

  "dependencies": {
    "prop-types": "^15.5.8",
    "react": "15.5.4",
    "react-native": "0.42.3",
    "react-native-fabric": "^0.4.1",
    "react-native-keep-awake": "2.0.4",
    "react-native-maps": "0.13.1",
    "react-navigation": "1.0.0-beta.9",
    "react-redux": "5.0.4",
    "redux": "3.6.0",
    "redux-thunk": "2.2.0"
  },
  "devDependencies": {
    "babel-jest": "20.0.0",
    "babel-plugin-module-resolver": "^2.7.0",
    "babel-preset-react-native": "1.9.1",
    "jest": "20.0.0",
    "react-test-renderer": "15.5.4"
  },
  "jest": {
    "preset": "react-native"
  }

Update

It's looking increasingly likely that this is a memory issue. Here is a snippet from the logs around the time the problems started happening:

[1077527.452315] binder: release 15127:15138 transaction 80204186 in, still active
[1077527.452330] binder: send failed reply for transaction 80204186 to 15092:15126
[1077527.459627] binder: 15092: binder_alloc_buf, no vma
[1077527.459644] binder: 980:3503 transaction failed 29201, size 88-4
[1077527.493244] binder: release 15141:15141 transaction 80204387 out, still active
[1077527.562781] binder: 980:5223 transaction failed 29189, size 1940-8
[1077527.562797] binder: send failed reply for transaction 80204387, target dead
[1077528.120965] lowmemorykiller: Killing 'e.process.gapps' (15171), adj 0,
[1077528.120965]    to free 37840kB on behalf of 'kswapd0' (111) because
[1077528.120965]    cache 13264kB is below limit 61440kB for oom_score_adj 0
[1077528.120965]    Free memory is 9376kB above reserved.
[1077528.120965]    Free CMA is 10300kB
[1077528.120965]    Total reserve is 21676kB
[1077528.120965]    Total free pages is 22100kB
[1077528.120965]    Total file cache is 136564kB
[1077528.120965]    Slab Reclaimable is 9452kB
[1077528.120965]    Slab UnReclaimable is 535236kB
[1077528.120965]    Total Slab is 544688kB
[1077528.120965]    GFP mask is 0xd0
[1077528.153006] lowmemorykiller: Killing '.gms.persistent' (15158), adj 0,
[1077528.153006]    to free 36220kB on behalf of 'kswapd0' (111) because
[1077528.153006]    cache 13016kB is below limit 61440kB for oom_score_adj 0
[1077528.153006]    Free memory is 9452kB above reserved.
[1077528.153006]    Free CMA is 10300kB
[1077528.153006]    Total reserve is 21676kB
[1077528.153006]    Total free pages is 27744kB
[1077528.153006]    Total file cache is 136788kB
[1077528.153006]    Slab Reclaimable is 9452kB
[1077528.153006]    Slab UnReclaimable is 535236kB
[1077528.153006]    Total Slab is 544688kB
[1077528.153006]    GFP mask is 0xd0
[1077528.179007] binder: 15158: binder_alloc_buf, no vma
[1077528.179024] binder: 980:994 transaction failed 29201, size 88-4
[1077531.534580] CHG: get_prop_capacity: soc samples[0] = 100
[1077531.534597] CHG: get_prop_capacity: soc samples[1] = 100
[1077531.534608] CHG: get_prop_capacity: soc samples[2] = 100
[1077531.534618] CHG: get_prop_capacity: soc samples[3] = 100
[1077531.537690] BMS_DEBUG 107535      16:28:30     4177573    100%    266C
[1077531.544665] CHG: get_prop_capacity: soc samples[0] = 100
[1077531.544680] CHG: get_prop_capacity: soc samples[1] = 100
[1077531.544691] CHG: get_prop_capacity: soc samples[2] = 100
[1077531.544700] CHG: get_prop_capacity: soc samples[3] = 100
[1077531.548164] CHG: get_prop_capacity: soc samples[0] = 100
[1077531.548178] CHG: get_prop_capacity: soc samples[1] = 100
[1077531.548188] CHG: get_prop_capacity: soc samples[2] = 100
[1077531.548197] CHG: get_prop_capacity: soc samples[3] = 100
[1077537.472422] type=1400 audit(1496766516.553:45833): avc: denied { search } for pid=2370 comm="ndroid.systemui" name="15206" dev="proc" ino=12174739 scontext=u:r:platform_app:s0:c512,c768 tcontext=u:r:system_app:s0 tclass=dir permissive=0
[1077537.472735] type=1400 audit(1496766516.553:45834): avc: denied { search } for pid=2370 comm="ndroid.systemui" name="15206" dev="proc" ino=12174739 scontext=u:r:platform_app:s0:c512,c768 tcontext=u:r:system_app:s0 tclass=dir permissive=0
[1077537.472999] type=1400 audit(1496766516.553:45835): avc: denied { search } for pid=2370 comm="ndroid.systemui" name="15206" dev="proc" ino=12174739 scontext=u:r:platform_app:s0:c512,c768 tcontext=u:r:system_app:s0 tclass=dir permissive=0
[1077541.017542] init: Service 'atfwd' (pid 9821) exited with status 255
[1077541.017582] init: Service 'atfwd' (pid 9821) killing any children in process group
[1077541.018827] init: Starting service 'atfwd'...


问:
shuffle array in Go
I tried to translate the following Python code to Go

```<code>import random

list = [i for i in range(1, 25)]
random.shuffle(list)
print(list)
</code>```

but found my Go version lengthy and awkward because there is no shuffle function and I had to implement interfaces and convert types.

What would be an idiomatic Go version of my code?

答:
When using the math/rand package, do not forget to set a source

```<code>// Random numbers are generated by a Source. Top-level functions, such as
// Float64 and Int, use a default shared Source that produces a deterministic
// sequence of values each time a program is run. Use the Seed function to
// initialize the default Source if different behavior is required for each run.
</code>```

So I wrote a Shuffle function that takes this into consideration:

```<code>import (
    "math/rand"
)

func Shuffle(array []interface{}, source rand.Source) {
    random := rand.New(source)
    for i := len(array) - 1; i > 0; i-- {
        j := random.Intn(i + 1)
        array[i], array[j] = array[j], array[i]
    }
}
</code>```

And to use it:

```<code>source := rand.NewSource(time.Now().UnixNano())
array := []interface{}{"a", "b", "c"}

Shuffle(array, source) // [c b a]
</code>```

If you would like to use it, you can find it here https://github.com/shomali11/util

Title: shuffle array in Go

Body:
I tried to translate the following Python code to Go

import random

list = [i for i in range(1, 25)]
random.shuffle(list)
print(list)

but found my Go version lengthy and awkward because there is no shuffle function and I had to implement interfaces and convert types.

What would be an idiomatic Go version of my code?

Body:
When using the math/rand package, do not forget to set a source

// Random numbers are generated by a Source. Top-level functions, such as
// Float64 and Int, use a default shared Source that produces a deterministic
// sequence of values each time a program is run. Use the Seed function to
// initialize the default Source if different behavior is required for each run.

So I wrote a Shuffle function that takes this into consideration:

import (
    "math/rand"
)

func Shuffle(array []interface{}, source rand.Source) {
    random := rand.New(source)
    for i := len(array) - 1; i > 0; i-- {
        j := random.Intn(i + 1)
        array[i], array[j] = array[j], array[i]
    }
}

And to use it:

source := rand.NewSource(time.Now().UnixNano())
array := []interface{}{"a", "b", "c"}

Shuffle(array, source) // [c b a]

If you would like to use it, you can find it here https://github.com/shomali11/util


问:
When build opencv, could not find the file "cv2.so"
I compiled OpenCV 3.0.0 with python2.7 in Debian system at a Board with a extended SD card (BeagleBone Black).

After OpenCV installed, there seems no error. There are many generated files in the 'Lib' folder.

Those files are named like:

```<code>libopencv_core.so
libopencv_dataset.so
libopencv_imgproc.so ...
</code>```

I could not find the file cv2.so, even searched the whole file system.

I have tried several times, just can not find cv2.so.

Who knows the reason? Thanks.

make config checked, seems correct:

```<code>sudo cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local -D
</code>```

答:
I think you may try to find cv2.so in your download OpenCV directory.

I meet the same problem and finally find it in

dir = "./myopencv/opencv/build/lib".

When I try to solve the problem, I find that cv2.so may be a collection of some .so files. As if your version is matched, even you getting it from other's computer is OK.

ContentLicense: CC BY-SA 4.0

Body:
I compiled OpenCV 3.0.0 with python2.7 in Debian system at a Board with a extended SD card (BeagleBone Black).

After OpenCV installed, there seems no error. There are many generated files in the 'Lib' folder.

Those files are named like:

libopencv_core.so
libopencv_dataset.so
libopencv_imgproc.so ...

I could not find the file cv2.so, even searched the whole file system.

I have tried several times, just can not find cv2.so.

Who knows the reason? Thanks.

make config checked, seems correct:

sudo cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local -D


问:
How do I reference an object within an array within an object in xcode 8?
I'm looking to try and reference all "titles" within this json (link here) in xcode 8. The issue is there's an object and array that need to be referenced (i believe) before I can pull the title data, and I'm not sure how to do that.

So far this is what i've got:

```<code>func fetchFeed(){
    let urlRequest = URLRequest(url: URL(string: "http://itunes.apple.com/us/rss/topalbums/limit=10/json")!)

    let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in

        if error != nil {
            print(error)
            return
        }

        self.artists = [Artist]()
        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]

            if let feedFromJson = json["feed"]?["entry"] as? [[String : AnyObject]] {
                for feedFromJson in feedsFromJson {
                    let feed = Feed()
                    if let entry = feedFromJson["entry"] as? String, let author = feedFromJson["domain"] as? String {

                        feed.entry = entry

                        article.headline = title

                    }
                    self.articles?.append(article)
                }
            }
            DispatchQueue.main.async {
                self.tableview.reloadData()
</code>```

And thank you for your help in advance!

答:
I'm working hard to try to understand what you need. If you want to get an Article array where the headline is the title label for the entry, here is how I cheated it out.

```<code>func articles(from json: Any?) -> [Article] {
    guard let json = json as? NSDictionary, let entries = json.value(forKeyPath: "feed.entry") as? [NSDictionary] else {
        return []
    }

    return entries.flatMap { entry in
        guard let title = entry.value(forKeyPath: "title.label") as? String else {
            return nil
        }

        var article = Article()
        article.headline = title
        return article
    }
}
</code>```

you call it as such

```<code>self.articles = articles(from: json)
</code>```

NSDictionary has the method value(forKeyPath:) that is near magic. Calling json.value(forKeyPath: "feed.entry") returns an array of dictionaries. Each dictionary is an "entry" object in the json. Next, I map each entry to call entry.value(forKeyPath: "title.label") which returns a string.

If this is something more than a quick solution, then I would consider adding SwiftyJSON to your project.

```<code>func articles(from json: Any?) -> [Article] {
    return JSON(json)["feed"]["entry"].arrayValue.flatMap { entry in
        guard let title = entry["title"]["label"].string else {
            return nil
        }

        var article = Article()
        article.headline = title
        return article
    }
}
</code>```

Body:
I'm looking to try and reference all "titles" within this json (link here) in xcode 8. The issue is there's an object and array that need to be referenced (i believe) before I can pull the title data, and I'm not sure how to do that.

So far this is what i've got:

func fetchFeed(){
    let urlRequest = URLRequest(url: URL(string: "http://itunes.apple.com/us/rss/topalbums/limit=10/json")!)

    let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in

        if error != nil {
            print(error)
            return
        }

        self.artists = [Artist]()
        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]

            if let feedFromJson = json["feed"]?["entry"] as? [[String : AnyObject]] {
                for feedFromJson in feedsFromJson {
                    let feed = Feed()
                    if let entry = feedFromJson["entry"] as? String, let author = feedFromJson["domain"] as? String {

                        feed.entry = entry

                        article.headline = title

                    }
                    self.articles?.append(article)
                }
            }
            DispatchQueue.main.async {
                self.tableview.reloadData()

And thank you for your help in advance!

Body:
I'm working hard to try to understand what you need. If you want to get an Article array where the headline is the title label for the entry, here is how I cheated it out.

func articles(from json: Any?) -> [Article] {
    guard let json = json as? NSDictionary, let entries = json.value(forKeyPath: "feed.entry") as? [NSDictionary] else {
        return []
    }

    return entries.flatMap { entry in
        guard let title = entry.value(forKeyPath: "title.label") as? String else {
            return nil
        }

        var article = Article()
        article.headline = title
        return article
    }
}

you call it as such

self.articles = articles(from: json)

NSDictionary has the method value(forKeyPath:) that is near magic. Calling json.value(forKeyPath: "feed.entry") returns an array of dictionaries. Each dictionary is an "entry" object in the json. Next, I map each entry to call entry.value(forKeyPath: "title.label") which returns a string.

If this is something more than a quick solution, then I would consider adding SwiftyJSON to your project.

func articles(from json: Any?) -> [Article] {
    return JSON(json)["feed"]["entry"].arrayValue.flatMap { entry in
        guard let title = entry["title"]["label"].string else {
            return nil
        }

        var article = Article()
        article.headline = title
        return article
    }
}


问:
Selenium: FirefoxProfile exception Can't load the profile. Python script called from PHP
My python script has the following code:

```<code>firefox_profile = webdriver.FirefoxProfile()
self.driver = webdriver.Firefox(firefox_profile=firefox_profile)
</code>```

When I execute the script from bash it works, but if I call the script from a PHP file, with the following command:

```<code>shell_exec("python path_to_the_script");
</code>```

I receive the exception:

```<code>selenium.common.exceptions.WebDriverException: Message: Can't load the profile. Profile Dir: /tmp/tmp7Ob0z6/webdriver-py-profilecopy If you specified a log_file in the FirefoxBinary constructor, check it for details.
</code>```

I've also tried to set the profile manually, like this:

```<code> firefox_profile = webdriver.FirefoxProfile(profile_directory='path_to_the_profile_dir')
</code>```

But nothing changed, while if I set the profile directory path like this:

```<code>firefox_profile = webdriver.FirefoxProfile(profile_directory='path_to_the_profile_dir')
firefox_profile.profile_dir = 'path_to_the_profile_dir'
</code>```

The exception error changes to this:

```<code>selenium.common.exceptions.WebDriverException: Message: Can't load the profile. Profile Dir: path_to_the_profile_dir If you specified a log_file in the FirefoxBinary constructor, check it for details.
</code>```

I've set the permissions to 777 for all the involved directories, and also tried to override the FirefoxBinary.launch_browser function so that it uses a greater timeout value, but id did not work.
I'm using Python 2.7, Selenium 2.53.6 and Firefox 46.0.1

Firefox is working in headless mode, through Xvfb and pyvirtualdisplay.

答:
This happens because you have updated firefox to a version that's no longer supported by selenium.

So to fix this you have 2 options.

Downgrade your firefox to an older version then 47

Update Selenium and Install geckodriver (recommended and easy)

If you have ubuntu follow this fix below:

1. Update selenium with "sudo pip install -U selenium"

2. Download the geckodriver from github -->
Gecko Github Link

3. Extract the tar.gz folder and move the gecko executable to /usr/local/bin

4. Now open your terminal and enter this command:
export PATH=$PATH:/usr/local/bin/geckodriver

That should fix the issue... atleast it worked for me.

My Source: StackOverflow - Geckodriver

Body:
My python script has the following code:

firefox_profile = webdriver.FirefoxProfile()
self.driver = webdriver.Firefox(firefox_profile=firefox_profile)

When I execute the script from bash it works, but if I call the script from a PHP file, with the following command:

shell_exec("python path_to_the_script");

I receive the exception:

selenium.common.exceptions.WebDriverException: Message: Can't load the profile. Profile Dir: /tmp/tmp7Ob0z6/webdriver-py-profilecopy If you specified a log_file in the FirefoxBinary constructor, check it for details.

I've also tried to set the profile manually, like this:

 firefox_profile = webdriver.FirefoxProfile(profile_directory='path_to_the_profile_dir')

But nothing changed, while if I set the profile directory path like this:

firefox_profile = webdriver.FirefoxProfile(profile_directory='path_to_the_profile_dir')
firefox_profile.profile_dir = 'path_to_the_profile_dir'

The exception error changes to this:

selenium.common.exceptions.WebDriverException: Message: Can't load the profile. Profile Dir: path_to_the_profile_dir If you specified a log_file in the FirefoxBinary constructor, check it for details.

I've set the permissions to 777 for all the involved directories, and also tried to override the FirefoxBinary.launch_browser function so that it uses a greater timeout value, but id did not work.
I'm using Python 2.7, Selenium 2.53.6 and Firefox 46.0.1

Firefox is working in headless mode, through Xvfb and pyvirtualdisplay.


问:
Remove Sub Strings pandas, python
I have a df of high schools.  I'm trying to strip out the generic endings of the school's name.

```<code>in[1]:df
out[2]:
     time    school
1    09:00   Brown Academy
2    10:00   Covfefe High School
3    11:00   Bradley High
4    12:00   Johnson Prep

school_endings = ['Academy','Prep,'High','High School']
</code>```

Desired:

```<code>out[3]:
     time    school
1    09:00   Brown
2    10:00   Covfefe
3    11:00   Bradley
4    12:00   Johnson
</code>```

答:
```<code>endings = ['Academy', 'Prep', 'High', 'High School']

endings = sorted(endings, key=len, reverse=True)

df.assign(school=df.school.replace(endings, '', regex=True).str.strip())

    time   school
1  09:00    Brown
2  10:00  Covfefe
3  11:00  Bradley
4  12:00  Johnson
</code>```

Title: Remove Sub Strings pandas, python

Body:
I have a df of high schools.  I'm trying to strip out the generic endings of the school's name.

in[1]:df
out[2]:
     time    school
1    09:00   Brown Academy
2    10:00   Covfefe High School
3    11:00   Bradley High
4    12:00   Johnson Prep

school_endings = ['Academy','Prep,'High','High School']

Desired:

out[3]:
     time    school
1    09:00   Brown
2    10:00   Covfefe
3    11:00   Bradley
4    12:00   Johnson


答:
Just open the file, and then split these lines, I realized that the result you need is like (int, string) ,so you can use map to do this and then return tuple:

```<code>with open('out.csv') as f:
    print([tuple(map(lambda x: int (x) if x.isdigit() else x,i.split())) for i in f])
</code>```

Output:

```<code>[(1712, 'Albert'), (1703, 'Benny'), (1799, 'Henry'), (1735, 'Jessica'), (1722, 'Lucas'), (1701, 'Luke'), (1757, 'William'), (1777, 'Jenny'), (1783, 'Lucia'), (1764, 'Venus'), (1718, 'Felicitas')]
</code>```

Body:
Just open the file, and then split these lines, I realized that the result you need is like (int, string) ,so you can use map to do this and then return tuple:

with open('out.csv') as f:
    print([tuple(map(lambda x: int (x) if x.isdigit() else x,i.split())) for i in f])

Output:

[(1712, 'Albert'), (1703, 'Benny'), (1799, 'Henry'), (1735, 'Jessica'), (1722, 'Lucas'), (1701, 'Luke'), (1757, 'William'), (1777, 'Jenny'), (1783, 'Lucia'), (1764, 'Venus'), (1718, 'Felicitas')]


问:
Color cell RED if cell above value is lower
I need a formula/script for a Google spreadsheet that will do this:

If the current cell value is higher than the value in the cell above the make the current cell background red (if less than or equal to then leave white), something like this: =IF((C34>B34),"make background red","leave background white") just not sure if this will work or I need a more complex script.

I need this formula to work across 224 cells (28 columns and 8 rows). Conditional formatting wont work.

There will be upto 20 people viewing the document on the day, only one will be editing the data. Will a script slow down the working of the live spreadsheet as I have a few more quite complex formulas I need to calculate the data from the main sheet to a summary sheet.

I have searched here and other forums but everyone's formulas are unique!

Cheers

答:
Conditional formatting wont work.

Probably not at the time that was written but it does now.

Assuming your array starts in B34 for its top left, clear formatting and select B35:AC41 and Format, Conditional formatting..., Format cells if... Custom formula is and:

```<code>=A35>A34
</code>```

select red fill and Done.

Body:
Conditional formatting wont work.

Probably not at the time that was written but it does now.

Assuming your array starts in B34 for its top left, clear formatting and select B35:AC41 and Format, Conditional formatting..., Format cells if... Custom formula is and:

=A35>A34

select red fill and Done.


Body:
Here's what I have in the text file:

1712 Albert
1703 Benny
1799 Henry
1735 Jessica
1722 Lucas
1701 Luke
1757 William
1777 Jenny
1783 Lucia
1764 Venus
1718 Felicitas

Here's what I have done to read the file but I have no idea how to put them into a list of tuples

def readRecords(filepath):
    file = open('Students1.txt', 'r')
    filecontent = file.readlines()
    file.close()
    return filecontent

Here's what the output is supposed to be:

Body:
Location = ["1712","1703","1799",...]
Name = ["Albert","Benny","Henry",...]

using a zip function:

z = zip(Location, Name)
print z

Output:

[("1712","Albert"),("1703","Benny"),...]


问:
How to summarize strings into shell globs
Are there any Ruby idioms or popular libraries for consolidating strings into a shell glob that would generate them? For example, given the strings,

```<code>abc1
abc2
abc3
</code>```

I want to produce the string abc{1..3} or abc{1,2,3}. It's much like summarizing subnets in IP addressing.

I imagine a Rubyesque approach might involve sorting the strings and then building an array of their constituent characters, placing characters that don't overlap into nested arrays, recursively. However if there is something already out there, I'd rather not reinvent that wheel.

答:
I borrowed the accepted solution to Finding common string in array of strings (ruby) and used a recursive algorithm:

```<code>def longest_common_substr(strings)
  shortest = strings.min_by &:length
  maxlen = shortest.length
  maxlen.downto(0) do |len|
    0.upto(maxlen - len) do |start|
      substr = shortest[start,len]
      return substr if strings.all?{|str| str.include? substr }
    end
  end
end

def create_glob(files)
  return '' if files.compact.empty?

  stub=longest_common_substr(files)
  if stub.length == 0
    expansion = files.uniq.join(',')
    return '' if expansion == ''
    return '{' + expansion + '}'
  end

  pre =  []
  post = []

  files.each do |file|
    i = file.index(stub)

    pre  << file[0, i]
    post << file[i+stub.length..-1]
  end
  return create_glob(pre) + stub + create_glob(post)
end
</code>```

That works well for your example:

```<code>puts create_glob(['abc1',
                  'abc2',
                  'abc3'
                 ])
#=> abc{1,2,3}
</code>```

It also covers more complicated cases such as variable prefixes:

```<code>puts create_glob(['first.abc1',
                  'second.abc2',
                  'third.abc3'
                 ])
#=> {first,second,third}.abc{1,2,3}
</code>```

And even missing values:

```<code>puts create_glob(['.abc1',
                  'abc',
                  'abc3'
                 ])
#=> {.,}abc{1,,3}
</code>```

Notice brace expansion might produce strings that are not files. For instance, the last example expands like this:

```<code>$ echo {.,}abc{1,,3}
.abc1 .abc .abc3 abc1 abc abc3
</code>```

So you have to be just a little bit careful using the output.

Body:
Are there any Ruby idioms or popular libraries for consolidating strings into a shell glob that would generate them? For example, given the strings,

abc1
abc2
abc3

I want to produce the string abc{1..3} or abc{1,2,3}. It's much like summarizing subnets in IP addressing.

I imagine a Rubyesque approach might involve sorting the strings and then building an array of their constituent characters, placing characters that don't overlap into nested arrays, recursively. However if there is something already out there, I'd rather not reinvent that wheel.

Body:
I borrowed the accepted solution to Finding common string in array of strings (ruby) and used a recursive algorithm:

def longest_common_substr(strings)
  shortest = strings.min_by &:length
  maxlen = shortest.length
  maxlen.downto(0) do |len|
    0.upto(maxlen - len) do |start|
      substr = shortest[start,len]
      return substr if strings.all?{|str| str.include? substr }
    end
  end
end

def create_glob(files)
  return '' if files.compact.empty?

  stub=longest_common_substr(files)
  if stub.length == 0
    expansion = files.uniq.join(',')
    return '' if expansion == ''
    return '{' + expansion + '}'
  end

  pre =  []
  post = []

  files.each do |file|
    i = file.index(stub)

    pre  << file[0, i]
    post << file[i+stub.length..-1]
  end
  return create_glob(pre) + stub + create_glob(post)
end

That works well for your example:

puts create_glob(['abc1',
                  'abc2',
                  'abc3'
                 ])
#=> abc{1,2,3}

It also covers more complicated cases such as variable prefixes:

puts create_glob(['first.abc1',
                  'second.abc2',
                  'third.abc3'
                 ])
#=> {first,second,third}.abc{1,2,3}

And even missing values:

puts create_glob(['.abc1',
                  'abc',
                  'abc3'
                 ])
#=> {.,}abc{1,,3}

Notice brace expansion might produce strings that are not files. For instance, the last example expands like this:

$ echo {.,}abc{1,,3}
.abc1 .abc .abc3 abc1 abc abc3

So you have to be just a little bit careful using the output.


问:
is $PROGRAMFILES a constant declared in NSIS or is it the environment variable read from Windows?
I'm a newbie to NSIS and was wondering how $PROGRAMFILES gets the value. I know:

In a 32-bit windows,

$PROGRAMFILES: represents C:\Program Files

and

In 64-bit windows,

$PROGRAMFILES, $PROGRAMFILES32: represents C:\Program Files (x86)

where as, $PROGRAMFILES64: represents C:\Program Files

My question is, are these the constants set in NSIS or these are values read from Windows environment variable??

Thanks in advance.

答:
I modified this NSIS Constants script a little bit to allow support for showing the correct environment variables available to both 32-bit and 64-bit machines. Just compile this script, execute, and view the supplied INI for for all available constants specific to your version of windows.

NSIS Constants

```<code>WindowIcon Off
SilentInstall Silent
AutoCloseWindow True
Name "NSIS Constants"
OutFile "NSIS_Constants.exe"

!define DISABLEREDIR `kernel32::Wow64EnableWow64FsRedirection(i0)`
!define ENABLEREDIR  `kernel32::Wow64EnableWow64FsRedirection(i1)`

Var VER
Section "Main"
    ReadRegStr $0 HKLM "SOFTWARE\Microsoft\Windows NT\CurrentVersion" CurrentVersion
    StrCpy $VER $0
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "Windows" "Version" "$VER"

    SetRegView 64
    ReadRegStr $R0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion" CommonFilesDir
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$COMMONFILES" "64bit COMMONFILES" "$R0"
    SetRegView 32
    ReadRegStr $R0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion" CommonFilesDir
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$COMMONFILES" "32bit COMMONFILES" "$R0"

    SetRegView 64
    ReadRegStr $R0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion" ProgramFilesDir
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$PROGRAMFILES" "64bit PROGRAMFILES" "$R0"
    SetRegView 32
    ReadRegStr $R0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion" ProgramFilesDir
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$PROGRAMFILES" "32bit PROGRAMFILES" "$R0"

    System::Call `${DISABLEREDIR}`
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$SYSDIR" "64bit SYSDIR" "$SYSDIR"
    System::Call `${ENABLEREDIR}`
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$SYSDIR" "32bit SYSDIR" "$SYSDIR"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$ADMINTOOLS" "current ADMINTOOLS" "$ADMINTOOLS"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$ADMINTOOLS" "all ADMINTOOLS" "$ADMINTOOLS"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$APPDATA" "current APPDATA" "$APPDATA"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$APPDATA" "all APPDATA" "$APPDATA"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$CDBURN_AREA" "current CDBURN_AREA" "$CDBURN_AREA"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$CDBURN_AREA" "all CDBURN_AREA" "$CDBURN_AREA"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$CMDLINE" "current CMDLINE" "$CMDLINE"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$CMDLINE" "all CMDLINE" "$CMDLINE"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$COMMONFILES" "current COMMONFILES" "$COMMONFILES"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$COMMONFILES" "all COMMONFILES" "$COMMONFILES"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$COOKIES" "current COOKIES" "$COOKIES"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$COOKIES" "all COOKIES" "$COOKIES"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$DESKTOP" "current DESKTOP" "$DESKTOP"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$DESKTOP" "all DESKTOP" "$DESKTOP"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$DOCUMENTS" "current DOCUMENTS" "$DOCUMENTS"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$DOCUMENTS" "all DOCUMENTS" "$DOCUMENTS"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$EXEDIR" "current EXEDIR" "$EXEDIR"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$EXEDIR" "all EXEDIR" "$EXEDIR"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$FAVORITES" "current FAVORITES" "$FAVORITES"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$FAVORITES" "all FAVORITES" "$FAVORITES"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$FONTS" "current FONTS" "$FONTS"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$FONTS" "all FONTS" "$FONTS"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$HISTORY" "current HISTORY" "$HISTORY"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$HISTORY" "all HISTORY" "$HISTORY"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$HWNDPARENT" "current HWNDPARENT" "$HWNDPARENT"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$HWNDPARENT" "all HWNDPARENT" "$HWNDPARENT"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$INSTDIR" "current INSTDIR" "$INSTDIR"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$INSTDIR" "all INSTDIR" "$INSTDIR"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$INTERNET_CACHE" "current INTERNET_CACHE" "$INTERNET_CACHE"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$INTERNET_CACHE" "all INTERNET_CACHE" "$INTERNET_CACHE"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$LANGUAGE" "current LANGUAGE" "$LANGUAGE"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$LANGUAGE" "all LANGUAGE" "$LANGUAGE"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$LOCALAPPDATA" "current LOCALAPPDATA" "$LOCALAPPDATA"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$LOCALAPPDATA" "all LOCALAPPDATA" "$LOCALAPPDATA"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$MUSIC" "current MUSIC" "$MUSIC"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$MUSIC" "all MUSIC" "$MUSIC"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$NETHOOD" "current NETHOOD" "$NETHOOD"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$NETHOOD" "all NETHOOD" "$NETHOOD"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$OUTDIR" "current OUTDIR" "$OUTDIR"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$OUTDIR" "all OUTDIR" "$OUTDIR"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$PICTURES" "current PICTURES" "$PICTURES"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$PICTURES" "all PICTURES" "$PICTURES"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$PLUGINSDIR" "current PLUGINSDIR" "$PLUGINSDIR"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$PLUGINSDIR" "all PLUGINSDIR" "$PLUGINSDIR"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$PRINTHOOD" "current PRINTHOOD" "$PRINTHOOD"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$PRINTHOOD" "all PRINTHOOD" "$PRINTHOOD"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$PROFILE" "current PROFILE" "$PROFILE"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$PROFILE" "all PROFILE" "$PROFILE"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$PROGRAMFILES" "current PROGRAMFILES" "$PROGRAMFILES"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$PROGRAMFILES" "all PROGRAMFILES" "$PROGRAMFILES"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$QUICKLAUNCH" "current QUICKLAUNCH" "$QUICKLAUNCH"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$QUICKLAUNCH" "all QUICKLAUNCH" "$QUICKLAUNCH"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$RECENT" "current RECENT" "$RECENT"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$RECENT" "all RECENT" "$RECENT"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$RESOURCES" "current RESOURCES" "$RESOURCES"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$RESOURCES" "all RESOURCES" "$RESOURCES"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$RESOURCES_LOCALIZED" "current RESOURCES_LOCALIZED" "$RESOURCES_LOCALIZED"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$RESOURCES_LOCALIZED" "all RESOURCES_LOCALIZED" "$RESOURCES_LOCALIZED"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$SENDTO" "current SENDTO" "$SENDTO"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$SENDTO" "all SENDTO" "$SENDTO"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$SMPROGRAMS" "current SMPROGRAMS" "$SMPROGRAMS"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$SMPROGRAMS" "all SMPROGRAMS" "$SMPROGRAMS"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$SMSTARTUP" "current SMSTARTUP" "$SMSTARTUP"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$SMSTARTUP" "all SMSTARTUP" "$SMSTARTUP"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$STARTMENU" "current STARTMENU" "$STARTMENU"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$STARTMENU" "all STARTMENU" "$STARTMENU"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$SYSDIR" "current SYSDIR" "$SYSDIR"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$SYSDIR" "all SYSDIR" "$SYSDIR"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$TEMP" "current TEMP" "$TEMP"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$TEMP" "all TEMP" "$TEMP"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$TEMPLATES" "current TEMPLATES" "$TEMPLATES"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$TEMPLATES" "all TEMPLATES" "$TEMPLATES"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$VIDEOS" "current VIDEOS" "$VIDEOS"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$VIDEOS" "all VIDEOS" "$VIDEOS"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$WINDIR" "current WINDIR" "$WINDIR"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$WINDIR" "all WINDIR" "$WINDIR"

    MessageBox MB_USERICON "NSIS Constants for this computer are in Windows_$VER_Constants.ini"

SectionEnd
</code>```

When executed it should output something similar to the following. These values or for a 64-bit Windows 8.1..

```<code>[Windows]
Version=6.3

[$APPDATA]
current APPDATA=C:\Users\Devin\AppData\Roaming
all APPDATA=C:\ProgramData

[$COMMONFILES]
current COMMONFILES=C:\Program Files (x86)\Common Files
all COMMONFILES=C:\Program Files (x86)\Common Files
64bit COMMONFILES=C:\Program Files\Common Files
32bit COMMONFILES=C:\Program Files (x86)\Common Files

[$DESKTOP]
current DESKTOP=C:\Users\Devin\Desktop
all DESKTOP=C:\Users\Public\Desktop

[$DOCUMENTS]
current DOCUMENTS=C:\Users\Devin\Documents
all DOCUMENTS=C:\Users\Public\Documents

[$PROGRAMFILES]
current PROGRAMFILES=C:\Program Files (x86)
all PROGRAMFILES=C:\Program Files (x86)
64bit PROGRAMFILES=C:\Program Files
32bit PROGRAMFILES=C:\Program Files (x86)

[$SYSDIR]
current SYSDIR=C:\Windows\system32
all SYSDIR=C:\Windows\system32
64bit SYSDIR=C:\Windows\system32
32bit SYSDIR=C:\Windows\system32
</code>```

There is plenty more given. This is just an example of what this script will output. Hope this helps. =)

Body:
I modified this NSIS Constants script a little bit to allow support for showing the correct environment variables available to both 32-bit and 64-bit machines. Just compile this script, execute, and view the supplied INI for for all available constants specific to your version of windows.

NSIS Constants

WindowIcon Off
SilentInstall Silent
AutoCloseWindow True
Name "NSIS Constants"
OutFile "NSIS_Constants.exe"

!define DISABLEREDIR `kernel32::Wow64EnableWow64FsRedirection(i0)`
!define ENABLEREDIR  `kernel32::Wow64EnableWow64FsRedirection(i1)`

Var VER
Section "Main"
    ReadRegStr $0 HKLM "SOFTWARE\Microsoft\Windows NT\CurrentVersion" CurrentVersion
    StrCpy $VER $0
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "Windows" "Version" "$VER"

    SetRegView 64
    ReadRegStr $R0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion" CommonFilesDir
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$COMMONFILES" "64bit COMMONFILES" "$R0"
    SetRegView 32
    ReadRegStr $R0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion" CommonFilesDir
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$COMMONFILES" "32bit COMMONFILES" "$R0"

    SetRegView 64
    ReadRegStr $R0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion" ProgramFilesDir
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$PROGRAMFILES" "64bit PROGRAMFILES" "$R0"
    SetRegView 32
    ReadRegStr $R0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion" ProgramFilesDir
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$PROGRAMFILES" "32bit PROGRAMFILES" "$R0"

    System::Call `${DISABLEREDIR}`
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$SYSDIR" "64bit SYSDIR" "$SYSDIR"
    System::Call `${ENABLEREDIR}`
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$SYSDIR" "32bit SYSDIR" "$SYSDIR"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$ADMINTOOLS" "current ADMINTOOLS" "$ADMINTOOLS"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$ADMINTOOLS" "all ADMINTOOLS" "$ADMINTOOLS"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$APPDATA" "current APPDATA" "$APPDATA"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$APPDATA" "all APPDATA" "$APPDATA"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$CDBURN_AREA" "current CDBURN_AREA" "$CDBURN_AREA"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$CDBURN_AREA" "all CDBURN_AREA" "$CDBURN_AREA"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$CMDLINE" "current CMDLINE" "$CMDLINE"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$CMDLINE" "all CMDLINE" "$CMDLINE"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$COMMONFILES" "current COMMONFILES" "$COMMONFILES"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$COMMONFILES" "all COMMONFILES" "$COMMONFILES"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$COOKIES" "current COOKIES" "$COOKIES"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$COOKIES" "all COOKIES" "$COOKIES"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$DESKTOP" "current DESKTOP" "$DESKTOP"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$DESKTOP" "all DESKTOP" "$DESKTOP"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$DOCUMENTS" "current DOCUMENTS" "$DOCUMENTS"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$DOCUMENTS" "all DOCUMENTS" "$DOCUMENTS"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$EXEDIR" "current EXEDIR" "$EXEDIR"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$EXEDIR" "all EXEDIR" "$EXEDIR"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$FAVORITES" "current FAVORITES" "$FAVORITES"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$FAVORITES" "all FAVORITES" "$FAVORITES"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$FONTS" "current FONTS" "$FONTS"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$FONTS" "all FONTS" "$FONTS"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$HISTORY" "current HISTORY" "$HISTORY"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$HISTORY" "all HISTORY" "$HISTORY"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$HWNDPARENT" "current HWNDPARENT" "$HWNDPARENT"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$HWNDPARENT" "all HWNDPARENT" "$HWNDPARENT"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$INSTDIR" "current INSTDIR" "$INSTDIR"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$INSTDIR" "all INSTDIR" "$INSTDIR"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$INTERNET_CACHE" "current INTERNET_CACHE" "$INTERNET_CACHE"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$INTERNET_CACHE" "all INTERNET_CACHE" "$INTERNET_CACHE"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$LANGUAGE" "current LANGUAGE" "$LANGUAGE"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$LANGUAGE" "all LANGUAGE" "$LANGUAGE"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$LOCALAPPDATA" "current LOCALAPPDATA" "$LOCALAPPDATA"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$LOCALAPPDATA" "all LOCALAPPDATA" "$LOCALAPPDATA"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$MUSIC" "current MUSIC" "$MUSIC"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$MUSIC" "all MUSIC" "$MUSIC"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$NETHOOD" "current NETHOOD" "$NETHOOD"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$NETHOOD" "all NETHOOD" "$NETHOOD"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$OUTDIR" "current OUTDIR" "$OUTDIR"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$OUTDIR" "all OUTDIR" "$OUTDIR"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$PICTURES" "current PICTURES" "$PICTURES"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$PICTURES" "all PICTURES" "$PICTURES"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$PLUGINSDIR" "current PLUGINSDIR" "$PLUGINSDIR"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$PLUGINSDIR" "all PLUGINSDIR" "$PLUGINSDIR"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$PRINTHOOD" "current PRINTHOOD" "$PRINTHOOD"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$PRINTHOOD" "all PRINTHOOD" "$PRINTHOOD"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$PROFILE" "current PROFILE" "$PROFILE"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$PROFILE" "all PROFILE" "$PROFILE"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$PROGRAMFILES" "current PROGRAMFILES" "$PROGRAMFILES"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$PROGRAMFILES" "all PROGRAMFILES" "$PROGRAMFILES"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$QUICKLAUNCH" "current QUICKLAUNCH" "$QUICKLAUNCH"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$QUICKLAUNCH" "all QUICKLAUNCH" "$QUICKLAUNCH"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$RECENT" "current RECENT" "$RECENT"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$RECENT" "all RECENT" "$RECENT"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$RESOURCES" "current RESOURCES" "$RESOURCES"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$RESOURCES" "all RESOURCES" "$RESOURCES"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$RESOURCES_LOCALIZED" "current RESOURCES_LOCALIZED" "$RESOURCES_LOCALIZED"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$RESOURCES_LOCALIZED" "all RESOURCES_LOCALIZED" "$RESOURCES_LOCALIZED"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$SENDTO" "current SENDTO" "$SENDTO"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$SENDTO" "all SENDTO" "$SENDTO"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$SMPROGRAMS" "current SMPROGRAMS" "$SMPROGRAMS"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$SMPROGRAMS" "all SMPROGRAMS" "$SMPROGRAMS"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$SMSTARTUP" "current SMSTARTUP" "$SMSTARTUP"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$SMSTARTUP" "all SMSTARTUP" "$SMSTARTUP"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$STARTMENU" "current STARTMENU" "$STARTMENU"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$STARTMENU" "all STARTMENU" "$STARTMENU"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$SYSDIR" "current SYSDIR" "$SYSDIR"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$SYSDIR" "all SYSDIR" "$SYSDIR"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$TEMP" "current TEMP" "$TEMP"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$TEMP" "all TEMP" "$TEMP"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$TEMPLATES" "current TEMPLATES" "$TEMPLATES"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$TEMPLATES" "all TEMPLATES" "$TEMPLATES"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$VIDEOS" "current VIDEOS" "$VIDEOS"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$VIDEOS" "all VIDEOS" "$VIDEOS"

    SetShellVarContext current
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$WINDIR" "current WINDIR" "$WINDIR"
    SetShellVarContext all
    WriteINIStr $EXEDIR\Windows_$VER_Constants.ini "$$WINDIR" "all WINDIR" "$WINDIR"

    MessageBox MB_USERICON "NSIS Constants for this computer are in Windows_$VER_Constants.ini"

SectionEnd

When executed it should output something similar to the following. These values or for a 64-bit Windows 8.1..

[Windows]
Version=6.3

[$APPDATA]
current APPDATA=C:\Users\Devin\AppData\Roaming
all APPDATA=C:\ProgramData

[$COMMONFILES]
current COMMONFILES=C:\Program Files (x86)\Common Files
all COMMONFILES=C:\Program Files (x86)\Common Files
64bit COMMONFILES=C:\Program Files\Common Files
32bit COMMONFILES=C:\Program Files (x86)\Common Files

[$DESKTOP]
current DESKTOP=C:\Users\Devin\Desktop
all DESKTOP=C:\Users\Public\Desktop

[$DOCUMENTS]
current DOCUMENTS=C:\Users\Devin\Documents
all DOCUMENTS=C:\Users\Public\Documents

[$PROGRAMFILES]
current PROGRAMFILES=C:\Program Files (x86)
all PROGRAMFILES=C:\Program Files (x86)
64bit PROGRAMFILES=C:\Program Files
32bit PROGRAMFILES=C:\Program Files (x86)

[$SYSDIR]
current SYSDIR=C:\Windows\system32
all SYSDIR=C:\Windows\system32
64bit SYSDIR=C:\Windows\system32
32bit SYSDIR=C:\Windows\system32

There is plenty more given. This is just an example of what this script will output. Hope this helps. =)


问:
integrating 2 lists and a data farme in RR
Please could you advise on the R code I could use in order to do the    following operation :

I have 2 lists of "genome coordinates" : a list is composed by numbers that represent genome coordinates;

let's say list N:

```<code>n1
n2
n3
n4
</code>```

and a list M:

```<code>m1
m2
m3
m4
m5
</code>```

and a dataframe C, where for some pairs of coordinates (n,m)    from the lists above, we have a numerical intensity;

for example:

```<code>n1; m1; 100
n1; m2; 300
</code>```

The question would be : what is the most efficient R code I could use in order to integrate the list N, the list M, and the   dataframe C, in order to obtain a dataframe with:

list N as the columns names

list M as the rows names

the values in the cells of N * M, corresponding to the numerical values in the data frame C.

A little example would be :

```<code>     n1  n2  n3 n4
m1  100  -   -   -
m2  300  -   -   -
m3   -   -   -   -
m4   -   -   -   -
m5   -   -   -   -
</code>```

答:
You can do this using spread in the tidyr package, making sure to keep all values of n and m that appear in the two lists, even if they don't appear in C:

```<code>library(tidyr)
## Replicating the data
listN = list("n1","n2","n3","n4","n5")
listM = list("m1","m2","m3","m4","m5")
C = data.frame(n=c("n1","n2","n3"),m=c("m1","m2","m3"),I=c(100,300,400))
   n  m   I
1 n1 m1 100
2 n2 m2 300
3 n3 m3 400

## Defining factor levels of C using listM and listN, and keeping unused levels when doing the spread
C$n = factor(C$n,levels=unlist(listN))
C$m = factor(C$m,levels=unlist(listM))
res = spread(C,key="n",value="I",drop=F)
</code>```

This returns:

```<code>   m  n1  n2  n3 n4 n5
1 m1 100  NA  NA NA NA
2 m2  NA 300  NA NA NA
3 m3  NA  NA 400 NA NA
4 m4  NA  NA  NA NA NA
5 m5  NA  NA  NA NA NA
</code>```

Body:
Please could you advise on the R code I could use in order to do the    following operation :

I have 2 lists of "genome coordinates" : a list is composed by numbers that represent genome coordinates;

let's say list N:

n1
n2
n3
n4

and a list M:

m1
m2
m3
m4
m5

and a dataframe C, where for some pairs of coordinates (n,m)    from the lists above, we have a numerical intensity;

for example:

n1; m1; 100
n1; m2; 300

The question would be : what is the most efficient R code I could use in order to integrate the list N, the list M, and the   dataframe C, in order to obtain a dataframe with:

list N as the columns names

list M as the rows names

the values in the cells of N * M, corresponding to the numerical values in the data frame C.

A little example would be :

     n1  n2  n3 n4
m1  100  -   -   -
m2  300  -   -   -
m3   -   -   -   -
m4   -   -   -   -
m5   -   -   -   -

Body:
You can do this using spread in the tidyr package, making sure to keep all values of n and m that appear in the two lists, even if they don't appear in C:

library(tidyr)
## Replicating the data
listN = list("n1","n2","n3","n4","n5")
listM = list("m1","m2","m3","m4","m5")
C = data.frame(n=c("n1","n2","n3"),m=c("m1","m2","m3"),I=c(100,300,400))
   n  m   I
1 n1 m1 100
2 n2 m2 300
3 n3 m3 400

## Defining factor levels of C using listM and listN, and keeping unused levels when doing the spread
C$n = factor(C$n,levels=unlist(listN))
C$m = factor(C$m,levels=unlist(listM))
res = spread(C,key="n",value="I",drop=F)

This returns:

   m  n1  n2  n3 n4 n5
1 m1 100  NA  NA NA NA
2 m2  NA 300  NA NA NA
3 m3  NA  NA 400 NA NA
4 m4  NA  NA  NA NA NA
5 m5  NA  NA  NA NA NA