问:
How to add labels on top of horizontal bar charts in matplotlib?
Can anyone help me out to add the city name on the top of each horizontal bars?
I have done everything else.
Only need to figure out that.

```<code>import pandas as pd
import matplotlib.pyplot as plt
df1 = pd.read_csv("city_populations.csv")

#selecting particular columns
df = df1[['name','group','year','value']]
year = df1['year']
df = df.sort_values(by=['value'],ascending=False)

#selceting rows with year 2020
curr_year = 2020
#create a variable with true if year == curr_year
curr_population = df['year'] == curr_year
curr_population = df[curr_population]
print(curr_population)

#drawing the graph
fig,ax = plt.subplots(figsize = (10,8))
#to flip barh
values = curr_population[::-1]['group']
labels = []
clrs = []
for x in values:
    if x == "India":
        clrs.append("#adb0ff")
    elif x == "Europe":
        clrs.append("#ffb3ff")
    elif x == "Asia":
        clrs.append('#90d595')
    elif x == "Latin America":
        clrs.append("#e48381")
    elif x == "Middle East":
        clrs.append("#aafbff")
    elif x == "North America":
        clrs.append("#f7bb5f")
    else:
        clrs.append("#eafb50")
bar_plot = ax.barh(curr_population[::-1]['name'],curr_population[::-1]['value'],color = clrs)
plt.show()
</code>```

This is the code I have written in order to get the bar graphs.
I need guidance for the labels on top of each bars.

答:
you have to add the label option to the barh method

enter code herebar_plot = ax.barh(curr_population[::-1]['name'],curr_population[::-1]['value'],color = clrs, label="test")

If you want to position a label more freely you can use something like this (taken from https://matplotlib.org/3.2.1/gallery/lines_bars_and_markers/barchart.html#sphx-glr-gallery-lines-bars-and-markers-barchart-py):

```<code>def autolabel(rects):
    """Attach a text label above each bar in *rects*, displaying its height."""
    for rect in rects:
        height = rect.get_height()
        ax.annotate('{}'.format(height),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')

autolabel(ax)
</code>```

Body:
Can anyone help me out to add the city name on the top of each horizontal bars?
I have done everything else.
Only need to figure out that.

import pandas as pd
import matplotlib.pyplot as plt
df1 = pd.read_csv("city_populations.csv")

#selecting particular columns
df = df1[['name','group','year','value']]
year = df1['year']
df = df.sort_values(by=['value'],ascending=False)

#selceting rows with year 2020
curr_year = 2020
#create a variable with true if year == curr_year
curr_population = df['year'] == curr_year
curr_population = df[curr_population]
print(curr_population)

#drawing the graph
fig,ax = plt.subplots(figsize = (10,8))
#to flip barh
values = curr_population[::-1]['group']
labels = []
clrs = []
for x in values:
    if x == "India":
        clrs.append("#adb0ff")
    elif x == "Europe":
        clrs.append("#ffb3ff")
    elif x == "Asia":
        clrs.append('#90d595')
    elif x == "Latin America":
        clrs.append("#e48381")
    elif x == "Middle East":
        clrs.append("#aafbff")
    elif x == "North America":
        clrs.append("#f7bb5f")
    else:
        clrs.append("#eafb50")
bar_plot = ax.barh(curr_population[::-1]['name'],curr_population[::-1]['value'],color = clrs)
plt.show()

This is the code I have written in order to get the bar graphs.
I need guidance for the labels on top of each bars.

Body:
you have to add the label option to the barh method

enter code herebar_plot = ax.barh(curr_population[::-1]['name'],curr_population[::-1]['value'],color = clrs, label="test")

If you want to position a label more freely you can use something like this (taken from https://matplotlib.org/3.2.1/gallery/lines_bars_and_markers/barchart.html#sphx-glr-gallery-lines-bars-and-markers-barchart-py):

def autolabel(rects):
    """Attach a text label above each bar in *rects*, displaying its height."""
    for rect in rects:
        height = rect.get_height()
        ax.annotate('{}'.format(height),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')

autolabel(ax)


来源: stackexchange

问:
How do I make 2 lists correspond to each other?
I have 2 lists here:

```<code>list1 = [happy, sad, grumpy, mad]
list2 = [2, 5, 6, 9]
</code>```

I want to make it so that the numbers are assigned to the emotions? (happy is equal to 2, sad is equal to 5, etc). Ideally, I want to make it so you can compare items from list1, for example:

```<code>if happy > sad:
    print ("you are happy")
</code>```

I want to make this code as efficient as possible, so I do not want to separately assign each variable from list1 a number.

答:
You can also use index(). Dictionary version, however, is better and cleaner for the typical key-value situation.

```<code>list1 = ['happy', 'sad', 'grumpy', 'mad']
list2 = [2, 5, 6, 9]

idx = list1.index

if list2[idx('happy')] < list2[idx('sad')]:
    print('sad')
else:
    print('happy')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have 2 lists here:

list1 = [happy, sad, grumpy, mad]
list2 = [2, 5, 6, 9]

I want to make it so that the numbers are assigned to the emotions? (happy is equal to 2, sad is equal to 5, etc). Ideally, I want to make it so you can compare items from list1, for example:

if happy > sad:
    print ("you are happy")

I want to make this code as efficient as possible, so I do not want to separately assign each variable from list1 a number.

Body:
You can also use index(). Dictionary version, however, is better and cleaner for the typical key-value situation.

list1 = ['happy', 'sad', 'grumpy', 'mad']
list2 = [2, 5, 6, 9]

idx = list1.index

if list2[idx('happy')] < list2[idx('sad')]:
    print('sad')
else:
    print('happy')


问:
Number of partitions in a spark RDD
I am creating an RDD (Spark 1.6) from a text file by specifying the number of partitions. But it gives me a different number of partitions than the specified one.

Case 1

```<code>scala> val people = sc.textFile("file:///home/pvikash/data/test.txt", 1)
people: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[50] at textFile at <console>:27

scala> people.getNumPartitions
res36: Int = 1

scala> val people = sc.textFile("file:///home/pvikash/data/test.txt", 2)
people: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[52] at textFile at <console>:27

scala> people.getNumPartitions
res37: Int = 2

scala> val people = sc.textFile("file:///home/pvikash/data/test.txt", 3)
people: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[54] at textFile at <console>:27

scala> people.getNumPartitions
res38: Int = 3

scala> val people = sc.textFile("file:///home/pvikash/data/test.txt", 4)
people: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[56] at textFile at <console>:27

scala> people.getNumPartitions
res39: Int = 4
</code>```

Case 2

```<code>scala> val people = sc.textFile("file:///home/pvikash/data/test.txt", 0)
people: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[72] at textFile at <console>:27

scala> people.getNumPartitions
res47: Int = 1
</code>```

Case 3

```<code>scala> val people = sc.textFile("file:///home/pvikash/data/test.txt", 5)
people: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[58] at textFile at <console>:27

scala> people.getNumPartitions
res40: Int = 6

scala> val people = sc.textFile("file:///home/pvikash/data/test.txt", 6)
people: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[60] at textFile at <console>:27

scala> people.getNumPartitions
res41: Int = 7

scala> val people = sc.textFile("file:///home/pvikash/data/test.txt", 7)
people: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[62] at textFile at <console>:27

scala> people.getNumPartitions
res42: Int = 8

scala> val people = sc.textFile("file:///home/pvikash/data/test.txt", 8)
people: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[64] at textFile at <console>:27

scala> people.getNumPartitions
res43: Int = 9

scala> val people = sc.textFile("file:///home/pvikash/data/test.txt", 10)
people: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[68] at textFile at <console>:27

scala> people.getNumPartitions
res45: Int = 11
</code>```

Case 4

```<code>scala> val people = sc.textFile("file:///home/pvikash/data/test.txt", 9)
people: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[66] at textFile at <console>:27

scala> people.getNumPartitions
res44: Int = 11

scala> val people = sc.textFile("file:///home/pvikash/data/test.txt", 11)
people: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[70] at textFile at <console>:27

scala> people.getNumPartitions
res46: Int = 13
</code>```

Contents of the file /home/pvikash/data/test.txt are:

This is a test file. Will be used for the rdd partition

On the basis of the above cases, I have a few questions.

For Case 2, the Explicitly specified number of partition is 0 but the actual number of partition is 1 (even default minimum partition is 2), why actual number of partition is 1?

For Case 3, why the actual number of partitions changed by +1 on a specified number of partitions?

For Case 4, why the actual number of partitions changed by +2 on a specified number of partitions?

Why spark is behaving differently in Case 1, Case 2, Case 3 and Case 4?

In case input data is small in size (which can fit into a single partition easily) then why spark creates empty partitions?

Any explanation would be appreciated.

答:
Not a full answer, but it might get you closer to it.

That number you are passing in is called minSplits. It has an effect on the minimum number of partitions, that is all.

def textFile(path: String, minSplits: Int = defaultMinSplits): RDD[String]
```

Number of splits should be governed by getSplits method (docs)

And this SO post should answer question 5

Title: Number of partitions in a spark RDD

Body:
I am creating an RDD (Spark 1.6) from a text file by specifying the number of partitions. But it gives me a different number of partitions than the specified one.

Case 1

scala> val people = sc.textFile("file:///home/pvikash/data/test.txt", 1)
people: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[50] at textFile at <console>:27

scala> people.getNumPartitions
res36: Int = 1

scala> val people = sc.textFile("file:///home/pvikash/data/test.txt", 2)
people: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[52] at textFile at <console>:27

scala> people.getNumPartitions
res37: Int = 2

scala> val people = sc.textFile("file:///home/pvikash/data/test.txt", 3)
people: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[54] at textFile at <console>:27

scala> people.getNumPartitions
res38: Int = 3

scala> val people = sc.textFile("file:///home/pvikash/data/test.txt", 4)
people: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[56] at textFile at <console>:27

scala> people.getNumPartitions
res39: Int = 4

Case 2

scala> val people = sc.textFile("file:///home/pvikash/data/test.txt", 0)
people: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[72] at textFile at <console>:27

scala> people.getNumPartitions
res47: Int = 1

Case 3

scala> val people = sc.textFile("file:///home/pvikash/data/test.txt", 5)
people: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[58] at textFile at <console>:27

scala> people.getNumPartitions
res40: Int = 6

scala> val people = sc.textFile("file:///home/pvikash/data/test.txt", 6)
people: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[60] at textFile at <console>:27

scala> people.getNumPartitions
res41: Int = 7

scala> val people = sc.textFile("file:///home/pvikash/data/test.txt", 7)
people: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[62] at textFile at <console>:27

scala> people.getNumPartitions
res42: Int = 8

scala> val people = sc.textFile("file:///home/pvikash/data/test.txt", 8)
people: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[64] at textFile at <console>:27

scala> people.getNumPartitions
res43: Int = 9

scala> val people = sc.textFile("file:///home/pvikash/data/test.txt", 10)
people: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[68] at textFile at <console>:27

scala> people.getNumPartitions
res45: Int = 11

Case 4

scala> val people = sc.textFile("file:///home/pvikash/data/test.txt", 9)
people: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[66] at textFile at <console>:27

scala> people.getNumPartitions
res44: Int = 11

scala> val people = sc.textFile("file:///home/pvikash/data/test.txt", 11)
people: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[70] at textFile at <console>:27

scala> people.getNumPartitions
res46: Int = 13

Contents of the file /home/pvikash/data/test.txt are:

This is a test file. Will be used for the rdd partition

On the basis of the above cases, I have a few questions.

For Case 2, the Explicitly specified number of partition is 0 but the actual number of partition is 1 (even default minimum partition is 2), why actual number of partition is 1?

For Case 3, why the actual number of partitions changed by +1 on a specified number of partitions?

For Case 4, why the actual number of partitions changed by +2 on a specified number of partitions?

Why spark is behaving differently in Case 1, Case 2, Case 3 and Case 4?

In case input data is small in size (which can fit into a single partition easily) then why spark creates empty partitions?

Any explanation would be appreciated.

Body:
Not a full answer, but it might get you closer to it.

That number you are passing in is called minSplits. It has an effect on the minimum number of partitions, that is all.

def textFile(path: String, minSplits: Int = defaultMinSplits): RDD[String]

Number of splits should be governed by getSplits method (docs)

And this SO post should answer question 5


问:
Using the clearInterval the function when function meets some condition
How can I use the clearInterval the function when function meets some condition?

Code:-

```<code>var checkRecordlock = function() {
  jQuery.ajax({
    url: "http://localhost/project/crl/Mzk="
  }).done(function(data) {
    var is_locked = data.locked;
    if (is_locked == 1) {
      alert("Locked");
    }
  });
}

checkRecordlock();
var checkRecordlockIntervalId = setInterval(checkRecordlock, 100);
</code>```

I want to clear the interval of the function if is_locked == 1.

答:
```<code>checkRecordlock();
var checkRecordlockIntervalId = setInterval(checkRecordlock, 100);

function checkRecordlock() {
  jQuery.ajax({
    url: "http://localhost/project/crl/Mzk="
  }).done(function(data) {
    var is_locked = data.locked;
    if (is_locked == 1) {
      clearInterval(checkRecordlockIntervalId);
    }
  });
}
</code>```

Body:
How can I use the clearInterval the function when function meets some condition?

Code:-

var checkRecordlock = function() {
  jQuery.ajax({
    url: "http://localhost/project/crl/Mzk="
  }).done(function(data) {
    var is_locked = data.locked;
    if (is_locked == 1) {
      alert("Locked");
    }
  });
}

checkRecordlock();
var checkRecordlockIntervalId = setInterval(checkRecordlock, 100);

I want to clear the interval of the function if is_locked == 1.


问:
ADO.NET Entity Framework tutorials
Does anyone know of any good tutorials on ADO.NET Entity Framework?

There are a few useful links here at Stack OverFlow, and I've found one tutorial at Jason's DotNet Architecture Blog, but can anyone recommend any other good tutorials?
Any tutorials available from Microsoft, either online or as part of any conference/course material?

答:
Here are some that Julie Lerman wrote:
http://www.thedatafarm.com/blog/2008/04/04/EightEntityFrameworkTutorialsOnDataDeveloperNET.aspx

And here's of course some info from Microsoft:
http://msdn.microsoft.com/en-us/library/bb386876.aspx

OwnerDisplayName: Yngvar

ContentLicense: CC BY-SA 2.5

Title: ADO.NET Entity Framework tutorials

LastEditorDisplayName: aku

OwnerDisplayName: Slavo


问:
Questions about boxing
I know that boxing is a popular concept with plenty of information available on it, but I have a few questions which I can't really find answers to:

1) If boxing leads to a value type (struct) being converted to an object (Reference type), or reference type, then why use a value type which will be boxed and incur a performance penalty? I am aware of the benefits and suitability in certain cases of either a struct or class. It is said (1) that values (value types) tend to live on the stack in a temporary storage space, but how long for? If I don't need the type, how can I ensure it is taken care of and disposed at that moment? Or is this where the disposable pattern comes into play? I assume the reason to use a struct will be due to its benefits.

Interestingly, if I use a struct to store two strings and a DateTime field, the struct will hold two references (strings) and the DateTime together. I obviously assume this is quicker than the values being scattered. Is there anything I need to be aware of in this design? (2).

1) http://en.csharp-online.net/Classes, Structs, and Objects—Boxing and Unboxing

2) http://dotnetperls.com/Content/Struct-Examples.aspx

