问:
How do I insert values into a sql table using python3?
I'm trying to setup a MQTT client using the Paho library. With that there are no problems, but I'm trying to insert the received publishes in a sql database. I'm converting the received payload string into a dictionary and add a few entries. When executing the following code:

```<code>def insert_values(db_connection=None, topic=None, payload=None, time_received=None):
    query_1 = "SELECT topic_id FROM topics WHERE topic = %s"
    query_2 = """INSERT INTO measurements (start_time, end_time, value, max_value, min_value, time_received, topic_id)
                 VALUES (%(start_time)s, %(end_time)s, %(value)s, %(max_value)s, %(min_value)s, %(time_received)s,
                        %(topic_id)s)"""
    cursor = db_connection.cursor(prepared=True)
    topic_id = cursor.execute(query_1, topic)
    payload["time_received"] = time_received
    payload["topic_id"] = topic_id
    cursor.executemany(query_2, payload)
    db_connection.commit()
    db_disconnect(db_connection, cursor)
</code>```

I get the following error:

```<code>Caught exception in on_message: 1210: Incorrect number of arguments executing prepared statement
</code>```

The payload looks like this:

```<code>payload = {
        "Starttime:": 2020-02-18 10:11:22.2145563,
        "Endtime:": 2020-02-18 10:12:22.2145563,
        "Average Humidity:": 44.256241,
        "Number of Values:": 22,
        "Max Humidity:": 44.586214,
        "Min Humidity:": 44.012148521)
}
</code>```

Plus some additional info, like the time the payload was received. In the insert_values method I'm trying to get the topic_id from the table topics and write it into the payload.

Edit: The table in which the measurements are to be written looks like this:

```<code>CREATE TABLE IF NOT EXISTS measurements
(measurement_id INT AUTO_INCREMENT,
 start_time DATETIME,
 end_time DATETIME,
 value FLOAT,
 max_value FLOAT,
 min_value FLOAT,
 time_received DATETIME,
 topic_id INT,
 PRIMARY KEY (measurement_id),
 FOREIGN KEY (topic_id) REFERENCES topics(topic_id))
</code>```

答:
Here:

```<code>"""VALUES (%(start_time)s, %(end_time)s, %(value)s, %(max_value)s, %(min_value)s, %(time_received)s, %(topic_id)s)"""
</code>```

and here:

```<code>payload = {
    "Starttime:": 2020-02-18 10:11:22.2145563,
    "Endtime:": 2020-02-18 10:12:22.2145563,
    "Average Humidity:": 44.256241,
    "Number of Values:": 22,
    "Max Humidity:": 44.586214,
    "Min Humidity:": 44.012148521)
}
</code>```

Your payload keys must match the query's placeholders names - or your placeholders match the payload keys. Your db client will definitly not try and guess that "start_time" and "Starttime" are actually supposed to be the same thing. And you of course must have mathcing keys for all the query's placeholders.

Body:
I'm trying to setup a MQTT client using the Paho library. With that there are no problems, but I'm trying to insert the received publishes in a sql database. I'm converting the received payload string into a dictionary and add a few entries. When executing the following code:

def insert_values(db_connection=None, topic=None, payload=None, time_received=None):
    query_1 = "SELECT topic_id FROM topics WHERE topic = %s"
    query_2 = """INSERT INTO measurements (start_time, end_time, value, max_value, min_value, time_received, topic_id)
                 VALUES (%(start_time)s, %(end_time)s, %(value)s, %(max_value)s, %(min_value)s, %(time_received)s,
                        %(topic_id)s)"""
    cursor = db_connection.cursor(prepared=True)
    topic_id = cursor.execute(query_1, topic)
    payload["time_received"] = time_received
    payload["topic_id"] = topic_id
    cursor.executemany(query_2, payload)
    db_connection.commit()
    db_disconnect(db_connection, cursor)

I get the following error:

Caught exception in on_message: 1210: Incorrect number of arguments executing prepared statement

The payload looks like this:

payload = {
        "Starttime:": 2020-02-18 10:11:22.2145563,
        "Endtime:": 2020-02-18 10:12:22.2145563,
        "Average Humidity:": 44.256241,
        "Number of Values:": 22,
        "Max Humidity:": 44.586214,
        "Min Humidity:": 44.012148521)
}

Plus some additional info, like the time the payload was received. In the insert_values method I'm trying to get the topic_id from the table topics and write it into the payload.

Edit: The table in which the measurements are to be written looks like this:

CREATE TABLE IF NOT EXISTS measurements
(measurement_id INT AUTO_INCREMENT,
 start_time DATETIME,
 end_time DATETIME,
 value FLOAT,
 max_value FLOAT,
 min_value FLOAT,
 time_received DATETIME,
 topic_id INT,
 PRIMARY KEY (measurement_id),
 FOREIGN KEY (topic_id) REFERENCES topics(topic_id))

Body:
Here:

"""VALUES (%(start_time)s, %(end_time)s, %(value)s, %(max_value)s, %(min_value)s, %(time_received)s, %(topic_id)s)"""

and here:

payload = {
    "Starttime:": 2020-02-18 10:11:22.2145563,
    "Endtime:": 2020-02-18 10:12:22.2145563,
    "Average Humidity:": 44.256241,
    "Number of Values:": 22,
    "Max Humidity:": 44.586214,
    "Min Humidity:": 44.012148521)
}

Your payload keys must match the query's placeholders names - or your placeholders match the payload keys. Your db client will definitly not try and guess that "start_time" and "Starttime" are actually supposed to be the same thing. And you of course must have mathcing keys for all the query's placeholders.


来源: stackexchange

问:
Parse stats in ffprobe
I'm gathering some metadata information of audio files using ffprobe. However, due to my unfamiliarity with this tool, I'm getting extra information that's not necessary. This is the command that I'm running:

ffprobe -f lavfi -i amovie=<audio_file>,astats=metadata=1:reset=4400 -hide_banner
```

<p>This is a short sample output of what I'm getting:</p>

```Input #0, lavfi, from 'amovie=<audio_file>,astats=metadata=1:reset=4400':
  Duration: N/A, start: 0.000000, bitrate: 3072 kb/s
    Stream #0:0: Audio: pcm_f32le, 48000 Hz, stereo, flt, 3072 kb/s
[Parsed_astats_1 @ 0x7fcfd4d01140] Channel: 1
[Parsed_astats_1 @ 0x7fcfd4d01140] DC offset: -0.032707
[Parsed_astats_1 @ 0x7fcfd4d01140] Min level: -0.041852
...
```

<p>Is there a combination of flags that will produce a nice <code>JSON</code> or <code>CSV</code> output, hiding the <code>Input #0 ... and [Parsed_astats_1 @ 0x7fcfd4d01140]</code> like this:</p>

```{
    "Channel": 1,
    "DC offset": -0.032707,
    "Min level": -0.041852
    ...
}
```

答:
The nicest solution I can come up with is using the ametadata filter and write the stats to a file.

$ ffmpeg -f lavfi -i sine -t 1s -af 'astats=metadata=1:reset=4400:metadata=true,ametadata=mode=print:file=stats' -f null -
$ cat stats
...
lavfi.astats.1.Bit_depth=16.000000
lavfi.astats.1.Bit_depth2=16.000000
lavfi.astats.1.Dynamic_range=78.265678
lavfi.astats.1.Zero_crossings=920.000000
lavfi.astats.1.Zero_crossings_rate=0.019965
lavfi.astats.Overall.DC_offset=0.000043
lavfi.astats.Overall.Min_level=-4095.000000
lavfi.astats.Overall.Max_level=4095.000000
lavfi.astats.Overall.Min_difference=0.000000
lavfi.astats.Overall.Max_difference=257.000000
lavfi.astats.Overall.Mean_difference=163.407865
lavfi.astats.Overall.RMS_difference=181.500114
lavfi.astats.Overall.Peak_level=-18.063656
lavfi.astats.Overall.RMS_level=-21.073770
lavfi.astats.Overall.RMS_peak=-21.058020
lavfi.astats.Overall.RMS_trough=-21.118775
lavfi.astats.Overall.Flat_factor=0.000000
lavfi.astats.Overall.Peak_count=502.000000
lavfi.astats.Overall.Bit_depth=16.000000
lavfi.astats.Overall.Bit_depth2=16.000000
lavfi.astats.Overall.Number_of_samples=46080.000000
```

I guess your interested in the last frames lavfi.astats.Overall.* values.

ContentLicense: CC BY-SA 4.0

Title: Parse stats in ffprobe

Body:
I'm gathering some metadata information of audio files using ffprobe. However, due to my unfamiliarity with this tool, I'm getting extra information that's not necessary. This is the command that I'm running:

ffprobe -f lavfi -i amovie=<audio_file>,astats=metadata=1:reset=4400 -hide_banner

This is a short sample output of what I'm getting:

Input #0, lavfi, from 'amovie=<audio_file>,astats=metadata=1:reset=4400':
  Duration: N/A, start: 0.000000, bitrate: 3072 kb/s
    Stream #0:0: Audio: pcm_f32le, 48000 Hz, stereo, flt, 3072 kb/s
[Parsed_astats_1 @ 0x7fcfd4d01140] Channel: 1
[Parsed_astats_1 @ 0x7fcfd4d01140] DC offset: -0.032707
[Parsed_astats_1 @ 0x7fcfd4d01140] Min level: -0.041852
...

Is there a combination of flags that will produce a nice JSON or CSV output, hiding the Input #0 ... and [Parsed_astats_1 @ 0x7fcfd4d01140] like this:

{
    "Channel": 1,
    "DC offset": -0.032707,
    "Min level": -0.041852
    ...
}

Body:
The nicest solution I can come up with is using the ametadata filter and write the stats to a file.

$ ffmpeg -f lavfi -i sine -t 1s -af 'astats=metadata=1:reset=4400:metadata=true,ametadata=mode=print:file=stats' -f null -
$ cat stats
...
lavfi.astats.1.Bit_depth=16.000000
lavfi.astats.1.Bit_depth2=16.000000
lavfi.astats.1.Dynamic_range=78.265678
lavfi.astats.1.Zero_crossings=920.000000
lavfi.astats.1.Zero_crossings_rate=0.019965
lavfi.astats.Overall.DC_offset=0.000043
lavfi.astats.Overall.Min_level=-4095.000000
lavfi.astats.Overall.Max_level=4095.000000
lavfi.astats.Overall.Min_difference=0.000000
lavfi.astats.Overall.Max_difference=257.000000
lavfi.astats.Overall.Mean_difference=163.407865
lavfi.astats.Overall.RMS_difference=181.500114
lavfi.astats.Overall.Peak_level=-18.063656
lavfi.astats.Overall.RMS_level=-21.073770
lavfi.astats.Overall.RMS_peak=-21.058020
lavfi.astats.Overall.RMS_trough=-21.118775
lavfi.astats.Overall.Flat_factor=0.000000
lavfi.astats.Overall.Peak_count=502.000000
lavfi.astats.Overall.Bit_depth=16.000000
lavfi.astats.Overall.Bit_depth2=16.000000
lavfi.astats.Overall.Number_of_samples=46080.000000

I guess your interested in the last frames lavfi.astats.Overall.* values.


问:
Memsql docker image: Could not reach local agent at 127.0.0.1:9000?
Please find below errors

