问:
convert length to point in svg (polygon) dynamically
I am doing a small assignment to find out the type of the triangle whether is equilateral, isosceles, or scalene based on the values a,b,c.

my problem is that I couldn't manage to convert the a,b,c values in order to draw the shape by using SVG (polygon) since it takes points and I have only values

function triangle(a, b, c) {
  if (a === b && a === c && b === c) return "equilateral";
  if (a === b && a === c) return "isosceles";
  else {
    return "scalene";
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div>
        <svg className="traingle" height="400" width="400">
          <polygon points={`200 ${b}, 200 ${a}, 0 ${c}`} />
        </svg>
      </div></code>```

答:
This question probably belongs in Maths StackExchange, but anyway.

Firstly, you need to first check whether it is possible for the combination of side lengths to form a triangle.

The way to do that is with the Triangle Inequality Theorem.  It states that each of the side lengths must be less than the sum of the other two.

So in your example, the lengths [5,200,300] cannot form a triangle because 300 is not less than (5 + 200).

Also, none of the lengths should be <= 0.

So let's work with three valid side lengths: [150, 200, 300].

The way to get the three points is to start with one side, and draw that first.  So we will start with the side that is 150.

You can draw that side anywhere, but let's make the line go from (0,0) to (150,0).

To get the third point we need to find where the other two sides would meet.  Imagine two circles centred at each end of that first line. Each circle has a radius corresponding to the remaining two side lengths.  The way to calculate the third point is to find the instersection point(s) of those two circles.

svg {
  background-color: linen;
  width: 500px;
}

line {
  stroke: black;
  stroke-width: 2;
}

.c300 {
  fill: none;
  stroke: blue;
  stroke-width: 2;
}

.c200 {
  fill: none;
  stroke: green;
  stroke-width: 2;
}

line.la {
  stroke: blue;
  stroke-dasharray: 4 6;
}

.lb {
  stroke: green;
  stroke-dasharray: 4 6;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg viewBox="-350 -350 750 700">

  <line class="l150" x1="0" y1="0" x2="150" y2="0"/>

  <circle class="c300" cx="0" cy="0" r="300"/>
  <circle class="c200" cx="150" cy="0" r="200"/>

  <line class="la" x1="0" y1="0" x2="241.667" y2="-177.756"/>
  <line class="lb" x1="150" y1="0" x2="241.667" y2="-177.756"/>

</svg>  </code>```

If we use Wolfram Alpha's version of the formula then we get the following:

```<code>     d^2 - r^2 + R^2
x = -----------------
          2 * d;
</code>```

and

```<code>     sqrt( 4 * d^2 * R^2 - ( d^2 - r^2 + R^2 )^2 )
y = -----------------------------------------------
                       2 * d
</code>```

where d is the length of that first side, and r and R are the lengths of the other two sides.

So for our example:

```<code>R = 300
r = 200
d^2 - r^2 + R^2 = 150^2 - 300^2 + 200^2
                = 72500

x = 72500 / 300
  = 241.667

y = sqrt( 4 * 22500 * 90000 - 72500^2) / 300
  = sqrt( 2843750000 ) / 300
  = 53326.823 / 300
  = 177.756
</code>```

And you can see these values for x and y in the example SVG above.

Note that the circles intersect both above and below the first line. So 177.756 and -177.656 are both valid solutions for y.

Body:
I am doing a small assignment to find out the type of the triangle whether is equilateral, isosceles, or scalene based on the values a,b,c.

my problem is that I couldn't manage to convert the a,b,c values in order to draw the shape by using SVG (polygon) since it takes points and I have only values

function triangle(a, b, c) {
  if (a === b && a === c && b === c) return "equilateral";
  if (a === b && a === c) return "isosceles";
  else {
    return "scalene";
  }
}

        <svg className="traingle" height="400" width="400">
          <polygon points={`200 ${b}, 200 ${a}, 0 ${c}`} />
        </svg>

Body:
This question probably belongs in Maths StackExchange, but anyway.

Firstly, you need to first check whether it is possible for the combination of side lengths to form a triangle.

The way to do that is with the Triangle Inequality Theorem.  It states that each of the side lengths must be less than the sum of the other two.

So in your example, the lengths [5,200,300] cannot form a triangle because 300 is not less than (5 + 200).

Also, none of the lengths should be <= 0.

So let's work with three valid side lengths: [150, 200, 300].

The way to get the three points is to start with one side, and draw that first.  So we will start with the side that is 150.

You can draw that side anywhere, but let's make the line go from (0,0) to (150,0).

To get the third point we need to find where the other two sides would meet.  Imagine two circles centred at each end of that first line. Each circle has a radius corresponding to the remaining two side lengths.  The way to calculate the third point is to find the instersection point(s) of those two circles.

svg {
  background-color: linen;
  width: 500px;
}

line {
  stroke: black;
  stroke-width: 2;
}

.c300 {
  fill: none;
  stroke: blue;
  stroke-width: 2;
}

.c200 {
  fill: none;
  stroke: green;
  stroke-width: 2;
}

line.la {
  stroke: blue;
  stroke-dasharray: 4 6;
}

.lb {
  stroke: green;
  stroke-dasharray: 4 6;
}

<svg viewBox="-350 -350 750 700">

  <line class="l150" x1="0" y1="0" x2="150" y2="0"/>

  <circle class="c300" cx="0" cy="0" r="300"/>
  <circle class="c200" cx="150" cy="0" r="200"/>

  <line class="la" x1="0" y1="0" x2="241.667" y2="-177.756"/>
  <line class="lb" x1="150" y1="0" x2="241.667" y2="-177.756"/>

</svg>

If we use Wolfram Alpha's version of the formula then we get the following:

     d^2 - r^2 + R^2
x = -----------------
          2 * d;

and

     sqrt( 4 * d^2 * R^2 - ( d^2 - r^2 + R^2 )^2 )
y = -----------------------------------------------
                       2 * d

where d is the length of that first side, and r and R are the lengths of the other two sides.

So for our example:

R = 300
r = 200
d^2 - r^2 + R^2 = 150^2 - 300^2 + 200^2
                = 72500

x = 72500 / 300
  = 241.667

y = sqrt( 4 * 22500 * 90000 - 72500^2) / 300
  = sqrt( 2843750000 ) / 300
  = 53326.823 / 300
  = 177.756

And you can see these values for x and y in the example SVG above.

Note that the circles intersect both above and below the first line. So 177.756 and -177.656 are both valid solutions for y.


来源: stackexchange

问:
preconfiguring WIFI SSID and password in AOSP build 9 and above
How to place SSID and password in AOSP before build
so that the device will automatically get connected to preconfigured wifi after flashing the rom into the device

for Android 7 and 8, we can add the credentials into wpa_supplicant_overlay.conf file
Is there any way for android 9 and above

答:
This is now being called Wi-Fi Easy Connect ...in wpa_supplicant/android.config:

```<code># Easy Connect (Device Provisioning Protocol - DPP R1 & R2)
CONFIG_DPP=y
CONFIG_DPP2=y
</code>```

The documentation misses CONFIG_DPP2 ...

Set update_config=1 to enable the use of tools, alike in wpa_supplicant_template.conf.
One still can configure just any network. as shown in the example wpa_supplicant.conf.

The specification: https://www.wi-fi.org/file/wi-fi-easy-connect-specification

ContentLicense: CC BY-SA 4.0

Body:
This is now being called Wi-Fi Easy Connect ...in wpa_supplicant/android.config:

# Easy Connect (Device Provisioning Protocol - DPP R1 & R2)
CONFIG_DPP=y
CONFIG_DPP2=y

The documentation misses CONFIG_DPP2 ...

Set update_config=1 to enable the use of tools, alike in wpa_supplicant_template.conf.
One still can configure just any network. as shown in the example wpa_supplicant.conf.

The specification: https://www.wi-fi.org/file/wi-fi-easy-connect-specification


问:
Unable to Access Jar File When Running Akka
I am using the tutorial provided at this link: https://developer.lightbend.com/guides/akka-quickstart-scala/index.html#running-the-example

It is a very basic tutorial on how to run a Hello World program using commands in Akka. I downloaded and extracted the zip file, navigated to the folder in the command prompt, and ran the sbt.bat command, but I get this dialogue as a result:

C:\akka-quickstart-scala>.\sbt-dist\bin\sbt.bat
Error: Unable to access jarfile C:\akka-quickstart-scala\sbt-dist\bin\java9-rt-export.jar
The filename, directory name, or volume label syntax is incorrect.
Error: Unable to access jarfile C:\akka-quickstart-scala\sbt-dist\bin\java9-rt-export.jar
Unrecognized VM option 'MaxPermSize=256m'
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

I am a university student taking a distributed operating systems class for context. Everyone else in the class got it to work except me. The professor couldn't even figure out why it wasn't running on my machine. Any help would be greatly appreciated.

答:
Seems the project is using jvm setting that was removed from java 9. So you could try downgrading java version on your machine to java 8

Unrecognized VM option 'MaxPermSize=512m' when running Zeppelin


问:
How to take a value of object automatically with help of ViewBag
I have a question how to take a value for variable from other model. I will try to explain.

There is a list of offices. "Office" model contains a number of office and name of PC there. Also, there is a list of requests here (for instance, for help support). Any request contains date, number of office, name of PC and comment. I did a system that user can choose number of office. But then I have a problem.

It is required that the PC name is taken from the Office list to the request form depend on Office number. How to do it?

Models: Office.cs and Request.cs

```<code>public class Office
    {
        public int Id { get; set; }
        public string Number { get; set; } = "";
        public string PC { get; set; } = "";
    }

public class Request
    {
        public int Id { get; set; }
        public DateTime DateRequest { get; set; }
        public string Office { get; set; } = "";
        public string PC { get; set; } = "";
        public string Comment { get; set; } = "";
    }
</code>```

Controller of form:

```<code>        private IRepository _repo;
        public RequestsController(IRepository repo)
        { _repo = repo;}

        [HttpGet]
         public IActionResult EditRequest(int? id)
        {
            var offices = _repo.GetAllOffices();
            ViewBag.Offices = new SelectList(offices, "Number", "Number");
            if (id == null)
                return View(new Request());
            else
            {
                var request = _repo.GetRequest((int)id);
                return View(request);
            }
        }

        [HttpPost]
        public async Task<IActionResult> EditRequest(Request request)
        {
            if (request.Id > 0)
                _repo.UpdateRequest(request);
            else
            {
                request.Created = DateTime.Now;
                _repo.AddRequest(request);
            }
            if (await _repo.SaveChangesAsync())
                return RedirectToAction("Home");
            else
                return View(request);
        }
    }
}
</code>```

View:

```<code><form asp-controller="Requests" asp-action="EditRequest" method="post">
        <input asp-for="id" type="hidden" />
        <div>
            <label>Date</label>
            <input asp-for="DateRequest" />
        </div>
        <div>
            <label asp-for="Office">Your office </label>
            <select asp-for="Office" asp-items="ViewBag.Offices"></select>
        </div>
        <input asp-for="PC" value="????" type="hidden" /> /* There is a problem! */
        <div>
            <label>Your Comment</label>
            <input asp-for="Comment" />
        </div>
        <input type="submit" value="Send" />
</form>
</code>```

For instance, the list of offices (number - PC name):
1 - Lenovo, 2 - HP, 3 - HP, 4 - Samsung, 5 - Lenovo.
If user chooses "3" in number, the form will add "HP" in "PC".

答:
For public SelectList(IEnumerable items, string dataValueField, string dataTextField);, the first parameter is the source, the second parameter is each option value in select, the third parameter is each option text in html.

So you need change your ViewBag design like below, it will generate the option text with the Number and option value with PC:

```<code>ViewBag.Offices = new SelectList(offices, "PC", "Number");
</code>```

Then add .change() event to set the value for <input asp-for="PC"/>:

```<code>@section Scripts
{
    <script>
        $('#Office').change(function() {
            $("#PC").val($(this).val());
        });
    </script>
}
</code>```

Body:
I have a question how to take a value for variable from other model. I will try to explain.

There is a list of offices. "Office" model contains a number of office and name of PC there. Also, there is a list of requests here (for instance, for help support). Any request contains date, number of office, name of PC and comment. I did a system that user can choose number of office. But then I have a problem.

It is required that the PC name is taken from the Office list to the request form depend on Office number. How to do it?

Models: Office.cs and Request.cs

public class Office
    {
        public int Id { get; set; }
        public string Number { get; set; } = "";
        public string PC { get; set; } = "";
    }

public class Request
    {
        public int Id { get; set; }
        public DateTime DateRequest { get; set; }
        public string Office { get; set; } = "";
        public string PC { get; set; } = "";
        public string Comment { get; set; } = "";
    }

Controller of form:

        private IRepository _repo;
        public RequestsController(IRepository repo)
        { _repo = repo;}

        [HttpGet]
         public IActionResult EditRequest(int? id)
        {
            var offices = _repo.GetAllOffices();
            ViewBag.Offices = new SelectList(offices, "Number", "Number");
            if (id == null)
                return View(new Request());
            else
            {
                var request = _repo.GetRequest((int)id);
                return View(request);
            }
        }

        [HttpPost]
        public async Task<IActionResult> EditRequest(Request request)
        {
            if (request.Id > 0)
                _repo.UpdateRequest(request);
            else
            {
                request.Created = DateTime.Now;
                _repo.AddRequest(request);
            }
            if (await _repo.SaveChangesAsync())
                return RedirectToAction("Home");
            else
                return View(request);
        }
    }
}