I have done a search on here for the answers I am after, but no luck. I usually do searches on this site for topics such as GC, generics, exception handling, etc, as there is a lot of wisdom to learn and share.

Thanks for the (potential) education to all posters! Please excuse any potential naivety. Learning the internals takes me nicely to spending some time on understanding IL, etc (something to tackle, soon).

答:
A couple other things to consider -

First, you want to make sure structs are immutable (in general).  Because of this, it's a good rule of thumb to not have structs containing reference types.  Strings can be an exception to this since they're immutable in C#, but in terms of a general-purpose rule of thumb for design, I'd be wary of this.

Second, there's another use case for structs that wasn't mentioned so far - large numbers of small objects.  If you have a large list or array of small objects, structs provide dramatically better cache coherency, and are absolutely critical.  This is why most 3D engines use structs for points/vectors - they tend to have large arrays of points for vertices, etc.

This is something worth paying attention to if performance is an important part of your application.  For example, in one of my apps, changing a single type from a class to a struct shaved 40% off a long running (>5 minute runtime) process.  Having the objects close together in memory if you are using them repeatedly in heavy math computations can provide huge gains.

Now - in your case, having 2 strings and a DateTime probably won't see any improvements from this.  The type of routines that would work on strings are probably not doing heavy computation (hopefully), ie: transforming a half a million points in space, or doing a large matrix solution, etc.

Finally - you'll notice that .net3.5sp1 made structs much more useful.  Prior to 3.5sp1 (on x86), there was no inlining of methods with struct calls.  This limited the performance gains possible via structs.  Updating your framework can make old struct code much, much faster (in certain cases).

OwnerDisplayName: GSS

Title: Questions about boxing

LastEditorDisplayName: jpalecek


问:
filebeat is not creating index with my name
I am using filebeat to send my application logs to Elasticsearch and directly connecting to my Elasticsearch for sending the logs.

My file beat configuration

```<code>filebeat.config:
  modules:
    path: ${path.config}/modules.d/*.yml
    reload.enabled: false

filebeat.inputs:
  - type: log
    paths:
      - "/var/log/*.log"
setup.ilm.enabled: false
setup.template.overwrite: true
output.elasticsearch:
  hosts: ["aws-es:443"]
  output.elasticsearch.index: "myapp-%{[agent.version]}-%{+yyyy.MM.dd}"
  username: '${ELASTICSEARCH_USERNAME:}'
  password: '${ELASTICSEARCH_PASSWORD:}
</code>```

Please note that in output.elasticsearch.index: I am giving myapp as prefix to my index name in Elasticsearch but filebeat is creating index with filebeat-7.7.0-2020.05.31 name ie using its own name filebeat as prefix which I don't want as I am having multiple applications and want to create a separate index for them.

答:
Your property name is wrong. It is output.elasticsearch.output.elasticsearch.index, but should be only output.elasticsearch.index
Change your config to

```<code>output.elasticsearch:
  hosts: ["aws-es:443"]
  index: "myapp-%{[agent.version]}-%{+yyyy.MM.dd}"
  username: '${ELASTICSEARCH_USERNAME:}'
  password: '${ELASTICSEARCH_PASSWORD:}
</code>```

Body:
I am using filebeat to send my application logs to Elasticsearch and directly connecting to my Elasticsearch for sending the logs.

My file beat configuration