```<code>Starting MemSQL Ops...
[WARNING] To avoid memory errors increase vm.max_map_count: sysctl -w vm.max_map_count=1000000000
[WARNING] To avoid network timeouts, increase net.core.somaxconn: sysctl -w net.core.somaxconn=1024
[WARNING] To avoid crashes on OOM conditions, increase vm.min_free_kbytes: sysctl -w vm.min_free_kbytes=162907
MemSQL Ops is running with pid 48
The web UI is running on port 9000
Could not reach local agent at 127.0.0.1:9000
</code>```

How can I fix this?

答:
I've had the same issue, I'm on Mac.
The solution is to downgrade your Docker to 2.1.0.5.
Link for the version (mac): https://download.docker.com/mac/stable/40693/Docker.dmg</p>

Body:
Please find below errors

Starting MemSQL Ops...
[WARNING] To avoid memory errors increase vm.max_map_count: sysctl -w vm.max_map_count=1000000000
[WARNING] To avoid network timeouts, increase net.core.somaxconn: sysctl -w net.core.somaxconn=1024
[WARNING] To avoid crashes on OOM conditions, increase vm.min_free_kbytes: sysctl -w vm.min_free_kbytes=162907
MemSQL Ops is running with pid 48
The web UI is running on port 9000
Could not reach local agent at 127.0.0.1:9000

How can I fix this?


问:
Hibernate: Identifier
When using Hibernate:

Must I identify an id or composite id for each entity,
What about if I want to use table without any primary key and without composite key ...

Thanx in advance

答:
A table without a key isn't a good relational model.  I would not recommend it.

Hibernate's best practices say you should have an id.  Composite ids are workable for legacy apps, but not always the best idea.

If you really must have a table without a key, I'd suggest that you shouldn't use Hibernate.  It's an ORM tool, and it sounds like you're thinking about neither objects nor relational tables properly.  Start with JDBC.

OwnerDisplayName: Moro

ContentLicense: CC BY-SA 2.5

Title: Hibernate: Identifier

LastEditorDisplayName: Fabian Steeg


问:
How to insert a value into a text field under a div using Watir
I used set  to insert a value in a text field under a div.

Below is the approach that I've used without success. This is the only way I was able to identify the element. When I tried to identify text field by name was not recognized.

```<code>@browser.div(:evaluation, :id => "evaluation_form_attributes").text_field(:id => "evaluation_form_name")
@browser.set('Teacher Evaluation Form')
</code>```

The following error was displayed:

```<code>undefined method `set' for #<Watir::IE:0x4dd9348>
</code>```

This is the HTML:

```<code>div id="evaluation_form_attributes"
</code>```

Evaluation name:

```<code>input id="evaluation_form_name" type="text" size="50" name="evaluation_form[name]" maxlength="30"
</code>```

答:
To set a value for a text field you simply need to find it and set it. The setting part you already know (set), so you need to string together something that finds the text field.

if Zejiko's answer doesn't work because of "unable to locate element" then it's not the setting that's failing, it's finding the text field. Use Firebug (in Firefox) or some kind of DOM toolkit (Tools>Developer Tools or F12 in IE8) to find the text field and see what kind of attributes it has.

Ensure the id is really "evaluation_form_name". This is case sensitive and sensitive to leading/trailing spaces. You could try the following to make your search broader:

```<code>@browser.text_field(:id => /evaluation/).set 'Teacher Evaluation Form'
</code>```

This uses a regular expression to identify the id. You can search by many things, not just :id, and you can use more than one. For example:

```<code>@browser.text_field(:id => /eval/, :index => 2)
</code>```

finds the second text field whose id contains "eval".

What you can use to identify the text field can be found here: https://github.com/watir/watir/wiki/HTML-Elements-Supported-by-Watir

ContentLicense: CC BY-SA 3.0

Body:
I used set  to insert a value in a text field under a div.

Below is the approach that I've used without success. This is the only way I was able to identify the element. When I tried to identify text field by name was not recognized.

@browser.div(:evaluation, :id => "evaluation_form_attributes").text_field(:id => "evaluation_form_name")
@browser.set('Teacher Evaluation Form')

The following error was displayed:

undefined method `set' for #<Watir::IE:0x4dd9348>

This is the HTML:

div id="evaluation_form_attributes"

Evaluation name:

input id="evaluation_form_name" type="text" size="50" name="evaluation_form[name]" maxlength="30"

Body:
To set a value for a text field you simply need to find it and set it. The setting part you already know (set), so you need to string together something that finds the text field.

if Zejiko's answer doesn't work because of "unable to locate element" then it's not the setting that's failing, it's finding the text field. Use Firebug (in Firefox) or some kind of DOM toolkit (Tools>Developer Tools or F12 in IE8) to find the text field and see what kind of attributes it has.

Ensure the id is really "evaluation_form_name". This is case sensitive and sensitive to leading/trailing spaces. You could try the following to make your search broader:

@browser.text_field(:id => /evaluation/).set 'Teacher Evaluation Form'

This uses a regular expression to identify the id. You can search by many things, not just :id, and you can use more than one. For example:

@browser.text_field(:id => /eval/, :index => 2)

finds the second text field whose id contains "eval".

What you can use to identify the text field can be found here: https://github.com/watir/watir/wiki/HTML-Elements-Supported-by-Watir


问:
How to navigate to a route while a named outlet is child of an unnamed outlet
I am using Angular 5. I have one  in app.component. I am dynamically routing to a particular component say 'dashboard'. this dashboard component have a named router-outlet and a set of child components. Now I have to change the content of the named router-outlet from dashboard component through router navigation. I have tried following navigation

```<code>1. this.router.navigate([{ outlets: { right: 'temp1' }}], {redirectTo: this.activatedRoute})
2. this.router.navigate(['/dashboard',{ outlets: { right: 'temp1' }}])
</code>```

But both are failing and getting following error

```<code>ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'dashboard'
</code>```

While I am changing the browser url then its working but couldn't load through the navigation. I think its because of the parent . Any help would be appreciated.

答:
this.router.navigate([{ outlets: { primary: 'dashboard', right: 'temp1' }}])

something like this should help

Body:
I am using Angular 5. I have one  in app.component. I am dynamically routing to a particular component say 'dashboard'. this dashboard component have a named router-outlet and a set of child components. Now I have to change the content of the named router-outlet from dashboard component through router navigation. I have tried following navigation

1. this.router.navigate([{ outlets: { right: 'temp1' }}], {redirectTo: this.activatedRoute})
2. this.router.navigate(['/dashboard',{ outlets: { right: 'temp1' }}])

But both are failing and getting following error

ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'dashboard'

While I am changing the browser url then its working but couldn't load through the navigation. I think its because of the parent . Any help would be appreciated.


问:
Marker is not aligning in Gauge chart using hight chart
I am trying to implement a gauge chart using high chart from data -100 to +100, when I tried to set initial data > 50 means custom marker aligning on the gauge. But if data is < 50 (Ex: 20 ) means custom marker is not aligning on the gauge line. JSFiddleLink

I tried in many way but unable to acheive.

```<code>Highcharts.chart('container', {
 chart: {
      style: {
        fontFamily: "FuturaPTCond",
        fontSize: "16px"
      },
      type: "solidgauge",
      events: {
        load: function() {
          var elementSVG;
          var chart = this,
            counter = 0,
            drawCircle = setInterval(function() {
              if (++counter >= 1000) {
                clearInterval(drawCircle);
              }
              renderCircle(chart);
              function renderCircle(chart) {
                let chartData = chart.userOptions.series[0].data[0];
                let color =
                  chartData < -21
                    ? "#DC143C"
                    : chartData > -21 && chartData < 21
                    ? "#FF4500"
                    : chartData > 21 && chartData < 51
                    ? "#FFFF00"
                    : chartData > 51 && chartData < 71
                    ? "#00BFFF"
                    : chartData > 71 && chartData < 91
                    ? "#ADFF2F"
                    : "#FF1493";
                var series = chart.series[0],
                  pathDivided = series.points[0].graphic.attr("d").split(" "),
                  pathElemArr = [];
                pathDivided.forEach(function(el, inx) {
                  if (el === "L") {
                    pathElemArr.push(parseFloat(pathDivided[inx + 1]));
                    pathElemArr.push(parseFloat(pathDivided[inx + 2]));
                  }
                });

                if (elementSVG) {
                  elementSVG.destroy();
                }
                document.getElementById(
                  "BackgroundColor"
                ).style.backgroundColor = "#fff";
                elementSVG = chart.renderer
                  .circle(pathElemArr[0] + 11.25, pathElemArr[1], 10)
                  .attr({
                    fill: "#fff",
                    stroke: color,
                    width: "30px",
                    "stroke-width": 8,
                    zIndex: 10,
                    startAngle: -90,
                    endAngle: 90
                  })
                  .add();

              }
            }, 1);
          $(".highcharts-axis-title").attr("x", 600.5);
          $(".highcharts-axis-title").attr("y", 395.25);
          $(".highcharts-credits").attr("x", 725);
        },
        redraw: function() {
          $(".highcharts-axis-title").attr("x", 600.5);
          $(".highcharts-axis-title").attr("y", 395.25);
          $(".highcharts-credits").attr("x", 725);
        }
      }
    },

    title: null,

    pane: {
      center: ["50%", "85%"],
      size: "98%",
      startAngle: -90,
      endAngle: 90,
      background: {
        backgroundColor: "#ffff",
        innerRadius: "0%",
        outerRadius: "0%"
      },
      shape: "arc"
    },
    // the value axis

    yAxis: {
      lineWidth: 0,
      tickWidth: 0,
      min: -100,
      max: 100,
      title: {
        text: "<p style='font-size: 20px; font-weight: bold'>Last 30 Days</p>",
        style: {
          color: "grey"
        }
      },
      tickPositions: [-100, -20, 20, 50, 70, 90, 100],
      minorTickInterval: 0,
      tickAmount: 0,
      plotBands: [
        {
          from: -100,
          to: -23,
          borderWidth: 5,
          borderColor: "#DC143C",
          color: "#DC143C",
          outerRadius: "95%"
        },
        {
          from: -20,
          to: 18,
          borderWidth: 5,
          borderColor: "#FF4500",
          color: "#FF4500",
          outerRadius: "95%"
        },
        {
          from: 21,
          to: 48,
          borderWidth: 5,
          borderColor: "#FFFF00",
          color: "#FFFF00",
          outerRadius: "95%"
        },
        {
          from: 51,
          to: 68,
          borderWidth: 5,
          borderColor: "#00BFFF",
          color: "#00BFFF",
          outerRadius: "95%"
        },
        {
          from: 71,
          to: 88,
          borderWidth: 5,
          borderColor: "#ADFF2F",
          color: "#ADFF2F",
          outerRadius: "95%"
        },
        {
          from: 91,
          to: 100,
          borderWidth: 5,
          borderColor: "#FF1493",
          color: "#FF1493",
          outerRadius: "95%"
        }
      ],
      labels: {
        enabled: true,
        distance: 10,
        rotation: 0,
        format: "<span style='fill:#00000; font-size: 16px'>{value}</span>"
      }
    },
    plotOptions: {
      solidgauge: {
        borderColor: "#009CE8",
        borderWidth: 0,
        radius: 90,
        innerRadius: "90%",
        dataLabels: {
          enabled: true,
          y: 5,
          borderWidth: 0,
          useHTML: true,
          format:
            '<div id="BackgroundColor" style="Width: 50px;text-align:center"><span style="font-size:70px;color: #000000; margin-left: -20px">{y}</span></div>'
        }
      }
    },
    series: [
      {
        name: "Speed",
        data: [20],
        animation: {
          duration: 1500
        }
      }
    ]
  });
</code>```