View:

<form asp-controller="Requests" asp-action="EditRequest" method="post">
        <input asp-for="id" type="hidden" />

            Date
            <input asp-for="DateRequest" />

            Your office
            <select asp-for="Office" asp-items="ViewBag.Offices"></select>

        <input asp-for="PC" value="????" type="hidden" /> /* There is a problem! */

            Your Comment
            <input asp-for="Comment" />

        <input type="submit" value="Send" />
</form>

For instance, the list of offices (number - PC name):
1 - Lenovo, 2 - HP, 3 - HP, 4 - Samsung, 5 - Lenovo.
If user chooses "3" in number, the form will add "HP" in "PC".

Body:
For public SelectList(IEnumerable items, string dataValueField, string dataTextField);, the first parameter is the source, the second parameter is each option value in select, the third parameter is each option text in html.

So you need change your ViewBag design like below, it will generate the option text with the Number and option value with PC:

ViewBag.Offices = new SelectList(offices, "PC", "Number");

Then add .change() event to set the value for <input asp-for="PC"/>:

@section Scripts
{
    <script>
        $('#Office').change(function() {
            $("#PC").val($(this).val());
        });
    </script>
}


问:
Retrieve the base url in rails
i am working on rails 2.3.11 .. and running my rails application with -P blogs

and the url will be like http://localhost:3000/application_name.

How to retrieve the above url inside the javascript of my rails view file

Please give suggestions

EDIT

localhost:3000/application_name is the base_url all over the app. I have a javascript with $.ajax with :url with "controller/action" which is not loading properly for the reason that its taking the loading page ctrllr as the ctrllr and not taking the ctrllr from the one i gave in the javascript .

答:
In rails basically every request specific can be found in request. Putting arequest.inspect may give you insight to this.

If you just need the path in your javascript, the file needs to be an erb (e.g. something.js.erb). then it would just be <%= blogs_path %>.

If you're talking about the assets/javascripts/sprockets feature in the new rails, I don't know because I haven't used that yet.

ContentLicense: CC BY-SA 3.0

Title: Retrieve the base url in rails


问:
'refactor' move files in VSCode - es6
If I move ComponentFoo.js from folder X to folder Y, than a bunch of import statements break.  Looking into this it seems there are many solutions for typescript, but what about js / es6?  If I move a file in the editor, it should find all the import statements and update them to the new location. Is this possible?

答:
Just use IntelliJ. It handles all kinds of refactoring perfectly. I'm a huge fan of VS Code, but refacotoring is definetly not one of it's stengths. Some imports don't get detected, and the imports can get modified in a weird way. For example, I had an import like this:

```<code>import { myStore} from 'src/common/stores/myStore';
</code>```

When moving the file of myStore.ts to a different folder, VS Code constructed this bull**it:

```<code>import { myStore} from 'src/common/composables/myStoreStore';
</code>```

The line above is no typo!

Btw I'm using vetur, maybe thats causing it, I don't know ...

Title: 'refactor' move files in VSCode - es6

Body:
Just use IntelliJ. It handles all kinds of refactoring perfectly. I'm a huge fan of VS Code, but refacotoring is definetly not one of it's stengths. Some imports don't get detected, and the imports can get modified in a weird way. For example, I had an import like this:

import { myStore} from 'src/common/stores/myStore';

When moving the file of myStore.ts to a different folder, VS Code constructed this bull**it:

import { myStore} from 'src/common/composables/myStoreStore';

The line above is no typo!

Btw I'm using vetur, maybe thats causing it, I don't know ...


问:
How can I patch / mock logging.getlogger()
I have this code that I want to test:

```<code>log = logging.getLogger(__name__)

class A(object):
    def __init__(self):
        log.debug('Init')
</code>```

but I cannot figure out how to assert that log.debug was called with 'Init'

I tried patching logger but inspecting it I only found a getLogger mock.

I'm sure its simple, but I just cant figure it!

Thanks in advance for any and all help!

答:
This also works:</p>
```<code>from unittest.mock import patch

class Test(TestCase):
    def test_logger(self):
        with patch('logging.Logger.warning') as mocked_logger:
            call_func()
            mocked_logger.assert_called_once_with('log')
</code>```

Body:
I have this code that I want to test:

log = logging.getLogger(__name__)

class A(object):
    def __init__(self):
        log.debug('Init')

but I cannot figure out how to assert that log.debug was called with 'Init'

I tried patching logger but inspecting it I only found a getLogger mock.

I'm sure its simple, but I just cant figure it!

Thanks in advance for any and all help!

Body:
This also works:

from unittest.mock import patch

class Test(TestCase):
    def test_logger(self):
        with patch('logging.Logger.warning') as mocked_logger:
            call_func()
            mocked_logger.assert_called_once_with('log')


问:
Is there any function in numpy to traverse an array in reverse order
I mean I have a 2d array. I can traverse it by row by row or column by column from the left side or the starting element. I want to do the same procedure starting from the top right and end at bottom right by row by row.
Also, want to traverse from top right and end at top left column by column.

Thanks in advance for the help!

答:
Try using np.flipud

```<code>import numpy as np
A = [1, 2,3,4,5]
np.flipud(A)
</code>```

Output:

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

Body:
Try using np.flipud

import numpy as np
A = [1, 2,3,4,5]
np.flipud(A)

Output:

array([5, 4, 3, 2, 1])


问:
Play videos with iframe in html
I want to play a video, but it is only downloading.

Here is my code:

```<code><iframe src="videos/1.mp4" width="540" height="310"></iframe>
</code>```

The Result when the page load is:

How can I play the video with iframe and not with the video tag?

答:
You can generate dynamic content like that:

let ifTest = document.getElementById('if-test');
let videoPath = 'https://file-examples.com/storage/fe63ea2155630fa7ba2b829/2017/04/file_example_MP4_480_1_5MG.mp4';
let videoHtml = '<video width="100%" autoplay="true" loop="true" muted="true" ><source src="' + videoPath + '" type="video/mp4" /></video>';

ifTest.setAttribute('srcdoc', videoHtml);
ifTest.setAttribute('style', 'width:264px; height:150px;')```
<pre class="snippet-code-html lang-html prettyprint-override"><code><iframe id="if-test" srcdoc=""></iframe></code>```

Title: Play videos with iframe in html

Body:
I want to play a video, but it is only downloading.

Here is my code:

The Result when the page load is:

How can I play the video with iframe and not with the video tag?

Body:
You can generate dynamic content like that:

let ifTest = document.getElementById('if-test');
let videoPath = 'https://file-examples.com/storage/fe63ea2155630fa7ba2b829/2017/04/file_example_MP4_480_1_5MG.mp4';
let videoHtml = '<html><body><video width="100%" autoplay="true" loop="true" muted="true" ><source src="' + videoPath + '" type="video/mp4" /></video></body></html>';

ifTest.setAttribute('srcdoc', videoHtml);
ifTest.setAttribute('style', 'width:264px; height:150px;')

<iframe id="if-test" srcdoc=""></iframe>


问:
Issues streaming data from Pub/Sub into BigQuery using Dataflow and Apache Beam (Python)
currently I am facing issues getting my beam pipeline running on Dataflow to write data from Pub/Sub into BigQuery. I've looked through the various steps and all the data itself seems to be getting altered as expected. The problem comes from the step using beam.io.gcp.bigquery.WriteToBigQuery. Checking the stackdriver shows:

```<code>There were errors inserting to BigQuery: [<InsertErrorsValueListEntry errors: [<ErrorProto debugInfo: '' location: 'root.array[0].thing' message: 'no such field.' reason: 'invalid'>] index: 0>,
</code>```

I cut the above log short, but the rest of it is more of the same; missing fields. While this error is accurate in that those fields do not exist in the schema, I pass the additional_bq_parameters as:

```<code>{
  'schemaUpdateOptions': ["ALLOW_FIELD_ADDITION"],
  'ignoreUnknownValues': True,
  'maxBadRecords': 1000,
}
</code>```

These additional arguments seem to get ignored whether I use a callable that just returns the above dictionary, or just set additional_bq_parameters equal to the dictionary itself.

The ParDo function's process looks like the following:

```<code>    def process(self, tuple):
        import apache_beam as beam

        def get_additional_bq_parameters(_element):
            return {
                'schemaUpdateOptions': ["ALLOW_FIELD_ADDITION"],
                'ignoreUnknownValues': True,
                'maxBadRecords': 1000,
            }

        key, data = tuple
        table_name = f"table.{key}"
        (data | 'Upload' >> beam.io.gcp.bigquery.WriteToBigQuery(
            table=table_name,
            schema=self.schemas[key], # list of schemas passed to init
            additional_bq_parameters=get_additional_bq_parameters,
            create_disposition=beam.io.BigQueryDisposition.CREATE_NEVER,
            write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND,
            method='STREAMING_INSERTS',
            insert_retry_strategy="RETRY_NEVER")
        )
</code>```