filebeat.config:
  modules:
    path: ${path.config}/modules.d/*.yml
    reload.enabled: false

filebeat.inputs:
  - type: log
    paths:
      - "/var/log/*.log"
setup.ilm.enabled: false
setup.template.overwrite: true
output.elasticsearch:
  hosts: ["aws-es:443"]
  output.elasticsearch.index: "myapp-%{[agent.version]}-%{+yyyy.MM.dd}"
  username: '${ELASTICSEARCH_USERNAME:}'
  password: '${ELASTICSEARCH_PASSWORD:}

Please note that in output.elasticsearch.index: I am giving myapp as prefix to my index name in Elasticsearch but filebeat is creating index with filebeat-7.7.0-2020.05.31 name ie using its own name filebeat as prefix which I don't want as I am having multiple applications and want to create a separate index for them.

Body:
Your property name is wrong. It is output.elasticsearch.output.elasticsearch.index, but should be only output.elasticsearch.index
Change your config to

output.elasticsearch:
  hosts: ["aws-es:443"]
  index: "myapp-%{[agent.version]}-%{+yyyy.MM.dd}"
  username: '${ELASTICSEARCH_USERNAME:}'
  password: '${ELASTICSEARCH_PASSWORD:}


问:
swift how to set autolayout programmatically
I have buttons inside a view which in potrait mode I want like this -

which is achieved by the following code -

```<code>//original potrait mode/////

 import UIKit
 class PotraitViewController: UIViewController {
 override func viewDidLoad() {
 let buttonred = UIButton()
 buttonred.backgroundColor = UIColor.red
 let buttonblue = UIButton()
 buttonblue.backgroundColor = UIColor.blue
 let landscapesmallview = UIView()
 view.addSubview(landscapesmallview)
 landscapesmallview.addSubview(buttonred)
 landscapesmallview.addSubview(buttonblue)
 buttonred.translatesAutoresizingMaskIntoConstraints = false
 buttonblue.translatesAutoresizingMaskIntoConstraints = false
 NSLayoutConstraint.activate([

    buttonred.topAnchor.constraint(equalTo: view.topAnchor,constant: 200),
    buttonred.centerXAnchor.constraint(equalTo: view.centerXAnchor),
    buttonred.trailingAnchor.constraint(equalTo: view.trailingAnchor,constant:-20),
    buttonred.widthAnchor.constraint(equalToConstant: 50),
    //-------
    buttonblue.topAnchor.constraint(equalTo: buttonred.bottomAnchor,constant: 40),
    buttonblue.leadingAnchor.constraint(equalTo: buttonred.leadingAnchor),
    buttonblue.trailingAnchor.constraint(equalTo:buttonred.trailingAnchor),
    buttonblue.widthAnchor.constraint(equalTo: buttonred.widthAnchor)

      ])
    }
  }
</code>```

and in landscape mode I want like this -

which is achieved by the following code -

```<code> // original lanscape mode/////

import UIKit
class LandscapeViewController: UIViewController {
override func viewDidLoad() {
let buttonred = UIButton()
buttonred.backgroundColor = UIColor.red
let buttonblue = UIButton()
buttonblue.backgroundColor = UIColor.blue
view.addSubview(buttonred)
view.addSubview(buttonblue)
buttonred.translatesAutoresizingMaskIntoConstraints = false
buttonblue.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([

    buttonred.centerYAnchor.constraint(equalTo: view.centerYAnchor),
    buttonred.leadingAnchor.constraint(equalTo: view.leadingAnchor,constant:40),
    buttonred.trailingAnchor.constraint(equalTo: view.centerXAnchor,constant:-20),
    buttonred.widthAnchor.constraint(equalToConstant: 50),

    //-------
    buttonblue.centerYAnchor.constraint(equalTo: buttonred.centerYAnchor),
    buttonblue.leadingAnchor.constraint(equalTo: view.centerXAnchor,constant:40),
    buttonblue.trailingAnchor.constraint(equalTo: view.trailingAnchor,constant:-20),
    buttonblue.widthAnchor.constraint(equalTo:buttonred.widthAnchor)

       ])
     }
  }
</code>```

So, I tried the following code to achieve by screen rotation i.e. two different layouts in potrait and landscape views programmatically with the help of the following code:-

```<code>import UIKit

class NewViewController: UIViewController {
override func viewDidLoad() {
let buttonredlandscape = UIButton()
buttonredlandscape.backgroundColor = UIColor.red
let buttonbluelandscape = UIButton()
buttonbluelandscape.backgroundColor = UIColor.blue
let buttonredportrait = UIButton()
buttonredportrait.backgroundColor = UIColor.red
let buttonblueportrait = UIButton()
buttonblueportrait.backgroundColor = UIColor.blue

let landscapesmallview = UIView()
let portraitsmallview = UIView()
landscapesmallview.backgroundColor = UIColor.gray
portraitsmallview.backgroundColor = UIColor.purple
landscapesmallview.frame = view.frame
portraitsmallview.frame = view.frame
view.addSubview(landscapesmallview)
view.addSubview(portraitsmallview)

landscapesmallview.addSubview(buttonredlandscape)
landscapesmallview.addSubview(buttonbluelandscape)
portraitsmallview.addSubview(buttonredportrait)
portraitsmallview.addSubview(buttonblueportrait)
buttonredlandscape.translatesAutoresizingMaskIntoConstraints = false
buttonbluelandscape.translatesAutoresizingMaskIntoConstraints = false
buttonredportrait.translatesAutoresizingMaskIntoConstraints = false
buttonblueportrait.translatesAutoresizingMaskIntoConstraints = false

NSLayoutConstraint.activate([

     buttonredlandscape.centerYAnchor.constraint(equalTo:landscapesmallview.centerYAnchor),
      buttonredlandscape.topAnchor.constraint(equalTo:landscapesmallview.topAnchor,constant:40),
    buttonredlandscape.trailingAnchor.constraint(equalTo:   landscapesmallview.centerXAnchor,constant:-20),
    buttonredlandscape.heightAnchor.constraint(equalTo:   landscapesmallview.heightAnchor,constant:50),

    buttonbluelandscape.centerYAnchor.constraint(equalTo:buttonredlandscape.centerYAnchor),
    buttonbluelandscape.leadingAnchor.constraint(equalTo: landscapesmallview.centerXAnchor,constant:40),
    buttonbluelandscape.trailingAnchor.constraint(equalTo: landscapesmallview.trailingAnchor,constant:-20),
    buttonbluelandscape.heightAnchor.constraint(equalTo: buttonredlandscape.heightAnchor),

    buttonredportrait.topAnchor.constraint(equalTo: portraitsmallview.topAnchor,constant: 200),
    buttonredportrait.centerXAnchor.constraint(equalTo: portraitsmallview.centerXAnchor),
    buttonredportrait.trailingAnchor.constraint(equalTo: portraitsmallview.trailingAnchor,constant:-20),
    buttonredportrait.widthAnchor.constraint(equalTo: buttonredportrait.widthAnchor),

    buttonblueportrait.topAnchor.constraint(equalTo: buttonredportrait.bottomAnchor,constant: 40),
    buttonblueportrait.leadingAnchor.constraint(equalTo: buttonredportrait.leadingAnchor),
    buttonblueportrait.trailingAnchor.constraint(equalTo:buttonredportrait.trailingAnchor),
    buttonblueportrait.widthAnchor.constraint(equalTo: buttonredportrait.widthAnchor)

     ])

//-------

func viewWillTransition(to size: CGSize, with coordinator:    ) {
    if UIDevice.current.orientation.isLandscape {
        landscapesmallview.translatesAutoresizingMaskIntoConstraints = false
        portraitsmallview.translatesAutoresizingMaskIntoConstraints = true
     } else if UIDevice.current.orientation.isPortrait {
        portraitsmallview.translatesAutoresizingMaskIntoConstraints = false
        landscapesmallview.translatesAutoresizingMaskIntoConstraints = true

        }
      }
    }
 }
</code>```

which in potrait mode shows -

and which in landscape mode shows -

How to achieve what I want programmatically i.e. topmost 2 buttons to rearrange themselves programmatically every-time the user rotates the device. Its not just the buttons. It can be labels, images, collectionview etc. or just anything. The upshot is that I want to achieve two different layouts in landscape and portrait modes programmatically irrespective of the device.

Points to be noted :-

i) I have tried used NSLayoutAnchor with "NSLayoutConstraint.activate" because apple recommends it, but if the code can be made shorter(and faster) with some other method like visual format etc. I'm okay with that as well/

ii) If possible, I do not want to use stackview or containerview, because there can be many more types of labels, buttons etc, but if there is no other way, then I will use it.

iii) Is my code DRY principle compliant ?

答:
refer this this image for handling in device orientation

take both buttons in stack view and make the stack view in center vertically and center horizontally

Body:
I have buttons inside a view which in potrait mode I want like this -

which is achieved by the following code -

//original potrait mode/////

 import UIKit
 class PotraitViewController: UIViewController {
 override func viewDidLoad() {
 let buttonred = UIButton()
 buttonred.backgroundColor = UIColor.red
 let buttonblue = UIButton()
 buttonblue.backgroundColor = UIColor.blue
 let landscapesmallview = UIView()
 view.addSubview(landscapesmallview)
 landscapesmallview.addSubview(buttonred)
 landscapesmallview.addSubview(buttonblue)
 buttonred.translatesAutoresizingMaskIntoConstraints = false
 buttonblue.translatesAutoresizingMaskIntoConstraints = false
 NSLayoutConstraint.activate([

    buttonred.topAnchor.constraint(equalTo: view.topAnchor,constant: 200),
    buttonred.centerXAnchor.constraint(equalTo: view.centerXAnchor),
    buttonred.trailingAnchor.constraint(equalTo: view.trailingAnchor,constant:-20),
    buttonred.widthAnchor.constraint(equalToConstant: 50),
    //-------
    buttonblue.topAnchor.constraint(equalTo: buttonred.bottomAnchor,constant: 40),
    buttonblue.leadingAnchor.constraint(equalTo: buttonred.leadingAnchor),
    buttonblue.trailingAnchor.constraint(equalTo:buttonred.trailingAnchor),
    buttonblue.widthAnchor.constraint(equalTo: buttonred.widthAnchor)

      ])
    }
  }

and in landscape mode I want like this -

which is achieved by the following code -

 // original lanscape mode/////

import UIKit
class LandscapeViewController: UIViewController {
override func viewDidLoad() {
let buttonred = UIButton()
buttonred.backgroundColor = UIColor.red
let buttonblue = UIButton()
buttonblue.backgroundColor = UIColor.blue
view.addSubview(buttonred)
view.addSubview(buttonblue)
buttonred.translatesAutoresizingMaskIntoConstraints = false
buttonblue.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([

    buttonred.centerYAnchor.constraint(equalTo: view.centerYAnchor),
    buttonred.leadingAnchor.constraint(equalTo: view.leadingAnchor,constant:40),
    buttonred.trailingAnchor.constraint(equalTo: view.centerXAnchor,constant:-20),
    buttonred.widthAnchor.constraint(equalToConstant: 50),

    //-------
    buttonblue.centerYAnchor.constraint(equalTo: buttonred.centerYAnchor),
    buttonblue.leadingAnchor.constraint(equalTo: view.centerXAnchor,constant:40),
    buttonblue.trailingAnchor.constraint(equalTo: view.trailingAnchor,constant:-20),
    buttonblue.widthAnchor.constraint(equalTo:buttonred.widthAnchor)

       ])
     }
  }

So, I tried the following code to achieve by screen rotation i.e. two different layouts in potrait and landscape views programmatically with the help of the following code:-

import UIKit

class NewViewController: UIViewController {
override func viewDidLoad() {
let buttonredlandscape = UIButton()
buttonredlandscape.backgroundColor = UIColor.red
let buttonbluelandscape = UIButton()
buttonbluelandscape.backgroundColor = UIColor.blue
let buttonredportrait = UIButton()
buttonredportrait.backgroundColor = UIColor.red
let buttonblueportrait = UIButton()
buttonblueportrait.backgroundColor = UIColor.blue

let landscapesmallview = UIView()
let portraitsmallview = UIView()
landscapesmallview.backgroundColor = UIColor.gray
portraitsmallview.backgroundColor = UIColor.purple
landscapesmallview.frame = view.frame
portraitsmallview.frame = view.frame
view.addSubview(landscapesmallview)
view.addSubview(portraitsmallview)

landscapesmallview.addSubview(buttonredlandscape)
landscapesmallview.addSubview(buttonbluelandscape)
portraitsmallview.addSubview(buttonredportrait)
portraitsmallview.addSubview(buttonblueportrait)
buttonredlandscape.translatesAutoresizingMaskIntoConstraints = false
buttonbluelandscape.translatesAutoresizingMaskIntoConstraints = false
buttonredportrait.translatesAutoresizingMaskIntoConstraints = false
buttonblueportrait.translatesAutoresizingMaskIntoConstraints = false

NSLayoutConstraint.activate([

     buttonredlandscape.centerYAnchor.constraint(equalTo:landscapesmallview.centerYAnchor),
      buttonredlandscape.topAnchor.constraint(equalTo:landscapesmallview.topAnchor,constant:40),
    buttonredlandscape.trailingAnchor.constraint(equalTo:   landscapesmallview.centerXAnchor,constant:-20),
    buttonredlandscape.heightAnchor.constraint(equalTo:   landscapesmallview.heightAnchor,constant:50),

    buttonbluelandscape.centerYAnchor.constraint(equalTo:buttonredlandscape.centerYAnchor),
    buttonbluelandscape.leadingAnchor.constraint(equalTo: landscapesmallview.centerXAnchor,constant:40),
    buttonbluelandscape.trailingAnchor.constraint(equalTo: landscapesmallview.trailingAnchor,constant:-20),
    buttonbluelandscape.heightAnchor.constraint(equalTo: buttonredlandscape.heightAnchor),

    buttonredportrait.topAnchor.constraint(equalTo: portraitsmallview.topAnchor,constant: 200),
    buttonredportrait.centerXAnchor.constraint(equalTo: portraitsmallview.centerXAnchor),
    buttonredportrait.trailingAnchor.constraint(equalTo: portraitsmallview.trailingAnchor,constant:-20),
    buttonredportrait.widthAnchor.constraint(equalTo: buttonredportrait.widthAnchor),

    buttonblueportrait.topAnchor.constraint(equalTo: buttonredportrait.bottomAnchor,constant: 40),
    buttonblueportrait.leadingAnchor.constraint(equalTo: buttonredportrait.leadingAnchor),
    buttonblueportrait.trailingAnchor.constraint(equalTo:buttonredportrait.trailingAnchor),
    buttonblueportrait.widthAnchor.constraint(equalTo: buttonredportrait.widthAnchor)

     ])

//-------

func viewWillTransition(to size: CGSize, with coordinator:    ) {
    if UIDevice.current.orientation.isLandscape {
        landscapesmallview.translatesAutoresizingMaskIntoConstraints = false
        portraitsmallview.translatesAutoresizingMaskIntoConstraints = true
     } else if UIDevice.current.orientation.isPortrait {
        portraitsmallview.translatesAutoresizingMaskIntoConstraints = false
        landscapesmallview.translatesAutoresizingMaskIntoConstraints = true

        }
      }
    }
 }

which in potrait mode shows -

and which in landscape mode shows -

How to achieve what I want programmatically i.e. topmost 2 buttons to rearrange themselves programmatically every-time the user rotates the device. Its not just the buttons. It can be labels, images, collectionview etc. or just anything. The upshot is that I want to achieve two different layouts in landscape and portrait modes programmatically irrespective of the device.

Points to be noted :-

i) I have tried used NSLayoutAnchor with "NSLayoutConstraint.activate" because apple recommends it, but if the code can be made shorter(and faster) with some other method like visual format etc. I'm okay with that as well/

ii) If possible, I do not want to use stackview or containerview, because there can be many more types of labels, buttons etc, but if there is no other way, then I will use it.

iii) Is my code DRY principle compliant ?


答:
You don't need to call checkRecordlock before the interval. In order to stop it when the condition reaches, use clearInterval and pass it checkRecordlockIntervalId. Here is an example:

var checkRecordlock = function() {
    is_locked++;
    console.log(is_locked);
    if (is_locked == 10) {
      alert("Locked");
      clearInterval(checkRecordlockIntervalId)
    }
}
let is_locked = 0;
//checkRecordlock();
var checkRecordlockIntervalId = setInterval(checkRecordlock, 100);```

Title: Using the clearInterval the function when function meets some condition


问:
I have a error in my e-commerce website, "'X' is not defined no-undef"
Error:

```<code>./src/reducers/productReducers.js
  Line 3:10:  'PRODUCT_LIST_REQUEST' is not defined  no-undef
  Line 5:10:  'PRODUCT_LIST_SUCCESS' is not defined  no-undef
  Line 7:10:  'PRODUCT_LIST_FAIL' is not defined     no-undef
</code>```

And my code down below

```<code>function productListReducer(state = { products: [] }, action) {
  switch (action.type) {
    case PRODUCT_LIST_REQUEST:
      return { loading: true, products: [] };
    case PRODUCT_LIST_SUCCESS:
      return { loading: false, products: action.payload };
    case PRODUCT_LIST_FAIL:
      return { loading: false, error: action.payload };
    default:
      return state;
  }
}
export { productListReducer };
</code>```

答:
You probably mean't to provide action types as strings or forgot to import it from other file

You can use it like

```<code>function productListReducer(state = { products: [] }, action) {
  switch (action.type) {
    case 'PRODUCT_LIST_REQUEST':
      return { loading: true, products: [] };
    case 'PRODUCT_LIST_SUCCESS':
      return { loading: false, products: action.payload };
    case 'PRODUCT_LIST_FAIL':
      return { loading: false, error: action.payload };
    default:
      return state;
  }
}
export { productListReducer };
</code>```

or by defining and importing actionTypes like

actionTypes.js

```<code>export const PRODUCT_LIST_REQUEST = 'PRODUCT_LIST_REQUEST';
export const PRODUCT_LIST_SUCCESS = 'PRODUCT_LIST_SUCCESS';
export const PRODUCT_LIST_FAIL = 'PRODUCT_LIST_FAIL';
</code>```

and import in reducer like

```<code>import {PRODUCT_LIST_FAIL, PRODUCT_LIST_SUCCESS, PRODUCT_LIST_REQUEST} from '/path/to/actionTypes.js'
</code>```

before using them like

```<code>function productListReducer(state = { products: [] }, action) {
  switch (action.type) {
    case PRODUCT_LIST_REQUEST:
      return { loading: true, products: [] };
    case PRODUCT_LIST_SUCCESS:
      return { loading: false, products: action.payload };
    case PRODUCT_LIST_FAIL:
      return { loading: false, error: action.payload };
    default:
      return state;
  }
}
export { productListReducer };
</code>```

Body:
Error:

./src/reducers/productReducers.js
  Line 3:10:  'PRODUCT_LIST_REQUEST' is not defined  no-undef
  Line 5:10:  'PRODUCT_LIST_SUCCESS' is not defined  no-undef
  Line 7:10:  'PRODUCT_LIST_FAIL' is not defined     no-undef

And my code down below

function productListReducer(state = { products: [] }, action) {
  switch (action.type) {
    case PRODUCT_LIST_REQUEST:
      return { loading: true, products: [] };
    case PRODUCT_LIST_SUCCESS:
      return { loading: false, products: action.payload };
    case PRODUCT_LIST_FAIL:
      return { loading: false, error: action.payload };
    default:
      return state;
  }
}
export { productListReducer };

Body:
You probably mean't to provide action types as strings or forgot to import it from other file

You can use it like

function productListReducer(state = { products: [] }, action) {
  switch (action.type) {
    case 'PRODUCT_LIST_REQUEST':
      return { loading: true, products: [] };
    case 'PRODUCT_LIST_SUCCESS':
      return { loading: false, products: action.payload };
    case 'PRODUCT_LIST_FAIL':
      return { loading: false, error: action.payload };
    default:
      return state;
  }
}
export { productListReducer };

or by defining and importing actionTypes like

actionTypes.js

export const PRODUCT_LIST_REQUEST = 'PRODUCT_LIST_REQUEST';
export const PRODUCT_LIST_SUCCESS = 'PRODUCT_LIST_SUCCESS';
export const PRODUCT_LIST_FAIL = 'PRODUCT_LIST_FAIL';

and import in reducer like

import {PRODUCT_LIST_FAIL, PRODUCT_LIST_SUCCESS, PRODUCT_LIST_REQUEST} from '/path/to/actionTypes.js'

before using them like

function productListReducer(state = { products: [] }, action) {
  switch (action.type) {
    case PRODUCT_LIST_REQUEST:
      return { loading: true, products: [] };
    case PRODUCT_LIST_SUCCESS:
      return { loading: false, products: action.payload };
    case PRODUCT_LIST_FAIL:
      return { loading: false, error: action.payload };
    default:
      return state;
  }
}
export { productListReducer };


问:
How to order html elements in the same order as array using jQuery?
I'd like to order html elements in the same order as arrayData.

JavaScript

```<code>    var arrayData = [59, 56, 57];
</code>```

HTML

```<code>    <div class="selectize-input">
        <div class="item" data-value="56">Dog</div>
        <div class="item" data-value="57">Rabbit</div>
        <div class="item" data-value="59">Cat</div>
    </div>
</code>```

I want the result like this.

```<code>    <div class="selectize-input">
        <div class="item" data-value="59">Cat</div>
        <div class="item" data-value="56">Dog</div>
        <div class="item" data-value="57">Rabbit</div>
    </div>
</code>```

Is there any good way to achive this?
Thank you in advance.

[Additional]
I want to get result something like this, but don't now how to apply it to html elements and render on browser.

```<code>const orderRule = ['Cat', 'Rabbit', 'Dog', 'Pig', 'Mouse'],
      array = ['Mouse','Rabbit', 'Pig', 'Dog', 'Cat'];

const sortArray = [...array].sort((a, b) => orderRule.indexOf(a) - orderRule.indexOf(b));
console.log(sortArray);
</code>```

答:
So, I'm not quite sure if I fully understand the question. But if you're trying to dynamically render a div for each piece of data, you could try something like...

JS:

```<code>const arrayData = [
    {value:59, title:"Cat"},
    {value:56, title:"Dog"},
    {...}
]

arrayData.forEach((dataObject) => {
    $('.selectize-input').append(
        document.createElement('div')
            .innerHTML(dataObj.title)
            .attr('data-value', dataObj.value)
            .addClass('item')
    )
}
</code>```

I'm not really a jQuery person, so I'm not entirely sure that this will work, but I believe it will send you in the right direction.

First, I am making your array into an array of objects which include both the value of the item, but also the title of the item.

Then, I am using a forEach loop to run through each item and create a new div based on it. It appends these divs to the .selectize-input.

I hope it helps you.

I should say, the stuff that you're doing here is something that ReactJS is really good at. It's like a souped-up javascript that allows you to create and manipulate HTML elements really easily.

Check it out at https://reactjs.org/!

Body:
I'd like to order html elements in the same order as arrayData.

JavaScript

    var arrayData = [59, 56, 57];

HTML

Dog

Rabbit

Cat

I want the result like this.

Cat

Dog

Rabbit

Is there any good way to achive this?
Thank you in advance.

[Additional]
I want to get result something like this, but don't now how to apply it to html elements and render on browser.

const orderRule = ['Cat', 'Rabbit', 'Dog', 'Pig', 'Mouse'],
      array = ['Mouse','Rabbit', 'Pig', 'Dog', 'Cat'];

const sortArray = [...array].sort((a, b) => orderRule.indexOf(a) - orderRule.indexOf(b));
console.log(sortArray);

Body:
So, I'm not quite sure if I fully understand the question. But if you're trying to dynamically render a div for each piece of data, you could try something like...

JS:

const arrayData = [
    {value:59, title:"Cat"},
    {value:56, title:"Dog"},
    {...}
]

arrayData.forEach((dataObject) => {
    $('.selectize-input').append(
        document.createElement('div')
            .innerHTML(dataObj.title)
            .attr('data-value', dataObj.value)
            .addClass('item')
    )
}

I'm not really a jQuery person, so I'm not entirely sure that this will work, but I believe it will send you in the right direction.

First, I am making your array into an array of objects which include both the value of the item, but also the title of the item.

Then, I am using a forEach loop to run through each item and create a new div based on it. It appends these divs to the .selectize-input.

I hope it helps you.

I should say, the stuff that you're doing here is something that ReactJS is really good at. It's like a souped-up javascript that allows you to create and manipulate HTML elements really easily.

Check it out at https://reactjs.org/!


问:
Is there a way to use an SSIS Merge Join with a SQLServer OLEDB source and MySQL/ODBC source
I’m using SQL Server 2012 and need to do a full outer join using the Merge Join in order to do delta updates/inserts/deletes.

We would really like to avoid using the sort transformation as it is fully blocking but I’m running out of ideas.

Both source outputs are sorted using order by clauses and the IsSorted property set to true/columnSort order set to 1.

The Character set of the MySQL database is UTF8 And in the order by clause of the source query I am collating using UTF8_bin

The collation of the SQLServer database is SQL_Latin1_General_CP1_CI_AS but in the order by clause within the source query I have collated to Latin1_General_bin (so the sort methods are the same)

However I am finding that the sets are not joining correctly. Most records do match but I have instances where values exist on the left and right side but the opposite side of the join is null (in theory they should match)

The Values we are trying to match on are in the following format(99999-99999-9999 AAA BBB CCC)

I am aware that UTF8 support in SQL server had not been introduced until SQL Server 2019 so could this be the issue. Are we inevitably going to have to use the Sort transformation?

答:
If you trust the sorting from both sources, you can just set the "Is Sorted" property in the Advanced Edit section for outputs from your data source. You then set a position for any column that the sort is applied to. If there's only one column that it's sorted on, just put a 1 against that column.

Be careful though as it will barf if it isn't in the same order. If it's a number, you'r probably fine, or that format you've mentioned is also probably fine. But strings in general, I wouldn't trust.


问:
Pandas - rearrange columns if column exists
I have a dataframes that are in jumbled order how can I rearrange the columns if they exits.

```<code>One      Two       Three  Six    Four     Five
1         2         3      6      4         5
1         2         3      6      4         5
...
</code>```

How can I arrange this columns in order? The issue here is that all six column might not be there in all occasions. So I need a simple line that can arrange it in order of One Two  Three  Four  Five  Six if that column exits. I mean if Two is not in df then it should be One Three Four Five Six

答:
You can change order by DataFrame.reindex and then remove only missing values columns:

```<code>df1 = (df.reindex(['One', 'Two','Three','Four','Five','Six'], axis=1)
          .dropna(how='all', axis=1))
print (df1)
   One  Three  Four  Five  Six
0    1      3     4     5    6
1    1      3     4     5    6
</code>```

Or is possible create order categoricals in columns and then sorting columns:

```<code>c = ['One', 'Two','Three','Four','Five','Six']
df.columns = pd.CategoricalIndex(df.columns, categories=c, ordered=True)
df1 = df.sort_index(axis=1)
print (df1)
   One  Three  Four  Five  Six
0    1      3     4     5    6
1    1      3     4     5    6
</code>```

Body:
I have a dataframes that are in jumbled order how can I rearrange the columns if they exits.

One      Two       Three  Six    Four     Five
1         2         3      6      4         5
1         2         3      6      4         5
...

How can I arrange this columns in order? The issue here is that all six column might not be there in all occasions. So I need a simple line that can arrange it in order of One Two  Three  Four  Five  Six if that column exits. I mean if Two is not in df then it should be One Three Four Five Six

Body:
You can change order by DataFrame.reindex and then remove only missing values columns:

df1 = (df.reindex(['One', 'Two','Three','Four','Five','Six'], axis=1)
          .dropna(how='all', axis=1))
print (df1)
   One  Three  Four  Five  Six
0    1      3     4     5    6
1    1      3     4     5    6

Or is possible create order categoricals in columns and then sorting columns:

c = ['One', 'Two','Three','Four','Five','Six']
df.columns = pd.CategoricalIndex(df.columns, categories=c, ordered=True)
df1 = df.sort_index(axis=1)
print (df1)
   One  Three  Four  Five  Six
0    1      3     4     5    6
1    1      3     4     5    6


问:
Extra output outputted
In this code I want the output as a b c, but at the end there is another a outputting. So, how can I do it?

window.onload = function() {
  for (let i = 0; i < 3; i++) {
    var story = document.getElementsByClassName('story')[0];

    let clone = story.cloneNode(true);

    let usr = ["a", "b", "c"];

    document.getElementsByClassName('story')[i].innerHTML = usr[i];

    document.getElementById("story").appendChild(clone);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="story">
  <p class="story"></p>
</div></code>```

答:
cloning an item does not delete the original item

Then, how can I get the required output? I tried deleting the the real element at the end of the code. But it creates another Bug. In this case output is b c a .

if your element is complex you can also use the DOM parser to create your new element

const DomParser   = new DOMParser()
  ,   usrTab      = ['a', 'b', 'c']
  ,   storyDiv    = document.getElementById('story')
  ;
const newElement_X=(arg)=>
  {
  let elmX = `<p class="story">${arg}</p>`
  return DomParser.parseFromString( elmX, 'text/html').body.firstChild
  }
window.onload=()=>
  {
  for (let usrVal of usrTab)
    {
    storyDiv.appendChild( newElement_X(usrVal) )
    }
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="story"></div></code>```

Title: Extra output outputted

Body:
cloning an item does not delete the original item

Then, how can I get the required output? I tried deleting the the real element at the end of the code. But it creates another Bug. In this case output is b c a .

if your element is complex you can also use the DOM parser to create your new element

const DomParser   = new DOMParser()
  ,   usrTab      = ['a', 'b', 'c']
  ,   storyDiv    = document.getElementById('story')
  ;
const newElement_X=(arg)=>
  {
  let elmX = `<p class="story">${arg}</p>`
  return DomParser.parseFromString( elmX, 'text/html').body.firstChild
  }
window.onload=()=>
  {
  for (let usrVal of usrTab)
    {
    storyDiv.appendChild( newElement_X(usrVal) )
    }
  }

<div id="story"></div>


问:
How do I get the real .height() of a overflow: hidden or overflow: scroll div?
I have a question regarding how to get a div height. I'm aware of .height() and innerHeight(), but none of them does the job for me in this case. The thing is that in this case I have a div that is overflown width a overflow: scroll and the div has a fixed height.

If I use .height() or innerHeight(), both of them gives me the height of the visible area, but if I want the overflown taken in to account, how do I go about?

答:
I have just cooked up another solution for this, where it's not longer necessary to use a -much to high- max-height value. It needs a few lines of javascript code to calculate the inner height of the collapsed DIV but after that, it's all CSS.

1) Fetching and setting height

Fetch the inner height of the collapsed element (using scrollHeight). My element has a class .section__accordeon__content and I actually run this in a forEach() loop to set the height for all panels, but you get the idea.

```<code>document.querySelectorAll( '.section__accordeon__content' ).style.cssText = "--accordeon-height: " + accordeonPanel.scrollHeight + "px";
</code>```

2) Use the CSS variable to expand the active item

Next, use the CSS variable to set the max-height value when the item has an .active class.

```<code>.section__accordeon__content.active {
  max-height: var(--accordeon-height);
}
</code>```

Final example

So the full example goes like this: first loop through all accordeon panels and store their scrollHeight values as CSS variables. Next use the CSS variable as the max-height value on the active/expanded/open state of the element.

Javascript:

```<code>document.querySelectorAll( '.section__accordeon__content' ).forEach(
  function( accordeonPanel ) {
    accordeonPanel.style.cssText = "--accordeon-height: " + accordeonPanel.scrollHeight + "px";
  }
);
</code>```

CSS:

```<code>.section__accordeon__content {
  max-height: 0px;
  overflow: hidden;
  transition: all 425ms cubic-bezier(0.465, 0.183, 0.153, 0.946);
}

.section__accordeon__content.active {
  max-height: var(--accordeon-height);
}
</code>```

And there you have it. A adaptive max-height animation using only CSS and a few lines of JavaScript code (no jQuery required).

Hope this helps someone in the future (or my future self for reference).

ContentLicense: CC BY-SA 3.0

Body:
I have just cooked up another solution for this, where it's not longer necessary to use a -much to high- max-height value. It needs a few lines of javascript code to calculate the inner height of the collapsed DIV but after that, it's all CSS.

1) Fetching and setting height

Fetch the inner height of the collapsed element (using scrollHeight). My element has a class .section__accordeon__content and I actually run this in a forEach() loop to set the height for all panels, but you get the idea.

document.querySelectorAll( '.section__accordeon__content' ).style.cssText = "--accordeon-height: " + accordeonPanel.scrollHeight + "px";

2) Use the CSS variable to expand the active item

Next, use the CSS variable to set the max-height value when the item has an .active class.

.section__accordeon__content.active {
  max-height: var(--accordeon-height);
}

Final example

So the full example goes like this: first loop through all accordeon panels and store their scrollHeight values as CSS variables. Next use the CSS variable as the max-height value on the active/expanded/open state of the element.

Javascript:

document.querySelectorAll( '.section__accordeon__content' ).forEach(
  function( accordeonPanel ) {
    accordeonPanel.style.cssText = "--accordeon-height: " + accordeonPanel.scrollHeight + "px";
  }
);

CSS:

.section__accordeon__content {
  max-height: 0px;
  overflow: hidden;
  transition: all 425ms cubic-bezier(0.465, 0.183, 0.153, 0.946);
}

.section__accordeon__content.active {
  max-height: var(--accordeon-height);
}

And there you have it. A adaptive max-height animation using only CSS and a few lines of JavaScript code (no jQuery required).

Hope this helps someone in the future (or my future self for reference).


问:
How to protect the Apps Script code in a Google spreadsheet?
I have written some code for my Google spreadsheet with the script editor.

I want to share this spreadsheet with my clients but I don't want to share the code I have written.

This code adds a menu to my spreadsheet which contains useful functions that should work/run when my clients open this spreadsheet with condition applied that: they shouldn't be able to see its code.

This is easy with Excel, but with Google spreadsheet I don't know. . I have searched a lot on Google but they all gives the idea about how to share a spreadsheet. For example in "View" mode, but in that case there is a problem: my menu function, which adds a menu,  is "onOpen" and  doesn't start when my clients open it.

How to implement this in Google Spreadsheet?

答:
Create 2 libraries; one is dummy (I call it Lib1) and another core library that has all the secret codes (I call it Lib2).

Add Lib2 as a library to Lib1 and use in it the necessary methods that are fully implemented in Lib2.

Share both libraries publicly and set their permission to Viewer.

From the sharing setting page of Lib1, there is a gear symbol. make sure the following option is unchecked "Viewers and commenters can see the option to download, print, and copy"

Add Lib1 to your clients' script (maybe a Spreadsheet script).

Share the script of your client as editor or viewer.

If the client could get Lib1 ID by accessing it from Resources/Libraries menu of his script, he won't be able to access the Resources/Libraries menu of Lib1. He also cannot make another copy of Lib1 because of the unchecked option done in step 4, preventing him from possibly seeing the ID of Lib2.


问:
Consume java spring rest api and insert records to mysql table
I am trying to consume a spring rest API and store the results into a staging table.
Here is what I tried. I am very new to java and spring, please forgive my mistakes.
My staging table name "greetingsstaging".
I am new to spring development, please help in understanding the issue.
I am using JPA and spring.

This is the main application.

```<code>package com.javatechie.spring.api;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import com.javatechie.spring.api.entty.Greetings;
import com.javatechie.spring.api.service.Greet;
import com.javatechie.spring.api.service.GreetInterface;
import com.javatechie.spring.api.service.GreetingsService;

@SpringBootApplication
public class GreetingsConsumerApplication {
    private static RestTemplate rs = new RestTemplate();
    private static String baseUrl = "http://localhost:8080/api/Greetings";

    private static GreetInterface greetInterface;

    @Autowired
    public GreetingsConsumerApplication(GreetInterface theGreetInterface) {
        greetInterface = theGreetInterface;
    }

    public static void main(String[] args) {
        SpringApplication.run(GreetingsConsumerApplication.class, args);

        ResponseEntity<List<GreetingsService>> response = rs.exchange(baseUrl, HttpMethod.GET, null,
                new ParameterizedTypeReference<List<GreetingsService>>() {
                });
        List<GreetingsService> gs = response.getBody();

        for (GreetingsService g : gs) {

            Greetings greetings = new Greetings(g.getId(), g.getName(), g.getAge(), g.getAddress());
            System.out.println("Id : " + greetings.getId() + " name : " + greetings.getName() + " Age : "
                    + greetings.getAge() + " Address : " + greetings.getAddress());
            greetInterface.save(greetings);
        }

    }

}
</code>```

Here is my service.

```<code>package com.javatechie.spring.api.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.javatechie.spring.api.entty.Greetings;
import com.javatechie.spring.api.repository.GreetingsRepository;

@Service
public class Greet implements GreetInterface{

    private GreetingsRepository repo;

    @Autowired
    public Greet(GreetingsRepository repo) {
        super();
        this.repo = repo;
    }
    @Override
    public void save(Greetings obj) {
        repo.save(obj);

    }
}
</code>```

Here is the repository interface.

```<code>package com.javatechie.spring.api.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.javatechie.spring.api.entty.Greetings;

@Repository
public interface GreetingsRepository extends JpaRepository<Greetings, Integer> {

}
</code>```

Here is my pojo class.

```<code>package com.javatechie.spring.api.entty;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="greetingsstaging")
public class Greetings {

    int id;
    String name;
    int age;
    String address;

    public Greetings(int id, String name, int age, String address) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
        this.address = address;
    }

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    @Override
    public String toString() {
        return "Greetings [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + "]";
    }

}
</code>```

I am getting following exception.

Error creating bean with name 'requestMappingHandlerAdapter' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Unsatisfied dependency expressed through method 'requestMappingHandlerAdapter' parameter 1; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mvcConversionService' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.format.support.FormattingConversionService]: Factory method 'mvcConversionService' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'greetingsRepository' defined in com.javatechie.spring.api.repository.GreetingsRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Cannot resolve reference to bean 'jpaMappingContext' while setting bean property 'mappingContext'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is org.hibernate.AnnotationException: No identifier specified for entity: com.javatechie.spring.api.entty.Greetings

My main idea is to store the results from API into a staging table.

答:
You're missing @Id annotation of Greetings class. Each JPA entity must have a primary key which uniquely identifies it.</p>

```<code>@Entity
@Table(name="greetingsstaging")
public class Greetings {

    @Id
    int id;
}
</code>```

Body:
I am trying to consume a spring rest API and store the results into a staging table.
Here is what I tried. I am very new to java and spring, please forgive my mistakes.
My staging table name "greetingsstaging".
I am new to spring development, please help in understanding the issue.
I am using JPA and spring.

This is the main application.

package com.javatechie.spring.api;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import com.javatechie.spring.api.entty.Greetings;
import com.javatechie.spring.api.service.Greet;
import com.javatechie.spring.api.service.GreetInterface;
import com.javatechie.spring.api.service.GreetingsService;

@SpringBootApplication
public class GreetingsConsumerApplication {
    private static RestTemplate rs = new RestTemplate();
    private static String baseUrl = "http://localhost:8080/api/Greetings";

    private static GreetInterface greetInterface;

    @Autowired
    public GreetingsConsumerApplication(GreetInterface theGreetInterface) {
        greetInterface = theGreetInterface;
    }

    public static void main(String[] args) {
        SpringApplication.run(GreetingsConsumerApplication.class, args);

        ResponseEntity<List<GreetingsService>> response = rs.exchange(baseUrl, HttpMethod.GET, null,
                new ParameterizedTypeReference<List<GreetingsService>>() {
                });
        List<GreetingsService> gs = response.getBody();

        for (GreetingsService g : gs) {

            Greetings greetings = new Greetings(g.getId(), g.getName(), g.getAge(), g.getAddress());
            System.out.println("Id : " + greetings.getId() + " name : " + greetings.getName() + " Age : "
                    + greetings.getAge() + " Address : " + greetings.getAddress());
            greetInterface.save(greetings);
        }

    }

}

Here is my service.

package com.javatechie.spring.api.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.javatechie.spring.api.entty.Greetings;
import com.javatechie.spring.api.repository.GreetingsRepository;

@Service
public class Greet implements GreetInterface{

    private GreetingsRepository repo;

    @Autowired
    public Greet(GreetingsRepository repo) {
        super();
        this.repo = repo;
    }
    @Override
    public void save(Greetings obj) {
        repo.save(obj);

    }
}

Here is the repository interface.

package com.javatechie.spring.api.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.javatechie.spring.api.entty.Greetings;

@Repository
public interface GreetingsRepository extends JpaRepository<Greetings, Integer> {

}

Here is my pojo class.

package com.javatechie.spring.api.entty;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="greetingsstaging")
public class Greetings {

    int id;
    String name;
    int age;
    String address;

    public Greetings(int id, String name, int age, String address) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
        this.address = address;
    }

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    @Override
    public String toString() {
        return "Greetings [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + "]";
    }

}

I am getting following exception.

Error creating bean with name 'requestMappingHandlerAdapter' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Unsatisfied dependency expressed through method 'requestMappingHandlerAdapter' parameter 1; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mvcConversionService' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.format.support.FormattingConversionService]: Factory method 'mvcConversionService' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'greetingsRepository' defined in com.javatechie.spring.api.repository.GreetingsRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Cannot resolve reference to bean 'jpaMappingContext' while setting bean property 'mappingContext'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is org.hibernate.AnnotationException: No identifier specified for entity: com.javatechie.spring.api.entty.Greetings

My main idea is to store the results from API into a staging table.

Body:
You're missing @Id annotation of Greetings class. Each JPA entity must have a primary key which uniquely identifies it.

@Entity
@Table(name="greetingsstaging")
public class Greetings {

    @Id
    int id;
}


问:
What is regular expression for "Test123"
I tried - "Test\d\d\d" and it works but problem is, String in expression could contain any number of digits so it could be "Test1" or "Test12" or "Test123". Hence it could be in range [000] to [999]</p>

答:
This should help
Test[0-9]{1,3}

[0-9] specifies any digits between 0 - 9

{1,3} specifies a range of number of
digits ranging from 1 to 3


问:
Base of Global Call Stack in C/C++
I have read that each function invocation leads to pushing of a stack frame in the global call stack and once the function call is completed the call stack is popped off and the control passes to the address that we get from the popped of stack frame. If a called function calls on to yet another function, it will push another return address onto the top of the same call stack, and so on, with the information stacking up and unstacking as the program dictates.

I was wondering what's at the base of global call stack in a C or C++ program?

I did some searching on the internet but none of the sources explicitly mention about it. Is the call stack empty when our program starts and only once a function is called, the call stack usage starts? OR Is the address where main() function has to return, gets implicitly pushed as the base of our call stack and is a stack frame in our call stack? I expect the main() would also have a stack frame in our call stack since we are always returning something at end of our main() function and there needs to be some address to return to. OR is this dependent on compiler/OS and differs according to implementation?

It would be helpful if someone has some informative links about this or could provide details on the process that goes into it.

答:
First of all, there is no such thing as a "global call stack". Each thread has a stack, and the stack for the main thread is often looking quite different from the thread of any thread spawned later on. And mostly, each of these "stacks" is just an arbitrary memory segment currently declared to be used as such, sub-allocated from any arbitrary suitable memory pool.

And due to compiler optimizations, many function calls will not even end up on the stack, usually. Meaning there isn't necessarily a distinguishable stack frame. You are only guaranteed that you can reference variables you put on the stack, but not that the compiler must preserve anything you didn't explicitly reference.

There is not even a guarantee that the memory layout for your call stack must even be organized in distinguishable frames. Function pointers are never guaranteed to be part of the stack frame, just happens to be an implementation detail in architectures where data and function pointers may co-exist in the address space. (As there are architectures which require return addresses to be stored in a different address space than the data used in the call stack.)

That aside, yes, there is code which is executed outside of the main() function. Specifically initializers for global static variables, code to set up the runtime environment (env, call parameters, stdin/stdout) etc.

E.g. when having linked to libc, there is __libc_start_main which will call your main function after initialization is done. And clean up when your main function returns.

__libc_start_main is about the point where "stack" starts being used, as far as you can see from within the program. That's not actually true though, there has already been some loader code been executed in kernel space, for reserving memory for your process to operate in initially (including memory for the future stack), initializing registers and memory to well defined values etc.

Right before actually "starting" your process, after dropping out of kernel mode, arbitrary pointers to a future stack, and the first instruction of your program, are loaded into the corresponding processor registers. Effectively, that's where __libc_start_main (or any other initialization function, depending on your runtime) starts running, and the stack visible to you starts building up.

Getting back into the kernel usually involves an interrupt now, which doesn't follow the stack either, but may just directly access processor registers to simply swap the contents of the corresponding processor registers. (E.g. if you call a function from the kernel, the memory required by the call stack inside the function call is not allocated from your stack, but from one you don't even have access to.)

Either way, everything that happens before main() is called, and whenever you enter a syscall, is implementation dependent, and you are not guaranteed any specific observable behavior. And messing around with processor registers, and thereby alternating the program flow, is also far outside defined behavior as far as a pure C / C++ run time is concerned.

Title: Base of Global Call Stack in C/C++


问:
Display full screen loading widget in flutter
I want to show full-screen loading view in flutter while API calling. But when I add loading widget in scaffold body it appears after appbar and bottom navigator.

I am spending lots of time for display loading view in full-screen. Also, I want to prevent back action while API calling.

答:
Full-screen loader: Best solution to display a full screen loader is to use package
https://pub.dev/packages/screen_loader.

Prevent back action while loading: This package this package provides a variable isLoading, use it to prevent navigating back. eg:

// --------------- some_screen.dart ---------------
import 'package:flutter/material.dart';
import 'package:screen_loader/screen_loader.dart';

class SomeScreen extends StatefulWidget {
  @override
  _SomeScreenState createState() => _SomeScreenState();
}

class _SomeScreenState extends State<SomeScreen> with ScreenLoader<SomeScreen> {
  getData() {
    this.performFuture(NetworkService.callApi);
  }

  @override
  Widget screen(BuildContext context) {
    return WillPopScope(
      child: Scaffold(
          // your beautiful design..
          ),
      onWillPop: () async {
        return !isLoading;
      },
    );
  }
}

// --------------- app_api.dart ---------------
class NetworkService {
  static Future callApi() async {

  }
}

```

NOTE: You'll need to see the definition of performFuture to see how it works for different scenarios.

Body:
Full-screen loader: Best solution to display a full screen loader is to use package
https://pub.dev/packages/screen_loader.

Prevent back action while loading: This package this package provides a variable isLoading, use it to prevent navigating back. eg:

// --------------- some_screen.dart ---------------
import 'package:flutter/material.dart';
import 'package:screen_loader/screen_loader.dart';

class SomeScreen extends StatefulWidget {
  @override
  _SomeScreenState createState() => _SomeScreenState();
}

class _SomeScreenState extends State<SomeScreen> with ScreenLoader<SomeScreen> {
  getData() {
    this.performFuture(NetworkService.callApi);
  }

  @override
  Widget screen(BuildContext context) {
    return WillPopScope(
      child: Scaffold(
          // your beautiful design..
          ),
      onWillPop: () async {
        return !isLoading;
      },
    );
  }
}

// --------------- app_api.dart ---------------
class NetworkService {
  static Future callApi() async {

  }
}

NOTE: You'll need to see the definition of performFuture to see how it works for different scenarios.


问:
Proper way (move semantics) to return a std::vector from function calling in C++11
I want to fill std::vector (or some other STL container):

```<code>class Foo {
public:
  Foo(int _n, const Bar &_m);
private:
  std::vector<Foo> fooes_;
}
</code>```

1.Good looking ctor, expensive performance

```<code>std::vector<Foo> get_vector(int _n, const Bar &_m) {
  std::vector<Foo> ret;
  ... // filling ret depending from arguments
  return ret;
}

Foo::Foo(int _n, const Bar &_m) : fooes_(get_vector(_n, _m) {}
</code>```

2. Better performance, worse looking ctor

```<code>void fill_vector(int _n, const Bar &_m, std::vector<Foo> &_ret) {
  ... // filling ret depending from arguments
}

Foo::Foo(int _n, const Bar &_m) { fill_vector(_n, _m, fooes_); }
</code>```

Is it possible to rewrite get_vector function from 1st example with C++0x (move semantics features and so on) to avoid redundant copying and constructor calls?

答:
If you're using a C++0x-compatible compiler and standard library, you get better performance from the first example without doing anything. The return value of get_vector(_n, _m) is a temporary, and the move constructor for std::vector (a constructor taking an rvalue reference) will automatically be called with no further work on your part.

In general, non-library writers won't need to use rvalue references directly; you'll just reap a decent chunk of the benefits automatically.

Body:
I want to fill std::vector (or some other STL container):

class Foo {
public:
  Foo(int _n, const Bar &_m);
private:
  std::vector<Foo> fooes_;
}

1.Good looking ctor, expensive performance

std::vector<Foo> get_vector(int _n, const Bar &_m) {
  std::vector<Foo> ret;
  ... // filling ret depending from arguments
  return ret;
}

Foo::Foo(int _n, const Bar &_m) : fooes_(get_vector(_n, _m) {}

2. Better performance, worse looking ctor

void fill_vector(int _n, const Bar &_m, std::vector<Foo> &_ret) {
  ... // filling ret depending from arguments
}

Foo::Foo(int _n, const Bar &_m) { fill_vector(_n, _m, fooes_); }

Is it possible to rewrite get_vector function from 1st example with C++0x (move semantics features and so on) to avoid redundant copying and constructor calls?


答:
const setup = () => {
 let storySource = document.querySelectorAll('.story')[0];
  let story = document.querySelector('#story');
  let userList = ["a", "b", "c"];

  for (let i = 0; i < 3; i++) {
  let clone = storySource.cloneNode(true);
    clone.textContent = userList[i];
    story.appendChild(clone);
  }
  storySource.remove();

};

//load
window.addEventListener('load', setup);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="story">
  <p class="story"></p>
</div></code>```

Title: Extra output outputted

Body:
In this code I want the output as a b c, but at the end there is another a outputting. So, how can I do it?

window.onload = function() {
  for (let i = 0; i < 3; i++) {
    var story = document.getElementsByClassName('story')[0];

    let clone = story.cloneNode(true);

    let usr = ["a", "b", "c"];

    document.getElementsByClassName('story')[i].innerHTML = usr[i];

    document.getElementById("story").appendChild(clone);
  }
}

Body:
const setup = () => {
 let storySource = document.querySelectorAll('.story')[0];
  let story = document.querySelector('#story');
  let userList = ["a", "b", "c"];

  for (let i = 0; i < 3; i++) {
  let clone = storySource.cloneNode(true);
    clone.textContent = userList[i];
    story.appendChild(clone);
  }
  storySource.remove();

};

//load
window.addEventListener('load', setup);

<div id="story">
  <p class="story"></p>
</div>


问:
How can I put the below java query in switch case?
// How can I put the below java query in switch case? I am working with spring-mobile project and I need to put the below code in switch help. </p>

```<code>try {
    if (device.isMobile()) {
        redirectUri = cfg.getEmail().getVerification().getMobile_success_redirect_url();
    }
} catch (Exception ex) {
    redirectUri = cfg.getEmail().getVerification().getMobile_failure_redirect_url();
    logger.error("Failed to verify email. Cause: {}", ex);
}
try {
    if (device.isTablet()) {
        redirectUri = cfg.getEmail().getVerification().getTablet_success_redirect_url();
    }
} catch (Exception ex) {
    redirectUri = cfg.getEmail().getVerification().getTablet_success_redirect_url();
    logger.error("Failed to verify email. Cause: {}", ex);
}
try {
    if (device.isNormal()) {
        redirectUri = cfg.getEmail().getVerification().getWeb_success_redirect_url();
    }
} catch (Exception ex) {
    redirectUri = cfg.getEmail().getVerification().getWeb_failure_redirect_url();
    logger.error("Failed to verify email. Cause: {}", ex);
}

response.sendRedirect(redirectUri);
</code>```

答:
Read the comment by @Naman. I agree, here are a few more details.

I am not sure if the class of type device is in your control.

But if it is, you should perhaps have field denoting device type, which can be an Enum with 3 values MOBILE, TABLET, NORMAL.

Now you can have a switch case on this Enum with each case containing code for that specific use case.

The method for this switch case should accept 2 params, the newly created DeviceType enum and the Object that is returned by cfg.getEmail().getVerification().

Rough outline but I hope you get the point.

String getRedirectUri(DeviceType deviceType, Verification verification) {
    switch(deviceType) {
        case TABLET:
        case MOBILE:
        case NORMAL:
        default
    }
}

Body:
// How can I put the below java query in switch case? I am working with spring-mobile project and I need to put the below code in switch help.

try {
    if (device.isMobile()) {
        redirectUri = cfg.getEmail().getVerification().getMobile_success_redirect_url();
    }
} catch (Exception ex) {
    redirectUri = cfg.getEmail().getVerification().getMobile_failure_redirect_url();
    logger.error("Failed to verify email. Cause: {}", ex);
}
try {
    if (device.isTablet()) {
        redirectUri = cfg.getEmail().getVerification().getTablet_success_redirect_url();
    }
} catch (Exception ex) {
    redirectUri = cfg.getEmail().getVerification().getTablet_success_redirect_url();
    logger.error("Failed to verify email. Cause: {}", ex);
}
try {
    if (device.isNormal()) {
        redirectUri = cfg.getEmail().getVerification().getWeb_success_redirect_url();
    }
} catch (Exception ex) {
    redirectUri = cfg.getEmail().getVerification().getWeb_failure_redirect_url();
    logger.error("Failed to verify email. Cause: {}", ex);
}

response.sendRedirect(redirectUri);


问:
C - how to get rid of memory leaks?
How can I get rid of memory leaks from for example this function:

```<code>void AddData(Data **head, char *sentence, int number) {
    Words *words = NULL;
    char delimiters[] = " \n\0";
    char *token = strtok(sentence, delimiters);
    while (token != NULL) {
        if (IsAlphabetical(token) == 1) {
            char *string = (char *)malloc((strlen(token) + 1) * sizeof(char));
            strcpy(string, token);
            AddWords(&words, string);
            free(string);
        }
        token = strtok(NULL, delimiters);
    }

    Data *temp = *head;
    Data *newData = (Data *)malloc(sizeof(Data));

    newData->lineNumber = number;
    newData->words = words;
    newData->pNext = NULL;

    if (*head == NULL)
        *head = newData;
    else {
        while (temp->pNext != NULL)
            temp = temp->pNext;

        temp->pNext = newData;
    }
}
</code>```

My personal opinion is the leaks appear because of newData, temp and words variables.

I have a few similar functions that cause the same problem.
I have also function for deleting Data struct, but when I call it at the end of previous function in such way DeleteData(&temp) program will not execute. I think it's because my whole list is deleted.

```<code>void DeleteData(Data **head) {
    Data *temp = *head;
    while (temp->pNext != NULL) {
        Data *next = temp->pNext;
        DeleteWords(&temp->words);
        free(temp);
        temp = next;
    }
    free(temp); /* to check that */
    *head = NULL;
}
</code>```

How can I fix this?

答:
Here are some problems I identified:

The trailing \0 in char delimiters[] = " \n\0"; is useless.

Testing if (IsAlphabetical(token) == 1) might be too restrictive. In C anything non 0 is true so you might test if (IsAlphabetical(token) != 0) or just if (IsAlphabetical(token)).

Why allocate a copy of the string to pass to AddWords(&words, string); and then free(string) thereafter? If Addwords() does not keep the pointer it gets, there is no need to allocate a copy.

Does AddWords() call strtok()? strtok() is non-reentrant, which means that if AddWords() or any other function called in this loop, such as IsAlphabetical() calls strtok(), the context used in the loop will be corrupted. You should use strtok_r() instead.

in function DeleteData, why do you iterate testing while (temp->pNext != NULL)? The last item in the list does not get freed properly, the DeleteWords(&temp->words); is not called. This may cause a memory leak. You should just write:

```<code>  void DeleteData(Data **head) {
      Data *temp = *head;
      while (temp != NULL) {
          Data *next = temp->pNext;
          DeleteWords(&temp->words);
          free(temp);
          temp = next;
      }
      *head = NULL;
  }