答:
I think something is wrong with how you are parsing the d attribute of the path?

Also, when you enter 100 as the data the circle is a bit short of 100?

And when you have data as 0 or 100, the circle is on the faint blue line, but otherwise, at zero (in the middle) it is off from the faint blue line:

This suggests to me that the x-position is correct but the y-position is offset negative direction (towards the top of the svg) and needs to be pushed down (translate positive y)

I changed the color to black just to see it better and then you can see with transform: 'translate(0 10)' the black circle falls perfectly on the light blue line (and also when the data is 100 it lines up with 100 correctly):

Finally, with all inner and outer radius adjusted etc. to centre it:

Note the following style is added to remove the light blue line from the chart:

```<code><style>
.highcharts-point{
  opacity: 0;
}
</style>
</code>```

Probably, this translation(0 10) is needed because of this element (and its translation):

<g data-z-index="0.1" class="highcharts-series highcharts-series-0 highcharts-solidgauge-series highcharts-tracker" transform="translate(10,10) scale(1 1)" clip-path="url(#highcharts-fh3kcab-2-)"/>

Full working demo: https://jsfiddle.net/alexander_L/1yewj7r5/26/

Body:
I am trying to implement a gauge chart using high chart from data -100 to +100, when I tried to set initial data > 50 means custom marker aligning on the gauge. But if data is < 50 (Ex: 20 ) means custom marker is not aligning on the gauge line. JSFiddleLink

I tried in many way but unable to acheive.

Highcharts.chart('container', {
 chart: {
      style: {
        fontFamily: "FuturaPTCond",
        fontSize: "16px"
      },
      type: "solidgauge",
      events: {
        load: function() {
          var elementSVG;
          var chart = this,
            counter = 0,
            drawCircle = setInterval(function() {
              if (++counter >= 1000) {
                clearInterval(drawCircle);
              }
              renderCircle(chart);
              function renderCircle(chart) {
                let chartData = chart.userOptions.series[0].data[0];
                let color =
                  chartData < -21
                    ? "#DC143C"
                    : chartData > -21 && chartData < 21
                    ? "#FF4500"
                    : chartData > 21 && chartData < 51
                    ? "#FFFF00"
                    : chartData > 51 && chartData < 71
                    ? "#00BFFF"
                    : chartData > 71 && chartData < 91
                    ? "#ADFF2F"
                    : "#FF1493";
                var series = chart.series[0],
                  pathDivided = series.points[0].graphic.attr("d").split(" "),
                  pathElemArr = [];
                pathDivided.forEach(function(el, inx) {
                  if (el === "L") {
                    pathElemArr.push(parseFloat(pathDivided[inx + 1]));
                    pathElemArr.push(parseFloat(pathDivided[inx + 2]));
                  }
                });

                if (elementSVG) {
                  elementSVG.destroy();
                }
                document.getElementById(
                  "BackgroundColor"
                ).style.backgroundColor = "#fff";
                elementSVG = chart.renderer
                  .circle(pathElemArr[0] + 11.25, pathElemArr[1], 10)
                  .attr({
                    fill: "#fff",
                    stroke: color,
                    width: "30px",
                    "stroke-width": 8,
                    zIndex: 10,
                    startAngle: -90,
                    endAngle: 90
                  })
                  .add();

              }
            }, 1);
          $(".highcharts-axis-title").attr("x", 600.5);
          $(".highcharts-axis-title").attr("y", 395.25);
          $(".highcharts-credits").attr("x", 725);
        },
        redraw: function() {
          $(".highcharts-axis-title").attr("x", 600.5);
          $(".highcharts-axis-title").attr("y", 395.25);
          $(".highcharts-credits").attr("x", 725);
        }
      }
    },

    title: null,

    pane: {
      center: ["50%", "85%"],
      size: "98%",
      startAngle: -90,
      endAngle: 90,
      background: {
        backgroundColor: "#ffff",
        innerRadius: "0%",
        outerRadius: "0%"
      },
      shape: "arc"
    },
    // the value axis

    yAxis: {
      lineWidth: 0,
      tickWidth: 0,
      min: -100,
      max: 100,
      title: {
        text: "
Last 30 Days
",
        style: {
          color: "grey"
        }
      },
      tickPositions: [-100, -20, 20, 50, 70, 90, 100],
      minorTickInterval: 0,
      tickAmount: 0,
      plotBands: [
        {
          from: -100,
          to: -23,
          borderWidth: 5,
          borderColor: "#DC143C",
          color: "#DC143C",
          outerRadius: "95%"
        },
        {
          from: -20,
          to: 18,
          borderWidth: 5,
          borderColor: "#FF4500",
          color: "#FF4500",
          outerRadius: "95%"
        },
        {
          from: 21,
          to: 48,
          borderWidth: 5,
          borderColor: "#FFFF00",
          color: "#FFFF00",
          outerRadius: "95%"
        },
        {
          from: 51,
          to: 68,
          borderWidth: 5,
          borderColor: "#00BFFF",
          color: "#00BFFF",
          outerRadius: "95%"
        },
        {
          from: 71,
          to: 88,
          borderWidth: 5,
          borderColor: "#ADFF2F",
          color: "#ADFF2F",
          outerRadius: "95%"
        },
        {
          from: 91,
          to: 100,
          borderWidth: 5,
          borderColor: "#FF1493",
          color: "#FF1493",
          outerRadius: "95%"
        }
      ],
      labels: {
        enabled: true,
        distance: 10,
        rotation: 0,
        format: "{value}"
      }
    },
    plotOptions: {
      solidgauge: {
        borderColor: "#009CE8",
        borderWidth: 0,
        radius: 90,
        innerRadius: "90%",
        dataLabels: {
          enabled: true,
          y: 5,
          borderWidth: 0,
          useHTML: true,
          format:
            '
{y}
'
        }
      }
    },
    series: [
      {
        name: "Speed",
        data: [20],
        animation: {
          duration: 1500
        }
      }
    ]
  });

Body:
I think something is wrong with how you are parsing the d attribute of the path?

Also, when you enter 100 as the data the circle is a bit short of 100?

And when you have data as 0 or 100, the circle is on the faint blue line, but otherwise, at zero (in the middle) it is off from the faint blue line:

This suggests to me that the x-position is correct but the y-position is offset negative direction (towards the top of the svg) and needs to be pushed down (translate positive y)

I changed the color to black just to see it better and then you can see with transform: 'translate(0 10)' the black circle falls perfectly on the light blue line (and also when the data is 100 it lines up with 100 correctly):

Finally, with all inner and outer radius adjusted etc. to centre it:

Note the following style is added to remove the light blue line from the chart:

<style>
.highcharts-point{
  opacity: 0;
}
</style>

Probably, this translation(0 10) is needed because of this element (and its translation):

<g data-z-index="0.1" class="highcharts-series highcharts-series-0 highcharts-solidgauge-series highcharts-tracker" transform="translate(10,10) scale(1 1)" clip-path="url(#highcharts-fh3kcab-2-)"/>

Full working demo: https://jsfiddle.net/alexander_L/1yewj7r5/26/


问:
Updating multiple rows in single column
I need to update newly added column(store the sum of all items of the invoice) with result from subquery which generates more than one rows. I added new column to Invoice table.

```<code>ALTER TABLE Invoice
ADD ItemsSum int NULL
</code>```

I tried following query but it gave error because of multiple results

```<code>UPDATE Invoice
SET ItemsSum = (SELECT SUM(Amount)
               FROM InvoiceItem it
               INNER JOIN Invoice i ON it.InvoiceID = i.ID
               GROUP BY i.ID)
</code>```

How to achieve this correctly in SQL Server?

答:
Yogesh's answer is correct, but if you like, you can also do this using an explicit aggregation:</p>

```<code>UPDATE i
    SET ItemsSum = ii.sumAmount
FROM Invoice i LEFT JOIN
     (SELECT ii.InvoiceID, SUM(Amount) as sumAmount
      FROM InvoiceItem it
      GROUP BY ii.InvoiceID
     ) ii
     ON ii.InvoiceID = i.ID
</code>```

Title: Updating multiple rows in single column

Body:
I need to update newly added column(store the sum of all items of the invoice) with result from subquery which generates more than one rows. I added new column to Invoice table.

ALTER TABLE Invoice
ADD ItemsSum int NULL

I tried following query but it gave error because of multiple results

UPDATE Invoice
SET ItemsSum = (SELECT SUM(Amount)
               FROM InvoiceItem it
               INNER JOIN Invoice i ON it.InvoiceID = i.ID
               GROUP BY i.ID)

How to achieve this correctly in SQL Server?

Body:
Yogesh's answer is correct, but if you like, you can also do this using an explicit aggregation:

UPDATE i
    SET ItemsSum = ii.sumAmount
FROM Invoice i LEFT JOIN
     (SELECT ii.InvoiceID, SUM(Amount) as sumAmount
      FROM InvoiceItem it
      GROUP BY ii.InvoiceID
     ) ii
     ON ii.InvoiceID = i.ID


问:
How to import css file from assets folder in nuxt.js
```<code><template>
  <div class="container">
    <head>
      <link rel="stylesheet" href="~assets/css/style-light.css" />
      <link rel="stylesheet" href="~assets/css/login-light.css" />
    </head>
  </div>
</template>
</code>```

Importing css like above results in this error

```<code>vue.runtime.esm.js:5717 GET http://localhost:3000/~assets/css/login-light.css net::ERR_ABORTED 404 (Not Found)
</code>```

Is there really no other way loading css other than putting the whole css in the template?

答:
The first thing you need to know is, you can't declare a html head inside any place, neither in yours tamplate, neither in yours components, neither in yours pages, neither in nowhere.

Keep in mind that you can't use a html tags for this, you will use a json schema.

take a look https://nuxtjs.org/guide/configuration for more detailed explanations.

Now about you doubt if you want to import the CSS as globally, the correct place is inside your nuxt.config.js, inside this file, you have a property called head, and inside the head we will configure all the imports.

So, inside nuxt.config.js find your head session, and then create new property called css, some thing like this:

   head: {
     css: [
       '~/assets/style/app.styl',
       '~/assets/style/main.css'
     ],
   }
   ...
```
<p>Another way, is import your css directly inside your component, for this you can do some thing like this:</p>
<pre class="lang-html prettyprint-override"><code>        <style scoped>
        @import '~/assets/style/main.css';
        </style>
    OR
        <style scoped src="@/assets/styles/mystyles.css">
        </style>
</code>```

In Nuxt, you will need a CSS loader instaled in your application too, so have sure you had intalled a "stylus" and "stylus-loader" in your app.

Body:
<template>

      <link rel="stylesheet" href="~assets/css/style-light.css" />
      <link rel="stylesheet" href="~assets/css/login-light.css" />

</template>

Importing css like above results in this error

vue.runtime.esm.js:5717 GET http://localhost:3000/~assets/css/login-light.css net::ERR_ABORTED 404 (Not Found)

Is there really no other way loading css other than putting the whole css in the template?

Body:
The first thing you need to know is, you can't declare a html head inside any place, neither in yours tamplate, neither in yours components, neither in yours pages, neither in nowhere.

Keep in mind that you can't use a html tags for this, you will use a json schema.

take a look https://nuxtjs.org/guide/configuration for more detailed explanations.