When running the pipeline on Dataflow I pass the following arguments:

```<code>python3 script.py \
  --project=<project> \
  --job_name=<name> \
  --streaming \
  --runner=DataflowRunner \
  --temp_location=<temp> \
  --experiments use_beam_bq_sink \
  --staging_location=<location> \
  --num_workers=2
</code>```

If anyone can elaborate why the additional arguments to BigQuery are seemingly not being recognized I'd greatly appreciate it.

Furthermore, I've tried returning the results from the write to BigQuery in an attempt to persist the failed rows to GCS. However, when I try to access the failed rows from the resulting PCollection with either results[beam.io.gcp.bigquery.BigQueryWriteFn.FAILED_ROWS] or results['FailedRows'] I get the error TypeError: 'PCollection' object is not subscriptable. Based on what I've seen, I thought that this was the proper approach. If anyone could clarify this as well, I would be really grateful.

答:
Ignoring fields that are not available in the target table's schema is now possible, starting from the 2.38.0 release. You need to pass ignore_unknown_columns=True argument to WriteToBigQuery.

Expanding your original example:

   (data | 'Upload' >> beam.io.gcp.bigquery.WriteToBigQuery(
            table=table_name,
            schema=self.schemas[key],
            ignore_unknown_columns=True, # PASS THIS PARAMETER TO IGNOR UNKNOWN FIELDS
            create_disposition=beam.io.BigQueryDisposition.CREATE_NEVER,
            write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND,
            method='STREAMING_INSERTS',
            insert_retry_strategy="RETRY_NEVER")
        )
```

Body:
currently I am facing issues getting my beam pipeline running on Dataflow to write data from Pub/Sub into BigQuery. I've looked through the various steps and all the data itself seems to be getting altered as expected. The problem comes from the step using beam.io.gcp.bigquery.WriteToBigQuery. Checking the stackdriver shows:

There were errors inserting to BigQuery: [<InsertErrorsValueListEntry errors: [<ErrorProto debugInfo: '' location: 'root.array[0].thing' message: 'no such field.' reason: 'invalid'>] index: 0>,

I cut the above log short, but the rest of it is more of the same; missing fields. While this error is accurate in that those fields do not exist in the schema, I pass the additional_bq_parameters as:

{
  'schemaUpdateOptions': ["ALLOW_FIELD_ADDITION"],
  'ignoreUnknownValues': True,
  'maxBadRecords': 1000,
}

These additional arguments seem to get ignored whether I use a callable that just returns the above dictionary, or just set additional_bq_parameters equal to the dictionary itself.

The ParDo function's process looks like the following:

    def process(self, tuple):
        import apache_beam as beam

        def get_additional_bq_parameters(_element):
            return {
                'schemaUpdateOptions': ["ALLOW_FIELD_ADDITION"],
                'ignoreUnknownValues': True,
                'maxBadRecords': 1000,
            }

        key, data = tuple
        table_name = f"table.{key}"
        (data | 'Upload' >> beam.io.gcp.bigquery.WriteToBigQuery(
            table=table_name,
            schema=self.schemas[key], # list of schemas passed to init
            additional_bq_parameters=get_additional_bq_parameters,
            create_disposition=beam.io.BigQueryDisposition.CREATE_NEVER,
            write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND,
            method='STREAMING_INSERTS',
            insert_retry_strategy="RETRY_NEVER")
        )

When running the pipeline on Dataflow I pass the following arguments:

python3 script.py \
  --project=<project> \
  --job_name=<name> \
  --streaming \
  --runner=DataflowRunner \
  --temp_location=<temp> \
  --experiments use_beam_bq_sink \
  --staging_location=<location> \
  --num_workers=2

If anyone can elaborate why the additional arguments to BigQuery are seemingly not being recognized I'd greatly appreciate it.

Furthermore, I've tried returning the results from the write to BigQuery in an attempt to persist the failed rows to GCS. However, when I try to access the failed rows from the resulting PCollection with either results[beam.io.gcp.bigquery.BigQueryWriteFn.FAILED_ROWS] or results['FailedRows'] I get the error TypeError: 'PCollection' object is not subscriptable. Based on what I've seen, I thought that this was the proper approach. If anyone could clarify this as well, I would be really grateful.


问:
why does this for loop in C++ using getline() work
I compiled this nested for loop in C++. It works, however I don't understand why. Can you please explain the mechanics, and also any information on why the push_back() is allowed in addition to the increment.

```<code>for (std::string line; std::getline(in, line); text->push_back(line), ++ln) // why does this work?
{
  // do something
  std::istringstream iss(line);
  for (std::string word; iss>>word;) // why does this work?
    // do something
};
</code>```

text is a shared_ptr<vector<string>>.

答:
Every part of a for loop is optional.

If there is no iteration expression, it nothing is done between the body and testing the condition. In this case that's fine, as the condition does the work.

Any expression that contextually coverts to bool can go in the condition.

You can chain multiple expressions with ,, it will evaluate them left to right and discard the values of all but the last.

Body:
I compiled this nested for loop in C++. It works, however I don't understand why. Can you please explain the mechanics, and also any information on why the push_back() is allowed in addition to the increment.

for (std::string line; std::getline(in, line); text->push_back(line), ++ln) // why does this work?
{
  // do something
  std::istringstream iss(line);
  for (std::string word; iss>>word;) // why does this work?
    // do something
};

text is a shared_ptr<vector<string>>.


问:
How do I prevent (uninstall) TypeScript installing and referencing it's own @types into AppData\Local
I'm running into a bit of a confusing issue where it seems that TypeScript is installing its own copy of React into it's own global cache (not sure what its called? assuming thats what it is) and referencing it in my project.

Specifically I end up with two references to React one that is located in the root of my project

```<code>C:\MyProject\node_modules\@types\react
</code>```

and then another reference in

```<code>C:\Users\MyUserName\AppData\Local\Microsoft\TypeScript\3.0\node_modules\@types\react
</code>```

How do I control and uninstall references that end up in the TypeScript local folder? What might I be doing in my project that could be causing this secondary reference?

Here is what my tsconfig.json file looks like:

```<code>{
  "compilerOptions": {
    "module": "commonjs",
    "moduleResolution": "node",

    "target": "es5",
    "sourceMap": true,
    "jsx": "react",
    "lib": [ "es6", "dom" ],
    "removeComments": true,
    "typeRoots": [
      "/Types/"
    ]
  },
  "compileOnSave": false,
  "exclude": [
    "/node_modules/",
    "/bin",
    "/obj"
  ]
}
</code>```

答:
These issues comes up depending on your IDE and is resolved in different ways

For Visual Studio 2019:

Go to Options-> Text Editor -> JavaScript/TypeScript-> Project and Uncheck TypeAcquisition  for Javascript

Close VisualStudio

Delete the Folder under C:\Users\ [Username]\AppData\Local\Microsoft\TypeScript\ [VersionOfConcern]

Reload Solution and your errors should be gone

VS Code Users should be refer to the tsconfig.json file option:

```<code>{
[...],
"typeAcquisition": {"enable": false}
}
</code>```

I did not test the Solution for VS Code.

Body:
I'm running into a bit of a confusing issue where it seems that TypeScript is installing its own copy of React into it's own global cache (not sure what its called? assuming thats what it is) and referencing it in my project.

Specifically I end up with two references to React one that is located in the root of my project

C:\MyProject\node_modules\@types\react

and then another reference in

C:\Users\MyUserName\AppData\Local\Microsoft\TypeScript\3.0\node_modules\@types\react

How do I control and uninstall references that end up in the TypeScript local folder? What might I be doing in my project that could be causing this secondary reference?

Here is what my tsconfig.json file looks like:

{
  "compilerOptions": {
    "module": "commonjs",
    "moduleResolution": "node",

    "target": "es5",
    "sourceMap": true,
    "jsx": "react",
    "lib": [ "es6", "dom" ],
    "removeComments": true,
    "typeRoots": [
      "/Types/"
    ]
  },
  "compileOnSave": false,
  "exclude": [
    "/node_modules/",
    "/bin",
    "/obj"
  ]
}

Body:
These issues comes up depending on your IDE and is resolved in different ways

For Visual Studio 2019:

Go to Options-> Text Editor -> JavaScript/TypeScript-> Project and Uncheck TypeAcquisition  for Javascript

Close VisualStudio

Delete the Folder under C:\Users\ [Username]\AppData\Local\Microsoft\TypeScript\ [VersionOfConcern]

Reload Solution and your errors should be gone

VS Code Users should be refer to the tsconfig.json file option:

{
[...],
"typeAcquisition": {"enable": false}
}

I did not test the Solution for VS Code.


问:
does date_default_timezone_set suffer from same process problem as setlocale?
Does date_default_timezone_set have the same problem as setlocale as defined in the php manual?

locale information is maintained per process, not per thread

is this the same for date default timezone set problem

答: According to the source of PHP 5.3.6 it's a thread safe function.</p>


答:
Let's assume point A is always at 0,0, and point B has the same y coordinate. You can calculate position of C using the law of cosines:

```<code>const calculateTriangle = (a, b, c) => {
  const ax = 0;
  const ay = 0;
  const bx = ax + c;
  const by = ay;
  const cosAlpha = (a * a - b * b - c * c) / (b * c * 2);
  const alpha = Math.acos(cosAlpha);
  const cx = ax - b * cosAlpha;
  const cy = ay + b * Math.sin(alpha);
  return {ax, ay, bx, by, cx, cy};
};
</code>```

Title: convert length to point in svg (polygon) dynamically

Body:
Let's assume point A is always at 0,0, and point B has the same y coordinate. You can calculate position of C using the law of cosines:

const calculateTriangle = (a, b, c) => {
  const ax = 0;
  const ay = 0;
  const bx = ax + c;
  const by = ay;
  const cosAlpha = (a * a - b * b - c * c) / (b * c * 2);
  const alpha = Math.acos(cosAlpha);
  const cx = ax - b * cosAlpha;
  const cy = ay + b * Math.sin(alpha);
  return {ax, ay, bx, by, cx, cy};
};


问:
prefer const with constant constructor
I have an error that shows this message "prefer const with constant constructor" when i deleting const on below class splashscreen theres not showing any error but throwing

heres my code

```<code>  const SplashScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: <Widget>[
          Container(
            child: Image.network(
                "https://cdn.kibrispdr.org/data/white-background-hd-0.jpg"),
          ),
          Container(
            padding: EdgeInsets.symmetric(horizontal: 50),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Image.asset(
                  "name",
                  height: 50,
                ),
                SizedBox(
                  height: 18,
                ),
                Row(
                  children: <Widget>[
                    Text(
                      "Management",
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: 15,
                          fontWeight: FontWeight.w800),
                    ),
                  ],
                ) //Image Asset untuk logo splashscreen
              ],
            ),
          )
