问:
How to iterate through a JSON Object with nested properties, manipulate and return a new object?
I have a JSON object with nested properties as follows:

```<code>var obj = {

 "a0": {
    "count": 41,
    "name": "Park",
    "new": {
      "id": 35,
      "registerid": 46
     }
  },

  "a1": {
    "count": 52,
    "name": "Greg",
    "old": {
      "id": 38,
      "registerid": 49
     }
  },

  "a2": {
    "count": 150,
    "name": "Sylvain",

  }

}
</code>```

I would like to iterate through this whole object and find the properties which have numeric values and replace them with a computed value, and return a new object.

So, if I pass in the above JSON object, I would like to return it back as:

```<code>result = {

     "a0": {
        "count": 411.067,
        "name": "Park",
        "new": {
          "id": 351.067,
          "registerid": 461.067
         }
      },

      "a1": {
        "count": 521.067,
        "name": "Greg",
        "old": {
          "id": 381.067,
          "registerid": 491.067
         }
      },

      "a2": {
        "count": 150.067,
        "name": "Sylvain"
      }

    }
</code>```

There is a similar question here which I asked previously and has a fabulous answer but it doesn't handle the nested case and it doesn't return the whole object with the replacements but does return a filtered object with numerical object properties.

I tried using the forEach on the Object.keys() and calling the map inside it, but seems like I am losing the variable scope inside the callback function.

```<code>let result = Object.keys(obj).forEach(function(key, index) {
  Object.keys(obj).map((key) => {
    let o = obj[key];
    console.log("Object is:", o);
    return Object.keys(o).reduce((r, k) => typeof o[k] === 'number' ? Object.assign(r, { [k]:precise(o[k], 5) }) : r , {});
  });
});

console.log(result);
</code>```

Could anyone please help me with this.

Thank you.

答:
I would use a recursive call:

```<code>function process(obj) {
  let result = {};
  Object.keys(obj).forEach(k => {
      if(typeof obj[k] === 'number') {
        result[k] = obj[k] += 0.067; // calculate you numeric properties here!
      }
      else if(typeof obj[k] === 'object') {
        result[k] = process(obj[k]); // a recursive call for nested objects
      }
      else {
        result[k] = obj[k]; // just pass an orginal value
      }
    }
  );
  return result;
}

let result = process(obj); // here the obj is the initial data object
</code>```

I also created Plunker demo.

Body:
I have a JSON object with nested properties as follows:

var obj = {

 "a0": {
    "count": 41,
    "name": "Park",
    "new": {
      "id": 35,
      "registerid": 46
     }
  },

  "a1": {
    "count": 52,
    "name": "Greg",
    "old": {
      "id": 38,
      "registerid": 49
     }
  },

  "a2": {
    "count": 150,
    "name": "Sylvain",

  }

}

I would like to iterate through this whole object and find the properties which have numeric values and replace them with a computed value, and return a new object.

So, if I pass in the above JSON object, I would like to return it back as:

result = {

     "a0": {
        "count": 411.067,
        "name": "Park",
        "new": {
          "id": 351.067,
          "registerid": 461.067
         }
      },

      "a1": {
        "count": 521.067,
        "name": "Greg",
        "old": {
          "id": 381.067,
          "registerid": 491.067
         }
      },

      "a2": {
        "count": 150.067,
        "name": "Sylvain"
      }

    }

There is a similar question here which I asked previously and has a fabulous answer but it doesn't handle the nested case and it doesn't return the whole object with the replacements but does return a filtered object with numerical object properties.

I tried using the forEach on the Object.keys() and calling the map inside it, but seems like I am losing the variable scope inside the callback function.

let result = Object.keys(obj).forEach(function(key, index) {
  Object.keys(obj).map((key) => {
    let o = obj[key];
    console.log("Object is:", o);
    return Object.keys(o).reduce((r, k) => typeof o[k] === 'number' ? Object.assign(r, { [k]:precise(o[k], 5) }) : r , {});
  });
});

console.log(result);

Could anyone please help me with this.

Thank you.

Body:
I would use a recursive call:

function process(obj) {
  let result = {};
  Object.keys(obj).forEach(k => {
      if(typeof obj[k] === 'number') {
        result[k] = obj[k] += 0.067; // calculate you numeric properties here!
      }
      else if(typeof obj[k] === 'object') {
        result[k] = process(obj[k]); // a recursive call for nested objects
      }
      else {
        result[k] = obj[k]; // just pass an orginal value
      }
    }
  );
  return result;
}

let result = process(obj); // here the obj is the initial data object

I also created Plunker demo.


来源: stackexchange

问:
R data.table by list of conditionals or row indices
I have a data table that includes distances. I want to run various operations within the data.table by my "id" variable and an inclusive distance threshold (e.g. Dist<1, Dist<2, etc.). I know how to run an operation by id and distance "by=list(id,Dist)", but I really want a by variable more like, "by=list(id,c(Dist<=1,Dist<=2,Dist<=3,Dist<=4,Dist<=5). Below is an example of my data structure and objective.

```<code>#load library
    library(data.table)
#create data
    set.seed(123L)
    dt<-data.table(id=factor(rep(1:10,5)),V1=rnorm(50,5,5),Dist=sample(1:5,50,replace=T))
#calculate mean of V1 by id and distance (wrong results)
    dt2<-dt[,.(MeanV1=mean(V1)),by=list(id,Dist)]
#calculate mean of V1 by id and conditional distance (right results, wrong method)
    dt2.1<-dt[Dist<=1,.(MeanV1=mean(V1)),by=id]
    dt2.2<-dt[Dist<=2,.(MeanV1=mean(V1)),by=id]
    dt2.3<-dt[Dist<=3,.(MeanV1=mean(V1)),by=id]
    dt2.4<-dt[Dist<=4,.(MeanV1=mean(V1)),by=id]
    dt2.5<-dt[Dist<=5,.(MeanV1=mean(V1)),by=id]
    dt2<-rbind(dt2.1,dt2.2,dt2.3,dt2.4,dt2.5)
#ideal methods if either were valid
    #syntax 1
        dt2<-dt[,.(MeanV1=mean(V1)),by=list(id,c(Dist<=1,Dist<=2,Dist<=3,Dist<=4,Dist<=5))]
    #syntax 2
        rowindices<-list(dt$Dist<=1,dt$Dist<=2,dt$Dist<=3,dt$Dist<=4,dt$Dist<=5)
        dt2<-dt[,.(MeanV1=mean(V1)),by=list(id,rowindices)]
</code>```

Thanks in advance.

答:
Frank's answer in the comments will achieve what you're after. Here's an explanation:

First, one thing you can do with data.table is a "non-equi join", which is what the first data.table call is doing.

First we create a table of thresholds we want to operate over:

```<code>> thresholds <- data.table(dist_threshold=1:5)
> thresholds
   dist_threshold
1:              1
2:              2
3:              3
4:              4
5:              5
</code>```

Next we perform a non-equi join on the original table with the thresholds table: this creates a new table where the dist column contains all entries for each ID below that threshold:

```<code>> passes_threshold <- dt[thresholds, on=.(Dist < dist_threshold), # non-equi join
+    allow.cartesian=TRUE, # Fixes error, see details in ?data.table
+    nomatch=0 # Do not include thresholds which no row satisfies (i.e. Dist < 1)
+   ]
> passes_threshold
# Here the Dist column now means "Dist < dist_threshold".
# There will be 5 rows where Dist < 2, 19 where Dist < 3,
# 30 where Dist < 4, and 40 Where Dist < 5
    id        V1 Dist
 1:  8  8.521825    2
 2:  5  2.002523    2
 3:  6  8.698732    2
 4:  9 -1.701028    2
 5:  2  6.114119    2
---
90:  6 -1.392776    5
91: 10  9.033493    5
92:  1  9.565713    5
93:  5  4.579124    5
94:  7  1.498690    5
</code>```

We can now combine the join with the summary operations in the j and by arguments to calculate the average distance per threshold:

```<code>> passes_threshold[,.(mean_Dist_by_threshold=mean(V1)), by=.(threshold=Dist)]
       threshold mean_Dist_per_threshold
1:         2                4.727234
2:         3                4.615258
3:         4                4.202856
4:         5                4.559240
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a data table that includes distances. I want to run various operations within the data.table by my "id" variable and an inclusive distance threshold (e.g. Dist<1, Dist<2, etc.). I know how to run an operation by id and distance "by=list(id,Dist)", but I really want a by variable more like, "by=list(id,c(Dist<=1,Dist<=2,Dist<=3,Dist<=4,Dist<=5). Below is an example of my data structure and objective.

#load library
    library(data.table)
#create data
    set.seed(123L)
    dt<-data.table(id=factor(rep(1:10,5)),V1=rnorm(50,5,5),Dist=sample(1:5,50,replace=T))
#calculate mean of V1 by id and distance (wrong results)
    dt2<-dt[,.(MeanV1=mean(V1)),by=list(id,Dist)]
#calculate mean of V1 by id and conditional distance (right results, wrong method)
    dt2.1<-dt[Dist<=1,.(MeanV1=mean(V1)),by=id]
    dt2.2<-dt[Dist<=2,.(MeanV1=mean(V1)),by=id]
    dt2.3<-dt[Dist<=3,.(MeanV1=mean(V1)),by=id]
    dt2.4<-dt[Dist<=4,.(MeanV1=mean(V1)),by=id]
    dt2.5<-dt[Dist<=5,.(MeanV1=mean(V1)),by=id]
    dt2<-rbind(dt2.1,dt2.2,dt2.3,dt2.4,dt2.5)
#ideal methods if either were valid
    #syntax 1
        dt2<-dt[,.(MeanV1=mean(V1)),by=list(id,c(Dist<=1,Dist<=2,Dist<=3,Dist<=4,Dist<=5))]
    #syntax 2
        rowindices<-list(dt$Dist<=1,dt$Dist<=2,dt$Dist<=3,dt$Dist<=4,dt$Dist<=5)
        dt2<-dt[,.(MeanV1=mean(V1)),by=list(id,rowindices)]

Thanks in advance.

Body:
Frank's answer in the comments will achieve what you're after. Here's an explanation:

First, one thing you can do with data.table is a "non-equi join", which is what the first data.table call is doing.

First we create a table of thresholds we want to operate over:

> thresholds <- data.table(dist_threshold=1:5)
> thresholds
   dist_threshold
1:              1
2:              2
3:              3
4:              4
5:              5

Next we perform a non-equi join on the original table with the thresholds table: this creates a new table where the dist column contains all entries for each ID below that threshold:

> passes_threshold <- dt[thresholds, on=.(Dist < dist_threshold), # non-equi join
+    allow.cartesian=TRUE, # Fixes error, see details in ?data.table
+    nomatch=0 # Do not include thresholds which no row satisfies (i.e. Dist < 1)
+   ]
> passes_threshold
# Here the Dist column now means "Dist < dist_threshold".
# There will be 5 rows where Dist < 2, 19 where Dist < 3,
# 30 where Dist < 4, and 40 Where Dist < 5
    id        V1 Dist
 1:  8  8.521825    2
 2:  5  2.002523    2
 3:  6  8.698732    2
 4:  9 -1.701028    2
 5:  2  6.114119    2
---
90:  6 -1.392776    5
91: 10  9.033493    5
92:  1  9.565713    5
93:  5  4.579124    5
94:  7  1.498690    5

We can now combine the join with the summary operations in the j and by arguments to calculate the average distance per threshold:

> passes_threshold[,.(mean_Dist_by_threshold=mean(V1)), by=.(threshold=Dist)]
       threshold mean_Dist_per_threshold
1:         2                4.727234
2:         3                4.615258
3:         4                4.202856
4:         5                4.559240


问:
Firebase Rest API for android app performance results
As we all know that App performance monitoring has been provided by Firebase. I have integrated my app with the same and got results at Firebase console. I would like to get the results through Rest API provided by Firebase or some other way. Please let me know if any API provided by the Firebase for the same.</p>

答: There's currently no REST API for Firebase Performance Monitoring.  Please file a feature request if you would like to see that.</p>


问:
Tallying elements in a dataframe that meet a logic check
I have a dataframe (studentData)

```<code>     StudentID   Freshmen    Sophomore      Lot200      Lot700
         001           1           0         200         000
         002           0           1         200         700
         003           1           0         200         000
</code>```

I want a total of what the different academic years spent on parking. If Freshmen is 1 that is their year, similarity for Sophomore being 1.

Want to have this dataframe (costs)

```<code>  Freshmen        Sophomore
  400             900