Now about you doubt if you want to import the CSS as globally, the correct place is inside your nuxt.config.js, inside this file, you have a property called head, and inside the head we will configure all the imports.

So, inside nuxt.config.js find your head session, and then create new property called css, some thing like this:

   head: {
     css: [
       '~/assets/style/app.styl',
       '~/assets/style/main.css'
     ],
   }
   ...

Another way, is import your css directly inside your component, for this you can do some thing like this:

        <style scoped>
        @import '~/assets/style/main.css';
        </style>
    OR
        <style scoped src="@/assets/styles/mystyles.css">
        </style>

In Nuxt, you will need a CSS loader instaled in your application too, so have sure you had intalled a "stylus" and "stylus-loader" in your app.


问:
Why I have error where existing data is checked (python)
There is an issue with code, it displays an error about indented block.
Can someone from different point of view check this code? And explain why there is issue with if statement? Maybe also you have some suggestions for current code.

Kind regards,
J.

```<code>from tkinter import *

root = Tk()
root.geometry("700x700")
ivn = StringVar()
inputVarName = Entry(root, textvariable=str(ivn))
ivn.set(str("text1"))
inputVarName.grid(row=0, column=0)

ivn2 = StringVar()
inputVarName2 = Entry(root, textvariable=str(ivn2))
ivn2.set(str("text2"))
inputVarName2.grid(row=1, column=0)

def printSomething():
    with open('help.txt') as f:
        r = f.read()
    label = Label(root, text=r)
    label.grid()

def checkdata():
    with open('help.txt') as f:
        r = f.read()
    return r.split("\n")

def writetofile():
    exist_data = checkdata()
    content_list = [ivn.get(), ivn2.get()]
    with open("help.txt", "a") as f:
        for item in content_list:
        if item in exist_data:
            msg = "Already exist "+item
            label = Label(root, text=msg)
            label.grid()
        elif not item in exist_data:
            f.write("%s\n" % item)

applyButton = Button(root, text="Add Data", command=writetofile)
applyButton.grid(row=2, column=1)

veiwButton = Button(root, text='View Data', command=printSomething)
veiwButton.grid(row=3, column=1)

root.mainloop()
</code>```

答:
Change your writetofile() function to this:

```<code>def writetofile():
    exist_data = checkdata()
    content_list = [ivn.get(), ivn2.get()]
    with open("help.txt", "a") as f:
        for item in content_list:
            if item in exist_data:
                msg = "Already exist "+item
                label = Label(root, text=msg)
                label.grid()
            elif not item in exist_data:
                f.write("%s\n" % item)
</code>```

I just indented the lines after the for item in exist_data:

Body:
There is an issue with code, it displays an error about indented block.
Can someone from different point of view check this code? And explain why there is issue with if statement? Maybe also you have some suggestions for current code.

Kind regards,
J.

from tkinter import *

root = Tk()
root.geometry("700x700")
ivn = StringVar()
inputVarName = Entry(root, textvariable=str(ivn))
ivn.set(str("text1"))
inputVarName.grid(row=0, column=0)

ivn2 = StringVar()
inputVarName2 = Entry(root, textvariable=str(ivn2))
ivn2.set(str("text2"))
inputVarName2.grid(row=1, column=0)

def printSomething():
    with open('help.txt') as f:
        r = f.read()
    label = Label(root, text=r)
    label.grid()

def checkdata():
    with open('help.txt') as f:
        r = f.read()
    return r.split("\n")

def writetofile():
    exist_data = checkdata()
    content_list = [ivn.get(), ivn2.get()]
    with open("help.txt", "a") as f:
        for item in content_list:
        if item in exist_data:
            msg = "Already exist "+item
            label = Label(root, text=msg)
            label.grid()
        elif not item in exist_data:
            f.write("%s\n" % item)

applyButton = Button(root, text="Add Data", command=writetofile)
applyButton.grid(row=2, column=1)

veiwButton = Button(root, text='View Data', command=printSomething)
veiwButton.grid(row=3, column=1)

root.mainloop()

Body:
Change your writetofile() function to this:

def writetofile():
    exist_data = checkdata()
    content_list = [ivn.get(), ivn2.get()]
    with open("help.txt", "a") as f:
        for item in content_list:
            if item in exist_data:
                msg = "Already exist "+item
                label = Label(root, text=msg)
                label.grid()
            elif not item in exist_data:
                f.write("%s\n" % item)

I just indented the lines after the for item in exist_data:


问:
How to sum specific integer values of Python List
I'm trying to sum integer values from the list using sum function. Unfortunately, it is adding all the values of the list but not those which I need from the user.

Here is my code:

```<code>tourist_attractions = []
distance = []
entry_cost = []

for i in range(3):
    tourist_attractions.append (input("Enter Tourist place: "))

    tourist_distance =(int(input("Enter distance: ")))

    if tourist_distance > 50:
        print("Invalid Entry")
        continue

    if tourist_distance <= 50:
        distance.append(tourist_distance)

    cost = (float(input("Enter cost: ")))

    if cost > 100:
        print("cost must be between 1-100")
        continue

    if cost > 0 or cost <= 100:
        entry_cost.append(cost)

print()

for line in tourist_attractions:
    print("Place:", line)

for line in distance:
    print("Distance:", line)

for line in entry_cost:
    print("Cost:", line)

print()

number_of_places_to_visit = int(input("Total number of places to visit: "))

x = 1

while x <= number_of_places_to_visit:

    select_tourist_place = input("select tourist place, 0-3: ")

    x = x + 1

    if select_tourist_place == "0":
        print(tourist_attractions[0], distance[0], entry_cost[0])

    elif select_tourist_place == "1":
        print(tourist_attractions[1], distance[1], entry_cost[1])

    elif select_tourist_place == "2":
        print(tourist_attractions[2], distance[2], entry_cost[2])

    elif select_tourist_place == "3":
        print(tourist_attractions[3], distance[3], entry_cost[3])

    elif select_tourist_place == "4":
        print(tourist_attractions[4], distance[4], entry_cost[4])

print("total cost: " , sum(entry_cost))
</code>```

Result I am getting:

```<code>Enter Tourist place: London
Enter distance: 25
Enter cost: 15
Enter Tourist place: Manchester
Enter distance: 30
Enter cost: 15
Enter Tourist place: Scotland
Enter distance: 50
Enter cost: 20

Place: London
Place: Manchester
Place: Scotland
Distance: 25
Distance: 30
Distance: 50
Cost: 15.0
Cost: 15.0
Cost: 20.0

Total number of places to visit: 2
select tourist place, 0-3: 0
London 25 15.0
select tourist place, 0-5: 1
Manchester 30 15.0
total cost:  50.0
>>>
</code>```

I can understand, at the moment it is summing up all the appended list of entry_cost and giving me the total of 50 which should be 15 from London and 15 from Manchester. Any help?

答:
```<code>print("total cost: " , sum(entry_cost))
</code>```

definitely states your are iterating over ALL entry costs. You would want to store the selected indices and sum over the entries of those indices.

Body:
I'm trying to sum integer values from the list using sum function. Unfortunately, it is adding all the values of the list but not those which I need from the user.

Here is my code:

tourist_attractions = []
distance = []
entry_cost = []

for i in range(3):
    tourist_attractions.append (input("Enter Tourist place: "))

    tourist_distance =(int(input("Enter distance: ")))

    if tourist_distance > 50:
        print("Invalid Entry")
        continue

    if tourist_distance <= 50:
        distance.append(tourist_distance)

    cost = (float(input("Enter cost: ")))

    if cost > 100:
        print("cost must be between 1-100")
        continue

    if cost > 0 or cost <= 100:
        entry_cost.append(cost)

print()

for line in tourist_attractions:
    print("Place:", line)

for line in distance:
    print("Distance:", line)

for line in entry_cost:
    print("Cost:", line)

print()

number_of_places_to_visit = int(input("Total number of places to visit: "))

x = 1

while x <= number_of_places_to_visit:

    select_tourist_place = input("select tourist place, 0-3: ")

    x = x + 1

    if select_tourist_place == "0":
        print(tourist_attractions[0], distance[0], entry_cost[0])

    elif select_tourist_place == "1":
        print(tourist_attractions[1], distance[1], entry_cost[1])

    elif select_tourist_place == "2":
        print(tourist_attractions[2], distance[2], entry_cost[2])

    elif select_tourist_place == "3":
        print(tourist_attractions[3], distance[3], entry_cost[3])

    elif select_tourist_place == "4":
        print(tourist_attractions[4], distance[4], entry_cost[4])

print("total cost: " , sum(entry_cost))

Result I am getting:

Enter Tourist place: London
Enter distance: 25
Enter cost: 15
Enter Tourist place: Manchester
Enter distance: 30
Enter cost: 15
Enter Tourist place: Scotland
Enter distance: 50
Enter cost: 20

Place: London
Place: Manchester
Place: Scotland
Distance: 25
Distance: 30
Distance: 50
Cost: 15.0
Cost: 15.0
Cost: 20.0

Total number of places to visit: 2
select tourist place, 0-3: 0
London 25 15.0
select tourist place, 0-5: 1
Manchester 30 15.0
total cost:  50.0
>>>

I can understand, at the moment it is summing up all the appended list of entry_cost and giving me the total of 50 which should be 15 from London and 15 from Manchester. Any help?

Body:
print("total cost: " , sum(entry_cost))

definitely states your are iterating over ALL entry costs. You would want to store the selected indices and sum over the entries of those indices.


问:
Shell split string and convert it to json objects format
I have a string in this format:

```<code>string= "[one,two,three,four,five]"
</code>```

I want to convert it to json format likely, without using any specific tool (jq or other) , I want to do it with pure shell:

```<code>[
{"id" : 0 , "word": "one"} ,
{"id" : 1 , "word": "two"} ,
{"id" : 2 , "word": "three"} ,
{"id" : 3 , "word": "four"} ,
{"id" : 4 , "word": "five"}
]
</code>```

Suggestions ?

答:
There is no legitimate reason not to use tr or jq for this.  Portably, you cannot use read -d as below, but this is so absurdly fragile that it's not worth worrying about portability.  This works in bash:

```<code>$ string="[one,two,three,four,five]"
$ c=0; echo '['; while read -d , i; do
    echo "{\"id\" : $((c++)), \"word\": \"${i%]}\"},"
done <<< "${string#[}",; echo ']';
[
{"id" : 0 , "word": "one"},
{"id" : 1 , "word": "two"},
{"id" : 2 , "word": "three"},
{"id" : 3 , "word": "four"},
{"id" : 4 , "word": "five"},
]
</code>```

At the moment, I can't think of a clean way to eliminate the trailing comma without tr (although I suppose you could use the rather banal if test "$c" -eq 5; then ...., but that's boring) so I'll just propose:

```<code>c=0; echo '['; while read -d , i; do
    printf "{\"id\" : $((c++)), \"word\": \"${i%]}\"}";
    expr $c = 5 | tr 10 ' ,'; done <<< "${string#[}",; echo ']'
</code>```

I'll reiterate that this is absurdly fragile and only has value as an exercise.  Use jq.

Body:
I have a string in this format:

string= "[one,two,three,four,five]"

I want to convert it to json format likely, without using any specific tool (jq or other) , I want to do it with pure shell:

[
{"id" : 0 , "word": "one"} ,
{"id" : 1 , "word": "two"} ,
{"id" : 2 , "word": "three"} ,
{"id" : 3 , "word": "four"} ,
{"id" : 4 , "word": "five"}
]