</code>```

can someone help with this error really appreciate your help.

答:
This is not really an error, it's just an info message. This message comes from the flutter_lints package that tells you the recommended best practices.

You can learn more about const in Dart from here.

If you want to disable linting then go to the analysis_options.yaml file (present inside the root directory of your Flutter project) and comment out the line:

```<code>include: package:flutter_lints/flutter.yaml
</code>```

But keep in mind this is not recommended.

Title: prefer const with constant constructor

Body:
I have an error that shows this message "prefer const with constant constructor" when i deleting const on below class splashscreen theres not showing any error but throwing

heres my code

  const SplashScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: <Widget>[
          Container(
            child: Image.network(
                "https://cdn.kibrispdr.org/data/white-background-hd-0.jpg"),
          ),
          Container(
            padding: EdgeInsets.symmetric(horizontal: 50),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Image.asset(
                  "name",
                  height: 50,
                ),
                SizedBox(
                  height: 18,
                ),
                Row(
                  children: <Widget>[
                    Text(
                      "Management",
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: 15,
                          fontWeight: FontWeight.w800),
                    ),
                  ],
                ) //Image Asset untuk logo splashscreen
              ],
            ),
          )

can someone help with this error really appreciate your help.

Body:
This is not really an error, it's just an info message. This message comes from the flutter_lints package that tells you the recommended best practices.

You can learn more about const in Dart from here.

If you want to disable linting then go to the analysis_options.yaml file (present inside the root directory of your Flutter project) and comment out the line:

include: package:flutter_lints/flutter.yaml

But keep in mind this is not recommended.


问:
My custom Simio user extension does not get picked up
I have created my custom UserExtension for Simio in C#. I have used one of their examples and changed a few thing just to try this functionality.
Unfortunately when I deploy it in the specific folder listed in their Reference guide the software never picks it up and I cannot use my extenstions.

At first I thought I did not follow some naming convention. But the I have tried opening one of their projects and simply change the description, then build it and replac the dll. It did not pick it up again. So I come to the conclusion that there is some incompatibility between my Visual Studio settings - I have VS 2013, and the Simio software. I have tried launching both the 32bit and 64bit versions of Simio - no difference.

I have registered in the Simio forums, but they are very restrictive and I cannot just ask a question there, I have to wait for permission...

I will be very grateful If someone has any clues what might be the reason.

答:
I also had the problem recently.
After some research I found out that Simio comes in different versions.

One limitation is that the license-free Simio Personal Edition does not allow addins to be activated by the user. Therefore, a license is required for use. (Which is strange, because some UserExtenions are already provided by SimIo and can be used).


问:
Not getting image file in nodejs after posting from react
I'm sending the image file from react to nodejs. I used the SetImage function where the image file selected by the user is set to the 'myimage' state variable and from handleSubmit I'm posting the images to the '/blog/posts' endpoint using Axios. the image file is getting loaded on the 'myimage' state variable but as I posted using the Axios, I can't see all the data of the image file and giving me the empty object.

This is my React code:-

```<code>import React, { useState, useRef } from "react";
import './postblog.css';
import axios from '../axios';

const PostBlog = () => {
    const [myimage,setImage] = useState("");
    const handleSubmit = (event) => {
        event.preventDefault();
        axios.post('/blog/posts', {
            image:myimage
        }).then((res) => {
            console.log(res.body);
            console.log('successfully posted');
        });
    }
    const SetImage = (e)=>{
        console.log(e.target.files[0]);
        setImage(e.target.files[0]);
        console.log(myimage);
    }
    return (
        <div className="postblog">
            <form onSubmit={handleSubmit} enctype="multipart/form-data">
                <input type="file" placeholder="Choose your file" onChange={(e)=>{SetImage(e)}} name="myImage"/>
               </div>
                <button type="submit">Post</button>
            </form>
        </div>
    );
}
export default PostBlog;
</code>```

This is my Nodejs code:-

```<code>var storage = multer.diskStorage({
    destination: function(req, res, cb) {
        cb(null, './Routers/blog/uploads');
    },
    filename: function(req, file, cb) {
        cb(null, Date.now() + file.originalname);
    }
});

var upload = multer({
    storage: storage,
    limits: {
        fieldsize: 1024 * 1024 * 3
    }
});

blog.post('/posts', upload.single('myimage'), (req, res, next) => {
    console.log(req.body);
    console.log(details);
})
</code>```

The output in the console I'm getting is an empty object

答:
You should send file with content type as multipart/form-data but in your code you are sending file as application/json content type.

```<code>...

 const handleSubmit = (event) => {
        event.preventDefault();
        const formData = new FormData();
        formData.append('file', myimage);

        const config = {
          headers: {
            'content-type': 'multipart/form-data'
          }
        };

        axios.post('/blog/posts', formData, config).then((res) => {
            console.log(res.body);
            console.log('successfully posted');
        });
    }

...
</code>```

Body:
I'm sending the image file from react to nodejs. I used the SetImage function where the image file selected by the user is set to the 'myimage' state variable and from handleSubmit I'm posting the images to the '/blog/posts' endpoint using Axios. the image file is getting loaded on the 'myimage' state variable but as I posted using the Axios, I can't see all the data of the image file and giving me the empty object.

This is my React code:-

import React, { useState, useRef } from "react";
import './postblog.css';
import axios from '../axios';

const PostBlog = () => {
    const [myimage,setImage] = useState("");
    const handleSubmit = (event) => {
        event.preventDefault();
        axios.post('/blog/posts', {
            image:myimage
        }).then((res) => {
            console.log(res.body);
            console.log('successfully posted');
        });
    }
    const SetImage = (e)=>{
        console.log(e.target.files[0]);
        setImage(e.target.files[0]);
        console.log(myimage);
    }
    return (

            <form onSubmit={handleSubmit} enctype="multipart/form-data">
                <input type="file" placeholder="Choose your file" onChange={(e)=>{SetImage(e)}} name="myImage"/>

                <button type="submit">Post</button>
            </form>

    );
}
export default PostBlog;

This is my Nodejs code:-

var storage = multer.diskStorage({
    destination: function(req, res, cb) {
        cb(null, './Routers/blog/uploads');
    },
    filename: function(req, file, cb) {
        cb(null, Date.now() + file.originalname);
    }
});

var upload = multer({
    storage: storage,
    limits: {
        fieldsize: 1024 * 1024 * 3
    }
});

blog.post('/posts', upload.single('myimage'), (req, res, next) => {
    console.log(req.body);
    console.log(details);
})

The output in the console I'm getting is an empty object

Body:
You should send file with content type as multipart/form-data but in your code you are sending file as application/json content type.

...

 const handleSubmit = (event) => {
        event.preventDefault();
        const formData = new FormData();
        formData.append('file', myimage);

        const config = {
          headers: {
            'content-type': 'multipart/form-data'
          }
        };

        axios.post('/blog/posts', formData, config).then((res) => {
            console.log(res.body);
            console.log('successfully posted');
        });
    }

...


问:
Unix command for find updated and newly added files/folder
I need to find out the listed for files or folders that has been added/updated in the file system path (/home/user01/myapps/) between two different time (scripts starting and ending time).

I am running a Shell scripts to do the updating/adding new files to the resource path /home/user01/myapps/ from different source. So, at the end of scripts I want to know the list of files or folders that has been added or updated.

I have the below command

find /opt/app/tds/tdsbatch -mtime -1

But, I am not sure about the script running time.

Any help indeed!

答:
At the start of script you can use touch command for any existing file or create a dummy file.

e.g.

script start

touch filename1  - It will change the time stamp of filename1 to current time

Then at the end of script you can use following command:

find directory name -newer filename1

It will give all the files modified or created  after timestamp of filename1 in that directory


问:
vscode won't build
I installed texlive correctly and installed the tex workshop in vscode. But when I click "build", the sofware is not responding, without any feedback.

答:
You are missing the document environment and a package which defines the align* environment, e.g. amsmath

```<code>\documentclass{article}

\usepackage{amsmath}

\begin{document}

\begin{align*}
lll
\end{align*}

\end{document}
</code>```

That being said, you seem to still be at the start of potentially great friendship with LaTeX. To make things easier, I highly suggest a dedicated latex editor like texstudio. This will provide better support to avoid mistakes like this. For example for running your document, it would have given you the following summary of errors:

I also don't know where your Tutorial_4.tex comes from, but I would recommend https://www.learnlatex.org/ if you want to learn latex.

Title: vscode won't build

Body:
You are missing the document environment and a package which defines the align* environment, e.g. amsmath

\documentclass{article}

\usepackage{amsmath}

\begin{document}

\begin{align*}
lll
\end{align*}

\end{document}

That being said, you seem to still be at the start of potentially great friendship with LaTeX. To make things easier, I highly suggest a dedicated latex editor like texstudio. This will provide better support to avoid mistakes like this. For example for running your document, it would have given you the following summary of errors:

I also don't know where your Tutorial_4.tex comes from, but I would recommend https://www.learnlatex.org/ if you want to learn latex.


问:
How to sum value in javascript array obj from specific search category to useState
I have js arr obj as below. My need is to sum value to useState base on category in the arr obj.

```<code>const [fit, setFit] = useState(0)
const [fat, setFat] = useState(0)
const [slim, setSlim] = useState(0)
const [test, setTest] = useState(0)

const arr = [
{id: '222', cost: 2, category: 'fit'},
{id: '333', cost: 3, category: 'fat'},
{id: '11', cost: 1, category: 'fat'},
{id: '11', cost: 0, category: 'fit'},
{id: '33', cost: 55, category: 'slim'},
{id: '55', cost: 33, category: 'slim'},
{id: '123', cost: 4, category: 'slim'}
]
</code>```

How can i interate arr to get this effect ?

```<code>const [fit, setFit] = useState(2)
const [fat, setFat] = useState(4)
const [slim, setSlim] = useState(92)
const [test, setTest] = useState(0)
</code>```

Thanks you for your help ;-)

答:
I didn't like the other answers. This one is different in that it will create an object based on all the properties in your array, dynamically uses useEffect, and only iterates through your array once.

const arr = [
  {id: '222', cost: 2, category: 'fit'},
  {id: '333', cost: 3, category: 'fat'},
  {id: '11', cost: 1, category: 'fat'},
  {id: '11', cost: 0, category: 'fit'},
  {id: '33', cost: 55, category: 'slim'},
  {id: '55', cost: 33, category: 'slim'},
  {id: '123', cost: 4, category: 'slim'}
];

// reduce list to an object of total costs
const values = arr.reduce((a, b) => {
  if (!a[b.category]) a[b.category] = b.cost;
  else a[b.category] += b.cost;
  return a;
}, {});
console.log(values);

// create your values and setters in an object
const effects = {};
for (let key in values) {
  let [val, set] = useEffect(values[key]); // useEffect is not defined on StackOverflow
  effects[key] = {val, set};
}
/*
Creates obj with this structure:
{
  "fit": {
    "val": fit,
    "set": setFit,
  },
  ...
}
*/```

Body:
I have js arr obj as below. My need is to sum value to useState base on category in the arr obj.

const [fit, setFit] = useState(0)
const [fat, setFat] = useState(0)
const [slim, setSlim] = useState(0)
const [test, setTest] = useState(0)