</code>```

Tried

```<code>    if(length(which(studentData$Freshmen ==1))
       {
          costs$Freshmen <- studentData$Lot200 + studentData$Lot700
       }
</code>```

But this results in returning TRUE for every entry and effectively adding every students expenditure on parking regardless of academic year. Any ideas how I might correct this?

答:
You could try this:

```<code>library(tidyverse)

df %>%
  mutate(lot_sum = Lot200 + Lot700,
         Freshmen = sum(lot_sum * Freshmen),
         Sophomore = sum(lot_sum * Sophomore)) %>%
  distinct(Freshmen, Sophomore)
</code>```

Which returns:

```<code>  Freshmen Sophomore
1      400       900
</code>```

Body:
I have a dataframe (studentData)

     StudentID   Freshmen    Sophomore      Lot200      Lot700
         001           1           0         200         000
         002           0           1         200         700
         003           1           0         200         000

I want a total of what the different academic years spent on parking. If Freshmen is 1 that is their year, similarity for Sophomore being 1.

Want to have this dataframe (costs)

  Freshmen        Sophomore
  400             900

Tried

    if(length(which(studentData$Freshmen ==1))
       {
          costs$Freshmen <- studentData$Lot200 + studentData$Lot700
       }

But this results in returning TRUE for every entry and effectively adding every students expenditure on parking regardless of academic year. Any ideas how I might correct this?

Body:
You could try this:

library(tidyverse)

df %>%
  mutate(lot_sum = Lot200 + Lot700,
         Freshmen = sum(lot_sum * Freshmen),
         Sophomore = sum(lot_sum * Sophomore)) %>%
  distinct(Freshmen, Sophomore)

Which returns:

  Freshmen Sophomore
1      400       900


问:
Using strtok() to store numeric values in a 2D array
I'm trying to write a program that takes a list of numbers from a file and stores each row of numbers in a 2D array using strtok(). The problem I'm having is that when I try to store values in the rows of my 2D array, the while loop goes into an infinite loop, but when i use the line token = strtok(NULL, " ") to stop the loop, I just store the first value of each line into the first cell of each column.

What am I doing wrong? Heres is my code

```<code>int main() {
  int myArray[240][30];
  char line[240];
  char *token;
  int i, n, j;
  FILE *fp;
  fp = fopen("array_list.txt", "rt");
  j = 0;
  i = 0;
  while (fgets(line, sizeof(line), fp)) {
    token = strtok(line, " ");

    while (token != NULL) {
      n = atoi(token);
      myArray[i][j] = n;
      token = strtok(line, " ");
      printf("%d ", myArray[i][j]);
      token = strtok(NULL, " ");
      j++;
    }

    printf("\n");
    i++;
  }
  return 0;
}
</code>```

Here is an example of the file I'm trying to read.

1 98 48 55 46 12 48 43 7 73 47 33

                                                                                97 26 67 25 67 47 46 74 67 43 78 98 90 58 6 5 53 19 37 42

81 84 36 70 59 65 99 56 94 23
79 73 27 47 98 78 8 2 3 43 84 19 59 98 51 72 2 13 55 3
20 61 25 84 28 70 56 23 52 69
86 70 60 90 72
51 71 92 91 55 6 72 67 73 64 78 43 65 30 49
99 82 40 72 5 44 20 21 22 72 99 74 27 59 25 1 26 26 22 66
63 27 54 46 46
91 65 77 45 94 94 95 11 77 46 64 14
69 70 75 48 68 22 55 78 1 4
31 76 55 12 93

答:
I think OP has been given some subtly tricky input.

What looks like 6 lines of input may be something else.  Although I edited OP's post, I stayed away from the "array_list.txt" data section as in the editor, it appears to have lines with spaces after the last number, a blank line, and maybe a line with more than 30 numbers.

In other words, "array_list.txt" may not be as well formatted as first thought and code needs to take defensive action to avoid over-runs, etc.

Set up constants

The magic numbers 240, 30, 240 carry little meaning and since 2 numbers are the same value, there role in code can get muddled - use constants.

```<code>//int myArray[240][30];
//char line[240];
#define LINE_N 240
#define INT_PER_LINE_N 30

// I think this should be more like (INT_PER_LINE_N * 13)
#define LINE_SIZE 240

int myArray[LINE_N][INT_PER_LINE_N];
char line[LINE_SIZE];
</code>```

Prefer strtol() over strtok()

strtok() is fine looking for tokens.  Code supplies a delimiter set like " \n\t" and life is good.  Yet what to do with non-delimiters, non-numerics?  strtol() handles that well for integers.

```<code>for (i=0; i<LINE_N; i++ {  // Do not read too many lines
  myArray[i][0] = 0;
  if (fgets(line, sizeof line, fp)) {
    char *p = line;
    int j = 0;
    while (j < (INT_PER_LINE_N - 1) && *p) {
      char *endptr;
      errno = 0;
      long value = strtol(p, &endptr);
      if (p == endptr) {  // no conversion
        p++; // TBD code, for now, simple advance to the next character;
      } else {
        if (errno || value < INT_MIN || value > INT_MAX) {  // some overflow?
          ; // TBD code: for now, ignore out of range int
        } else {
          myArray[i][++j] = (int) value;
        }
        p = endptr;  // go to text after this numeric token
      }
      // Consume trailing white-space, helps code get to the string end better
      while (isspace((unsigned char)*p) p++;
    }
    myArray[i][0] = j;
  } // end for
}
</code>```

Body:
I'm trying to write a program that takes a list of numbers from a file and stores each row of numbers in a 2D array using strtok(). The problem I'm having is that when I try to store values in the rows of my 2D array, the while loop goes into an infinite loop, but when i use the line token = strtok(NULL, " ") to stop the loop, I just store the first value of each line into the first cell of each column.

What am I doing wrong? Heres is my code

int main() {
  int myArray[240][30];
  char line[240];
  char *token;
  int i, n, j;
  FILE *fp;
  fp = fopen("array_list.txt", "rt");
  j = 0;
  i = 0;
  while (fgets(line, sizeof(line), fp)) {
    token = strtok(line, " ");

    while (token != NULL) {
      n = atoi(token);
      myArray[i][j] = n;
      token = strtok(line, " ");
      printf("%d ", myArray[i][j]);
      token = strtok(NULL, " ");
      j++;
    }

    printf("\n");
    i++;
  }
  return 0;
}

Here is an example of the file I'm trying to read.

1 98 48 55 46 12 48 43 7 73 47 33

                                                                                97 26 67 25 67 47 46 74 67 43 78 98 90 58 6 5 53 19 37 42

81 84 36 70 59 65 99 56 94 23
79 73 27 47 98 78 8 2 3 43 84 19 59 98 51 72 2 13 55 3
20 61 25 84 28 70 56 23 52 69
86 70 60 90 72
51 71 92 91 55 6 72 67 73 64 78 43 65 30 49
99 82 40 72 5 44 20 21 22 72 99 74 27 59 25 1 26 26 22 66
63 27 54 46 46
91 65 77 45 94 94 95 11 77 46 64 14
69 70 75 48 68 22 55 78 1 4
31 76 55 12 93

Body:
I think OP has been given some subtly tricky input.

What looks like 6 lines of input may be something else.  Although I edited OP's post, I stayed away from the "array_list.txt" data section as in the editor, it appears to have lines with spaces after the last number, a blank line, and maybe a line with more than 30 numbers.

In other words, "array_list.txt" may not be as well formatted as first thought and code needs to take defensive action to avoid over-runs, etc.

Set up constants

The magic numbers 240, 30, 240 carry little meaning and since 2 numbers are the same value, there role in code can get muddled - use constants.

//int myArray[240][30];
//char line[240];
#define LINE_N 240
#define INT_PER_LINE_N 30

// I think this should be more like (INT_PER_LINE_N * 13)
#define LINE_SIZE 240

int myArray[LINE_N][INT_PER_LINE_N];
char line[LINE_SIZE];

Prefer strtol() over strtok()

strtok() is fine looking for tokens.  Code supplies a delimiter set like " \n\t" and life is good.  Yet what to do with non-delimiters, non-numerics?  strtol() handles that well for integers.

for (i=0; i<LINE_N; i++ {  // Do not read too many lines
  myArray[i][0] = 0;
  if (fgets(line, sizeof line, fp)) {
    char *p = line;
    int j = 0;
    while (j < (INT_PER_LINE_N - 1) && *p) {
      char *endptr;
      errno = 0;
      long value = strtol(p, &endptr);
      if (p == endptr) {  // no conversion
        p++; // TBD code, for now, simple advance to the next character;
      } else {
        if (errno || value < INT_MIN || value > INT_MAX) {  // some overflow?
          ; // TBD code: for now, ignore out of range int
        } else {
          myArray[i][++j] = (int) value;
        }
        p = endptr;  // go to text after this numeric token
      }
      // Consume trailing white-space, helps code get to the string end better
      while (isspace((unsigned char)*p) p++;
    }
    myArray[i][0] = j;
  } // end for
}


问:
trouble iterating through dictionary keys and values in django template
I am trying to iterate through a context dictionary in a template in django. So far I've been unsuccessful and I'm not understanding what it is wrong.

This is my view:

```<code>def main_view(request):
    cat_dict = {'Other': 0,
                  'Meeting': 0,
                  'Project 1': 0,
                  'Project 2': 0,
                  'Project 3': 0,
                  'Project 4': 0,
                  'Collaboration 1': 0,
                  'Collaboration 2': 0,
                  'Collaboration 3': 0,
                  'Process 1': 0
                  }
    my_dict = gCalScriptMain.gCalScript(cat_dict)
    return render(request, 'gCalData/gCalData_main.html', context=my_dict)
</code>```

Instead, this is my template:

```<code>{% extends "base.html" %}
{% block content %}

<div class="jumbotron index-jumbotron">
    <h1 id="main-title">gCalData</h1>
    <ul style="color:white">

      {% for k,v in my_dict.items %}
          <li>{{ k }}: {{ v }}</li>

      {% endfor %}

    </ul>

</div>

{% endblock %}
</code>```

But I get nothing (not even an error).
The only thing I can do is retrieve a single value if I put this in the template:

```<code>{% extends "base.html" %}
{% block content %}

<div class="jumbotron index-jumbotron">
    <h1 id="main-title">gCalData</h1>
    <p style="color:white">{{ Other }}</p>

</div>

{% endblock %}
</code>```

答:
context that you give to render function is dictionary of variables you can use in template. This means that you can use Other, Meeting, etc.

If you want to use your dictionary, then you need to do

```<code>...
return render(request, 'gCalData/gCalData_main.html', context={"my_dict": my_dict})
</code>```

and then you can iterate over my_dict in template.

Body:
I am trying to iterate through a context dictionary in a template in django. So far I've been unsuccessful and I'm not understanding what it is wrong.

This is my view:

def main_view(request):
    cat_dict = {'Other': 0,
                  'Meeting': 0,
                  'Project 1': 0,
                  'Project 2': 0,
                  'Project 3': 0,
                  'Project 4': 0,
                  'Collaboration 1': 0,
                  'Collaboration 2': 0,
                  'Collaboration 3': 0,
                  'Process 1': 0
                  }
    my_dict = gCalScriptMain.gCalScript(cat_dict)
    return render(request, 'gCalData/gCalData_main.html', context=my_dict)

Instead, this is my template:

{% extends "base.html" %}
{% block content %}

gCalData

      {% for k,v in my_dict.items %}

{{ k }}: {{ v }}

      {% endfor %}

{% endblock %}

But I get nothing (not even an error).
The only thing I can do is retrieve a single value if I put this in the template:

{% extends "base.html" %}
{% block content %}

gCalData

{{ Other }}

{% endblock %}

Body:
context that you give to render function is dictionary of variables you can use in template. This means that you can use Other, Meeting, etc.

If you want to use your dictionary, then you need to do

...
return render(request, 'gCalData/gCalData_main.html', context={"my_dict": my_dict})

and then you can iterate over my_dict in template.


问:
What is the difference between a candidate key and a primary key?
Is it that a primary key is the selected candidate key chosen for a given table?</p>

答:
A Primary key is a special kind of index in that:

```<code>there can be only one;
it cannot be nullable
it must be unique.
</code>```

Candidate keys are selected from the set of super keys, the only thing we take care while selecting the candidate key is: It should not have any redundant attribute.

Example of an Employee table:
Employee (
Employee ID,
FullName,
SSN,
DeptID
)

Candidate Key: are individual columns in a table that qualifies for the uniqueness of all the rows. Here in Employee table EmployeeID & SSN are Candidate keys.

Primary Key: are the columns you choose to maintain uniqueness in a table. Here in Employee table, you can choose either EmployeeID or SSN columns, EmployeeID is a preferable choice, as SSN is a secure value.

Alternate Key: Candidate column other the Primary column, like if EmployeeID is PK then SSN would be the Alternate key.

Super Key: If you add any other column/attribute to a Primary Key then it becomes a super key, like EmployeeID + FullName, is a Super Key.

Composite Key: If a table does not have a single column that qualifies for a Candidate key, then you have to select 2 or more columns to make a row unique. Like if there is no EmployeeID or SSN columns, then you can make FullName + DateOfBirth as Composite primary Key. But still, there can be a narrow chance of duplicate row.

Body:
A Primary key is a special kind of index in that:

there can be only one;
it cannot be nullable
it must be unique.

Candidate keys are selected from the set of super keys, the only thing we take care while selecting the candidate key is: It should not have any redundant attribute.

Example of an Employee table:
Employee (
Employee ID,
FullName,
SSN,
DeptID
)

Candidate Key: are individual columns in a table that qualifies for the uniqueness of all the rows. Here in Employee table EmployeeID & SSN are Candidate keys.

Primary Key: are the columns you choose to maintain uniqueness in a table. Here in Employee table, you can choose either EmployeeID or SSN columns, EmployeeID is a preferable choice, as SSN is a secure value.

Alternate Key: Candidate column other the Primary column, like if EmployeeID is PK then SSN would be the Alternate key.

Super Key: If you add any other column/attribute to a Primary Key then it becomes a super key, like EmployeeID + FullName, is a Super Key.

Composite Key: If a table does not have a single column that qualifies for a Candidate key, then you have to select 2 or more columns to make a row unique. Like if there is no EmployeeID or SSN columns, then you can make FullName + DateOfBirth as Composite primary Key. But still, there can be a narrow chance of duplicate row.

ContentLicense: CC BY-SA 4.0


问:
Woocommerce: Display Product Variation Description on shop catalog page
I have a similar problem mentioned here and I want that a short description of the variable product was displayed on the catalog page.

I'm using WooCommerce Show Single Variations commercial pluginn, but it doesn't display short description.

Before that I used some code to display description of simple product on shop page that worked and it looks like this:

```<code>add_action( 'woocommerce_after_shop_loop_item_title',
'add_short_description', 9 );
function add_short_description() {
global $post;
$text = $post->post_excerpt;
$maxchar = 75; //максимальное кол-во символов

$text = preg_replace ('~\[[^\]]+\]~', '', $text ); //убираем шорткоды

//удаляем все html символы
//$text = strip_tags( $text);

// Обрезаем
if ( mb_strlen( $text ) > $maxchar ){
            $text = mb_substr( $text, 0, $maxchar );
            $text = preg_replace('@(.*)\s[^\s]*$@s', '\\1 ...', $text );
        }
echo "<span class='catalog-short-desc'>$text</span>";
}
</code>```

I would be grateful if you tell me how to change this code.

答:
Updated: As I dont have and I don't use your commercial plugin and as your question is not so clear… There is 2 possibilities:

1) You would like to add the short description (from the parent variable product) for the product variations that are displayed (with your plugin) on woocommerce archives pages (like shop …), just like the other products.

This should do the trick (untested with no errors):

```<code>add_action( 'woocommerce_after_shop_loop_item_title', 'add_short_description', 9 );
function add_short_description() {
    global $post;

    // 1. Product variation
    if ($post->post_type = 'product_variation'){
        $post_parent_id = $post->post_parent; // Get the parent variable product ID
        $post_parent = get_post( $post_parent_id ); // Get the parent variable WP_Post object
        $text = $post_parent->post_excerpt; // Get the short description from the parent variable product
    }
    // 2. Other cases (simple, variable …)
    else {
        $text = $post->post_excerpt;
    }

    $maxchar = 75; // Maximum number of characters

    $text = preg_replace ('~\[[^\]]+\]~', '', $text ); // Remove shortcodes

    // Remove all html symbols
    //$text = strip_tags( $text);

    // Crop
    if ( mb_strlen( $text ) > $maxchar ){
        $text = mb_substr( $text, 0, $maxchar );
        $text = preg_replace('@(.*)\s[^\s]*$@s', '\\1 ...', $text );
    }
    echo "<span class='catalog-short-desc'>$text</span>";
}
</code>```

2)  You would like to add the description of the product variations that are displayed (with your plugin) on woocommerce archives pages (like shop …), just like the other products… For Product variation short description doesn't exist (it's empty)…

This should do the trick (untested with no errors):

```<code>// For Woocommerce versions 3+ only
add_action( 'woocommerce_after_shop_loop_item_title', 'add_short_description', 9 );
function add_short_description() {
    global $post, $product;

    // 1. Product variation
    if ( $product->is_type('product_variation') ){
        // Get the product variation description
        // short description doesn't exist for product variations
        $text = $product->get_description();

        // If the product variation description is empty, we get the parent short description
        if( empty( $text ) ){
            $parent_id = $product->get_parent_id(); // The parent variable product ID
            $parent_product = wc_get_product( $parent_id ); // The parent WC_Product object
            $text = $parent_product->get_short_description();
        }
    }
    // 2. Other cases (simple, variable …)
    else {
        $text = $product->get_short_description();
    }

    $maxchar = 75; // Maximum number of characters

    $text = preg_replace ('~\[[^\]]+\]~', '', $text ); // Remove shortcodes

    // Remove all html symbols
    //$text = strip_tags( $text);

    // Crop
    if ( mb_strlen( $text ) > $maxchar ){
        $text = mb_substr( $text, 0, $maxchar );
        $text = preg_replace('@(.*)\s[^\s]*$@s', '\\1 ...', $text );
    }
    echo "<span class='catalog-short-desc'>$text</span>";
}
</code>```

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Body:
I have a similar problem mentioned here and I want that a short description of the variable product was displayed on the catalog page.

I'm using WooCommerce Show Single Variations commercial pluginn, but it doesn't display short description.

Before that I used some code to display description of simple product on shop page that worked and it looks like this:

add_action( 'woocommerce_after_shop_loop_item_title',
'add_short_description', 9 );
function add_short_description() {
global $post;
$text = $post->post_excerpt;
$maxchar = 75; //максимальное кол-во символов

$text = preg_replace ('~\[[^\]]+\]~', '', $text ); //убираем шорткоды

//удаляем все html символы
//$text = strip_tags( $text);

// Обрезаем
if ( mb_strlen( $text ) > $maxchar ){
            $text = mb_substr( $text, 0, $maxchar );
            $text = preg_replace('@(.*)\s[^\s]*$@s', '\\1 ...', $text );
        }
echo "$text";
}

I would be grateful if you tell me how to change this code.

Body:
Updated: As I dont have and I don't use your commercial plugin and as your question is not so clear… There is 2 possibilities:

1) You would like to add the short description (from the parent variable product) for the product variations that are displayed (with your plugin) on woocommerce archives pages (like shop …), just like the other products.

This should do the trick (untested with no errors):

add_action( 'woocommerce_after_shop_loop_item_title', 'add_short_description', 9 );
function add_short_description() {
    global $post;

    // 1. Product variation
    if ($post->post_type = 'product_variation'){
        $post_parent_id = $post->post_parent; // Get the parent variable product ID
        $post_parent = get_post( $post_parent_id ); // Get the parent variable WP_Post object
        $text = $post_parent->post_excerpt; // Get the short description from the parent variable product
    }
    // 2. Other cases (simple, variable …)
    else {
        $text = $post->post_excerpt;
    }

    $maxchar = 75; // Maximum number of characters

    $text = preg_replace ('~\[[^\]]+\]~', '', $text ); // Remove shortcodes

    // Remove all html symbols
    //$text = strip_tags( $text);

    // Crop
    if ( mb_strlen( $text ) > $maxchar ){
        $text = mb_substr( $text, 0, $maxchar );
        $text = preg_replace('@(.*)\s[^\s]*$@s', '\\1 ...', $text );
    }
    echo "<span class='catalog-short-desc'>$text</span>";
}

2)  You would like to add the description of the product variations that are displayed (with your plugin) on woocommerce archives pages (like shop …), just like the other products… For Product variation short description doesn't exist (it's empty)…

This should do the trick (untested with no errors):

// For Woocommerce versions 3+ only
add_action( 'woocommerce_after_shop_loop_item_title', 'add_short_description', 9 );
function add_short_description() {
    global $post, $product;

    // 1. Product variation
    if ( $product->is_type('product_variation') ){
        // Get the product variation description
        // short description doesn't exist for product variations
        $text = $product->get_description();

        // If the product variation description is empty, we get the parent short description
        if( empty( $text ) ){
            $parent_id = $product->get_parent_id(); // The parent variable product ID
            $parent_product = wc_get_product( $parent_id ); // The parent WC_Product object
            $text = $parent_product->get_short_description();
        }
    }
    // 2. Other cases (simple, variable …)
    else {
        $text = $product->get_short_description();
    }

    $maxchar = 75; // Maximum number of characters

    $text = preg_replace ('~\[[^\]]+\]~', '', $text ); // Remove shortcodes

    // Remove all html symbols
    //$text = strip_tags( $text);

    // Crop
    if ( mb_strlen( $text ) > $maxchar ){
        $text = mb_substr( $text, 0, $maxchar );
        $text = preg_replace('@(.*)\s[^\s]*$@s', '\\1 ...', $text );
    }
    echo "<span class='catalog-short-desc'>$text</span>";
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.


问:
Best way to make WPF ListView/GridView sort on column-header clicking?
There are lots of solutions on the internet attempting to fill this seemingly very-basic omission from WPF. I'm really confused as to what would be the "best" way. For example... I want there to be little up/down arrows in the column header to indicate sort direction. There are apparently like 3 different ways to do this, some using code, some using markup, some using markup-plus-code, and all seeming rather like a hack.

Has anyone run into this problem before, and found a solution they are completely happy with? It seems bizarre that such a basic WinForms piece of functionality is missing from WPF and needs to be hacked in.

答:
If you have a listview and turn it into a gridview you can easily make your gridview columns headers clickable by doing this.

```<code>        <Style TargetType="GridViewColumnHeader">
            <Setter Property="Command" Value="{Binding CommandOrderBy}"/>
            <Setter Property="CommandParameter" Value="{Binding RelativeSource={RelativeSource Self},Path=Content}"/>
        </Style>
</code>```

Then just set a delegate command in your code.

```<code>    public DelegateCommand CommandOrderBy { get { return new DelegateCommand(Delegated_CommandOrderBy); } }

    private void Delegated_CommandOrderBy(object obj)
    {
        throw new NotImplementedException();
    }
</code>```

Im going to assume you all know how to make the ICommand DelegateCommand here.
this allowed me to keep all my View clicking in the ViewModel.

I only added this so that there is multiple ways to accomplish the same thing.
I did not write code for adding arrow buttons in the header, but that would be done in XAML style, you would need to redesign the entire header which JanDotNet has in their code.

ContentLicense: CC BY-SA 2.5

Body:
If you have a listview and turn it into a gridview you can easily make your gridview columns headers clickable by doing this.

        <Style TargetType="GridViewColumnHeader">
            <Setter Property="Command" Value="{Binding CommandOrderBy}"/>
            <Setter Property="CommandParameter" Value="{Binding RelativeSource={RelativeSource Self},Path=Content}"/>
        </Style>

Then just set a delegate command in your code.

    public DelegateCommand CommandOrderBy { get { return new DelegateCommand(Delegated_CommandOrderBy); } }

    private void Delegated_CommandOrderBy(object obj)
    {
        throw new NotImplementedException();
    }

Im going to assume you all know how to make the ICommand DelegateCommand here.
this allowed me to keep all my View clicking in the ViewModel.

I only added this so that there is multiple ways to accomplish the same thing.
I did not write code for adding arrow buttons in the header, but that would be done in XAML style, you would need to redesign the entire header which JanDotNet has in their code.


问:
Google Analytics PDF reports not displaying data
Since a few days back our custom dashboard reports (scheduled e-mail PDFs) are not showing any data and the layout is broken.

There has not been any changes done to the dashboards and they’ve been working for months. When generating and sending the PDF reports manually they show up just fine.

The only difference in the reports is that a text that wasn't there before has been added: "All users on your account, regardless of permissions, will soon be able to see who else has access to that account. Learn More"

Please view attached screenshot (link).
Screenshot of broken GA PDF report

Does anyone else have the same issue?
Has someone been able to fix this?

Cheers,
Thomas

答:
I had this happen to my reports as well. The change that triggered it was a part of GA navigation 'upgrade' which messed up the original email PDF template.

I had to re-create all the scheduled email reports from scratch in GA and when those come in, they are in the correct format. Try that if it helps.


答:
To fix this, we can either start the string with a double quote or use single quotes throughout and escape the apostrophe:

Example :echo 'It\'s time to stop writting errors ';

Or use \_

Body:
Here is my code:

<?php
  if ($_POST["p_500"] or $_POST["p_750"] or $_POST["p_1000"] or //line 2
  $_POST["p_1250"] or $_POST["p_1500"] or $_POST["p_1750"] or
  $_POST["p_2000"] or $_POST["p_2500"] or $_POST["p_3000"] or
  $_POST["p_4000"] or $_POST["p_5000"] or $_POST["p_6000"] or
  $_POST["p_7000"] or $_POST["p_8000"] or $_POST["p_10000"]) {
      if ($_POST["p_500"]) {$a0=0;$b0=500;
      } else {$a0=100000;$b0=0;}
      if ($_POST["p_750"]) {$a1=500;$b1=750;
      } else {$a1=100000;$b1=0;}
      if ($_POST["p_1000"]) {$a2=750;$b2=1000;
      } else {$a2=100000;$b2=0;}
      if ($_POST["p_1250"]) {$a3=1000;$b3=1250;
      } else {$a3=100000;$b3=0;}
      if ($_POST["p_1500"]) {$a4=1250;$b4=1500;
      } else {$a4=100000;$b4=0;}
      if ($_POST["p_1750"]) {$a5=1500;$b5=1750;
      } else {$a5=100000;$b5=0;}
      if ($_POST["p_2000"]) {$a6=1750;$b6=2000;
      } else {$a6=100000;$b6=0;}
      if ($_POST["p_2500"]) {$a7=2000;$b7=2500;
      } else {$a7=100000;$b7=0;}
      if ($_POST["p_3000"]) {$a8=2500;$b8=3000;
      } else {$a8=100000;$b8=0;}
      if ($_POST["p_4000"]) {$a9=3000;$b9=4000;
      } else {$a9=100000;$b9=0;}
      if ($_POST["p_5000"]) {$a10=4000;$b10=5000;
      } else {$a10=100000;$b10=0;}
      if ($_POST["p_6000"]) {$a11=5000;$b11=6000;
      } else {$a11=100000;$b11=0;}
      if ($_POST["p_7000"]) {$a12=6000;$b12=7000;
      } else {$a12=100000;$b12=0;}
      if ($_POST["p_8000"]) {$a13=7000;$b13=8000;
      } else {$a13=100000;$b13=0;}
      if ($_POST["p_10000"]) {$a14=8000;$b14=10000;
      } else {$a14=100000;$b14=0;}
      $price_lower=min($a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7,$a8,$a9,$a10,$a11,$a12,$a13,$a14);
      $price_upper=max($b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$b10,$b11,$b12,$b13,$b14);
      $sql_new_string=" AND price<$price_upper AND price=>$price_lower";
      $sql=$sql.$sql_new_string;
  }
?>

When I run it I get the following error:

Parse error: syntax error, unexpected ' ' (T_STRING) in C:\wamp64\x\x\x.php on line 2

Can someone please tell me why I am getting this error?


问:
Javascript download doesn't work without seemingly unrelated return function
I'm struggling a javascript problem that I think stems from a lack of conceptual understanding. I'll dive right in:

I have an web page that I want to have download a file when a button is clicked. The relevant html js is here:

```<code>// Js within html
var mypage = new MyPage();

$(document).ready(function() {
  mypage.onReady();
});
</code>```

The document.ready executes on a button push which is definitely working. Next, my MyPage.js file:

```<code>onReady() {
  $('.my-form').on('submit', function() {
    $.ajax({
      type: 'GET',
      url: '/my/url',
      data: {
        'data': JSON.stringify(my_data)
      }
    }).done((response) => {
      window.location.href = response.msg;
    }).fail(function(data) {
      console.log(data)
    });
    return false; //relevant line
  });
}
</code>```

Now that return false line looks irrelevant. However, for some reason when I take it out the download fails, and with it in it succeeds. Can someone explain to me why that is the case? Happy to post more info if it's needed.

答:
According to the documentation:

Returning false from an event handler will automatically call
  event.stopPropagation() and event.preventDefault().

Body:
I'm struggling a javascript problem that I think stems from a lack of conceptual understanding. I'll dive right in:

I have an web page that I want to have download a file when a button is clicked. The relevant html js is here:

// Js within html
var mypage = new MyPage();

$(document).ready(function() {
  mypage.onReady();
});

The document.ready executes on a button push which is definitely working. Next, my MyPage.js file:

onReady() {
  $('.my-form').on('submit', function() {
    $.ajax({
      type: 'GET',
      url: '/my/url',
      data: {
        'data': JSON.stringify(my_data)
      }
    }).done((response) => {
      window.location.href = response.msg;
    }).fail(function(data) {
      console.log(data)
    });
    return false; //relevant line
  });
}

Now that return false line looks irrelevant. However, for some reason when I take it out the download fails, and with it in it succeeds. Can someone explain to me why that is the case? Happy to post more info if it's needed.


问:
Sending email from Azure
Hope someone can help. I want to send email from my Azure account. My domain name is configured to work with Azure.

I could not find easily on the web how to send an email from an Azure account. There was some mention of SendGrid, but it seems my account does not support it.

Can someone please guide me through how to send email from a website hosted in Azure?

答:
A nice way to achieve this "if you have an office 365 account" is to use Office 365 outlook connector integrated with Azure Logic App,

Hope this helps someone!

Title: Sending email from Azure


问:
Dynamic way to read a file in Java
I have the following piece of code in my reading File method:

```<code>FileReader fileReader = new FileReader(fName);
bf = new BufferedReader(fileReader);
while ((line = bf.readLine()) != null) {
    if (line.contains("Worker")) {
        info  = line.split(" ");
        int x = Integer.parseInt(info[1]);
        int y = Integer.parseInt(info[2]);
        worker = new Worker(new Point(x, y);
        globalList.add(worker);
    }
    if (line.contains("Work")) {
        info  = line.split(" ");
        int x = Integer.parseInt(info[1]);
        int y = Integer.parseInt(info[2]);
        work = new Work(new Point(x, y);
        globalList.add(work);
    }
    if (line.contains("Bulldozer")) {
        info  = line.split(" ");
        int x = Integer.parseInt(info[1]);
        int y = Integer.parseInt(info[2]);
        bulldozer = new Bulldozer(new Point(x, y);
        globalList.add(bulldozer);
    }
}
</code>```

With this piece of code I'm reading from a file that looks like this:

```<code>Worker 5 0
Bulldozer 7 5
Work 4 2
Work 4 8
</code>```

I am using BufferedReader to do this, I am creating instances of a class in this case classes Worker, Bulldozer and Work, reading the word in the file(that is the name of the class) and getting the x and y position, and add that object to a list.

And this works perfectly, my problem is that this looks really hard coded and that's not a good idea, since this a school project, so do you guys have any tip to help me make this code a bit more dynamic, maybe with just on if statement?

答:
Basically, all three branches of your if do the same thing - they read two integers, prepare a point, then inject it into an object.

The only thing that varies is the first string and the class name. With reflection, you could make it universal - search the package for the class named like the string, create the Point, then call a single-argument constructor of the class.

Without reflection, you can still extract it by a method that takes as arguments a String and a Function<Point, Object> that serves as the factory.

The method would do this:

```<code>public void readIfMatches(String line, String match, Function<Point, Object> factory) {
    if (line.contains(match)) {
        String info  = line.split(" ");
        int x = Integer.parseInt(info[1]);
        int y = Integer.parseInt(info[2]);
        globalList.add(factory.apply(new Point(x, y));
    }
}
</code>```

Then you call the three iterations like this:

```<code>readIfMatches(line, "Bulldozer", Bulldozer::new)
</code>```

Title: Dynamic way to read a file in Java

Body:
I have the following piece of code in my reading File method:

FileReader fileReader = new FileReader(fName);
bf = new BufferedReader(fileReader);
while ((line = bf.readLine()) != null) {
    if (line.contains("Worker")) {
        info  = line.split(" ");
        int x = Integer.parseInt(info[1]);
        int y = Integer.parseInt(info[2]);
        worker = new Worker(new Point(x, y);
        globalList.add(worker);
    }
    if (line.contains("Work")) {
        info  = line.split(" ");
        int x = Integer.parseInt(info[1]);
        int y = Integer.parseInt(info[2]);
        work = new Work(new Point(x, y);
        globalList.add(work);
    }
    if (line.contains("Bulldozer")) {
        info  = line.split(" ");
        int x = Integer.parseInt(info[1]);
        int y = Integer.parseInt(info[2]);
        bulldozer = new Bulldozer(new Point(x, y);
        globalList.add(bulldozer);
    }
}

With this piece of code I'm reading from a file that looks like this:

Worker 5 0
Bulldozer 7 5
Work 4 2
Work 4 8

I am using BufferedReader to do this, I am creating instances of a class in this case classes Worker, Bulldozer and Work, reading the word in the file(that is the name of the class) and getting the x and y position, and add that object to a list.

And this works perfectly, my problem is that this looks really hard coded and that's not a good idea, since this a school project, so do you guys have any tip to help me make this code a bit more dynamic, maybe with just on if statement?

Body:
Basically, all three branches of your if do the same thing - they read two integers, prepare a point, then inject it into an object.

The only thing that varies is the first string and the class name. With reflection, you could make it universal - search the package for the class named like the string, create the Point, then call a single-argument constructor of the class.

Without reflection, you can still extract it by a method that takes as arguments a String and a Function<Point, Object> that serves as the factory.

The method would do this:

public void readIfMatches(String line, String match, Function<Point, Object> factory) {
    if (line.contains(match)) {
        String info  = line.split(" ");
        int x = Integer.parseInt(info[1]);
        int y = Integer.parseInt(info[2]);
        globalList.add(factory.apply(new Point(x, y));
    }
}

Then you call the three iterations like this:

readIfMatches(line, "Bulldozer", Bulldozer::new)


问:
How to make API issue only one token per user (opened in multiple tabs)?
I have a web API in .net core 1.0 which issues JWT token(access_token) to the clients at login. Now, the token has a short expiry period(10 mins) and the client requests a new token in every 8 mins for the continuity of the session. This token is stored in the cookie in the browser at the client side.
Now, this works fine if the client works in only one tab of the browser. However, if the client opens two or more tabs, every 8 minutes request for a new token is made to the API. This results in multiple requests from the same user simultaneously and my application issues token for each and every request but only one of the tokens is stored at client side cookie. But it results in multiple token out of which only single one is used throughout its lifetime.

I have tried storing the userId and token in DB and cross-checking them during API request, however, the same user in multiple tabs makes simultaneous request and the logic fails here.

How can I resolve this situation? I want my API to issue only one token per user opened in multiple tabs. Any help is appreciated.

答:
This is tricky. If you try to store the token in the DB and not issue a fresh token until the old expires it will create a plethora of problems. Think of the case, when the user uses multiple devices. This logic won't work. There are many more cases.

And storing the JWT in the server is very redundant and counter-intuitive, IMO. One of the primary benefits of JWT is that you don't have to make a DB call everytime a protected resource is requested. The JWT itself has all the information for authorizing the user.

I believe, the solution you are looking for is throttling or rate limiting. You can limit the token issue endpoint to 1request/sec/ip (experiment and find the rate which works well). The idea is to block the concurrent requests for new token issues from the same IP and process just one of them. You can achieve this through IIS or through Attributes. Play around and see what works best for you.


问:
R Map CSV & SHP
I'm trying to plot latitude & longitude coordinates on top of a shapefile.  I am told they have the same coordinate system (NAD27).  I have tried numerous ways after researching it, but nothing works perfectly.  They either map one or the other, but not both.  Below is an example of reading them in, but I don't even know how to begin starting to plot since my csv is from the sp package my the shp is from the maptools package.

```<code>pts <- read.csv("locations.csv")
pts <- pts[,4:5]
names(pts) <- c("Latitude", "Longitude")
pts <- pts[complete.cases(pts),]
pts <- SpatialPoints(pts)
border <- maptools::readShapePoly("landman_one shape.shp")
</code>```

Any help would be greatly appreciated.

Below are the different structures.

```<code>> str(pts)
Formal class 'SpatialPoints' [package "sp"] with 3 slots
  ..@ coords     : num [1:372, 1:2] 30.9 30.9 31 31 31 ...
  .. ..- attr(*, "dimnames")=List of 2
  .. .. ..$ : chr [1:372] "1" "2" "3" "4" ...
  .. .. ..$ : chr [1:2] "Latitude" "Longitude"
  ..@ bbox       : num [1:2, 1:2] 29.5 -105.2 36 -76.1
  .. ..- attr(*, "dimnames")=List of 2
  .. .. ..$ : chr [1:2] "Latitude" "Longitude"
  .. .. ..$ : chr [1:2] "min" "max"
  ..@ proj4string:Formal class 'CRS' [package "sp"] with 1 slot
  .. .. ..@ projargs: chr NA

> str(border)
Formal class 'SpatialPolygonsDataFrame' [package "sp"] with 5 slots
  ..@ data       :'data.frame': 1 obs. of  2 variables:
  .. ..$ Id       : int 0
  .. ..$ PERIM_GEO: num 998432
  .. ..- attr(*, "data_types")= chr [1:2] "N" "F"
  ..@ polygons   :List of 1
  .. ..$ :Formal class 'Polygons' [package "sp"] with 5 slots
  .. .. .. ..@ Polygons :List of 1
  .. .. .. .. ..$ :Formal class 'Polygon' [package "sp"] with 5 slots
  .. .. .. .. .. .. ..@ labpt  : num [1:2] 922511 545445
  .. .. .. .. .. .. ..@ area   : num 3.45e+10
  .. .. .. .. .. .. ..@ hole   : logi FALSE
  .. .. .. .. .. .. ..@ ringDir: int 1
  .. .. .. .. .. .. ..@ coords : num [1:252, 1:2] 954182 954073 954006 953914 953828 ...
  .. .. .. ..@ plotOrder: int 1
  .. .. .. ..@ labpt    : num [1:2] 922511 545445
  .. .. .. ..@ ID       : chr "0"
  .. .. .. ..@ area     : num 3.45e+10
  ..@ plotOrder  : int 1
  ..@ bbox       : num [1:2, 1:2] 819851 386743 1042230 669865
  .. ..- attr(*, "dimnames")=List of 2
  .. .. ..$ : chr [1:2] "x" "y"
  .. .. ..$ : chr [1:2] "min" "max"
  ..@ proj4string:Formal class 'CRS' [package "sp"] with 1 slot
  .. .. ..@ projargs: chr NA
</code>```

Also, I'm not too familiar with projections, so any guidance with that would be appreciated.  Also, if there's a way to do this with the same package I'd be open to that.

答:
The problem is that neither of your spatial data sets have a projection set and are using different coordinate systems. You can see this in the @proj4string line, which are both currently NA. A quick way to ascertain that the coordinate systems are different is with the @bbox slot ('bounding box'). In pts these are longitude/latitude as they are within -180/+180 and -90/+90 respectively. border, on the other hand, has values that are in entirely different units (819851 386743 1042230 669865). Neither of these look to be in the NAD27 coordinate system.

To solve this, first I would use rgdal::readOGR() or sf::read_sf() to read in your border shape file. These functions load in a projection if one is present, so this should tell you what projection this data is in.

Second, to set the projection for pts you can use proj4string():

```<code>proj4string(pts) = CRS("+init=epsg:4326")
</code>```

Once both pts and border have a projection set, you can transform one to the other coordinate system with spTransform(). As I don't know what the CRS/projection for border is I'll convert this to WGS84 (the projection of pts), but just swap them to convert pts to the same projection as border once you know its CRS.

```<code>border = spTransform(border, CRS("+init=epsg:4326"))
</code>```

Once in the same projection they should plot together. You can confirm their projections match with:

```<code>proj4string(border) == proj4string(pts)
</code>```

Title: R Map CSV & SHP

Body:
I'm trying to plot latitude & longitude coordinates on top of a shapefile.  I am told they have the same coordinate system (NAD27).  I have tried numerous ways after researching it, but nothing works perfectly.  They either map one or the other, but not both.  Below is an example of reading them in, but I don't even know how to begin starting to plot since my csv is from the sp package my the shp is from the maptools package.

pts <- read.csv("locations.csv")
pts <- pts[,4:5]
names(pts) <- c("Latitude", "Longitude")
pts <- pts[complete.cases(pts),]
pts <- SpatialPoints(pts)
border <- maptools::readShapePoly("landman_one shape.shp")

Any help would be greatly appreciated.

Below are the different structures.

> str(pts)
Formal class 'SpatialPoints' [package "sp"] with 3 slots
  ..@ coords     : num [1:372, 1:2] 30.9 30.9 31 31 31 ...
  .. ..- attr(*, "dimnames")=List of 2
  .. .. ..$ : chr [1:372] "1" "2" "3" "4" ...
  .. .. ..$ : chr [1:2] "Latitude" "Longitude"
  ..@ bbox       : num [1:2, 1:2] 29.5 -105.2 36 -76.1
  .. ..- attr(*, "dimnames")=List of 2
  .. .. ..$ : chr [1:2] "Latitude" "Longitude"
  .. .. ..$ : chr [1:2] "min" "max"
  ..@ proj4string:Formal class 'CRS' [package "sp"] with 1 slot
  .. .. ..@ projargs: chr NA

> str(border)
Formal class 'SpatialPolygonsDataFrame' [package "sp"] with 5 slots
  ..@ data       :'data.frame': 1 obs. of  2 variables:
  .. ..$ Id       : int 0
  .. ..$ PERIM_GEO: num 998432
  .. ..- attr(*, "data_types")= chr [1:2] "N" "F"
  ..@ polygons   :List of 1
  .. ..$ :Formal class 'Polygons' [package "sp"] with 5 slots
  .. .. .. ..@ Polygons :List of 1
  .. .. .. .. ..$ :Formal class 'Polygon' [package "sp"] with 5 slots
  .. .. .. .. .. .. ..@ labpt  : num [1:2] 922511 545445
  .. .. .. .. .. .. ..@ area   : num 3.45e+10
  .. .. .. .. .. .. ..@ hole   : logi FALSE
  .. .. .. .. .. .. ..@ ringDir: int 1
  .. .. .. .. .. .. ..@ coords : num [1:252, 1:2] 954182 954073 954006 953914 953828 ...
  .. .. .. ..@ plotOrder: int 1
  .. .. .. ..@ labpt    : num [1:2] 922511 545445
  .. .. .. ..@ ID       : chr "0"
  .. .. .. ..@ area     : num 3.45e+10
  ..@ plotOrder  : int 1
  ..@ bbox       : num [1:2, 1:2] 819851 386743 1042230 669865
  .. ..- attr(*, "dimnames")=List of 2
  .. .. ..$ : chr [1:2] "x" "y"
  .. .. ..$ : chr [1:2] "min" "max"
  ..@ proj4string:Formal class 'CRS' [package "sp"] with 1 slot
  .. .. ..@ projargs: chr NA

Also, I'm not too familiar with projections, so any guidance with that would be appreciated.  Also, if there's a way to do this with the same package I'd be open to that.

Body:
The problem is that neither of your spatial data sets have a projection set and are using different coordinate systems. You can see this in the @proj4string line, which are both currently NA. A quick way to ascertain that the coordinate systems are different is with the @bbox slot ('bounding box'). In pts these are longitude/latitude as they are within -180/+180 and -90/+90 respectively. border, on the other hand, has values that are in entirely different units (819851 386743 1042230 669865). Neither of these look to be in the NAD27 coordinate system.

To solve this, first I would use rgdal::readOGR() or sf::read_sf() to read in your border shape file. These functions load in a projection if one is present, so this should tell you what projection this data is in.

Second, to set the projection for pts you can use proj4string():

proj4string(pts) = CRS("+init=epsg:4326")

Once both pts and border have a projection set, you can transform one to the other coordinate system with spTransform(). As I don't know what the CRS/projection for border is I'll convert this to WGS84 (the projection of pts), but just swap them to convert pts to the same projection as border once you know its CRS.

border = spTransform(border, CRS("+init=epsg:4326"))

Once in the same projection they should plot together. You can confirm their projections match with:

proj4string(border) == proj4string(pts)


答:
```<code>$('.my-form').on('submit', function() {
</code>```

Whether it is intentionally ot not, you are submitting a form or simply just the page, and by that the page is refreshed as soon the button is clicked.

Adding return false prevent the form or page from beeing submitted, and by that the AJAX call have a chance to finish, and the window.location.href redirect to go through.

Title: Javascript download doesn't work without seemingly unrelated return function

Body:
$('.my-form').on('submit', function() {

Whether it is intentionally ot not, you are submitting a form or simply just the page, and by that the page is refreshed as soon the button is clicked.

Adding return false prevent the form or page from beeing submitted, and by that the AJAX call have a chance to finish, and the window.location.href redirect to go through.


问:
How to update record using Entity Framework 6?
I am trying to update a record using EF6. First finding the record, if it exists, update.
Here is my code:

```<code>var book = new Model.Book
{
    BookNumber =  _book.BookNumber,
    BookName = _book.BookName,
    BookTitle = _book.BookTitle,
};
using (var db = new MyContextDB())
{
    var result = db.Books.SingleOrDefault(b => b.BookNumber == bookNumber);
    if (result != null)
    {
        try
        {
            db.Books.Attach(book);
            db.Entry(book).State = EntityState.Modified;
            db.SaveChanges();
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}
</code>```

Every time I try to update the record using the above code, I am getting this error:

{System.Data.Entity.Infrastructure.DbUpdateConcurrencyException: Store
update, insert, or delete statement affected an unexpected number of
rows (0). Entities may have been modified or deleted since entities
were loaded. Refresh ObjectStateManager entries

答:
You should use the Entry()  method in case you want to update all the fields in your object.
Also keep in mind you cannot change the field id (key)  therefore first set the Id to the same as you edit. </p>

```<code>using(var context = new ...())
{
    var EditedObj = context
        .Obj
        .Where(x => x. ....)
        .First();

    NewObj.Id = EditedObj.Id; //This is important when we first create an object (NewObj), in which the default Id = 0. We can not change an existing key.

    context.Entry(EditedObj).CurrentValues.SetValues(NewObj);

    context.SaveChanges();
}
</code>```

Body:
I am trying to update a record using EF6. First finding the record, if it exists, update.
Here is my code:

var book = new Model.Book
{
    BookNumber =  _book.BookNumber,
    BookName = _book.BookName,
    BookTitle = _book.BookTitle,
};
using (var db = new MyContextDB())
{
    var result = db.Books.SingleOrDefault(b => b.BookNumber == bookNumber);
    if (result != null)
    {
        try
        {
            db.Books.Attach(book);
            db.Entry(book).State = EntityState.Modified;
            db.SaveChanges();
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}

Every time I try to update the record using the above code, I am getting this error:

{System.Data.Entity.Infrastructure.DbUpdateConcurrencyException: Store
update, insert, or delete statement affected an unexpected number of
rows (0). Entities may have been modified or deleted since entities
were loaded. Refresh ObjectStateManager entries

Body:
You should use the Entry()  method in case you want to update all the fields in your object.
Also keep in mind you cannot change the field id (key)  therefore first set the Id to the same as you edit.

using(var context = new ...())
{
    var EditedObj = context
        .Obj
        .Where(x => x. ....)
        .First();

    NewObj.Id = EditedObj.Id; //This is important when we first create an object (NewObj), in which the default Id = 0. We can not change an existing key.

    context.Entry(EditedObj).CurrentValues.SetValues(NewObj);

    context.SaveChanges();
}


问:
Android scheduled files to server
Ok i know how to send a file to the server...What i am looking for is code which looks in a folder on the sd card and then sends all the text files in there and then deletes them..However it needs to keep looking in there until there is internet connection so that it completes the job, otherwise it keeps looking in there every 30 seconds..? hope i explained correctly</p>

答:
For me you should build a service which does those operations.

```<code>public class UploadService extends Service {

    private WakeLock cpuLock;
    private WifiLock wifiLock;
    private UploadFilesTask task;

    @Override
    public IBinder onBind(Intent i) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        final PowerManager powerMgr = (PowerManager)getSystemService(Context.POWER_SERVICE);
        cpuLock = powerMgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "my_lock");
        cpuLock.acquire();
        final WifiManager wifiMgr = (WifiManager)getSystemService(Context.WIFI_SERVICE);
        wifiLock = wifiMgr.createWifiLock(WifiManager.WIFI_MODE_FULL, "my_lock");
        wifiLock.acquire();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        if ( intent.hasExtra("start") && taskIsNotRunning() ) {
            task = new UploadFilesTask();
            task.execute(null);
            return;
        }
    }

    private boolean taskIsNotRunning() {
        return task == null || task.getStatus() != AsyncTask.Status.RUNNING || task.isCancelled();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        cpuLock.release();
        wifiLock.release();
    }

    private class UploadFilesTask extends AsyncTask<Object, Object, Object> {

        private String dirName;

        public  UploadFilesTask(String directoryName) {
            dirName = directoryName;
        }

        @Override
        protected Object doInBackground(Object... arg0) {
            final File uploadDirectory = new File(Environment.getExternalStorageDirectory(), dirName);
            final File filesToUpload[] = uploadDirectory.listFiles(new FileFilter() {
                public boolean accept(File f) {
                    return f.getName().toLowerCase().endsWith(".txt");
                }
            });
            for ( File f : filesToUpload ) {
                            try {
                 // invoke your method for upload
                             f.delete();
                            } catch ( Exception e ) {};
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object result) {
            super.onPostExecute(result);
            stopSelf();
        }
    }

}
</code>```

Don't forget about putting service declaration into AndroidManifest.xml file.

You can launch the service with "boot complete" intent or directly from your activity.

However it needs to keep looking in
  there until there is internet
  connection so that it completes the
  job, otherwise it keeps looking in
  there every 30 seconds..? hope i
  explained correctly

Try to launch the service when wifi/3G internet connection appear. Your service can be triggered by this intent (You have to add intent-filter in AndroidManifest.xml file).

Let me put some advice about background operations:

add some rules to decrease the rate of service runs. In other case your battery will drain very quickly. Also consider AlarmManager.

check battery level before upload (BatteryManager).

check if you are in roaming mode and if user is fine with that (SystemSettings).

Title: Android scheduled files to server

Body:
For me you should build a service which does those operations.

public class UploadService extends Service {

    private WakeLock cpuLock;
    private WifiLock wifiLock;
    private UploadFilesTask task;

    @Override
    public IBinder onBind(Intent i) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        final PowerManager powerMgr = (PowerManager)getSystemService(Context.POWER_SERVICE);
        cpuLock = powerMgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "my_lock");
        cpuLock.acquire();
        final WifiManager wifiMgr = (WifiManager)getSystemService(Context.WIFI_SERVICE);
        wifiLock = wifiMgr.createWifiLock(WifiManager.WIFI_MODE_FULL, "my_lock");
        wifiLock.acquire();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        if ( intent.hasExtra("start") && taskIsNotRunning() ) {
            task = new UploadFilesTask();
            task.execute(null);
            return;
        }
    }

    private boolean taskIsNotRunning() {
        return task == null || task.getStatus() != AsyncTask.Status.RUNNING || task.isCancelled();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        cpuLock.release();
        wifiLock.release();
    }

    private class UploadFilesTask extends AsyncTask<Object, Object, Object> {

        private String dirName;

        public  UploadFilesTask(String directoryName) {
            dirName = directoryName;
        }

        @Override
        protected Object doInBackground(Object... arg0) {
            final File uploadDirectory = new File(Environment.getExternalStorageDirectory(), dirName);
            final File filesToUpload[] = uploadDirectory.listFiles(new FileFilter() {
                public boolean accept(File f) {
                    return f.getName().toLowerCase().endsWith(".txt");
                }
            });
            for ( File f : filesToUpload ) {
                            try {
                 // invoke your method for upload
                             f.delete();
                            } catch ( Exception e ) {};
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object result) {
            super.onPostExecute(result);
            stopSelf();
        }
    }

}

Don't forget about putting service declaration into AndroidManifest.xml file.

You can launch the service with "boot complete" intent or directly from your activity.

However it needs to keep looking in
  there until there is internet
  connection so that it completes the
  job, otherwise it keeps looking in
  there every 30 seconds..? hope i
  explained correctly

Try to launch the service when wifi/3G internet connection appear. Your service can be triggered by this intent (You have to add intent-filter in AndroidManifest.xml file).

Let me put some advice about background operations:

add some rules to decrease the rate of service runs. In other case your battery will drain very quickly. Also consider AlarmManager.

check battery level before upload (BatteryManager).

check if you are in roaming mode and if user is fine with that (SystemSettings).


问:
Space in CFBundleDisplayName with plutil
I am trying to rename my CFBundleDisplayName using plutil on my build server. Here is part of the bash script that I am running.

```<code>BUNDLE_DISPLAY_NAME='MY'" "'APP'
plutil -replace CFBundleDisplayName -string "$BUNDLE_DISPLAY_NAME" $PLIST_ADDRESS
</code>```

I expect this script, changes the CFBundleDisplayName to "MY APP" but what I have now is MY APP.

Anyone has any idea how can I get my expected output from plutil?

答:
In case that anyone faced similar issue with space in CFBundleDisplayName with plutil, what I ended up to do is to copy the " " (actual character for FIGURE SPACE not the UTF-16 (hex) code) in the script to resolve the problem.

```<code>BUNDLE_DISPLAY_NAME='MY'" "'APP'
plutil -replace CFBundleDisplayName -string "$BUNDLE_DISPLAY_NAME" $PLIST_ADDRESS
</code>```

Body:
I am trying to rename my CFBundleDisplayName using plutil on my build server. Here is part of the bash script that I am running.

BUNDLE_DISPLAY_NAME='MY'" "'APP'
plutil -replace CFBundleDisplayName -string "$BUNDLE_DISPLAY_NAME" $PLIST_ADDRESS

I expect this script, changes the CFBundleDisplayName to "MY APP" but what I have now is MY&#x2007;APP.

Anyone has any idea how can I get my expected output from plutil?

Body:
In case that anyone faced similar issue with space in CFBundleDisplayName with plutil, what I ended up to do is to copy the " " (actual character for FIGURE SPACE not the UTF-16 (hex) code) in the script to resolve the problem.

BUNDLE_DISPLAY_NAME='MY'" "'APP'
plutil -replace CFBundleDisplayName -string "$BUNDLE_DISPLAY_NAME" $PLIST_ADDRESS


问:
Cannot read property 'substring' of undefined
I have the following code that is causing me an error stating Cannot read property 'substring' of undefined

```<code>      <div class="extra">
        <p><%- blog.body.substring(0, 120) %> ... </p>
        <a href="/blogs/<%= blog._id %>">Read More</a>
      </div>
</code>```

However the error is occuring on my index.js page only when new content is added to the page, not on the existing content. I am using express on the backend. The change that I have made was

```<code>router.post("/blogs", isLoggedIn, function(req, res){
    // create blog
    req.body.blog.body = req.sanitize(req.body.blog.body);
    Blog.create(req.body.blog, function(err, newBlog){
        if(err){
            res.render("blogs/new");
        } else {
            //then, redirect to the index
            res.redirect("/blogs");
        }
    });
});
</code>```

to this

```<code>// CREATE ROUTE
router.post("/blogs", isLoggedIn, function(req, res){
    var title = req.body.title;
    var image = req.body.image;
    var description =  req.body.description;
    var author = {
        id: req.user._id,
        username: req.user.username
    }
    var blogPost = {title: title, image: image, description: description, author: author}
    req.body.blog.body = req.sanitize(req.body.blog.body);
    Blog.create(blogPost, function(err, newBlog){
        if(err){
            res.render("blogs/new");
        } else {
            //then, redirect to the index
            res.redirect("/blogs");
</code>```

答:
I don't see how the change you've described could cause this problem, it looks to me like that template would not have worked with either the old or the new router code.

The variables in a template come from what are known locals. One way to provide locals is to pass them in when calling render:

```<code>res.render("blogs/new", {
    blog: req.body.blog
});
</code>```

You can also assign locals using res.locals or app.locals. It wouldn't be appropriate to use app.locals here as they would be shared between all requests but using res.locals would be a viable option:

```<code>res.locals.blog = req.body.blog;
</code>```

The locals are merged by Express before calling the template, with the locals passed to render taking precedence over those on res.

If the old router code did work with that template then my best guess would be that some code you haven't provided was setting the relevant value on res.locals and your change has somehow broken that.

Body:
I have the following code that is causing me an error stating Cannot read property 'substring' of undefined

<%- blog.body.substring(0, 120) %> ...

        <a href="/blogs/<%= blog._id %>">Read More

However the error is occuring on my index.js page only when new content is added to the page, not on the existing content. I am using express on the backend. The change that I have made was

router.post("/blogs", isLoggedIn, function(req, res){
    // create blog
    req.body.blog.body = req.sanitize(req.body.blog.body);
    Blog.create(req.body.blog, function(err, newBlog){
        if(err){
            res.render("blogs/new");
        } else {
            //then, redirect to the index
            res.redirect("/blogs");
        }
    });
});

to this

// CREATE ROUTE
router.post("/blogs", isLoggedIn, function(req, res){
    var title = req.body.title;
    var image = req.body.image;
    var description =  req.body.description;
    var author = {
        id: req.user._id,
        username: req.user.username
    }
    var blogPost = {title: title, image: image, description: description, author: author}
    req.body.blog.body = req.sanitize(req.body.blog.body);
    Blog.create(blogPost, function(err, newBlog){
        if(err){
            res.render("blogs/new");
        } else {
            //then, redirect to the index
            res.redirect("/blogs");

Body:
I don't see how the change you've described could cause this problem, it looks to me like that template would not have worked with either the old or the new router code.

The variables in a template come from what are known locals. One way to provide locals is to pass them in when calling render:

res.render("blogs/new", {
    blog: req.body.blog
});

You can also assign locals using res.locals or app.locals. It wouldn't be appropriate to use app.locals here as they would be shared between all requests but using res.locals would be a viable option:

res.locals.blog = req.body.blog;

The locals are merged by Express before calling the template, with the locals passed to render taking precedence over those on res.

If the old router code did work with that template then my best guess would be that some code you haven't provided was setting the relevant value on res.locals and your change has somehow broken that.


问:
Creating empty files when I rename them
I'm learning python and also english. And I have a problem that might be easy, but I can't solve it.
I have a folder of .txt's, I was able to extract by regular expression a sequence of 17 numbers of each one.I need to rename each file with the sequence I extracted from .txt

```<code>import os
import re

path_txt = (r'C:\Users\usuario\Desktop\files')

name_files = os.listdir(path_txt)

for TXT in name_files:
    with open(path_txt + '\\' + TXT, "r") as content:
        search = re.search(r'(\d{5}\.?\d{4}\.?\d{3}\.?\d{2}\.?\d{2}\-?\d)', content.read())
        if search is not None:
            print(search.group(0))
            f = open(os.path.join( "Processes" , search.group(0) + ".txt"), "w")
        for line in content:
            print(line)
            f.write(line)
            f.close()
</code>```

Its creating .txt's empty in the "Processes" folder, but named the way I need it.

ps: using Python 3

答:
You are not renaming the files.  Instead you are opening a file in write mode.  If the file does not already exist it will be created.

Instead you want to rename the file:

```<code># search the file for desired text
with open(os.path.join(path_txt, TXT), "r") as content:
    search = re.search(r'(\d{5}\.?\d{4}\.?\d{3}\.?\d{2}\.?\d{2}\-?\d)', content.read())

# we do this *outside* the `with` so file is closed before rename
if search is not None:
    os.rename(os.path.join(path_txt, TXT),
        os.path.join("Processes" , search.group(0) + ".txt"))
</code>```

Title: Creating empty files when I rename them

Body:
I'm learning python and also english. And I have a problem that might be easy, but I can't solve it.
I have a folder of .txt's, I was able to extract by regular expression a sequence of 17 numbers of each one.I need to rename each file with the sequence I extracted from .txt

import os
import re

path_txt = (r'C:\Users\usuario\Desktop\files')

name_files = os.listdir(path_txt)

for TXT in name_files:
    with open(path_txt + '\\' + TXT, "r") as content:
        search = re.search(r'(\d{5}\.?\d{4}\.?\d{3}\.?\d{2}\.?\d{2}\-?\d)', content.read())
        if search is not None:
            print(search.group(0))
            f = open(os.path.join( "Processes" , search.group(0) + ".txt"), "w")
        for line in content:
            print(line)
            f.write(line)
            f.close()

Its creating .txt's empty in the "Processes" folder, but named the way I need it.

ps: using Python 3

Body:
You are not renaming the files.  Instead you are opening a file in write mode.  If the file does not already exist it will be created.

Instead you want to rename the file:

# search the file for desired text
with open(os.path.join(path_txt, TXT), "r") as content:
    search = re.search(r'(\d{5}\.?\d{4}\.?\d{3}\.?\d{2}\.?\d{2}\-?\d)', content.read())

# we do this *outside* the `with` so file is closed before rename
if search is not None:
    os.rename(os.path.join(path_txt, TXT),
        os.path.join("Processes" , search.group(0) + ".txt"))


问:
NodeJs : Insert data to parse table
I am inserting data to table of parse.

I have import Parse from 'parse/node'; on the top.

And inserting the data like :

```<code>const game = Parse.Object.extend('Game');
const query = new Parse.Query(game);
query.set('name', 'Delta');
query.save(null, {
    success(DOD) {
        console.log('Success');
    },
    error(DOD, error) {
        console.log('Failed');
    },
});
</code>```

It throws error :

TypeError: query.set is not a function.

What am i missing ?

答: This method is simply not available. See API Parse</p>

Title: NodeJs : Insert data to parse table

Body:
I am inserting data to table of parse.

I have import Parse from 'parse/node'; on the top.

And inserting the data like :

const game = Parse.Object.extend('Game');
const query = new Parse.Query(game);
query.set('name', 'Delta');
query.save(null, {
    success(DOD) {
        console.log('Success');
    },
    error(DOD, error) {
        console.log('Failed');
    },
});

It throws error :

TypeError: query.set is not a function.

What am i missing ?


问:
(window).height() for iPad screens
I have a popup on my site.  After the popup opens, I resize it to take up most of the screen:

```<code>jQuery( window ).resize(function() {
    var windowHeight = jQuery(window).height();
    jQuery('#BookingFrame').css('height', windowHeight * 0.9 | 0);
});
</code>```

Problem: On iPad, the window resizes past the viewport and the bottom half of the popup disappears. There is literally no way to complete the form on an iPad.

I've seen a lot of explanations on here about the "why" but I have not been able to find a workable solution. Any changes suggested in these forums results in breaking another part of the page or site on other devices.

I'm thinking I need to identify the device ($device==iPad) and then change the windowHeight to windowHeight * 0.5 or something similar. Is this the best solution? or is there something simpler?

答: Depending on what browsers you need to support you could use vh units instead of px/rem/% so you eliminate the need for js to resize the popup.</p>

Title: (window).height() for iPad screens

Body:
I have a popup on my site.  After the popup opens, I resize it to take up most of the screen:

jQuery( window ).resize(function() {
    var windowHeight = jQuery(window).height();
    jQuery('#BookingFrame').css('height', windowHeight * 0.9 | 0);
});

Problem: On iPad, the window resizes past the viewport and the bottom half of the popup disappears. There is literally no way to complete the form on an iPad.

I've seen a lot of explanations on here about the "why" but I have not been able to find a workable solution. Any changes suggested in these forums results in breaking another part of the page or site on other devices.

I'm thinking I need to identify the device ($device==iPad) and then change the windowHeight to windowHeight * 0.5 or something similar. Is this the best solution? or is there something simpler?