</code>```

Title: C - how to get rid of memory leaks?

Body:
How can I get rid of memory leaks from for example this function:

void AddData(Data **head, char *sentence, int number) {
    Words *words = NULL;
    char delimiters[] = " \n\0";
    char *token = strtok(sentence, delimiters);
    while (token != NULL) {
        if (IsAlphabetical(token) == 1) {
            char *string = (char *)malloc((strlen(token) + 1) * sizeof(char));
            strcpy(string, token);
            AddWords(&words, string);
            free(string);
        }
        token = strtok(NULL, delimiters);
    }

    Data *temp = *head;
    Data *newData = (Data *)malloc(sizeof(Data));

    newData->lineNumber = number;
    newData->words = words;
    newData->pNext = NULL;

    if (*head == NULL)
        *head = newData;
    else {
        while (temp->pNext != NULL)
            temp = temp->pNext;

        temp->pNext = newData;
    }
}

My personal opinion is the leaks appear because of newData, temp and words variables.

I have a few similar functions that cause the same problem.
I have also function for deleting Data struct, but when I call it at the end of previous function in such way DeleteData(&temp) program will not execute. I think it's because my whole list is deleted.

void DeleteData(Data **head) {
    Data *temp = *head;
    while (temp->pNext != NULL) {
        Data *next = temp->pNext;
        DeleteWords(&temp->words);
        free(temp);
        temp = next;
    }
    free(temp); /* to check that */
    *head = NULL;
}

How can I fix this?

Body:
Here are some problems I identified:

The trailing \0 in char delimiters[] = " \n\0"; is useless.

Testing if (IsAlphabetical(token) == 1) might be too restrictive. In C anything non 0 is true so you might test if (IsAlphabetical(token) != 0) or just if (IsAlphabetical(token)).

Why allocate a copy of the string to pass to AddWords(&words, string); and then free(string) thereafter? If Addwords() does not keep the pointer it gets, there is no need to allocate a copy.

Does AddWords() call strtok()? strtok() is non-reentrant, which means that if AddWords() or any other function called in this loop, such as IsAlphabetical() calls strtok(), the context used in the loop will be corrupted. You should use strtok_r() instead.

in function DeleteData, why do you iterate testing while (temp->pNext != NULL)? The last item in the list does not get freed properly, the DeleteWords(&temp->words); is not called. This may cause a memory leak. You should just write:

  void DeleteData(Data **head) {
      Data *temp = *head;
      while (temp != NULL) {
          Data *next = temp->pNext;
          DeleteWords(&temp->words);
          free(temp);
          temp = next;
      }
      *head = NULL;
  }


问:
How do I clear a combobox?
I have some combo-boxes that are set up as drop down lists, and the user can pick a number in them. I also have a Clear button that should clear the text from the combo boxes but I can't seem to get it. I've tried:

```<code> //doesn't work
 cboxHour.Text = "";