const arr = [
{id: '222', cost: 2, category: 'fit'},
{id: '333', cost: 3, category: 'fat'},
{id: '11', cost: 1, category: 'fat'},
{id: '11', cost: 0, category: 'fit'},
{id: '33', cost: 55, category: 'slim'},
{id: '55', cost: 33, category: 'slim'},
{id: '123', cost: 4, category: 'slim'}
]

How can i interate arr to get this effect ?

const [fit, setFit] = useState(2)
const [fat, setFat] = useState(4)
const [slim, setSlim] = useState(92)
const [test, setTest] = useState(0)

Thanks you for your help ;-)


问:
I am getting an error create is missing in typeof

Property 'create' is missing in type 'typeof import("D:/Project once more/examfrontend/node_module
s/@types/ckeditor__ckeditor5-build-classic/index")' but required in type 'EditorConstructor'.

```<code>35                       <ckeditor [editor]="Editor" data="Hello"></ckeditor>
</code>```

I am getting is error. I do not know where I am wrong.

答:
My issue is resolved actually I was having restricted properties in my tsconfig.json file

"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
```

I removed those and got the output.

Body:
Property 'create' is missing in type 'typeof import("D:/Project once more/examfrontend/node_module
s/@types/ckeditor__ckeditor5-build-classic/index")' but required in type 'EditorConstructor'.

35                       <ckeditor [editor]="Editor" data="Hello"></ckeditor>

I am getting is error. I do not know where I am wrong.

Body:
My issue is resolved actually I was having restricted properties in my tsconfig.json file

"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true

I removed those and got the output.


问:
Regex for differentiating between phone number and year
My regex matches a year range in the string when I only want to match phone numbers.

Here is an example test string:

```<code>Call on tel: (425) 882-8080 or 852-9876 and it does not
necessarily reflect the views of Microsoft Corp from 1986-1989.

</code>```

Here the matched strings are:

```<code>(425) 882-8080
852-9876
986-1989
</code>```

It takes "986-1989" from the date "1986-1989".

My regex:

```<code>((?:\d{1}[-\/\.\s]|\+\d{2}[-\/\.\s]??|\d{2}[-\/\.\s]??|\d{3}[-\/\.\s]??|\d{4}[-\/\.\s]??)?(?:\d{3}[-\/\.\s]??\d{3}[-\/\.\s]??\d{4}|\(\d{3}\)\s*\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4}))

</code>```

Any suggestions on how to change this regex so that it doesn't consider the year?

答:
In Python, you can use lookarounds, so you can use a pattern that only matches your phone numbers if there are no digits on both ends of the potential match.

re.findall(r'(?<!\d)(?:\d[-/.\s]|\+\d{2}[-/.\s]?|\d{2,4}[-/.\s]?)?(?:\d{3}[-/.\s]?\d{3}[-/.\s]?\d{4}|\(\d{3}\)\s*\d{3}[-.\s]?\d{4}|\d{3}[-.\s]?\d{4})(?!\d)', text)
```

See the regex demo.

Note you do not need to escape forward backslash in a Python regex string since / is not any special regex metacharacter.

Note also the (?<!\d) lookbehind and (?!\d) lookahead that fail the match if there is a digit before or after the pattern respectively.

I suggest replacing ?? with ? in your regex because the lazy pattern does not have any advantage here.

The \d{2}[-\/\.\s]??|\d{3}[-\/\.\s]??|\d{4}[-\/\.\s]?? part only differs in the amount of digits matched, so I shortened it to \d{2,4}[-/.\s]?.

The . char inside a character class needs no escaping as it only denotes a literal dot char there ([.] = \. in regex)

Body:
My regex matches a year range in the string when I only want to match phone numbers.

Here is an example test string:

Call on tel: (425) 882-8080 or 852-9876 and it does not
necessarily reflect the views of Microsoft Corp from 1986-1989.

Here the matched strings are:

(425) 882-8080
852-9876
986-1989

It takes "986-1989" from the date "1986-1989".

My regex:

((?:\d{1}[-\/\.\s]|\+\d{2}[-\/\.\s]??|\d{2}[-\/\.\s]??|\d{3}[-\/\.\s]??|\d{4}[-\/\.\s]??)?(?:\d{3}[-\/\.\s]??\d{3}[-\/\.\s]??\d{4}|\(\d{3}\)\s*\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4}))

Any suggestions on how to change this regex so that it doesn't consider the year?

Body:
In Python, you can use lookarounds, so you can use a pattern that only matches your phone numbers if there are no digits on both ends of the potential match.

re.findall(r'(?<!\d)(?:\d[-/.\s]|\+\d{2}[-/.\s]?|\d{2,4}[-/.\s]?)?(?:\d{3}[-/.\s]?\d{3}[-/.\s]?\d{4}|\(\d{3}\)\s*\d{3}[-.\s]?\d{4}|\d{3}[-.\s]?\d{4})(?!\d)', text)

See the regex demo.

Note you do not need to escape forward backslash in a Python regex string since / is not any special regex metacharacter.

Note also the (?<!\d) lookbehind and (?!\d) lookahead that fail the match if there is a digit before or after the pattern respectively.

I suggest replacing ?? with ? in your regex because the lazy pattern does not have any advantage here.

The \d{2}[-\/\.\s]??|\d{3}[-\/\.\s]??|\d{4}[-\/\.\s]?? part only differs in the amount of digits matched, so I shortened it to \d{2,4}[-/.\s]?.

The . char inside a character class needs no escaping as it only denotes a literal dot char there ([.] = \. in regex)


问:
Resize an IplImage in ruby-opencv
I'm using ruby-opencv to do some image processing. I have an IplImage object that I need to resize. Calling the resize method on that object returns a CvMat object. How do I convert that CvMat object into an IplImage object? Alternatively, is there another way to resize the image?</p>

答: The problem is with the ruby-opencv wrapper. The resize method in CvMat (from which IplImage is inherited in the C++ library) was incorrectly determining the type of the Ruby class to return (i.e., it was returning CvMat instead of IplImage when resize was called on an IplImage). This has been fixed in recent forks of ruby-opencv. For example: https://github.com/ser1zw/ruby-opencv</p>

Title: Resize an IplImage in ruby-opencv


问:
The label parameter should be set so this transition can be better inspected in Animation Preview
I follow the example code in https://developer.android.com/jetpack/compose/animation#updateTransition, and notice a warning as below. I tried Shift-Option-Enter, but it is not auto fixed.

I am not sure what the fix should be. Can someone advise?

答:
This warning asks you for the label parameter:

```<code>updateTransition(currentState, label = "inspection label")
</code>```

Body:
This warning asks you for the label parameter:

updateTransition(currentState, label = "inspection label")


问:
how can route an array as a parameter in angular?
I configured routing module as following:

const routes: Routes = [
  {
    path: "engineering/:branches",
    component: BranchesTabsComponent
  },
  {
    path: "humanities/:branches",
    component: BranchesTabsComponent
  },
];```
</div>
</div>
</p>
<p>and in the main-continer.component.ts:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>titlesOfEngineeringTabs: string[] = ['E1','E2','E3'];
titlesOfHumanitiesTabs: string[] = ['H1','H2'];

constructor(private router: Router) {}

handleEnginTabs():void{
    this.router.navigate(['/engineering', this.titlesOfEngineeringTabs]);
}
handleHumanTabs():void{
    this.router.navigate(['/humanities', this.titlesOfHumanitiesTabs]);
}</code>```

and also main-continer.component.html contains:

<router-outlet></router-outlet>```
</div>
</div>
</p>
<p>and then in branches-tabs.component.ts have:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>tabsLable: string[] = [''];

ngOnInit(): void {
     this.route.params.subscribe(param => this.tabsLable = param["branches"]);
}</code>```

till here, it is obvious that we want to replace <router-outlet> with branches-tabs component in which deferent tab labels are shown Depending on selected menu...
but I get this error:

```<code>*core.mjs:6485 ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'engineering;0=%DA%A9%D8%A7%D9%85%D9%BE%DB%8C%D9%88%D8%AA%D8%B1;1=%D8%B5%D9%86%D8%A7%DB%8C%D8%B9;2=%D9%85%D8%AA%D8%A7%D9%84%D9%88%D8%B1%DA%98%DB%8C'
Error: Cannot match any routes. URL Segment: 'engineering;0=%DA%A9%D8%A7%D9%85%D9%BE%DB%8C%D9%88%D8%AA%D8%B1;1=%D8%B5%D9%86%D8%A7%DB%8C%D8%B9;2=%D9%85%D8%AA%D8%A7%D9%84%D9%88%D8%B1%DA%98%DB%8C'*
</code>```

how can pass a string array as parameter and fix above error?
best regards

答:
If you want to put the array in the url, it needs to be a string. So you can use JSON.stringify() and JSON.parse()

handleEnginTabs():void{
    this.router.navigate(['/engineering', JSON.stringify(this.titlesOfEngineeringTabs)]);
}
```
<pre class="lang-js prettyprint-override"><code>ngOnInit(): void {
     this.route.params.subscribe(param => this.tabsLable = JSON.parse(param["branches"]));
}
</code>```

But queryParams is probably more appropriate.

  handleEnginTabs(): void {
    this.router.navigate(['/engineering'], {
      queryParams: { branches: this.titlesOfEngineeringTabs },
    });
  }
```
<pre class="lang-js prettyprint-override"><code>  ngOnInit(): void {
    this.tabsLable = this.route.snapshot.queryParams['branches'];
  }
</code>```

and removing the parameter from the path

  {
    path: "engineering",
    component: BranchesTabsComponent
  },