Suggestions ?

Body:
There is no legitimate reason not to use tr or jq for this.  Portably, you cannot use read -d as below, but this is so absurdly fragile that it's not worth worrying about portability.  This works in bash:

$ string="[one,two,three,four,five]"
$ c=0; echo '['; while read -d , i; do
    echo "{\"id\" : $((c++)), \"word\": \"${i%]}\"},"
done <<< "${string#[}",; echo ']';
[
{"id" : 0 , "word": "one"},
{"id" : 1 , "word": "two"},
{"id" : 2 , "word": "three"},
{"id" : 3 , "word": "four"},
{"id" : 4 , "word": "five"},
]

At the moment, I can't think of a clean way to eliminate the trailing comma without tr (although I suppose you could use the rather banal if test "$c" -eq 5; then ...., but that's boring) so I'll just propose:

c=0; echo '['; while read -d , i; do
    printf "{\"id\" : $((c++)), \"word\": \"${i%]}\"}";
    expr $c = 5 | tr 10 ' ,'; done <<< "${string#[}",; echo ']'

I'll reiterate that this is absurdly fragile and only has value as an exercise.  Use jq.


问:
How reload tableView after searching and deleting a data from sqlite
I added a button on an UITableView to delete data in SQLite. The button works perfectly but I'm having a hard time reloading the tableview after deletion.
I used tableview.reload() but it wouldn't reload while I'm searching. If I add two data such as "aaa" and "aaaa" and search "aa" to delete one, you can see the two data and if you delete "aaaa", it doesn't reload automatically, and if you remove "a" after that deletion, which means the left letters are "aaa". It shows up. without typing again, there would be another way to reload tableview automatically after deletion?</p>

```<code>   func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableview.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! CustomizedCell

    cell.requiredAction = { [unowned self] in

        let DB = FMDatabase(path: self.databasesPath)
        if DB.open() {
            let result : FMResultSet? = DB.executeQuery("select * from table", withArgumentsIn: [])

            self.fullData = []
            while result?.next() == true {
                if let appendedData = result?.string(forColumn: "keyword") {
                    self.fullData.append(appendedData)
                }
            }
            self.targetData = self.searching ? self.searchedArr : self.fullData

            let query = "delete from table where keyword='\(self.targetData[indexPath.row])'"
            DB.executeStatements(query)
            self.fullData = []
            let secondResult: FMResultSet? = DB.executeQuery("select * from table", withArgumentsIn: [])

            while secondResult?.next() == true {
                if let appendedData = secondResult?.string(forColumn: "keyword") {
                    self.fullData.append(appendedData)
                }
            }
            self.tableview.reloadData()
            self.targetData = self.searching ? self.searchedArr : self.fullData

        }
    }
    cell.myLableCell1.font = UIFont.boldSystemFont(ofSize: 17)

    targetData = searching ? searchedArr : fullData
    cell.myLableCell1?.text = targetData[indexPath.row]

    return cell
}
</code>```

答:
Hi you are loading data in tableview cell file....just do the out of the class....and after
create one getdata method in class and fill array

then delete row and data from sqlite...
after again call getdata.
In getdata method you need to write tableview.reload()

i hope you got....
follow instagram : styoloholic_007 and gunatitsolutions

Body:
I added a button on an UITableView to delete data in SQLite. The button works perfectly but I'm having a hard time reloading the tableview after deletion.
I used tableview.reload() but it wouldn't reload while I'm searching. If I add two data such as "aaa" and "aaaa" and search "aa" to delete one, you can see the two data and if you delete "aaaa", it doesn't reload automatically, and if you remove "a" after that deletion, which means the left letters are "aaa". It shows up. without typing again, there would be another way to reload tableview automatically after deletion?

   func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableview.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! CustomizedCell

    cell.requiredAction = { [unowned self] in

        let DB = FMDatabase(path: self.databasesPath)
        if DB.open() {
            let result : FMResultSet? = DB.executeQuery("select * from table", withArgumentsIn: [])

            self.fullData = []
            while result?.next() == true {
                if let appendedData = result?.string(forColumn: "keyword") {
                    self.fullData.append(appendedData)
                }
            }
            self.targetData = self.searching ? self.searchedArr : self.fullData

            let query = "delete from table where keyword='\(self.targetData[indexPath.row])'"
            DB.executeStatements(query)
            self.fullData = []
            let secondResult: FMResultSet? = DB.executeQuery("select * from table", withArgumentsIn: [])

            while secondResult?.next() == true {
                if let appendedData = secondResult?.string(forColumn: "keyword") {
                    self.fullData.append(appendedData)
                }
            }
            self.tableview.reloadData()
            self.targetData = self.searching ? self.searchedArr : self.fullData

        }
    }
    cell.myLableCell1.font = UIFont.boldSystemFont(ofSize: 17)

    targetData = searching ? searchedArr : fullData
    cell.myLableCell1?.text = targetData[indexPath.row]

    return cell
}


问:
AngularJS directive not being called
I'm trying to implement a d3 directive in Angular, and it's hard because visually nothing is happening, and no errors are being thrown on the console.

Here's my d3 directive:

```<code>myApp.directive('d3-bars', ['d3Service', function($window, d3Service) {
  return {
    restrict: 'EA',
    scope: {},
    link: function(scope, element, attrs) {

// More code below ....
</code>```

Here is my HTML:

```<code><d3-bars bar-height="20" bar-padding="5"></d3-bars>
</code>```

At first I thought it wasn't appending an svg, because inspecting the element that's what it looks like, but now I don't think the directive is even running at all.  I stuck a console.log inside of it at the very beginning and it didn't appear either.  Am I missing something simple?

EDIT:

I tried changing the top line to

```<code>angular.module('myApp.directives', ['d3'])
.directive('d3-bars', ['d3Service', function($window, d3Service) {
</code>```

But that didn't work either.  I don't even know what's the difference between the two headers anyway...

答:
One more thing happened to me that made the directive not to work at all

when you have one module have a directive and you created a new module with a new directive but due to the copy-paste you forget change Module name, this way AngulerJs somehow will remove the first directive

so

make sure that every module have unique name

Title: AngularJS directive not being called

Body:
I'm trying to implement a d3 directive in Angular, and it's hard because visually nothing is happening, and no errors are being thrown on the console.

Here's my d3 directive:

myApp.directive('d3-bars', ['d3Service', function($window, d3Service) {
  return {
    restrict: 'EA',
    scope: {},
    link: function(scope, element, attrs) {

// More code below ....

Here is my HTML:

<d3-bars bar-height="20" bar-padding="5"></d3-bars>

At first I thought it wasn't appending an svg, because inspecting the element that's what it looks like, but now I don't think the directive is even running at all.  I stuck a console.log inside of it at the very beginning and it didn't appear either.  Am I missing something simple?

EDIT:

I tried changing the top line to

angular.module('myApp.directives', ['d3'])
.directive('d3-bars', ['d3Service', function($window, d3Service) {

But that didn't work either.  I don't even know what's the difference between the two headers anyway...


问:
CameraX AF-S / MF
Is it possible to set the camera focus to AF-S or MF using CameraX?

I don't want my camera to focus automaticaly.

I've been making some google search about it, but didn't found anything about this subject yet.

Is it possible to use Camera2 capabilities on CameraX in order to achive this?

答:
After some debug just found how to AF-S instead of AF-C with CameraX.

By default when you set a FocusMeteringAction it has a default cancelation of 5secs, what does it mean?

After you tap for focus or focus in an area for example after 5 secs it will automaticaly cancel your FocusMeteringAction and return to AF-C mode.

In order to AF-S in CameraX the only thing you need to do is to disableAutoCancel() when you are building your FocusMeteringAction.

Make sure that you manually cancel your previous FocusMeteringAction before you create a new one with cancelFocusAndMetering().

Title: CameraX AF-S / MF


问:
Spring Security CORS issue when passing Authorization header
I had wasted lot's of time fixing this issue, but none of the existing solutions work in my case.
Let me explain you the server set up I have.
I have 2 docker containers, one for angular app (nginx - url - http://localhost:8080) and spring boot application (tomcat - url - http://localhost:8081).
This app is using Oauth2 jdbcToken authentication for API request.

This app is a simple user registration app.

I could register a new user since the register url is not secured and not passing any Authorization header.
But once when user logs in the CORS issue kick in. below I have listed the errors.

Access to XMLHttpRequest at 'http://localhost:8081/v1/api/group/find/shib' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Let me tell you what I had done to resolve this.
In angular HTTP request I have added the following headers.

```<code>'Authorization' : 'Bearer '+this.token(),
'Access-Control-Allow-Methods' : '*',
'Access-Control-Allow-Origin' : "*",
'Access-Control-Allow-Headers' : 'Content-Type, Accept, X-Requested-With, remember-me, Authorization',
"Access-Control-Expose-Headers" : "Content-Type, Accept, X-Requested-With, remember-me, Authorization"
</code>```

In spring boot I added @CrossOrigin / @CrossOrigin("http:localhost:8080") on Rest controllers added with a CORSFilter

```<code>@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me, Authorization");
    chain.doFilter(req, res);
}
</code>```

After all the trial and error, I am still getting the same error

答:
I read and understood much more on preflight requests and the way it work.
A quick thought i had was to let OPTIONS request to go through so i had added the following code to my WebSecurityConfigurerAdapter.

```<code>@Override
protected void configure(HttpSecurity http) throws Exception {
    http
    .csrf().disable()
    .authorizeRequests()
    .antMatchers(HttpMethod.OPTIONS,"*").permitAll()//allow CORS option calls
    .antMatchers("/oauth/token").permitAll()
    .anyRequest().authenticated()
    .and()
    .formLogin()
    .and()
    .httpBasic();
}
</code>```

And no extra headers from Angular ui except Authorization.

I hope this works for everyone. I know now that OPTIONS are vulnerable, but this was just a quick workarount.
Please suggest me if you have a better, safer solution.

Body:
I had wasted lot's of time fixing this issue, but none of the existing solutions work in my case.
Let me explain you the server set up I have.
I have 2 docker containers, one for angular app (nginx - url - http://localhost:8080) and spring boot application (tomcat - url - http://localhost:8081).
This app is using Oauth2 jdbcToken authentication for API request.

This app is a simple user registration app.

I could register a new user since the register url is not secured and not passing any Authorization header.
But once when user logs in the CORS issue kick in. below I have listed the errors.

Access to XMLHttpRequest at 'http://localhost:8081/v1/api/group/find/shib' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Let me tell you what I had done to resolve this.
In angular HTTP request I have added the following headers.

'Authorization' : 'Bearer '+this.token(),
'Access-Control-Allow-Methods' : '*',
'Access-Control-Allow-Origin' : "*",
'Access-Control-Allow-Headers' : 'Content-Type, Accept, X-Requested-With, remember-me, Authorization',
"Access-Control-Expose-Headers" : "Content-Type, Accept, X-Requested-With, remember-me, Authorization"

In spring boot I added @CrossOrigin / @CrossOrigin("http:localhost:8080") on Rest controllers added with a CORSFilter

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me, Authorization");
    chain.doFilter(req, res);
}

After all the trial and error, I am still getting the same error

Body:
I read and understood much more on preflight requests and the way it work.
A quick thought i had was to let OPTIONS request to go through so i had added the following code to my WebSecurityConfigurerAdapter.

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
    .csrf().disable()
    .authorizeRequests()
    .antMatchers(HttpMethod.OPTIONS,"*").permitAll()//allow CORS option calls
    .antMatchers("/oauth/token").permitAll()
    .anyRequest().authenticated()
    .and()
    .formLogin()
    .and()
    .httpBasic();
}

And no extra headers from Angular ui except Authorization.

I hope this works for everyone. I know now that OPTIONS are vulnerable, but this was just a quick workarount.
Please suggest me if you have a better, safer solution.


问:
parent form closing invoke child form which has background worker in it
I try to achieve this:
i have the main form, when user click the red cross on the top right to exit the application, it popup a progress bar form indicating the application is updating/saving information. After the background worker in the progress bar form finishes, it closes the progress bar form and close the main form as well.
the problem i have is, it closes the main from first without even running the background worker. how to fix this? i tried to use e.cancel= true it just gave my dead loop.

here is my main form:

```<code> private static void mainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
 UpdatingForm pbar = new UpdatingForm ();

            pbar.Show();
}
</code>```

in my updatingform:

```<code>public UpdatingForm()
        {
            InitializeComponent();

            bgWorker.RunWorkerAsync();
        }

    private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
            {
    ....
    }

private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

            this.Close();
            // Application.Exit();
        }
</code>```

答:
Setting e.Cancel to true is correct. However, once your UpdatingForm closes, Application.Exit() fires the mainForm_FormClosing() event again, so you get one more UpdatingForm etc.

```<code>private static bool isClosing = false;
private static void mainForm_FormClosing(object sender, FormClosingEventArgs e)
{
    if (!isClosing)
    {
        isClosing = true;
        e.Cancel = true;
        UpdatingForm pbar = new UpdatingForm ();
        pbar.Show();
    }
}
</code>```

Body:
I try to achieve this:
i have the main form, when user click the red cross on the top right to exit the application, it popup a progress bar form indicating the application is updating/saving information. After the background worker in the progress bar form finishes, it closes the progress bar form and close the main form as well.
the problem i have is, it closes the main from first without even running the background worker. how to fix this? i tried to use e.cancel= true it just gave my dead loop.

here is my main form:

 private static void mainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
 UpdatingForm pbar = new UpdatingForm ();

            pbar.Show();
}

in my updatingform:

public UpdatingForm()
        {
            InitializeComponent();

            bgWorker.RunWorkerAsync();
        }

    private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
            {
    ....
    }

private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

            this.Close();
            // Application.Exit();
        }

Body:
Setting e.Cancel to true is correct. However, once your UpdatingForm closes, Application.Exit() fires the mainForm_FormClosing() event again, so you get one more UpdatingForm etc.

private static bool isClosing = false;
private static void mainForm_FormClosing(object sender, FormClosingEventArgs e)
{
    if (!isClosing)
    {
        isClosing = true;
        e.Cancel = true;
        UpdatingForm pbar = new UpdatingForm ();
        pbar.Show();
    }
}


问:
java streams: easiest way to find adjacent value match
How would it be possible to convert this iterative block of code to streams?</p>

```<code>Integer prev = -1;
boolean adjacentPair = false;

for(Integer num : numberList) {
    if (num.equals(prev)) {
        adjacentNumberSame = true;
        break;
    }
    prev = num;
}
return adjacentNumberSame
</code>```

答:
Streams aren't the way to go. This is quite a general statement.

A particular problem here is that you cannot fold and short-circuit.

The streamy solution I came up with was similar to @vbezhenar, except it is well behaved (has the combiner) and doesn't introduce an accumulator class.

```<code>    // Accumulator is: { leftElement, match, rightElement }
    //    (Could introduce a record.)
    // States of the accumulator are:
    //    { null null null } - initial
    //    { x null x } - first element
    //    { x m null } - found match m
    //    { x null y } - no matches found
    Integer[] result = numberList.stream().<Integer[]>collect(
        // supplier
        () -> new Integer[3],
        // accumulator
        (acc,t) -> {
            if (acc[0] == null) {
                // First into acc.
                acc[0] = acc[2] = t;
            } else if (acc[1] != null) {
                // Already found pair to the left.
            } else if (t.equals(acc[2])) {
                // Found first pair.
                acc[1] = t;
                acc[2] = null;
            } else {
                // Otherwise, t replaces rightmost.
                acc[2] = t;
            }
        },
        // combiner
        (acc, other) -> {
            if (acc[1] != null) {
                // Alread found pair to the left.
            } else if (acc[2] == null) {
                // Necessary anyone? Empty acc is combined.
                acc[0] = other[0];
                acc[1] = other[1];
                acc[2] = other[2];
            } else if (acc[2].equals(other[0])) {
                // Found match.
                acc[1] = acc[2];
                acc[2] = null;
            } else {
                // Otherwise, leftmost element with rest as other acc.
                acc[1] = other[1];
                acc[2] = other[2];
            }
        }
    );
    return result[1] != null;
</code>```

I haven't actually tested the combiner. I suspect most combiners have never been tested either.

If we make similar assumptions about stream behaviour as @vbezhenar did, then dropWhile is our Johnny 5 friend.

```<code>    return numberList.stream().dropWhile(new Predicate<>() {
        Integer last;
        public boolean test(Integer t) {
            Integer lastLast = last;
            last = t;
            return !t.equals(lastLast);
        }
    }).findFirst().isPresent();
</code>```

Anonymous inner classes ftw!!

Body:
How would it be possible to convert this iterative block of code to streams?

Integer prev = -1;
boolean adjacentPair = false;

for(Integer num : numberList) {
    if (num.equals(prev)) {
        adjacentNumberSame = true;
        break;
    }
    prev = num;
}
return adjacentNumberSame

Body:
Streams aren't the way to go. This is quite a general statement.

A particular problem here is that you cannot fold and short-circuit.

The streamy solution I came up with was similar to @vbezhenar, except it is well behaved (has the combiner) and doesn't introduce an accumulator class.

    // Accumulator is: { leftElement, match, rightElement }
    //    (Could introduce a record.)
    // States of the accumulator are:
    //    { null null null } - initial
    //    { x null x } - first element
    //    { x m null } - found match m
    //    { x null y } - no matches found
    Integer[] result = numberList.stream().<Integer[]>collect(
        // supplier
        () -> new Integer[3],
        // accumulator
        (acc,t) -> {
            if (acc[0] == null) {
                // First into acc.
                acc[0] = acc[2] = t;
            } else if (acc[1] != null) {
                // Already found pair to the left.
            } else if (t.equals(acc[2])) {
                // Found first pair.
                acc[1] = t;
                acc[2] = null;
            } else {
                // Otherwise, t replaces rightmost.
                acc[2] = t;
            }
        },
        // combiner
        (acc, other) -> {
            if (acc[1] != null) {
                // Alread found pair to the left.
            } else if (acc[2] == null) {
                // Necessary anyone? Empty acc is combined.
                acc[0] = other[0];
                acc[1] = other[1];
                acc[2] = other[2];
            } else if (acc[2].equals(other[0])) {
                // Found match.
                acc[1] = acc[2];
                acc[2] = null;
            } else {
                // Otherwise, leftmost element with rest as other acc.
                acc[1] = other[1];
                acc[2] = other[2];
            }
        }
    );
    return result[1] != null;

I haven't actually tested the combiner. I suspect most combiners have never been tested either.

If we make similar assumptions about stream behaviour as @vbezhenar did, then dropWhile is our Johnny 5 friend.

    return numberList.stream().dropWhile(new Predicate<>() {
        Integer last;
        public boolean test(Integer t) {
            Integer lastLast = last;
            last = t;
            return !t.equals(lastLast);
        }
    }).findFirst().isPresent();

Anonymous inner classes ftw!!


问:
Redis: How to access keys in specific keyspace
I have 2 keyspaces in my redis server:

```<code>db0:keys=1,expires=0
db1:keys=36679593,expires=0
</code>```

But if I run

```<code>redis-cli KEYS '*'
</code>```

I only get keys in db0. How can i search the keys in db1?

答:
first, you need to select the db1. To do that use select 1.
Then you can get all keys using KEYS *

```<code>select 1 // selects db 1

keys * // search all keys in selected db (db -1 )
</code>```

Body:
I have 2 keyspaces in my redis server:

db0:keys=1,expires=0
db1:keys=36679593,expires=0

But if I run

redis-cli KEYS '*'

I only get keys in db0. How can i search the keys in db1?

Body:
first, you need to select the db1. To do that use select 1.
Then you can get all keys using KEYS *

select 1 // selects db 1

keys * // search all keys in selected db (db -1 )


问:
ES6 destructuring not returning correct result
I an trying to destructure two object with the same property names but only the names of the first set are observed.

```<code>let a, b,
 ({ a,b } = myObject1);
({ a,b } = myObject2);
</code>```

ie; only the values for myObject1 are in the console.log()

Does anyone know how to destructure properties of the same name from different objects ? I do not want to manually assign each variable.

I had tried

```<code>let a, b,
     ({ a,b } = myObject1);
    ({ a : test1,b: test2 } = myObject2)
console.log(test1)
</code>```

and

```<code>  let a, b,
         { a,b } = myObject1;
         { a : test1,b: test2 } = myObject2
    console.log(test1)
</code>```

But test1 is undefined

答:
If you have more objects with the same structure, you could take a function which returns an array of wanted properties.</p>

```<code>const getProps = ({ a, b }) => [a, b];

let [a, b] = getProps(myObject1),
    [c, d] = getProps(myObject2);
</code>```

Body:
I an trying to destructure two object with the same property names but only the names of the first set are observed.

let a, b,
 ({ a,b } = myObject1);
({ a,b } = myObject2);

ie; only the values for myObject1 are in the console.log()

Does anyone know how to destructure properties of the same name from different objects ? I do not want to manually assign each variable.

I had tried

let a, b,
     ({ a,b } = myObject1);
    ({ a : test1,b: test2 } = myObject2)
console.log(test1)

and

  let a, b,
         { a,b } = myObject1;
         { a : test1,b: test2 } = myObject2
    console.log(test1)

But test1 is undefined

Body:
If you have more objects with the same structure, you could take a function which returns an array of wanted properties.

const getProps = ({ a, b }) => [a, b];

let [a, b] = getProps(myObject1),
    [c, d] = getProps(myObject2);


问:
Unhandled Rejection (Error): The shape of dict['image_tensor'] provided in model.execute(dict) must be [X,X,X,X], but was X,X,X]
TensorFlow.js version
v1.5.2

Browser version
Chrome 79.0.3945.130

Describe the problem or feature request
I trained my own object with the tensorflow 1.15.0 with faster_rcnn_inception_v2_coco_2018_01_28. After that saved model was converted web models with tensorflow converter. tensorflowjs version is 1.5.2.

This created model using web app error The shape of dict['image_tensor'] provided in model.execute(dict) must be [X,X,X,X], but was [X,X,X]

Create saved model

```<code>python export_inference_graph.py --input_type image_tensor --pipeline_config_path training/faster_rcnn_inception_v2_pets.config --trained_checkpoint_prefix training/model.ckpt-XXXX --output_directory inference_graph
</code>```

Convert saved model

```<code>tensorflowjs_converter
--input_format=tf_saved_model
--output_node_names='MobilenetV1/Predictions/Reshape_1'
--saved_model_tags=serve
/mobilenet/saved_model
/mobilenet/web_model
</code>```

tensorflowjs web app

```<code>const img = document.getElementById('img');
const model = await tf.loadGraphModel('model.json')
model.predict(tf.browser.fromPixels(img)) // or model.predict(img)
</code>```

What is wrong this process ?

答:
It is a shape mismatch error.

It seems that the model is expecting a 4d tensor whereas you are supplying a 3d tensor. expandDims or reshape can be used to add a new dimension to the 3d tensor used as argument

Body:
TensorFlow.js version
v1.5.2

Browser version
Chrome 79.0.3945.130

Describe the problem or feature request
I trained my own object with the tensorflow 1.15.0 with faster_rcnn_inception_v2_coco_2018_01_28. After that saved model was converted web models with tensorflow converter. tensorflowjs version is 1.5.2.

This created model using web app error The shape of dict['image_tensor'] provided in model.execute(dict) must be [X,X,X,X], but was [X,X,X]

Create saved model

python export_inference_graph.py --input_type image_tensor --pipeline_config_path training/faster_rcnn_inception_v2_pets.config --trained_checkpoint_prefix training/model.ckpt-XXXX --output_directory inference_graph

Convert saved model

tensorflowjs_converter
--input_format=tf_saved_model
--output_node_names='MobilenetV1/Predictions/Reshape_1'
--saved_model_tags=serve
/mobilenet/saved_model
/mobilenet/web_model

tensorflowjs web app

const img = document.getElementById('img');
const model = await tf.loadGraphModel('model.json')
model.predict(tf.browser.fromPixels(img)) // or model.predict(img)

What is wrong this process ?


问:
Sort a list of abstract objects based on their child's field
My abstract object :

```<code>public abstract class ContentEntry {
    private double score;
}
</code>```

ContentEntry has four children, two of them (Movie and Song) having the field long date;

I have a List<ContentEntry> that I was previously sorting by score with :

```<code>.flatMap(entries -> Flux.fromIterable(entries)
                        .sort(Comparator.comparing(ContentEntry::getScore))
                        .collectList()
        )
</code>```

I would now like to sort by date but I don't see how using Comparator. Thx!

答:
Obviously, you first have to define how instances of classes without the date field are compared, and how they compare to objects that have a data field.

Once this is done you can define a class

```<code>class MyComparator implements Comparator<ContentEntry> {
  public int compare(ContentEntry e1, ContentEntry e2) {
    long date1 = -1; // Date of first entry, -1 indicates "no date"
    long date2 = -1; // Date of first entry, -1 indicates "no date"
    if ( e1 instanceof Movie ) date1 = ((Movie)e1).date;
    else if ( e1 instanceof Song ) date1 = ((Song)e1).date;
    if ( e2 instanceof Movie ) date2 = ((Movie)e2).date;
    else if ( e2 instanceof Song ) date2 = ((Song)e2).date;

    // Now compare based on date1, date2, and potentially other things
    ...
  }
}
</code>```

Note that it may be better to introduce a function getSortKey() that returns the key that is used for sorting. That function could be overridden by classes like Movie and Song. The could return something that includes the date.

Body:
My abstract object :

public abstract class ContentEntry {
    private double score;
}

ContentEntry has four children, two of them (Movie and Song) having the field long date;

I have a List<ContentEntry> that I was previously sorting by score with :

.flatMap(entries -> Flux.fromIterable(entries)
                        .sort(Comparator.comparing(ContentEntry::getScore))
                        .collectList()
        )

I would now like to sort by date but I don't see how using Comparator. Thx!

Body:
Obviously, you first have to define how instances of classes without the date field are compared, and how they compare to objects that have a data field.

Once this is done you can define a class

class MyComparator implements Comparator<ContentEntry> {
  public int compare(ContentEntry e1, ContentEntry e2) {
    long date1 = -1; // Date of first entry, -1 indicates "no date"
    long date2 = -1; // Date of first entry, -1 indicates "no date"
    if ( e1 instanceof Movie ) date1 = ((Movie)e1).date;
    else if ( e1 instanceof Song ) date1 = ((Song)e1).date;
    if ( e2 instanceof Movie ) date2 = ((Movie)e2).date;
    else if ( e2 instanceof Song ) date2 = ((Song)e2).date;

    // Now compare based on date1, date2, and potentially other things
    ...
  }
}

Note that it may be better to introduce a function getSortKey() that returns the key that is used for sorting. That function could be overridden by classes like Movie and Song. The could return something that includes the date.


问:
Validate field value against another with arrays in Laravel

I want to validate min value in array validation against another value
  in this array in Laravel MVC

Current Rules

$rules['criteria.*.inputOne'] = 'required|numeric';
$rules['criteria.*.inputTwo']='required|min:criteria.*.inputOne';

Needed Rules

I want to use criteria.*.inputOne in min validation in $rules['criteria.*.inputTwo']

答:
I find this solution to my problem:-

```<code>$rules['criteria.*.inputOne']='required|gt:criteria.*.inputTwo';
</code>```

Body:
I find this solution to my problem:-

$rules['criteria.*.inputOne']='required|gt:criteria.*.inputTwo';


问:
Using DirectoryInfo.Exists is false even if the directory exists
I'm having a problem when creating a DirectoryInfo, The directory I give when creating the DirectoryInfo is this:

"S:\PUBLICO\ESTUDIOS
  DIGITALIZADOS\PREVENTIVA\ELECTROS\2020\01-ENERO\08\"

And when checking if DirectoryInfo exists it's false, even though it exists. This is a problem because it throws an exception even when using di.GetFiles().

Also, when accessing folders from 2019 instead of 2020 it works perfectly, and uses the exact same code

This is the code that matters:

```<code>strDirectorioBase = strDirectorioECG + "\\" + Anio + "\\" + Mes + "-" + NombreMes + "\\" + Dia + "\\";

        try
        {
            DirectoryInfo di = new DirectoryInfo(strDirectorioBase);
            /*FileInfo[] a = di.GetFiles(strFiltro, SearchOption.AllDirectories);*/
            MessageBox.Show(di.Exists.ToString());
            if (di.Exists)
            {
                MessageBox.Show("Existe");
            }
            foreach (var fi in di.GetFiles(strFiltro, SearchOption.AllDirectories))
            {
</code>```

答:
If you do not have access to the folder GetFiles will not continue past exception.  You need to use recursive code like below</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;

namespace SAveDirectoriesXml
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        const string FOLDER = @"c:\temp";
        static XmlWriter writer = null;
        static void Main(string[] args)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;

            writer = XmlWriter.Create(FILENAME, settings);
            writer.WriteStartDocument(true);

            DirectoryInfo info = new DirectoryInfo(FOLDER);
            WriteTree(info);

            writer.WriteEndDocument();
            writer.Flush();
            writer.Close();
            Console.WriteLine("Enter Return");
            Console.ReadLine();

        }
        static long WriteTree(DirectoryInfo info)
        {
            long size = 0;
            writer.WriteStartElement("Folder");
            try
            {
                writer.WriteAttributeString("name", info.Name);
                writer.WriteAttributeString("numberSubFolders", info.GetDirectories().Count().ToString());
                writer.WriteAttributeString("numberFiles", info.GetFiles().Count().ToString());
                writer.WriteAttributeString("date", info.LastWriteTime.ToString());

                foreach (DirectoryInfo childInfo in info.GetDirectories())
                {
                    size += WriteTree(childInfo);
                }

            }
            catch (Exception ex)
            {
                string errorMsg = string.Format("Exception Folder : {0}, Error : {1}", info.FullName, ex.Message);
                Console.WriteLine(errorMsg);
                writer.WriteElementString("Error", errorMsg);
            }

            FileInfo[] fileInfo = null;
            try
            {
                fileInfo = info.GetFiles();
            }
            catch (Exception ex)
            {
                string errorMsg = string.Format("Exception FileInfo : {0}, Error : {1}", info.FullName, ex.Message);
                Console.WriteLine(errorMsg);
                writer.WriteElementString("Error",errorMsg);
            }

            if (fileInfo != null)
            {
                foreach (FileInfo finfo in fileInfo)
                {
                    try
                    {
                        writer.WriteStartElement("File");
                        writer.WriteAttributeString("name", finfo.Name);
                        writer.WriteAttributeString("size", finfo.Length.ToString());
                        writer.WriteAttributeString("date", info.LastWriteTime.ToString());
                        writer.WriteEndElement();
                        size += finfo.Length;
                    }
                    catch (Exception ex)
                    {
                        string errorMsg = string.Format("Exception File : {0}, Error : {1}", finfo.FullName, ex.Message);
                        Console.WriteLine(errorMsg);
                        writer.WriteElementString("Error", errorMsg);
                    }
                }
            }

            writer.WriteElementString("size", size.ToString());
            writer.WriteEndElement();
            return size;

        }
    }
}
</code>```

Body:
I'm having a problem when creating a DirectoryInfo, The directory I give when creating the DirectoryInfo is this:

"S:\PUBLICO\ESTUDIOS
  DIGITALIZADOS\PREVENTIVA\ELECTROS\2020\01-ENERO\08\"

And when checking if DirectoryInfo exists it's false, even though it exists. This is a problem because it throws an exception even when using di.GetFiles().

Also, when accessing folders from 2019 instead of 2020 it works perfectly, and uses the exact same code

This is the code that matters:

strDirectorioBase = strDirectorioECG + "\\" + Anio + "\\" + Mes + "-" + NombreMes + "\\" + Dia + "\\";

        try
        {
            DirectoryInfo di = new DirectoryInfo(strDirectorioBase);
            /*FileInfo[] a = di.GetFiles(strFiltro, SearchOption.AllDirectories);*/
            MessageBox.Show(di.Exists.ToString());
            if (di.Exists)
            {
                MessageBox.Show("Existe");
            }
            foreach (var fi in di.GetFiles(strFiltro, SearchOption.AllDirectories))
            {

Body:
If you do not have access to the folder GetFiles will not continue past exception.  You need to use recursive code like below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;

namespace SAveDirectoriesXml
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        const string FOLDER = @"c:\temp";
        static XmlWriter writer = null;
        static void Main(string[] args)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;

            writer = XmlWriter.Create(FILENAME, settings);
            writer.WriteStartDocument(true);

            DirectoryInfo info = new DirectoryInfo(FOLDER);
            WriteTree(info);

            writer.WriteEndDocument();
            writer.Flush();
            writer.Close();
            Console.WriteLine("Enter Return");
            Console.ReadLine();

        }
        static long WriteTree(DirectoryInfo info)
        {
            long size = 0;
            writer.WriteStartElement("Folder");
            try
            {
                writer.WriteAttributeString("name", info.Name);
                writer.WriteAttributeString("numberSubFolders", info.GetDirectories().Count().ToString());
                writer.WriteAttributeString("numberFiles", info.GetFiles().Count().ToString());
                writer.WriteAttributeString("date", info.LastWriteTime.ToString());

                foreach (DirectoryInfo childInfo in info.GetDirectories())
                {
                    size += WriteTree(childInfo);
                }

            }
            catch (Exception ex)
            {
                string errorMsg = string.Format("Exception Folder : {0}, Error : {1}", info.FullName, ex.Message);
                Console.WriteLine(errorMsg);
                writer.WriteElementString("Error", errorMsg);
            }

            FileInfo[] fileInfo = null;
            try
            {
                fileInfo = info.GetFiles();
            }
            catch (Exception ex)
            {
                string errorMsg = string.Format("Exception FileInfo : {0}, Error : {1}", info.FullName, ex.Message);
                Console.WriteLine(errorMsg);
                writer.WriteElementString("Error",errorMsg);
            }

            if (fileInfo != null)
            {
                foreach (FileInfo finfo in fileInfo)
                {
                    try
                    {
                        writer.WriteStartElement("File");
                        writer.WriteAttributeString("name", finfo.Name);
                        writer.WriteAttributeString("size", finfo.Length.ToString());
                        writer.WriteAttributeString("date", info.LastWriteTime.ToString());
                        writer.WriteEndElement();
                        size += finfo.Length;
                    }
                    catch (Exception ex)
                    {
                        string errorMsg = string.Format("Exception File : {0}, Error : {1}", finfo.FullName, ex.Message);
                        Console.WriteLine(errorMsg);
                        writer.WriteElementString("Error", errorMsg);
                    }
                }
            }

            writer.WriteElementString("size", size.ToString());
            writer.WriteEndElement();
            return size;

        }
    }
}


问:
Difference between let arrayName = [...this.A, this.B] and let arrayName = [...this.A] arrayName.push(this.B)
So ive been watching freeCodeCamp's Vue Youtube Tutorial.

At one point they use this code:

```<code>let answers = [...this.currentQuestion.incorrect_answers];
answers.push(this.currentQuestion.correct_answer);
</code>```

And then this one:

```<code>let answers = [...this.currentQuestion.incorrect_answers, this.currentQuestion.correct_answer]
</code>```

Are they any different? Im more familiar with the push method, but if the other method works and doesnt have any downsides, why bother pushing?

答: They are basically equivalent, they both unpack a JS iterator into an array and append to this array a new value. The first method does it by mutating the array, the second at construction.</p>

Body:
So ive been watching freeCodeCamp's Vue Youtube Tutorial.

At one point they use this code:

let answers = [...this.currentQuestion.incorrect_answers];
answers.push(this.currentQuestion.correct_answer);

And then this one:

let answers = [...this.currentQuestion.incorrect_answers, this.currentQuestion.correct_answer]

Are they any different? Im more familiar with the push method, but if the other method works and doesnt have any downsides, why bother pushing?


问:
Error on recording UTF8 string with Datasnap
Recently i've migrated from D2007 to 10.3.3 and i'm having the issue below.

I have a TClientDataSet that record data an encrypted string into .cds format, by storing it in a TStringField and using the .saveToFile method. Problem is, the string is not being record correclty into the CDS table.

Here my encrypt function :

```<code>function encrypt(const ent: string): string;
var m, i, k : integer;
r, s : string;
begin
m := 3;
r := '';
for I := 1 to Length(ent) do
  begin
  k := ord(ent[i]);
  s := chr(k+m);
  r := r + s;
  inc(m);
  end;
result := r;
end;
</code>```

And here is my decrypt function :

```<code>function decrypt(const ent: string): string;
var m, i,j,K : integer;
r, s : string;
begin
m := 3;
r := '';
s := ent;
for I := 1 to length(s) do
  begin
  if ord(s[i]) < 68 then j := 1 else
    j := -1;
  k := ord(s[i]);
  r := r + chr(k-m);
  inc(m);
  end;
result := r;
end;
</code>```

Now i want to call this function with the string 'engajamento1234'.
Here is how the watch shows the encrypted string  :

And here is how the string is actually inserted into the TStringField column of the table :

Because the string end up being insert incorrectly on the clientdataset, when i call decrypt function with 'hrlgqivoy?|?ACE' string, i get the incorrect original string as 'engajamen3o1234'...

Seems like this problem is related to UTF8 support in the new Delphi version, which the old version did not have.

What i need to do to the string record correctly into the clientdataset and the .cds file, so i get the correct decrypted string back ?

答:
I've expanded your code into an MRE which illustrates the problem you are having and how to
solve it.  Basically it seems that the string field you are using to store the encrypted data
is a TStringField, whereas it needs to be a TWideStringField to work with Unicode.  TStringField's
SetAsString and GetAsString methods both use calls which treat the data as an ANSIString (which is the type of Delphi string which predates the introduction of Unicode).

The code uses a conditional define, UseWideString, which determines whether the CDS field is of type ftString (as was used in D2007) or ftWideString, which is the Unicode equivalent.  You should find that with the UseWideString define in effect, the code executes without error,
meaning that the decrypted string is the same as the original input.  If you comment out the
UseWideString define, the

```<code>Assert(sInput = sDecrypted);
</code>```

fails.

Code

```<code>program EncryptTest;

{$APPTYPE CONSOLE}

uses
  SysUtils, db, dbclient;

function encrypt(const ent: string): string;
var m, i, k : integer;
r, s : string;
begin
m := 3;
r := '';
for I := 1 to Length(ent) do
  begin
  k := ord(ent[i]);
  s := chr(k+m);
  r := r + s;
  inc(m);
  end;
result := r;
end;

function decrypt(const ent: string): string;
var m, i,j,K : integer;
r, s : string;
begin
m := 3;
r := '';
s := ent;
for I := 1 to length(s) do
  begin
  if ord(s[i]) < 68 then j := 1 else
    j := -1;
  k := ord(s[i]);
  r := r + chr(k-m);
  inc(m);
  end;
result := r;
end;

var
  sInput,
  sEncrypted,
  sDecrypted : String;
  CDS : TClientDataSet;
  Field : TField;

begin
  CDS := TClientDataSet.Create(Nil);

{.$define UseWideString}
{$ifdef UseWideString}
  Field := TWideStringfield.Create(Nil);
{$else}
  Field := TStringfield.Create(Nil);
{$endif}
  Field.FieldKind := fkData;
  Field.Size := 80;
  Field.FieldName := 'Something';
  Field.DataSet := CDS;

  CDS.CreateDataSet;
  CDS.Append;
  CDS.Edit;

  sInput := 'engajamento1234';
  sEncrypted := encrypt(sInput);
  Field.AsString := sEncrypted;
  sDecrypted := decrypt(Field.AsString);
  Assert(sInput = sDecrypted);

  CDS.Cancel;
  Field.Free;
  CDS.Free;

end.
</code>```

Btw, in your decrypt function, the

```<code>if ord(s[i]) < 68 then j := 1 else
  j := -1;
</code>```

is superfluous because the value of j is never used.

Body:
Recently i've migrated from D2007 to 10.3.3 and i'm having the issue below.

I have a TClientDataSet that record data an encrypted string into .cds format, by storing it in a TStringField and using the .saveToFile method. Problem is, the string is not being record correclty into the CDS table.

Here my encrypt function :

function encrypt(const ent: string): string;
var m, i, k : integer;
r, s : string;
begin
m := 3;
r := '';
for I := 1 to Length(ent) do
  begin
  k := ord(ent[i]);
  s := chr(k+m);
  r := r + s;
  inc(m);
  end;
result := r;
end;

And here is my decrypt function :

function decrypt(const ent: string): string;
var m, i,j,K : integer;
r, s : string;
begin
m := 3;
r := '';
s := ent;
for I := 1 to length(s) do
  begin
  if ord(s[i]) < 68 then j := 1 else
    j := -1;
  k := ord(s[i]);
  r := r + chr(k-m);
  inc(m);
  end;
result := r;
end;

Now i want to call this function with the string 'engajamento1234'.
Here is how the watch shows the encrypted string  :

And here is how the string is actually inserted into the TStringField column of the table :

Because the string end up being insert incorrectly on the clientdataset, when i call decrypt function with 'hrlgqivoy?|?ACE' string, i get the incorrect original string as 'engajamen3o1234'...

Seems like this problem is related to UTF8 support in the new Delphi version, which the old version did not have.

What i need to do to the string record correctly into the clientdataset and the .cds file, so i get the correct decrypted string back ?

Body:
I've expanded your code into an MRE which illustrates the problem you are having and how to
solve it.  Basically it seems that the string field you are using to store the encrypted data
is a TStringField, whereas it needs to be a TWideStringField to work with Unicode.  TStringField's
SetAsString and GetAsString methods both use calls which treat the data as an ANSIString (which is the type of Delphi string which predates the introduction of Unicode).

The code uses a conditional define, UseWideString, which determines whether the CDS field is of type ftString (as was used in D2007) or ftWideString, which is the Unicode equivalent.  You should find that with the UseWideString define in effect, the code executes without error,
meaning that the decrypted string is the same as the original input.  If you comment out the
UseWideString define, the

Assert(sInput = sDecrypted);

fails.

Code

program EncryptTest;

{$APPTYPE CONSOLE}

uses
  SysUtils, db, dbclient;

function encrypt(const ent: string): string;
var m, i, k : integer;
r, s : string;
begin
m := 3;
r := '';
for I := 1 to Length(ent) do
  begin
  k := ord(ent[i]);
  s := chr(k+m);
  r := r + s;
  inc(m);
  end;
result := r;
end;

function decrypt(const ent: string): string;
var m, i,j,K : integer;
r, s : string;
begin
m := 3;
r := '';
s := ent;
for I := 1 to length(s) do
  begin
  if ord(s[i]) < 68 then j := 1 else
    j := -1;
  k := ord(s[i]);
  r := r + chr(k-m);
  inc(m);
  end;
result := r;
end;

var
  sInput,
  sEncrypted,
  sDecrypted : String;
  CDS : TClientDataSet;
  Field : TField;

begin
  CDS := TClientDataSet.Create(Nil);

{.$define UseWideString}
{$ifdef UseWideString}
  Field := TWideStringfield.Create(Nil);
{$else}
  Field := TStringfield.Create(Nil);
{$endif}
  Field.FieldKind := fkData;
  Field.Size := 80;
  Field.FieldName := 'Something';
  Field.DataSet := CDS;

  CDS.CreateDataSet;
  CDS.Append;
  CDS.Edit;

  sInput := 'engajamento1234';
  sEncrypted := encrypt(sInput);
  Field.AsString := sEncrypted;
  sDecrypted := decrypt(Field.AsString);
  Assert(sInput = sDecrypted);

  CDS.Cancel;
  Field.Free;
  CDS.Free;

end.

Btw, in your decrypt function, the

if ord(s[i]) < 68 then j := 1 else
  j := -1;

is superfluous because the value of j is never used.


问:
How to get value for a certain key in multidimentionnal php array?
A certain php array give me this :

```<code>myarray{
    0=>array { "key_01"=>"value_01", "key_02"=>"value_02"..."key_0n"=>"value_0n"}
    1=>array { "key_11"=>"value_11", "key_12"=>"value_12"..."key_1n"=>"value_1n"}
    .
    .
    .
    n=>array { "key_n1"=>"value_n1", "key_n2"=>"value_n2"..."key_nn"=>"value_nn"}
}
</code>```

And i would like to get this one array:

```<code>$newarray = {value_01,value_11,value_n1......value_nn}
</code>```

答:
```<code>// Loop through your original array
foreach($myarray as $array){
   // ensures that the keys are in alphabetical/numerical order
   ksort($array);

   // add the first value into your new array
   $newarray[] = reset($array);
}
</code>```

Body:
A certain php array give me this :

myarray{
    0=>array { "key_01"=>"value_01", "key_02"=>"value_02"..."key_0n"=>"value_0n"}
    1=>array { "key_11"=>"value_11", "key_12"=>"value_12"..."key_1n"=>"value_1n"}
    .
    .
    .
    n=>array { "key_n1"=>"value_n1", "key_n2"=>"value_n2"..."key_nn"=>"value_nn"}
}

And i would like to get this one array:

$newarray = {value_01,value_11,value_n1......value_nn}