</code>```

and

```<code>//doesn't work
cboxHour.ResetText();
</code>```

This seems like it should be so straight forward but I'm just not getting it.

答:
This worked for me when I added ComboBox.Focus()

```<code>ComboBox.Items.Clear();
ComboBox.ResetText();
ComboBox.Focus();
</code>```

Title: How do I clear a combobox?

Body:
I have some combo-boxes that are set up as drop down lists, and the user can pick a number in them. I also have a Clear button that should clear the text from the combo boxes but I can't seem to get it. I've tried:

 //doesn't work
 cboxHour.Text = "";

and

//doesn't work
cboxHour.ResetText();

This seems like it should be so straight forward but I'm just not getting it.

Body:
This worked for me when I added ComboBox.Focus()

ComboBox.Items.Clear();
ComboBox.ResetText();
ComboBox.Focus();


问:
Loop through coordinates and find the closest shop to a point Swift 3
Idea :

App lets drivers see the closest shop/restaurants to customers.

What I have :

Coordinates saved as strings

let clientLat = "24.449384"
let clientLng = "56.343243"

a function to find all the shops in my local area

I tried to save all the coordinates of a shop in my local area and I succeeded:

```<code>  var coordinates: [CLLocationCoordinate2D] = [CLLocationCoordinate2D]()

 func performSearch() {
    coordinates.removeAll()

    let request = MKLocalSearchRequest()
    request.naturalLanguageQuery = "starbucks"
    request.region = mapView.region

    let search = MKLocalSearch(request: request)

    search.start(completionHandler: {(response, error) in

        if error != nil {
            print("Error occured in search: \(error!.localizedDescription)")
        } else if response!.mapItems.count == 0 {
            print("No matches found")
        } else {
            print("Matches found")

            for item in response!.mapItems {

                self.coordinates.append(item.placemark.coordinate)

               // need to sort coordinates

                // need to find the closest

                let annotation = MKPointAnnotation()
                annotation.coordinate = item.placemark.coordinate
                annotation.title = item.name
                self.mapView.addAnnotation(annotation)
            }
        }
    })
</code>```

}

What I need:

I wish to loop through the coordinates and find the closest shop (kilometers) to the lat and long strings then put a pin on it.

UPDATE

```<code>  func performSearch() {
    coordinates.removeAll()

    let request = MKLocalSearchRequest()
    request.naturalLanguageQuery = "starbucks"
    request.region = mapView.region

    let search = MKLocalSearch(request: request)

    search.start(completionHandler: {(response, error) in

        if error != nil {
            print("Error occured in search: \(error!.localizedDescription)")
        } else if response!.mapItems.count == 0 {
            print("No matches found")
        } else {
            print("Matches found")

            for item in response!.mapItems {

                self.coordinates.append(item.placemark.coordinate)

                let pointToCompare = CLLocation(latitude: 24.741721, longitude: 46.891440)
              let  storedCorrdinates =  self.coordinates.map({CLLocation(latitude: $0.latitude, longitude: $0.longitude)}).sorted(by: {
                    $0.distance(from: pointToCompare) < $1.distance(from: pointToCompare)

                })
                self.coordinate = storedCorrdinates
            }

            let annotation = MKPointAnnotation()
            annotation.coordinate = self.coordinate[0].coordinate
            self.mapView.addAnnotation(annotation)
        }
    })
</code>```

}
 Thank you @brimstone

答:
I would like to share my solution :)

1) In my case, I upload data from the API, so I need to create a model.

```<code>import MapKit

struct StoresMap: Codable {
    let id: Int?
    let title: String?
    let latitude: Double?
    let longitude: Double?
    let schedule: String?
    let phone: String?
    let ukmStoreId: Int?
    var distanceToUser: CLLocationDistance?
}
</code>```

The last variable is not from API, but from myself to define distance for each store.

2) In ViewController I define:

```<code>func fetchStoresList() {
    NetworkManager.downloadStoresListForMap(firstPartURL: backendURL) { (storesList) in
        self.shopList = storesList
        let initialLocation = self.locationManager.location!

        for i in 0..<self.shopList.count {
            self.shopList[i].distanceToUser = initialLocation.distance(from: CLLocation(latitude: self.shopList[i].latitude!, longitude: self.shopList[i].longitude!))
        }
        self.shopList.sort(by: { $0.distanceToUser! < $1.distanceToUser!})
        print("Closest shop - ", self.shopList[0])
    }
}
</code>```

3) Don't forget to call the function in viewDidLoad() and import MapView framework :)

Body:
Idea :

App lets drivers see the closest shop/restaurants to customers.

What I have :

Coordinates saved as strings

let clientLat = "24.449384"
let clientLng = "56.343243"

a function to find all the shops in my local area

I tried to save all the coordinates of a shop in my local area and I succeeded:

  var coordinates: [CLLocationCoordinate2D] = [CLLocationCoordinate2D]()

 func performSearch() {
    coordinates.removeAll()

    let request = MKLocalSearchRequest()
    request.naturalLanguageQuery = "starbucks"
    request.region = mapView.region

    let search = MKLocalSearch(request: request)

    search.start(completionHandler: {(response, error) in

        if error != nil {
            print("Error occured in search: \(error!.localizedDescription)")
        } else if response!.mapItems.count == 0 {
            print("No matches found")
        } else {
            print("Matches found")

            for item in response!.mapItems {

                self.coordinates.append(item.placemark.coordinate)

               // need to sort coordinates

                // need to find the closest

                let annotation = MKPointAnnotation()
                annotation.coordinate = item.placemark.coordinate
                annotation.title = item.name
                self.mapView.addAnnotation(annotation)
            }
        }
    })

}

What I need:

I wish to loop through the coordinates and find the closest shop (kilometers) to the lat and long strings then put a pin on it.

UPDATE

  func performSearch() {
    coordinates.removeAll()

    let request = MKLocalSearchRequest()
    request.naturalLanguageQuery = "starbucks"
    request.region = mapView.region

    let search = MKLocalSearch(request: request)

    search.start(completionHandler: {(response, error) in

        if error != nil {
            print("Error occured in search: \(error!.localizedDescription)")
        } else if response!.mapItems.count == 0 {
            print("No matches found")
        } else {
            print("Matches found")

            for item in response!.mapItems {

                self.coordinates.append(item.placemark.coordinate)

                let pointToCompare = CLLocation(latitude: 24.741721, longitude: 46.891440)
              let  storedCorrdinates =  self.coordinates.map({CLLocation(latitude: $0.latitude, longitude: $0.longitude)}).sorted(by: {
                    $0.distance(from: pointToCompare) < $1.distance(from: pointToCompare)

                })
                self.coordinate = storedCorrdinates
            }

            let annotation = MKPointAnnotation()
            annotation.coordinate = self.coordinate[0].coordinate
            self.mapView.addAnnotation(annotation)
        }
    })

}
 Thank you @brimstone

Body:
I would like to share my solution :)

1) In my case, I upload data from the API, so I need to create a model.

import MapKit

struct StoresMap: Codable {
    let id: Int?
    let title: String?
    let latitude: Double?
    let longitude: Double?
    let schedule: String?
    let phone: String?
    let ukmStoreId: Int?
    var distanceToUser: CLLocationDistance?
}

The last variable is not from API, but from myself to define distance for each store.

2) In ViewController I define:

func fetchStoresList() {
    NetworkManager.downloadStoresListForMap(firstPartURL: backendURL) { (storesList) in
        self.shopList = storesList
        let initialLocation = self.locationManager.location!

        for i in 0..<self.shopList.count {
            self.shopList[i].distanceToUser = initialLocation.distance(from: CLLocation(latitude: self.shopList[i].latitude!, longitude: self.shopList[i].longitude!))
        }
        self.shopList.sort(by: { $0.distanceToUser! < $1.distanceToUser!})
        print("Closest shop - ", self.shopList[0])
    }
}

3) Don't forget to call the function in viewDidLoad() and import MapView framework :)