```

Keep in mind the user can change the values of your array by editing the url. If that's something you don't want to happen, you'll have to use other means of passing the data.

This thread goes over some other ways of passing data to routes:

How do I pass data to Angular routed components?

However, a lot of them will not persist on refresh. So if you want that, you'll have to write to / read from localStorage as well.

Body:
I configured routing module as following:

const routes: Routes = [
  {
    path: "engineering/:branches",
    component: BranchesTabsComponent
  },
  {
    path: "humanities/:branches",
    component: BranchesTabsComponent
  },
];

and in the main-continer.component.ts:

titlesOfEngineeringTabs: string[] = ['E1','E2','E3'];
titlesOfHumanitiesTabs: string[] = ['H1','H2'];

constructor(private router: Router) {}

handleEnginTabs():void{
    this.router.navigate(['/engineering', this.titlesOfEngineeringTabs]);
}
handleHumanTabs():void{
    this.router.navigate(['/humanities', this.titlesOfHumanitiesTabs]);
}

and also main-continer.component.html contains:

<router-outlet></router-outlet>

and then in branches-tabs.component.ts have:

tabsLable: string[] = [''];

ngOnInit(): void {
     this.route.params.subscribe(param => this.tabsLable = param["branches"]);
}

till here, it is obvious that we want to replace <router-outlet> with branches-tabs component in which deferent tab labels are shown Depending on selected menu...
but I get this error:

*core.mjs:6485 ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'engineering;0=%DA%A9%D8%A7%D9%85%D9%BE%DB%8C%D9%88%D8%AA%D8%B1;1=%D8%B5%D9%86%D8%A7%DB%8C%D8%B9;2=%D9%85%D8%AA%D8%A7%D9%84%D9%88%D8%B1%DA%98%DB%8C'
Error: Cannot match any routes. URL Segment: 'engineering;0=%DA%A9%D8%A7%D9%85%D9%BE%DB%8C%D9%88%D8%AA%D8%B1;1=%D8%B5%D9%86%D8%A7%DB%8C%D8%B9;2=%D9%85%D8%AA%D8%A7%D9%84%D9%88%D8%B1%DA%98%DB%8C'*

how can pass a string array as parameter and fix above error?
best regards

Body:
If you want to put the array in the url, it needs to be a string. So you can use JSON.stringify() and JSON.parse()

handleEnginTabs():void{
    this.router.navigate(['/engineering', JSON.stringify(this.titlesOfEngineeringTabs)]);
}

ngOnInit(): void {
     this.route.params.subscribe(param => this.tabsLable = JSON.parse(param["branches"]));
}

But queryParams is probably more appropriate.

  handleEnginTabs(): void {
    this.router.navigate(['/engineering'], {
      queryParams: { branches: this.titlesOfEngineeringTabs },
    });
  }

  ngOnInit(): void {
    this.tabsLable = this.route.snapshot.queryParams['branches'];
  }

and removing the parameter from the path

  {
    path: "engineering",
    component: BranchesTabsComponent
  },

Keep in mind the user can change the values of your array by editing the url. If that's something you don't want to happen, you'll have to use other means of passing the data.

This thread goes over some other ways of passing data to routes:

How do I pass data to Angular routed components?

However, a lot of them will not persist on refresh. So if you want that, you'll have to write to / read from localStorage as well.


问:
setReadOnly not working on PostgreSQL Connection
I have a problem setting a read-only connection with a PostgreSQL database using JDBC.

I'm creating an application which loads queries to execute from a file, and I want to execute only SELECT (read-only) queries. Setting permissions on users who will run the application is not an option, so setting permissions at code level through the Connection.setReadOnly(boolean) method was the only option I could think of.

Now the problem is that I tried my application for an insert and delete query and they run normally, so my solution does not work.

Any tips on how to solve the problem?

Here below the simple code snippet which I'm testing:

```<code>public class Test{

public static void main(String[] args) {
    connectAndExecute();
}

public static void connectAndExecute() {
    try {
        Class.forName("org.postgresql.Driver");
    } catch (ClassNotFoundException e1) {
        e1.printStackTrace();
        return;
    }

    Connection connection;

    String connString = "jdbc:postgresql://localhost:5432/testdb";
    try {
        connection = DriverManager.getConnection(connString, "user", "password");
    } catch (SQLException e) {
        e.printStackTrace();
        return;
    }

    try {
        connection.setReadOnly(true);
        connection.createStatement().execute("delete from testtable");
        // connection.createStatement().execute("insert intotesttable(testfield1)values('test')");
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
</code>```

and this is the JDBC driver I'm using

```<code><groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.10</version>
</code>```

PostgreSQL version: 11.6

答:
Just to be clear : the specification for setReadOnly method does not aim to prevent from updating the database.

As the Java's API says :

https://docs.oracle.com/javase/8/docs/api/java/sql/Connection.html#setReadOnly-boolean-

"Puts this connection in read-only mode as a hint to the driver to enable database optimizations"

So it is not a good idea to rely on this method in order to secure anything related to the need of having readonly transactions :)

Body:
I have a problem setting a read-only connection with a PostgreSQL database using JDBC.

I'm creating an application which loads queries to execute from a file, and I want to execute only SELECT (read-only) queries. Setting permissions on users who will run the application is not an option, so setting permissions at code level through the Connection.setReadOnly(boolean) method was the only option I could think of.

Now the problem is that I tried my application for an insert and delete query and they run normally, so my solution does not work.

Any tips on how to solve the problem?

Here below the simple code snippet which I'm testing:

public class Test{

public static void main(String[] args) {
    connectAndExecute();
}

public static void connectAndExecute() {
    try {
        Class.forName("org.postgresql.Driver");
    } catch (ClassNotFoundException e1) {
        e1.printStackTrace();
        return;
    }

    Connection connection;

    String connString = "jdbc:postgresql://localhost:5432/testdb";
    try {
        connection = DriverManager.getConnection(connString, "user", "password");
    } catch (SQLException e) {
        e.printStackTrace();
        return;
    }

    try {
        connection.setReadOnly(true);
        connection.createStatement().execute("delete from testtable");
        // connection.createStatement().execute("insert intotesttable(testfield1)values('test')");
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

and this is the JDBC driver I'm using

<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.10</version>

PostgreSQL version: 11.6


问:
How do I disconnect a user from a discord channel with discord js?
The main issue seems to be that things are undefined. For example, a very simple version of something I have tried:

```<code>else if (message.content.startsWith("!dc")) {
    message.author.voice.setChannel(null);
}
</code>```

Resulting in the terminal returning:

TypeError: Cannot read properties of undefined (reading 'setChannel')

I'm not quite sure how to "define" these as some solutions I've found online seem to do what I am trying to do in a similar way. Am I just missing something obvious?

I also have these Intents declared at the top.

```<code>const client = new Discord.Client({
intents: [
    Discord.Intents.FLAGS.GUILDS,
    Discord.Intents.FLAGS.GUILD_MESSAGES,
    Discord.Intents.FLAGS.GUILD_VOICE_STATES,
    Discord.Intents.FLAGS.GUILD_MEMBERS
    ]
});
</code>```

答:
Try this code:

message.member.voice.disconnect()
    .catch(console.error);
```

Body:
The main issue seems to be that things are undefined. For example, a very simple version of something I have tried:

else if (message.content.startsWith("!dc")) {
    message.author.voice.setChannel(null);
}

Resulting in the terminal returning:

TypeError: Cannot read properties of undefined (reading 'setChannel')

I'm not quite sure how to "define" these as some solutions I've found online seem to do what I am trying to do in a similar way. Am I just missing something obvious?

I also have these Intents declared at the top.

const client = new Discord.Client({
intents: [
    Discord.Intents.FLAGS.GUILDS,
    Discord.Intents.FLAGS.GUILD_MESSAGES,
    Discord.Intents.FLAGS.GUILD_VOICE_STATES,
    Discord.Intents.FLAGS.GUILD_MEMBERS
    ]
});


问:
Getting near real time updates from normalised tables
My question is related to Change data capture and real time updates. I have a mysql database which has close to 250 tables whose change data is captured using debezium and sent to kafka on their respective topics.

These tables are highly normalised and I am interested in a denormalised view which  is created by joining some of the tables. Now I need to know whenever there is a change in the table, I get to see that as a change in the denormalised topic in a near real time.

How can I do so. How does log compaction works?
Do I need to log compact all the topics in order to get denormalised topic view?

What other possibilities I have here?

答:
This is not very straight forward to accomplish.

The following are some options you could try.

The first option is using KSQL

https://debezium.io/blog/2018/05/24/querying-debezium-change-data-eEvents-with-ksql/

The other option is to create aggregate views

https://debezium.io/blog/2018/09/20/materializing-aggregate-views-with-hibernate-and-debezium/

Another option that we tried for a similar problem was to have streaming listener on Kafka and then have logic there to merge data into de-normal data structures that have been set up on another datastore


问:
How can I write a where clause in SQL to filter a DATETIME column by the time of day?
I have data that is timestamped with a DATETIME column and I want to filter it down to the set of records where the DATETIME is between 9:30am and 5:30pm for any day.  What's the best way to do this?

UPDATE: Changed because I need precision to the minute, not just hour.  Sorry about that.

答:
```<code>SELECT *
FROM your_table
WHERE (DATEPART(hh, date_column) = 9 AND DATEPART(mi, date_column) >= 30)
    OR (DATEPART(hh, date_column) = 17 AND DATEPART(mi, date_column) <= 30)
    OR DATEPART(hh, date_column) BETWEEN 10 AND 16
</code>```

OwnerDisplayName: Bialecki

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Milen A. Radev

OwnerDisplayName: Luke

LastEditorDisplayName: Luke


问:
How to toggle two icons in v-for list item in Vue
I have a list of items and icons which I want to toggle. How should I do that? Right now my click affects all of the items.</p>
```<code><ion-item
        v-for="course in courses"
        :key="course.id">
  <ion-label class="ion-text-wrap">{{ course.name }}</ion-label>
  <span @click="toggleIcons">
    <ion-icon v-if="isSelected" :icon="ellipseOutline" slot="end"></ion-icon>
    <ion-icon v-else :icon="checkmarkCircleOutline" slot="end"></ion-icon>
  </span>
</ion-item>

///

data() {
    return {
        isSelected: false,
        }
    },
methods: {
    toggleIcons(){
        this.isSelected = !this.isSelected
    }
}
</code>```

答:
Try like following snipet:

new Vue({
  el: "#demo",
  data() {
      return {
        courses: [{id:1, name: 'aaa'}, {id:2, name: 'bbb'},{id:3, name: 'ccc'}],
        isSelected:  null
      }
    },
    methods: {
      toggleIcons(id){
        this.isSelected === id ? this.isSelected=null : this.isSelected = id
      }
    }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <div v-for="course in courses" :key="course.id">
    <label class="ion-text-wrap">{{ course.name }}</label>
    <button @click="toggleIcons(course.id)">
    click
      <div v-if="isSelected === course.id " slot="end">1</div>
      <div v-if="isSelected !== course.id " slot="end">2</div>
    </button>
  </div>
</div></code>```

Body:
I have a list of items and icons which I want to toggle. How should I do that? Right now my click affects all of the items.

<ion-item
        v-for="course in courses"
        :key="course.id">
  <ion-label class="ion-text-wrap">{{ course.name }}</ion-label>

    <ion-icon v-if="isSelected" :icon="ellipseOutline" slot="end"></ion-icon>
    <ion-icon v-else :icon="checkmarkCircleOutline" slot="end"></ion-icon>

</ion-item>

///

data() {
    return {
        isSelected: false,
        }
    },
methods: {
    toggleIcons(){
        this.isSelected = !this.isSelected
    }
}

Body:
Try like following snipet:

new Vue({
  el: "#demo",
  data() {
      return {
        courses: [{id:1, name: 'aaa'}, {id:2, name: 'bbb'},{id:3, name: 'ccc'}],
        isSelected:  null
      }
    },
    methods: {
      toggleIcons(id){
        this.isSelected === id ? this.isSelected=null : this.isSelected = id
      }
    }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <div v-for="course in courses" :key="course.id">
    <label class="ion-text-wrap">{{ course.name }}</label>
    <button @click="toggleIcons(course.id)">
    click
      <div v-if="isSelected === course.id " slot="end">1</div>
      <div v-if="isSelected !== course.id " slot="end">2</div>
    </button>
  </div>
</div>


问:
How do I access data in "int20_t"?
I got a lot of memory pieces in 512 bits. I need to write numbers in 20 bits.

For example:

```<code>// a piece of 512 bits memory
void *p = malloc(64);

struct Coords {
  int20_t x, y;
};

// usage
Coords *pcoord = (Coords *)p;

for (int i = 0; i < 512 / 40/*sizeof(Coords)*/; ++i) {
  pcoord[i].x = i;
  pcoord[i].y = 2 * i;
}
</code>```

How to implement int20_t ?

I need exactly 20 bits for an integer. The numbers must be continuous.
( [0]  to [19] for the first Coords.x;
[20] to [39] for the first Coords.y;
...
There are 12 pairs of Coords with 480 bits and 32 bits for the pad.)

答:
You can't. In int20_t x, y;, you would require fractional alignment (unless you have 10 bits hardware somehow).

The rationale is that &y must be an int20_t*, convertable to void*.

You can create a wrapper type for the whole 480 bits, with an operator[].

Title: How do I access data in "int20_t"?

Body:
I got a lot of memory pieces in 512 bits. I need to write numbers in 20 bits.

For example:

// a piece of 512 bits memory
void *p = malloc(64);

struct Coords {
  int20_t x, y;
};

// usage
Coords *pcoord = (Coords *)p;

for (int i = 0; i < 512 / 40/*sizeof(Coords)*/; ++i) {
  pcoord[i].x = i;
  pcoord[i].y = 2 * i;
}

How to implement int20_t ?

I need exactly 20 bits for an integer. The numbers must be continuous.
( [0]  to [19] for the first Coords.x;
[20] to [39] for the first Coords.y;
...
There are 12 pairs of Coords with 480 bits and 32 bits for the pad.)


问:
Change column sum output of shiny datatable
This is a follow up question to this question: Adding Total/Subtotal to the bottom of a DataTable in Shiny with the following code snippet:

```<code>library(shiny)
library(DT)

ui <- shinyUI(fluidPage(
  h1('Testing TableTools'),
  mainPanel(
    dataTableOutput('display')
  )
))

Names <- c("",names(mtcars))
FooterNames <- c(rep("",4),Names[5:6],rep("",6))

server <- function(input, output, session) {

  sketch <- htmltools::withTags(table(
    tableHeader(Names),tableFooter(FooterNames)
  ))

  opts <- list(
    dom = 'Bfrtip', buttons = list('colvis','print',list(extend='collection',text='Download',buttons = list('copy','csv','excel','pdf'))),
               footerCallback = JS(
                 "function( tfoot, data, start, end, display ) {",
                 "var api = this.api(), data;",
                 "$( api.column(5).footer()).html('SubTotal:  '+",
                 "api.column(5).data().reduce( function ( a, b ) {",
                 "return a + b;",
                 "} )",
                 ");",
                 "$( api.column(4).footer()).html('SubTotal: '+",
                 "api.column(4).data().reduce( function ( a, b ) {",
                 "return a + b;",
                 "} )",
                 ");","}")
  )

  output$display <- DT::renderDataTable(container = sketch,extensions = 'Buttons',options = opts,{
    mtcars
  })
}

shinyApp(ui = ui, server = server)
</code>```

In my dataframe I have columns that contain doubles with two digits after the comma. The subTotal is shown as something like this:

1234,51999999999 instead of 1234,52.

What do I have to change in the Javascript code to get only two digits after the comma, thounsander seperators as a dot and the decimal point as a comma and also, a Euro (€) symbol next to the sum?

答:
Why you want to do this in JavaScript if you are using shiny? This is the R way:

```<code>paste0(
  formatC(1234.51999999999, format="f", big.mark=".",
  decimal.mark = ",", digits=2), "€"
)
# [1] "1.234,52€"
</code>```

Or use JS to do the job:

```<code>library(shiny)
library(DT)

ui <- shinyUI(fluidPage(
  h1("Testing TableTools"),
  mainPanel(
    dataTableOutput("display")
  )
))

Names <- c("", names(mtcars))
FooterNames <- c(rep("", 4), Names[5:6], rep("", 6))

server <- function(input, output, session) {
  sketch <- htmltools::withTags(table(
    tableHeader(Names), tableFooter(FooterNames)
  ))

  opts <- list(
    dom = "Bfrtip", buttons = list("colvis", "print", list(extend = "collection", text = "Download", buttons = list("copy", "csv", "excel", "pdf"))),
    footerCallback = JS(
      "
      function(tfoot, data, start, end, display) {
    var api = this.api(),
        data;
    var sum1 =  api.column(5).data().reduce(function(a, b) {
        return a + b;
    });
    sum1 = Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(sum1)

    $(api.column(5).footer()).html('SubTotal:  ' + sum1)
}
"
    )
  )

  output$display <- DT::renderDataTable(container = sketch, extensions = "Buttons", options = opts, {
    mtcars
  })
}

shinyApp(ui = ui, server = server)
</code>```

Body:
This is a follow up question to this question: Adding Total/Subtotal to the bottom of a DataTable in Shiny with the following code snippet:

library(shiny)
library(DT)

ui <- shinyUI(fluidPage(
  h1('Testing TableTools'),
  mainPanel(
    dataTableOutput('display')
  )
))

Names <- c("",names(mtcars))
FooterNames <- c(rep("",4),Names[5:6],rep("",6))

server <- function(input, output, session) {

  sketch <- htmltools::withTags(table(
    tableHeader(Names),tableFooter(FooterNames)
  ))

  opts <- list(
    dom = 'Bfrtip', buttons = list('colvis','print',list(extend='collection',text='Download',buttons = list('copy','csv','excel','pdf'))),
               footerCallback = JS(
                 "function( tfoot, data, start, end, display ) {",
                 "var api = this.api(), data;",
                 "$( api.column(5).footer()).html('SubTotal:  '+",
                 "api.column(5).data().reduce( function ( a, b ) {",
                 "return a + b;",
                 "} )",
                 ");",
                 "$( api.column(4).footer()).html('SubTotal: '+",
                 "api.column(4).data().reduce( function ( a, b ) {",
                 "return a + b;",
                 "} )",
                 ");","}")
  )

  output$display <- DT::renderDataTable(container = sketch,extensions = 'Buttons',options = opts,{
    mtcars
  })
}

shinyApp(ui = ui, server = server)

In my dataframe I have columns that contain doubles with two digits after the comma. The subTotal is shown as something like this:

1234,51999999999 instead of 1234,52.

What do I have to change in the Javascript code to get only two digits after the comma, thounsander seperators as a dot and the decimal point as a comma and also, a Euro (€) symbol next to the sum?

Body:
Why you want to do this in JavaScript if you are using shiny? This is the R way:

paste0(
  formatC(1234.51999999999, format="f", big.mark=".",
  decimal.mark = ",", digits=2), "€"
)
# [1] "1.234,52€"

Or use JS to do the job:

library(shiny)
library(DT)

ui <- shinyUI(fluidPage(
  h1("Testing TableTools"),
  mainPanel(
    dataTableOutput("display")
  )
))

Names <- c("", names(mtcars))
FooterNames <- c(rep("", 4), Names[5:6], rep("", 6))

server <- function(input, output, session) {
  sketch <- htmltools::withTags(table(
    tableHeader(Names), tableFooter(FooterNames)
  ))

  opts <- list(
    dom = "Bfrtip", buttons = list("colvis", "print", list(extend = "collection", text = "Download", buttons = list("copy", "csv", "excel", "pdf"))),
    footerCallback = JS(
      "
      function(tfoot, data, start, end, display) {
    var api = this.api(),
        data;
    var sum1 =  api.column(5).data().reduce(function(a, b) {
        return a + b;
    });
    sum1 = Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(sum1)

    $(api.column(5).footer()).html('SubTotal:  ' + sum1)
}
"
    )
  )

  output$display <- DT::renderDataTable(container = sketch, extensions = "Buttons", options = opts, {
    mtcars
  })
}

shinyApp(ui = ui, server = server)


问:
Computing hash of large file to detect duplicates in storage
I want to detect duplicate files in storage by computing hash for them. But some files could be large and it won't be cheap to retrieve the full content of a file to calculate.
The algorithm could be MD5 and files could be video, audio, images.
Is it a good idea to compute the hash for the small first part of such large files, e.g. 1MB?</p>

答: You can try the file size and the beginning of the file 1MB.</p>


问:
nokogiri excluded elements from select all by class
I'm just trying to exclude a couple of child elements by class from a selection of all the children of a node

```<code>page.css('div.parent > *').each do |child|
  if (child["class"].content != 'this' && child["class"].content != 'that')
    array.push(child.text.to_s)
  end
end
</code>```

I know this not the write syntax, but have been unable to find how to select an elements class, as opposed to selects and element by class.

答:
The css method gives you Nokogiri::XML::Element instances and those get most of their behavior from their Nokogiri::XML::Node parent class. To get an attribute out of a Node, use []:

```<code>page.css('div.parent > *').each do |child|
  if(!%w{this that}.include?(child['class']))
    array.push(child.text.to_s)
  end
end
</code>```

You could also use if(child['class'] != 'this' && child['class'] != 'that') if that makes more sense to you.

However, class attributes can have multiple values so you might want to split them into pieces on whitespace:

```<code>exclude = %w{this that}
page.css('div.parent > *').each do |child|
  classes = (child['class'] || '').split(/\s+/)
  if((classes & exclude).length > 0)
    array.push(child.text.to_s)
  end
end
</code>```

The intersection is just an easy way to see if the two arrays have any elements in common (i.e. classes contains anything that you want to exclude).

Body:
I'm just trying to exclude a couple of child elements by class from a selection of all the children of a node

page.css('div.parent > *').each do |child|
  if (child["class"].content != 'this' && child["class"].content != 'that')
    array.push(child.text.to_s)
  end
end

I know this not the write syntax, but have been unable to find how to select an elements class, as opposed to selects and element by class.

Body:
The css method gives you Nokogiri::XML::Element instances and those get most of their behavior from their Nokogiri::XML::Node parent class. To get an attribute out of a Node, use []:

page.css('div.parent > *').each do |child|
  if(!%w{this that}.include?(child['class']))
    array.push(child.text.to_s)
  end
end

You could also use if(child['class'] != 'this' && child['class'] != 'that') if that makes more sense to you.

However, class attributes can have multiple values so you might want to split them into pieces on whitespace:

exclude = %w{this that}
page.css('div.parent > *').each do |child|
  classes = (child['class'] || '').split(/\s+/)
  if((classes & exclude).length > 0)
    array.push(child.text.to_s)
  end
end

The intersection is just an easy way to see if the two arrays have any elements in common (i.e. classes contains anything that you want to exclude).


问:
Functions that return the previous value of a nodejs typescript variable
I hope you can help me, I have these routes that, when making requests to their routes, return the previous value of the request and if I make the request again, it just shows me the data I requested.

```<code>import { BaseProduct, Product } from "./product.interface";
import { Products } from "./products.interface"
import { db } from "../db"
/**
 * query Store
 */

 let products: Products
/**
 * Service Methods
 */
 export const findAll = async (): Promise<Product[]> => {

     db.query('SELECT * FROM bsale_test.product;',(err,results)=>{
      products=Object.values(results)
     })
    return Object.values(products)
};

 export const find = async (id: number): Promise<Product> => {
   db.query(`SELECT * FROM bsale_test.product where id=${id};`,(err,result)=>{
    products=Object.values(result)
   })
  return products[0]
};
</code>```

because when you make the request
GET http://localhost:3000/api/products/109
It shows me the data of the previous request and if I make the request again it just shows me the data of the request.

```<code>{
  "id": 108,
  "name": "PISCO",
  "url_image": "https://dojiw2m9tvv09.cloudfront.net/11132/product/alto8532.jpg",
  "price": 790,
  "discount": 10,
  "category": 2
}
</code>```

what would be the following

```<code>{
  "id": 109,
  "name": "PISCO ",
  "url_image": "https://dojiw2m9tvv09.cloudfront.net/11132/product/alto408581.jpg",
  "price": 5990,
  "discount": 0,
  "category": 2
}
</code>```

my routes

```<code>// GET products
productsRouter.get("/", async (req: Request, res: Response) => {
    try {
      const products: Product[] = await productService.findAll();

      res.status(200).send(products);
    } catch (e:any) {
      res.status(500).send(e.message);
    }
  });
// GET products/:id
productsRouter.get("/:id", async (req: Request, res: Response) => {
    const id: number = parseInt(req.params.id, 10);

    try {
      const product: Product = await productService.find(id);

      if (product) {
        console.log(product)
        return res.status(200).send(product);
      }

      res.status(404).send("product not found");
    } catch (e:any) {
      res.status(500).send(e.message);
    }
  });
</code>```

答:
Problem is that you are returning the value before computing it, thus, you are returning the previous computed value. See the code you have:

```<code> export const findAll = async (): Promise<Product[]> => {

     db.query('SELECT * FROM bsale_test.product;',(err,results)=>{
         products=Object.values(results) // You are assigning the values of products once the db.query completes
     })
    return Object.values(products) // you are returning the value of product instantly, since you are not waiting for db query to finish
};
</code>```

Instead, you should return a couple of Promises. This way, you will return the value you want once the callback of the db.query() is called, after the method is completed.

Try with the following code for your methods:

```<code>export const findAll = async (): Promise<Product[]> => {
    return new Promise<Product[]>((resolve, reject) => {
        db.query('SELECT * FROM bsale_test.product;', (err, results) => {
            if (err) {
                reject(err)
            } else {
                resolve(Object.values(results))

            }
        })
    })
};

export const find = async (id: number): Promise<Product> => {
    return new Promise<Product>((resolve, reject) => {
        db.query(`SELECT * FROM bsale_test.product where id=${id};`,(err, result) => {
            if (err) {
                reject(err)
            } else {
                resolve(Object.values(result))
            }
        })
    }
}
</code>```

Body:
I hope you can help me, I have these routes that, when making requests to their routes, return the previous value of the request and if I make the request again, it just shows me the data I requested.

import { BaseProduct, Product } from "./product.interface";
import { Products } from "./products.interface"
import { db } from "../db"
/**
 * query Store
 */

 let products: Products
/**
 * Service Methods
 */
 export const findAll = async (): Promise<Product[]> => {

     db.query('SELECT * FROM bsale_test.product;',(err,results)=>{
      products=Object.values(results)
     })
    return Object.values(products)
};

 export const find = async (id: number): Promise<Product> => {
   db.query(`SELECT * FROM bsale_test.product where id=${id};`,(err,result)=>{
    products=Object.values(result)
   })
  return products[0]
};

because when you make the request
GET http://localhost:3000/api/products/109
It shows me the data of the previous request and if I make the request again it just shows me the data of the request.

{
  "id": 108,
  "name": "PISCO",
  "url_image": "https://dojiw2m9tvv09.cloudfront.net/11132/product/alto8532.jpg",
  "price": 790,
  "discount": 10,
  "category": 2
}

what would be the following

{
  "id": 109,
  "name": "PISCO ",
  "url_image": "https://dojiw2m9tvv09.cloudfront.net/11132/product/alto408581.jpg",
  "price": 5990,
  "discount": 0,
  "category": 2
}

my routes

// GET products
productsRouter.get("/", async (req: Request, res: Response) => {
    try {
      const products: Product[] = await productService.findAll();

      res.status(200).send(products);
    } catch (e:any) {
      res.status(500).send(e.message);
    }
  });
// GET products/:id
productsRouter.get("/:id", async (req: Request, res: Response) => {
    const id: number = parseInt(req.params.id, 10);

    try {
      const product: Product = await productService.find(id);

      if (product) {
        console.log(product)
        return res.status(200).send(product);
      }

      res.status(404).send("product not found");
    } catch (e:any) {
      res.status(500).send(e.message);
    }
  });

Body:
Problem is that you are returning the value before computing it, thus, you are returning the previous computed value. See the code you have:

 export const findAll = async (): Promise<Product[]> => {

     db.query('SELECT * FROM bsale_test.product;',(err,results)=>{
         products=Object.values(results) // You are assigning the values of products once the db.query completes
     })
    return Object.values(products) // you are returning the value of product instantly, since you are not waiting for db query to finish
};

Instead, you should return a couple of Promises. This way, you will return the value you want once the callback of the db.query() is called, after the method is completed.

Try with the following code for your methods:

export const findAll = async (): Promise<Product[]> => {
    return new Promise<Product[]>((resolve, reject) => {
        db.query('SELECT * FROM bsale_test.product;', (err, results) => {
            if (err) {
                reject(err)
            } else {
                resolve(Object.values(results))

            }
        })
    })
};

export const find = async (id: number): Promise<Product> => {
    return new Promise<Product>((resolve, reject) => {
        db.query(`SELECT * FROM bsale_test.product where id=${id};`,(err, result) => {
            if (err) {
                reject(err)
            } else {
                resolve(Object.values(result))
            }
        })
    }
}


问:
Django Session Variable Is Accessible Even After Deletion
I tried to delete the session after the work is complete. But, it still shows a different value when checking if the session variable exists.

```<code>if 'order_id' in request.session:
    # here the value of session variable is 28
    del request.session['order_id']
    request.session.modified = True
</code>```

When I checked again it returned True even though I deleted the variable,

```<code>if 'order_id' in request.session:
    # here the value of session variable is 5118
    print('yes')
</code>```

答:
your request.session['order_id'] is created for the second time from your another view function after you delete it. That is why you are seeing a different value.

Check all your views.py file where you assigned a value to request.session['order_id'] unknowingly.

Body:
I tried to delete the session after the work is complete. But, it still shows a different value when checking if the session variable exists.

if 'order_id' in request.session:
    # here the value of session variable is 28
    del request.session['order_id']
    request.session.modified = True

When I checked again it returned True even though I deleted the variable,

if 'order_id' in request.session:
    # here the value of session variable is 5118
    print('yes')


问:
How to deal with Xcode "Embed App Extension" build phase
When creating a "Share extension" via adding new target Xcode adds build phase named "Embed App Extension" in app "Build Phases" tab of app target settings. It is possible to remove this phase, but if you try to add it by pressing "+" at the left upper corner you'll find "Embed App Extension" is not listed among available options.

Why is it so? How to embed app extension to the target app without adding new target?

答:
The "Embed App Extension" is just a "Copy File Phase" that has been renamed.

So just use the "+" at the left upper corner, select "New Copy Files Phase", expand it and manually set its properties.

You can also double click on the name of the phase to rename it back to "Embed App Extension".


问:
Pyspark convert df to array of objects
```<code>from pyspark.sql import SparkSession
from pyspark.sql.functions import col

spark = SparkSession.builder.getOrCreate()

simpleData = [("James", "Sales", "NY", 90000, 34, 10000),
                ("Michael", "Sales", "NY", 86000, 56, 20000),
                ("Robert", "Sales", "CA", 81000, 30, 23000),
                ("Maria", "Finance", "CA", 90000, 24, 23000),
                ("Raman", "Finance", "CA", 99000, 40, 24000),
                ("Scott", "Finance", "NY", 83000, 36, 19000),
                ("Jen", "Finance", "NY", 79000, 53, 15000),
                ("Jeff", "Marketing", "CA", 80000, 25, 18000),
                ("Kumar", "Marketing", "NY", 91000, 50, 21000)
                ]
schema = ["employee_name", "department",
            "state", "salary", "age", "bonus"]
df = spark.createDataFrame(data=simpleData, schema=schema)
data = df.groupBy("department").count() \
    .select(col("department").alias("name"), col("count").alias("value")) \
    .toJSON().collect()
print(data)

spark.stop()
</code>```

When I ran the code it gives an array string:

```<code>[
 '{"name":"Sales","value":3}',
 '{"name":"Finance","value":4}',
 '{"name":"Marketing","value":2}'
]
</code>```

but I don't want an array string, I want an array object to send to frontend

```<code>[
 {"name":"Sales","value":3},
 {"name":"Finance","value":4},
 {"name":"Marketing","value":2}
]
</code>```

Can anyone help me?

答:
Remove the toJSON() and use the following list comprehension

```<code>[d.asDict() for d in data]
</code>```

Title: Pyspark convert df to array of objects

Body:
from pyspark.sql import SparkSession
from pyspark.sql.functions import col

spark = SparkSession.builder.getOrCreate()

simpleData = [("James", "Sales", "NY", 90000, 34, 10000),
                ("Michael", "Sales", "NY", 86000, 56, 20000),
                ("Robert", "Sales", "CA", 81000, 30, 23000),
                ("Maria", "Finance", "CA", 90000, 24, 23000),
                ("Raman", "Finance", "CA", 99000, 40, 24000),
                ("Scott", "Finance", "NY", 83000, 36, 19000),
                ("Jen", "Finance", "NY", 79000, 53, 15000),
                ("Jeff", "Marketing", "CA", 80000, 25, 18000),
                ("Kumar", "Marketing", "NY", 91000, 50, 21000)
                ]
schema = ["employee_name", "department",
            "state", "salary", "age", "bonus"]
df = spark.createDataFrame(data=simpleData, schema=schema)
data = df.groupBy("department").count() \
    .select(col("department").alias("name"), col("count").alias("value")) \
    .toJSON().collect()
print(data)

spark.stop()

When I ran the code it gives an array string:

[
 '{"name":"Sales","value":3}',
 '{"name":"Finance","value":4}',
 '{"name":"Marketing","value":2}'
]

but I don't want an array string, I want an array object to send to frontend

[
 {"name":"Sales","value":3},
 {"name":"Finance","value":4},
 {"name":"Marketing","value":2}
]

Can anyone help me?

Body:
Remove the toJSON() and use the following list comprehension

[d.asDict() for d in data]


问:
How can i configure my Geany Text Editor like this below picture?
Geany with Cool Font & Theme

In this picture above, i want to know which font & which theme is this ?

I also want to configure my Geany Text Editor like above picture.
I tried myfont.com, whatfontis.com & fontsquirrel also but unable to find the name of this font.

答:
On Debian/Ubuntu font is set in ~/.config/geany/geany.conf Look the settings matching pattern: *_font.

According to the documentation, font settings is also available in UI: Preferences > Interface Preferences > Fonts