问:
ExperimentHandler CSV output value separator environment dependant
(I'm not a pyschologist nor pysychopy export but helping one)
We're developing an expirement using the Coder (not Builder).

The output of an experiment is written out using the data.ExperimentHandler.addData().
When I run the application on my machine I get output like this:

```<code>,,1,1,z,f,o,o,1.254349554568762,0.8527608618387603,0.0,1.0,FSAS,,,,,,,,,,,,,,,52,male,52,
</code>```

When the other person runs the application she gets:

```<code>;;0;1;z;z;j;j;105.498.479.999.369;0.501072800019756;1.0;1.0;FNES;;;;;;;;;;;;;;;23;male;0
</code>```

(the difference I want to show is about format, not the values)

There are 2 differences:

RT values > 1 are printed wrong: the value 105.498.479.999.369 (RT less then 1.5s) should be 1.05498479999369

value separator is ; in my output and , in hers. I don't know what is the best value separator comma or semilcolon for later processing in R ?

I think it has to do something with regional settings.

Question: Is it possible to force the format so the application always generates the same output format independant from local settings ?

答:
You don't specify whether you are using the graphical Builder interface to PsychoPy to generate your Python script, or writing a custom script directly in Python.

If using the Builder interface, click the "Experiment settings" toolbar icon select the "Data" tab, and specify that the datafile delimiter should be "comma" rather than "auto".

If running your own script, then in the saveAsWideText() method of the ExperimentHandler class, similarly specify ',' as the delim parameter. The API is here:
https://psychopy.org/api/data.html

In future, you will likely get better support at the dedicated PsychoPy forum at https://discourse.psychopy.org
The actual PsychoPy developers and other experienced users are much more likely to see your queries there compared to here at StackOverflow.

Body:
(I'm not a pyschologist nor pysychopy export but helping one)
We're developing an expirement using the Coder (not Builder).

The output of an experiment is written out using the data.ExperimentHandler.addData().
When I run the application on my machine I get output like this:

,,1,1,z,f,o,o,1.254349554568762,0.8527608618387603,0.0,1.0,FSAS,,,,,,,,,,,,,,,52,male,52,

When the other person runs the application she gets:

;;0;1;z;z;j;j;105.498.479.999.369;0.501072800019756;1.0;1.0;FNES;;;;;;;;;;;;;;;23;male;0

(the difference I want to show is about format, not the values)

There are 2 differences:

RT values > 1 are printed wrong: the value 105.498.479.999.369 (RT less then 1.5s) should be 1.05498479999369

value separator is ; in my output and , in hers. I don't know what is the best value separator comma or semilcolon for later processing in R ?

I think it has to do something with regional settings.

Question: Is it possible to force the format so the application always generates the same output format independant from local settings ?


来源: stackexchange

问:
Symfony/MySQL: full text search syntax error for special chars
I've got a problem with full-text search query. It is being sent from the inside of Symfony (2.8) controller, if that's important. The code is:

```<code>// not processed text (apart from multiple spaces) from form:
$searchTerm = preg_replace('!\s+!', ' ', trim($data['query']));
// for full-text search:
$searchTermPhrase = str_replace(' ', '* ', $searchTerm) . '*';

$entityManager = $this->getDoctrine()->getManager();
// as far as I remember, query taken from StackOverflow after some tests
$statement = $entityManager->getConnection()
                           ->prepare(
                             "SELECT COUNT(id) AS books_count
                              FROM book
                              WHERE
                              MATCH(title) AGAINST (:searchTermPhrase IN BOOLEAN MODE) > 5
                              AND active = true
                              ");
$statement->execute(array('searchTermPhrase' => $searchTermPhrase));

$titlesCount = $statement->fetch();
$titlesCount = $titlesCount['books_count'];
</code>```

Now, it works great. Most of the time. But if user puts some special chars inside, for example (title), "title" etc., it fails:

```<code>SQLSTATE[42000]: Syntax error or access violation:
1064 syntax error, unexpected $end, expecting
FTS_TERM or FTS_NUMB or '*'
</code>```

I don't get it, I use parametrized query, it should automatically take care of such cases...? I don't want to end up stripping all non-alphanumeric characters, or testing, which exactly cause problems, but I'm out of ideas.

答:
Well, as mentioned, got the same problem. I looked at our code and it is clear that BOOLEAN MODE causes this problems.

First of all: "title" should work, while "title should throw the error above.

Take a look at all the boolean operators: https://dev.mysql.com/doc/refman/8.0/en/fulltext-boolean.html

With this mode you can provide great search experience by letting the user search for apples but not bananas: +apple -banana. But wrongly entered Parenthesis or Quotes break it logic.

Question is: is there a regex or function to detect if the search term is valid for boolean mode? Else it should default to natural language mode.

ContentLicense: CC BY-SA 3.0

Body:
I've got a problem with full-text search query. It is being sent from the inside of Symfony (2.8) controller, if that's important. The code is:

// not processed text (apart from multiple spaces) from form:
$searchTerm = preg_replace('!\s+!', ' ', trim($data['query']));
// for full-text search:
$searchTermPhrase = str_replace(' ', '* ', $searchTerm) . '*';

$entityManager = $this->getDoctrine()->getManager();
// as far as I remember, query taken from StackOverflow after some tests
$statement = $entityManager->getConnection()
                           ->prepare(
                             "SELECT COUNT(id) AS books_count
                              FROM book
                              WHERE
                              MATCH(title) AGAINST (:searchTermPhrase IN BOOLEAN MODE) > 5
                              AND active = true
                              ");
$statement->execute(array('searchTermPhrase' => $searchTermPhrase));

$titlesCount = $statement->fetch();
$titlesCount = $titlesCount['books_count'];

Now, it works great. Most of the time. But if user puts some special chars inside, for example (title), "title" etc., it fails:

SQLSTATE[42000]: Syntax error or access violation:
1064 syntax error, unexpected $end, expecting
FTS_TERM or FTS_NUMB or '*'

I don't get it, I use parametrized query, it should automatically take care of such cases...? I don't want to end up stripping all non-alphanumeric characters, or testing, which exactly cause problems, but I'm out of ideas.

ContentLicense: CC BY-SA 4.0


问:
How to return the content of the
```
<p>.</p>
```url = 'https://unminify.com/'
browser.get(url)
elements = browser.find_elements_by_xpath('/html/body/script[1]')
type_ = [e.get_attribute('type') for e in elements]
text_ = [e.text for e in elements]
```

I get an empty list for text and attribute.

screenshot from inspecting the page

答:
you can create a script element and access its contents with the variable of the create element + ".text"

OR

you can put an id for a script element and access its contents with document.getElementById("scriptId").text

(you should change "scriptId" to the id of the script)

var myJs = document.getElementById("myJs");
console.log(myJs.text);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script id="myJs">
alert("This is myJs in action.");
</script></code>```

Title: How to return the content of the <script> element with python

Body:
I am trying to access the content of the script element of a generic website with Selenium.

.

url = 'https://unminify.com/'
browser.get(url)
elements = browser.find_elements_by_xpath('/html/body/script[1]')
type_ = [e.get_attribute('type') for e in elements]
text_ = [e.text for e in elements]

I get an empty list for text and attribute.

screenshot from inspecting the page

Body:
you can create a script element and access its contents with the variable of the create element + ".text"

OR

you can put an id for a script element and access its contents with document.getElementById("scriptId").text

(you should change "scriptId" to the id of the script)

var myJs = document.getElementById("myJs");
console.log(myJs.text);

<script id="myJs">
alert("This is myJs in action.");
</script>


问:
What is the diff between sls deploy and serverless deploy?
What is the dff between sls deploy and serverless deploy?
sls deploy vs serverless deploy

答: No difference. sls is a symbolic link to serverless.


问:
Please help me to sort this kinda lists
first of all, im still kinda new to coding and have not that much knowledge ^^
So here is my problem, I need to create a class/method that can sort a list, that look like this:

```<code>.Add("1");
.Add("1.1");
.Add("1.2");
.Add("1.1.1-1");
.Add("1.1.1-1usa");
.Add("7.2");
.Add("8.");
.Add("9.");
.Add("10.1)
</code>```

the list should be ascend(?) meaning, it starts with the lowest number going up to the highest.

I tried to make char arrays out of them and then compare each char with an if-statement.
some mor informations: 1.1.1 > 1.1 and as you can see, there are also letters inside. If someone has an idea I would be very thankful for every tip :)

NOTE: if I would sort it like list.Sort();, 10.1 wouldnt come right after 9, instead its bewtween 1.1 and 2.1 for example

答:
Again a big thanks to everyone. This is the solution i decided to take advantage of:</p>
```<code>Numbers= Numbers.OrderBy(v => string.Concat(v.Split('.').Select(x => x.PadLeft(5, '0')))).ToList();
</code>```

Title: Please help me to sort this kinda lists

Body:
first of all, im still kinda new to coding and have not that much knowledge ^^
So here is my problem, I need to create a class/method that can sort a list, that look like this:

.Add("1");
.Add("1.1");
.Add("1.2");
.Add("1.1.1-1");
.Add("1.1.1-1usa");
.Add("7.2");
.Add("8.");
.Add("9.");
.Add("10.1)

the list should be ascend(?) meaning, it starts with the lowest number going up to the highest.

I tried to make char arrays out of them and then compare each char with an if-statement.
some mor informations: 1.1.1 > 1.1 and as you can see, there are also letters inside. If someone has an idea I would be very thankful for every tip :)

NOTE: if I would sort it like list.Sort();, 10.1 wouldnt come right after 9, instead its bewtween 1.1 and 2.1 for example

Body:
Again a big thanks to everyone. This is the solution i decided to take advantage of:

Numbers= Numbers.OrderBy(v => string.Concat(v.Split('.').Select(x => x.PadLeft(5, '0')))).ToList();


问:
How to upload file using selenium python in Headless browser for HTML element [type=button]
```<code><button id="upload-button" class="btn btn-default ml-2 ng-pristine ng-valid ng-not-empty ng-
touched" type="button" ng-model="files" ngf-select="uploadFiles($files)" ngf-pattern="pattern"
accept="application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document,text/plain,application/xml,application/x-zip-compressed"
multiple="multiple" ngf-keep="true" ngf-valid-only="false" ngf-validate-fn="validate($file,
invalidFiles)" ngf-model-invalid="invalidFiles" aria-invalid="false" style="">Select file(s)... </button>
</code>```

This is the HTML code to upload files. When I click this button it is opening a windows filedalogue to upload files.

I tried send_keys() method but it is not working for this type=button

```<code>button = self.browser.find_element_by_id('upload-button')
button.send_keys(filepath)
</code>```

So I tried python library pyautogui to handle the filedialogue but it is not working in Headless browser.
Anyone can help me out of this problem using python + selenium , it should work in headless browser.

答:
Uploading a file with Selenium is NOT done by sending the file to a button user clicks to open upload dialog etc.

There is a special invisible element on the page that is actually accepting the uploaded file.

This element can be located by this XPath: //input[@type='file'].

So uploading file with Selenium is done by:

button = self.browser.find_element_by_xpath("//input[@type='file']")
button.send_keys(filepath)
```

Body:
<button id="upload-button" class="btn btn-default ml-2 ng-pristine ng-valid ng-not-empty ng-
touched" type="button" ng-model="files" ngf-select="uploadFiles($files)" ngf-pattern="pattern"
accept="application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document,text/plain,application/xml,application/x-zip-compressed"
multiple="multiple" ngf-keep="true" ngf-valid-only="false" ngf-validate-fn="validate($file,
invalidFiles)" ngf-model-invalid="invalidFiles" aria-invalid="false" style="">Select file(s)... </button>

This is the HTML code to upload files. When I click this button it is opening a windows filedalogue to upload files.

I tried send_keys() method but it is not working for this type=button

button = self.browser.find_element_by_id('upload-button')
button.send_keys(filepath)

So I tried python library pyautogui to handle the filedialogue but it is not working in Headless browser.
Anyone can help me out of this problem using python + selenium , it should work in headless browser.


问:
Align button and image vertically
I wanted to align button and Image vertically in center, right now button is showing on top of line, I am using bootstrap, can anyone help?

```<code><div class="col-md-12">
<div class="col-md-5" style="margin-left: -37px;"><p class="imageSveMsg" style="display:none">Save</p><button style="display:none" fieldid="81" class="saveimgbtn fileUpload btn btn-primary">Save Image</button>
<div class="fileUpload hideFileUpload btn btn-primary">  <span class="chooseimagetext"><b>Change Image</b></span><input rowid="submission_81" id="uploadImage" onchange="PreviewImage();" tabindex="13" type="file" name="matrix_submission_data81" accept="image/png, image/jpeg , image/jpeg" class="upload   matrix_submission_draft  ">
 </div></div>
 <div class="col-md-4">
<input type="hidden" name="oldmatrix_submission_data81" value="16440505543.png"><img id="uploadPreview" src="https://staging-reconresearchlive.kinsta.cloud/wp-content/plugins/matrix-engine/includes/submission_images/16440505543.png" width="50px !important;" height="50px !important;" style="margin-left:30px;max-width: 200px;max-height: 100px;min-height: 100px;vertical-align: middle !important;"></div></div>
</code>```

css:

```<code>.fileUpload {
    position: relative;
    overflow: hidden;
    margin: 10px;
    background-color: #E2A169 !important;
    border-color: #E2A169 !important;
}
img{
margin-left: 30px;
    max-width: 200px;
    max-height: 100px;
    min-height: 100px;
    vertical-align: middle !important;
}
</code>```

Output:
Current Output Image

答:
You can use align-items: center

Please check fiddle
https://jsfiddle.net/zc5axdnr/1/

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
<!DOCTYPE html>

          Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras nec lorem eu leo interdum mollis at quis ligula. Sed pharetra ante metus, sed fermentum diam efficitur vitae. Pellentesque ac porttitor nunc. Mauris lacus quam, facilisis sed congue vulputate, aliquam nec nibh. Maecenas et nulla lacus. Fusce commodo egestas mauris, ut viverra sapien cursus id. Morbi cursus tristique posuere. Pellentesque tincidunt nulla id commodo fermentum. Phasellus sit amet imperdiet orci, eget cursus ipsum. Duis quis metus nunc. Curabitur ex ipsum, suscipit non erat sit amet, lacinia pharetra mi.

Ut vel velit ante. Duis facilisis nisi in sapien posuere gravida. Proin mollis nibh tellus, vitae sodales purus tincidunt eget. Praesent a ullamcorper justo. Integer mollis porttitor sem. Pellentesque vulputate et justo eget blandit. Praesent non lacus mauris. Nam urna ligula, interdum egestas dictum quis, hendrerit pulvinar lorem. Quisque varius eros felis, a dapibus leo consequat eget. Nulla laoreet eros dui, laoreet laoreet libero cursus ullamcorper. Suspendisse hendrerit consequat purus, vel tincidunt risus blandit sed. Nulla mattis laoreet urna quis blandit. Donec et odio facilisis metus congue dictum rhoncus eget turpis. Suspendisse aliquet sit amet ligula quis pellentesque. Cras ullamcorper nec magna id aliquam.

            <button class="btn btn-primary">
            Button
            </button>

```

Title: Align button and image vertically

Body:
I wanted to align button and Image vertically in center, right now button is showing on top of line, I am using bootstrap, can anyone help?

Save
<button style="display:none" fieldid="81" class="saveimgbtn fileUpload btn btn-primary">Save Image</button>

  Change Image<input rowid="submission_81" id="uploadImage" onchange="PreviewImage();" tabindex="13" type="file" name="matrix_submission_data81" accept="image/png, image/jpeg , image/jpeg" class="upload   matrix_submission_draft  ">

<input type="hidden" name="oldmatrix_submission_data81" value="16440505543.png">

css:

.fileUpload {
    position: relative;
    overflow: hidden;
    margin: 10px;
    background-color: #E2A169 !important;
    border-color: #E2A169 !important;
}
img{
margin-left: 30px;
    max-width: 200px;
    max-height: 100px;
    min-height: 100px;
    vertical-align: middle !important;
}

Output:
Current Output Image

Body:
You can use align-items: center

Please check fiddle
https://jsfiddle.net/zc5axdnr/1/

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
<!DOCTYPE html>
<html>

<head>

</head>

<body>
    <div class="container">
        <div class="row" style="align-items: center;">
          <div class="col-6">
          Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras nec lorem eu leo interdum mollis at quis ligula. Sed pharetra ante metus, sed fermentum diam efficitur vitae. Pellentesque ac porttitor nunc. Mauris lacus quam, facilisis sed congue vulputate, aliquam nec nibh. Maecenas et nulla lacus. Fusce commodo egestas mauris, ut viverra sapien cursus id. Morbi cursus tristique posuere. Pellentesque tincidunt nulla id commodo fermentum. Phasellus sit amet imperdiet orci, eget cursus ipsum. Duis quis metus nunc. Curabitur ex ipsum, suscipit non erat sit amet, lacinia pharetra mi.

Ut vel velit ante. Duis facilisis nisi in sapien posuere gravida. Proin mollis nibh tellus, vitae sodales purus tincidunt eget. Praesent a ullamcorper justo. Integer mollis porttitor sem. Pellentesque vulputate et justo eget blandit. Praesent non lacus mauris. Nam urna ligula, interdum egestas dictum quis, hendrerit pulvinar lorem. Quisque varius eros felis, a dapibus leo consequat eget. Nulla laoreet eros dui, laoreet laoreet libero cursus ullamcorper. Suspendisse hendrerit consequat purus, vel tincidunt risus blandit sed. Nulla mattis laoreet urna quis blandit. Donec et odio facilisis metus congue dictum rhoncus eget turpis. Suspendisse aliquet sit amet ligula quis pellentesque. Cras ullamcorper nec magna id aliquam.

          </div>
          <div class="col-6 align-items-center">
            <button class="btn btn-primary">
            Button
            </button>
          </div>
        </div>
    </div>
</body>

</html>


问:
Null Pointer Exception for read properties file in Idea
after define a property file in idea 10.5 when i try to use it,compiler show me Null Pointer Exception!I try anything that i think fix it among change property file path,...
here is the code that i write:
thanks.
beginner programmer!!!</p>

```<code>public class MainDlg{
    Properties properties=new Properties();
    public MainDlg() {
        try {
            InputStream reader=MainDlg.class.getResourceAsStream("propFile");
            properties.load(reader);
</code>```

答:
Sounds like the reader is null. Make sure the path is correct.

If property file is the root then you should

```<code>InputStream reader=MainDlg.class.getResourceAsStream("/propFile");
</code>```

Body:
after define a property file in idea 10.5 when i try to use it,compiler show me Null Pointer Exception!I try anything that i think fix it among change property file path,...
here is the code that i write:
thanks.
beginner programmer!!!

public class MainDlg{
    Properties properties=new Properties();
    public MainDlg() {
        try {
            InputStream reader=MainDlg.class.getResourceAsStream("propFile");
            properties.load(reader);

Body:
Sounds like the reader is null. Make sure the path is correct.

If property file is the root then you should

InputStream reader=MainDlg.class.getResourceAsStream("/propFile");


问:
Is there a way to pre-run tests on the would-be merge commit, if branch were merged, before merge?
We are automatically running tests on feature branches. After the feature is complete and tests pass, it is merged into the main branch.

But now we have to wait for tests to run on master, before deploying it (manually).

So, is there a way to automatically run tests on the would-be merge commit for the Feature Branch, before it is merged to master?

If that were possible, then we would know that tests on master will pass after the Feature Branch is merged.

答:
For this the merged results pipelines might be useful for you. Take a look at https://docs.gitlab.com/ee/ci/pipelines/merged_results_pipelines.html

Quoting from docs

A merged results pipeline is a type of merge request pipeline. It is a
pipeline that runs against the results of the source and target
branches merged together.

So you could have the tests run preemptively and run the deploy manually

This functionality is available if your organization has a Gitlab account which is at least in PREMIUM tier.

By default they are not enabled, to enable merged results pipelines in a project, you must have at least the Maintainer role:

On the top bar, select Menu > Projects and find your project.

On the left sidebar, select Settings > General.

Expand Merge requests.

Select Enable merged results pipelines.

Select Save changes.


问:
How to make absolute element in relative element responsive?
I have problem with change size while manipulating browser size. I need to keep one column on another so I use relative + absolute combination.

I'm wondering if there is an option with only CSS to make such element responsive.

```<code><div class="clock">
 <div id="apDiv3" class="opening">

   <div class="clock">

    <img id="apDiv2" class="clock" src="./assets/stoper-01.png" usemap="#image-map">
    <img id="apDiv1" class="clockArrow" src="./assets/stoper-01-arrow.png">

   <map name="image-map">
    <area area settings>
    ...
   </map>

  </div>
 </div>
</div>
</code>```
```<code>div.clock {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}
img.clock {
  position: relative;
}
.clockArrow {
  position: absolute;
}

</code>```

答:
You could try using the CSS calc() function like the given eg.

```<code>.top-img{
  ...
  width: calc(var(--background-img-width) - var(--offset));
  ...
}
</code>```

Here, add --background-ing-width to your :root and apply it in .background-img's  width. Then you can add --offset in your :root and add to .top-img as shown and tweak these two variables to your liking.

Body:
I have problem with change size while manipulating browser size. I need to keep one column on another so I use relative + absolute combination.

I'm wondering if there is an option with only CSS to make such element responsive.

   <map name="image-map">
    <area area settings>
    ...
   </map>

div.clock {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}
img.clock {
  position: relative;
}
.clockArrow {
  position: absolute;
}

Body:
You could try using the CSS calc() function like the given eg.

.top-img{
  ...
  width: calc(var(--background-img-width) - var(--offset));
  ...
}

Here, add --background-ing-width to your :root and apply it in .background-img's  width. Then you can add --offset in your :root and add to .top-img as shown and tweak these two variables to your liking.


问:
composer git repository checkout as git-repo and not as a copy
I've a composer based TYPO3 installation, which contains a private gitlab-repository. The private git-repository should be used as dev-master (as a real repository) so that I'm able to develope inside. But composer checks out only the master repository files, but without the .git folder.

Any clue what's wrong? In some other projects this works like expected.

My composer.json:

{
    "name": "my-vendor/my-project",
    "description" : "TYPO3 CMS Website",
    "license": "GPL-2.0-or-later",
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "platform-check": false,
        "allow-plugins": {
            "typo3/class-alias-loader": true,
            "typo3/cms-composer-installers": true,
            "captainhook/plugin-composer": true
        }
    },
    "repositories": [
        { "type": "composer", "url": "https://composer.typo3.org/" },
        { "type": "path", "url": "./packages/*" },
        { "type": "vcs", "url": "git@gitlab.com:myvendor/typo3-amp.git" }
    ],
    "require": {
        "typo3/cms-about": "^11.0",
        "typo3/cms-backend": "^11.0",
        "typo3/cms-belog": "^11.0",
        "typo3/cms-beuser": "^11.0",
        "typo3/cms-core": "^11.0",
        "typo3/cms-dashboard": "^11.0",
        "typo3/cms-extbase": "^11.0",
        "typo3/cms-extensionmanager": "^11.0",
        "typo3/cms-felogin": "^11.0",
        "typo3/cms-filelist": "^11.0",
        "typo3/cms-fluid": "^11.0",
        "typo3/cms-fluid-styled-content": "^11.0",
        "typo3/cms-form": "^11.0",
        "typo3/cms-frontend": "^11.0",
        "typo3/cms-info": "^11.0",
        "typo3/cms-install": "^11.0",
        "typo3/cms-lowlevel": "^11.0",
        "typo3/cms-opendocs": "^11.0",
        "typo3/cms-recordlist": "^11.0",
        "typo3/cms-recycler": "^11.0",
        "typo3/cms-redirects": "^11.0",
        "typo3/cms-reports": "^11.0",
        "typo3/cms-rte-ckeditor": "^11.0",
        "typo3/cms-scheduler": "^11.0",
        "typo3/cms-seo": "^11.0",
        "typo3/cms-setup": "^11.0",
        "typo3/cms-sys-note": "^11.0",
        "typo3/cms-t3editor": "^11.0",
        "typo3/cms-tstemplate": "^11.0",
        "typo3/cms-viewpage": "^11.0",
        "helhum/typo3-console": "~7.0",
        "my-vendor/sitepackage": "@dev",
        "my-vendor/amp": "dev-master as 2.0.0",
        "ext-simplexml": "*",
        "ext-pdo": "*",
        "ext-zip": "*",
        "ext-libxml": "*",
        "ext-curl": "*",
        "ext-gd": "*",
        "ext-json": "*"
    },
    "require-dev": {
        "phpstan/phpstan": "^0.12.98",
        "saschaegerer/phpstan-typo3": "^0.13.3",
        "friendsofphp/php-cs-fixer": "^3.0",
        "captainhook/captainhook": "^5.10",
        "captainhook/plugin-composer": "^5.3",
        "rector/rector": "0.11.53"
    },
    "extra": {
        "captainhook": {
            "force-install": true
        }
    },
    "scripts": {
        "php-cs-fixer": "vendor/bin/php-cs-fixer fix packages",
        "phpstan": "vendor/bin/phpstan analyse",
        "rector": "vendor/bin/rector process packages",
        "ci": [
            "@php-cs-fixer",
            "@phpstan",
            "@rector"
        ]
    }
}
```

答:
Let's have a look in the manual:

If you set the no-api key to true on a github repository it will clone the repository as it would with any other git repository instead of using the GitHub API. But unlike using the git driver directly, Composer will still attempt to use github's zip files.

The simple trick seems to be not to use the vcs driver but instead the git driver for the private repo...


问:
Where to place ||
I know that this is a really simple question, but where should I place the || below if I want to check for both CAF and AAC? Thanks!</p>

```<code>if ([[file pathExtension] isEqualToString:@"caf"])
</code>```

答:
```<code>if ([[file pathExtension] isEqualToString:@"caf"] ||
    [[file pathExtension] isEqualToString:@"aac"] )
</code>```

Note - this is a literal comparison so it is not case insensitive - if you want to do a case insensitive comparison:

```<code>if ([[file pathExtension] compare:@"caf" options:NSCaseInsensitiveSearch] == NSOrderedSame ||
    [[file pathExtension] compare:@"aac" options:NSCaseInsensitiveSearch] == NSOrderedSame)
</code>```

Title: Where to place ||

Body:
I know that this is a really simple question, but where should I place the || below if I want to check for both CAF and AAC? Thanks!

if ([[file pathExtension] isEqualToString:@"caf"])

Body:
if ([[file pathExtension] isEqualToString:@"caf"] ||
    [[file pathExtension] isEqualToString:@"aac"] )

Note - this is a literal comparison so it is not case insensitive - if you want to do a case insensitive comparison:

if ([[file pathExtension] compare:@"caf" options:NSCaseInsensitiveSearch] == NSOrderedSame ||
    [[file pathExtension] compare:@"aac" options:NSCaseInsensitiveSearch] == NSOrderedSame)


问:
Provisioning profile “match x” doesn't include signing certificate “Apple Distribution: Company (ID)” when using fastlane match
This error was encountered while trying to build one of our apps that had signing via fastlane match set up. </p>

答: I got the same error. In my case, I had to delete the old ones from my macs Keychain. After that fastlane did its magic.</p>


问:
in trim function there's an if-check not working properly, why?
EDIT: I've edited my code, and this is the result:

```<code>#include <stdlib.h>
#include <ctype.h>

char *trim(const char *s) {
    if (s == NULL) {
        return NULL;
    }
    size_t count_1 = 0;
    for (size_t i = 0; s[i] != '\0'; i++) {
        count_1++;
    }
    if (count_1 < 1) {
        return NULL;
    }
    size_t count_2 = 0;
    if (isspace(s[0])) {
        count_2++;
    }
    if (isspace(s[count_1 - 1])) {
        count_2++;
    }
    size_t max_length = (count_1 - count_2) + 1u;
    if (max_length >= count_1) {
        return NULL;
    }
    char *str = malloc(max_length);
    if (!str) {
        return NULL;
    }
    for (size_t i = 0; s[i] != '\0'; i++) {
        if (isspace(s[i]) == 0) { // if isspace is false.
            str[i] = s[i];
        }
    }
    str[count_1 - count_2] = 0;
    return str;
}

int main(void) {
    char s[] = " a b ";
    char *str;
    str = trim(s);

    free(str);
    return 0;
}
</code>```

now, the problem is here

```<code>    for (size_t i = 0; s[i] != '\0'; i++) {
        if (isspace(s[i]) == 0) { // if isspace is false.
            str[i] = s[i];
        }
</code>```

I have a buffer overrun, even if I've checked the length. In fact, if count_1 is equal to zero, I have a buffer overrun error, but I've excluded this case, but the problem persists. By debugging line-by-line, I've noticed I have an undefined behavior.

I wanted to try to simplify the suggested solution for this exercise, therefore I've written another code for the same exercise.

this is the original answer: trim function halve the memory size to remove the whitespaces?

this is the minimal reproducible code:

```<code>#include <stdlib.h>
#include <ctype.h>

char *trim(const char *s) {
    size_t count_1 = 0;
    for (size_t i = 0; s[i] != '\0'; i++) {
        count_1++;
    }
    size_t count_2 = 0;
    if (isspace(s[0])) {
        count_2++;
    }
    if (isspace(s[count_1])) {
        count_2++;
    }
    size_t max_length = (count_1 - count_2) + 1u;
    if (max_length >= count_1) {
        return NULL;
    }
    char *str = malloc(max_length);
    if (!str) {
        return NULL;
    }
    for (size_t i = 0; s[i] != '\0'; i++) {
        if (isalpha(s[i]) == 0) { // if isalpha is false.
            str[i] = s[i];
        }
        str[count_1 - count_2] = 0;
    }
    return str;
}

int main(void) {
    char s[] = " a b ";
    char *str;
    str = trim(s);

    free(str);
    return 0;
}
</code>```

here's the detailed explanation about what I've done so far:

I've counted characters of the string s, and the length is stored in count_1.

I've counted how many whitespaces I have at the beginning of the string, and at the end of the string; and the amount is stored in count_2.

note: I've chosen to use isspace function (in <ctype.h>), because I tried to type ' ' (i.e a whitespace), but the result is not correct, and these if-checks are not evaluated whatsoever. (I used the debugger line-by-line to state this thing).

before malloc the memory I've used a check condition to avoid buffer overrun (it's similar to the question I asked yesterday), meaning I've allocated enough memory if and only if max_length is less than count_1. doing this way, I have no buffer overrun warning.

I think I can avoid to explain the final steps, because they are self explanatory and I also think they doesn't cause errors. If I'm wrong, I'll edit this point.

issue I have no clue how to fix it:

by debugging line-by-line, I've noticed that when the flow of execution goes to the 2nd if-check, the if body is not executed whatsoever. And this is strange, because the first one works fine.

答:
There are multiple problems in your code:

count_1 is the length of the string, you should name it more explicitly as len

you return NULL if no trimming is needed. This is questionable. You should probably return a copy of the string in all cases and only return NULL in case of allocation failure.

you only test for 1 space char at the start of the string.

you only test for 1 space char at the end of the string.

furthermore this space might be counted twice if the string is " ".

max_length is a misnomer: it is not the length of the new string, but the allocation size, new_size seems more appropriate.

in the final loop, you use the same index i into the original and the new string: this is incorrect. You should use a separate index so characters from the original string can be copied after skipping the initial space.

str[count_1 - count_2] = 0; is redundant inside the loop: you should move this statement after the end of the loop.

argument values of type char should be cast as (unsigned char) when passed to the functions and macros defined in <ctype.h> to avoid undefined behavior on negative values on platforms where the char type is signed. These functions are only defined for the values of type unsigned char (between 0 and UCHAR_MAX) and the special negative value EOF. These values are the ones returned by getchar() and getc().

Here is a modified version:

```<code>#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>

char *trim(const char *s) {
    if (s == NULL) {
        return NULL;
    }
    size_t start, end;
    for (start = 0; isspace((unsigned char)s[start]); start++) {
        continue;
    }
    for (end = start; s[end] != '\0'; end++) {
        continue;
    }
    while (end > start && isspace((unsigned char)s[end - 1])) {
        end--;
    }
    // if you are allowed to use strndup, you can return the new string this way:
    //return strndup(str + start, end - start);

    char *new_str = malloc(end - start + 1);
    if (new_str) {
        size_t j = 0;  // index into the new string
        for (size_t i = start; i < end; i++) {
            new_str[j++] = str[i];
        }
        new_str[j] = '\0';
    }
    return new_str;
}

int main(void) {
    char s[] = " a b ";
    char *str = trim(s);
    printf("trim(\"%s\") -> \"%s\"\n", s, str);
    free(str);
    return 0;
}
</code>```

Body:
EDIT: I've edited my code, and this is the result:

#include <stdlib.h>
#include <ctype.h>

char *trim(const char *s) {
    if (s == NULL) {
        return NULL;
    }
    size_t count_1 = 0;
    for (size_t i = 0; s[i] != '\0'; i++) {
        count_1++;
    }
    if (count_1 < 1) {
        return NULL;
    }
    size_t count_2 = 0;
    if (isspace(s[0])) {
        count_2++;
    }
    if (isspace(s[count_1 - 1])) {
        count_2++;
    }
    size_t max_length = (count_1 - count_2) + 1u;
    if (max_length >= count_1) {
        return NULL;
    }
    char *str = malloc(max_length);
    if (!str) {
        return NULL;
    }
    for (size_t i = 0; s[i] != '\0'; i++) {
        if (isspace(s[i]) == 0) { // if isspace is false.
            str[i] = s[i];
        }
    }
    str[count_1 - count_2] = 0;
    return str;
}

int main(void) {
    char s[] = " a b ";
    char *str;
    str = trim(s);

    free(str);
    return 0;
}

now, the problem is here

    for (size_t i = 0; s[i] != '\0'; i++) {
        if (isspace(s[i]) == 0) { // if isspace is false.
            str[i] = s[i];
        }

I have a buffer overrun, even if I've checked the length. In fact, if count_1 is equal to zero, I have a buffer overrun error, but I've excluded this case, but the problem persists. By debugging line-by-line, I've noticed I have an undefined behavior.

I wanted to try to simplify the suggested solution for this exercise, therefore I've written another code for the same exercise.

this is the original answer: trim function halve the memory size to remove the whitespaces?

this is the minimal reproducible code:

#include <stdlib.h>
#include <ctype.h>

char *trim(const char *s) {
    size_t count_1 = 0;
    for (size_t i = 0; s[i] != '\0'; i++) {
        count_1++;
    }
    size_t count_2 = 0;
    if (isspace(s[0])) {
        count_2++;
    }
    if (isspace(s[count_1])) {
        count_2++;
    }
    size_t max_length = (count_1 - count_2) + 1u;
    if (max_length >= count_1) {
        return NULL;
    }
    char *str = malloc(max_length);
    if (!str) {
        return NULL;
    }
    for (size_t i = 0; s[i] != '\0'; i++) {
        if (isalpha(s[i]) == 0) { // if isalpha is false.
            str[i] = s[i];
        }
        str[count_1 - count_2] = 0;
    }
    return str;
}

int main(void) {
    char s[] = " a b ";
    char *str;
    str = trim(s);

    free(str);
    return 0;
}

here's the detailed explanation about what I've done so far:

I've counted characters of the string s, and the length is stored in count_1.

I've counted how many whitespaces I have at the beginning of the string, and at the end of the string; and the amount is stored in count_2.

note: I've chosen to use isspace function (in <ctype.h>), because I tried to type ' ' (i.e a whitespace), but the result is not correct, and these if-checks are not evaluated whatsoever. (I used the debugger line-by-line to state this thing).

before malloc the memory I've used a check condition to avoid buffer overrun (it's similar to the question I asked yesterday), meaning I've allocated enough memory if and only if max_length is less than count_1. doing this way, I have no buffer overrun warning.

I think I can avoid to explain the final steps, because they are self explanatory and I also think they doesn't cause errors. If I'm wrong, I'll edit this point.

issue I have no clue how to fix it:

by debugging line-by-line, I've noticed that when the flow of execution goes to the 2nd if-check, the if body is not executed whatsoever. And this is strange, because the first one works fine.

Body:
There are multiple problems in your code:

count_1 is the length of the string, you should name it more explicitly as len

you return NULL if no trimming is needed. This is questionable. You should probably return a copy of the string in all cases and only return NULL in case of allocation failure.

you only test for 1 space char at the start of the string.

you only test for 1 space char at the end of the string.

furthermore this space might be counted twice if the string is " ".

max_length is a misnomer: it is not the length of the new string, but the allocation size, new_size seems more appropriate.

in the final loop, you use the same index i into the original and the new string: this is incorrect. You should use a separate index so characters from the original string can be copied after skipping the initial space.

str[count_1 - count_2] = 0; is redundant inside the loop: you should move this statement after the end of the loop.

argument values of type char should be cast as (unsigned char) when passed to the functions and macros defined in <ctype.h> to avoid undefined behavior on negative values on platforms where the char type is signed. These functions are only defined for the values of type unsigned char (between 0 and UCHAR_MAX) and the special negative value EOF. These values are the ones returned by getchar() and getc().

Here is a modified version:

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>

char *trim(const char *s) {
    if (s == NULL) {
        return NULL;
    }
    size_t start, end;
    for (start = 0; isspace((unsigned char)s[start]); start++) {
        continue;
    }
    for (end = start; s[end] != '\0'; end++) {
        continue;
    }
    while (end > start && isspace((unsigned char)s[end - 1])) {
        end--;
    }
    // if you are allowed to use strndup, you can return the new string this way:
    //return strndup(str + start, end - start);

    char *new_str = malloc(end - start + 1);
    if (new_str) {
        size_t j = 0;  // index into the new string
        for (size_t i = start; i < end; i++) {
            new_str[j++] = str[i];
        }
        new_str[j] = '\0';
    }
    return new_str;
}

int main(void) {
    char s[] = " a b ";
    char *str = trim(s);
    printf("trim(\"%s\") -> \"%s\"\n", s, str);
    free(str);
    return 0;
}


问:
setting multiple column using one update
How to set multiple columns of a table using update query in mysql?</p>

答:
Let's take an example where you have a people table and you would like to update the age and the name column for the person with id equals to 5. The query will look like this:

```<code>UPDATE people SET age = 34, name = "John" WHERE id = 5
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Let's take an example where you have a people table and you would like to update the age and the name column for the person with id equals to 5. The query will look like this:

UPDATE people SET age = 34, name = "John" WHERE id = 5


问:
Simplify chained expression in ANTLR listener
I have an ANTLR listener for C++ where I want to get the name of a member declarator. Currently, I'm using this approach:

def enterMemberDeclarator(self, ctx: CPP14Parser.MemberDeclaratorContext):
    id = ctx.declarator().pointerDeclarator().noPointerDeclarator().noPointerDeclarator().declaratorid().idExpression().unqualifiedId()
```

which is just a horrible expression. I feel like there should be some way of getting the id immediately without having to go down that rabbit hole. Additionally, some of these expressions might be None so I fear that I would have to make even more effort to get to the result...

The grammar is from here

答:
ANTLR4 supports XPath expressions to find specific nodes (see the documentation). That's somewhat easier to read than your expression, especially when you have to check for null:

```<code>ids = XPath.findAll(ctx, "/declarator/pointerDeclarator/noPointerDeclarator/noPointerDeclarator/declaratorid/idExpression/unqualifiedId")
</code>```

(this is just pseudo code, I don't know python well).

Body:
I have an ANTLR listener for C++ where I want to get the name of a member declarator. Currently, I'm using this approach:

def enterMemberDeclarator(self, ctx: CPP14Parser.MemberDeclaratorContext):
    id = ctx.declarator().pointerDeclarator().noPointerDeclarator().noPointerDeclarator().declaratorid().idExpression().unqualifiedId()

which is just a horrible expression. I feel like there should be some way of getting the id immediately without having to go down that rabbit hole. Additionally, some of these expressions might be None so I fear that I would have to make even more effort to get to the result...

The grammar is from here

Body:
ANTLR4 supports XPath expressions to find specific nodes (see the documentation). That's somewhat easier to read than your expression, especially when you have to check for null:

ids = XPath.findAll(ctx, "/declarator/pointerDeclarator/noPointerDeclarator/noPointerDeclarator/declaratorid/idExpression/unqualifiedId")

(this is just pseudo code, I don't know python well).


问:
Can't convert object of type 'function' to 'str' for 'text
Good day everyone I'm sorry I'm new to python programming sorry if I'm asking this even this is basic or not. Someone can help me with this? The problem is I want to put the data that has been read by my Pyserial from my Arduino temperature sensor but I don't know how.

Here code for the Temperature to pyserial:

```<code>def tempe():
    import serial
    import time

    ser = serial.Serial('COM5', 9600)
    time.sleep(2)

    data =[]                       # empty list to store the data
    for i in range(50):
        b = ser.readline()         # read a byte string
        string = b.rstrip()        # remove \n and \r

        temp =  string             <= this data here I want to show to my opencv

        data.append(string)        # add to the end of data list
        time.sleep(0.1)            # wait (sleep) 0.1 seconds

    ser.close()
</code>```

And here's the whole code that I want to show in my PutText on opencv:

```<code>def offrecog():

screen2.destroy() <=dont mind this
screen.destroy()  <= dont mind this
def recog2(img, classifier, scaleFactor,miNeighbors, color, text, clf):
    image =  cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    features = classifier.detectMultiScale(image, scaleFactor, miNeighbors)

    for (x,y,w,h) in features:
        cv2.rectangle(img, (x,y),(x+w,y+h), color, 2)

        id, pred = clf.predict(image [y:y+h, x:x+w])
        confidence = int(100*(1-pred/300))

        databases = mysql.connector.connect(
        host ="localhost",
        user = "userdata",
        password = "",
        database = "facerecog"
        )

        mycursor = databases.cursor()

        mycursor.execute("SELECT names FROM record WHERE ids= " + str(id))
        datas = mycursor.fetchone()
        datas = "+".join(datas)

        cursor2 = databases.cursor()
        cursor2.execute("SELECT course_year FROM record WHERE ids= " + str(id))
        datas1 = mycursor.fetchone()
        datas1 = "+".join(datas1)

        cursor3 = databases.cursor()
        cursor3.execute("SELECT positions FROM record WHERE ids= " + str(id))
        datas2 = mycursor.fetchone()
        datas2 = "+".join(datas2)

        if confidence>70:
            cv2.putText(img, datas, (x,y+205), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
            cv2.putText(img, datas1, (x,y+230), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
            cv2.putText(img, datas2, (x,y+250), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
            cv2.putText(img, tempe, (x,y+280), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
            markattend(datas,datas1,datas2)

        else:

            cv2.putText(img, "UNKNOWN", (x,y+205), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,0,255), 1, cv2.LINE_AA)

    return img

faceCascade = cv2.CascadeClassifier("C:\\Users\\So_Low\\Desktop\\final_recog\\haarcascade_frontalface_default.xml")

clf = cv2.face.LBPHFaceRecognizer_create()
clf.read("trained.xml")

video_capture = cv2.VideoCapture(0)

while True:
    ret, img = video_capture.read()
    img = recog2(img, faceCascade, 1.3, 4, (255,255,255), "Face", clf)
    cv2.imshow("FACE RECOGNITION", img)

    if cv2.waitKey(1) & 0xFF == ord('!'):
        break
video_capture.release()
cv2.destroyAllWindows()
screen2.destroy()
</code>```

and I got this error when I run it:

```<code>File "c:\Users\So_Low\Desktop\Offrecog\offrecog.py", line 97, in recog2
    cv2.putText(img, wew, (x,y+280), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
cv2.error: OpenCV(4.5.3) :-1: error: (-5:Bad argument) in function 'putText'
> Overload resolution failed:
>  - Can't convert object of type 'function' to 'str' for 'text'
>  - Can't convert object of type 'function' to 'str' for 'text'

[ WARN:0] global C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-u4kjpz2z\opencv\modules\videoio\src\cap_msmf.cpp (438) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback

[Done] exited with code=0 in 14.22 seconds

[Running] python -u "c:\Users\So_Low\Desktop\Offrecog\offrecog.py"
Exception in Tkinter callback
Traceback (most recent call last):
  File "I:\Python\lib\tkinter\__init__.py", line 1883, in __call__
    return self.func(*args)
  File "c:\Users\So_Low\Desktop\Offrecog\offrecog.py", line 136, in login_verify
    offrecog()
  File "c:\Users\So_Low\Desktop\Offrecog\offrecog.py", line 113, in offrecog
    img = recog2(img, faceCascade, 1.3, 4, (255,255,255), "Face", clf)
  File "c:\Users\So_Low\Desktop\Offrecog\offrecog.py", line 95, in recog2
    cv2.putText(img, temps, (x,y+280), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
cv2.error: OpenCV(4.5.3) :-1: error: (-5:Bad argument) in function 'putText'
> Overload resolution failed:
>  - Can't convert object of type 'module' to 'str' for 'text'
>  - Can't convert object of type 'module' to 'str' for 'text'
</code>```

Even If I don't put the temperature code into function It run the pyserial 1st before the opencv.
Please Help I don't know what to do. Please

答:
presumably you want to sample your temperature 50 times and then return a single value?

```<code>def get_temp(ser, num_samples=50):
    float_vals = [float(ser.readline()) for _ in range(num_samples)]
    avg_val = sum(float_vals)/len(float_vals)
    return str(avg_val) # convert to string for open cv
</code>```

then in your opencv call use get_temp(ser) instead of tempe

where ser is a serial instance thats already open

if taking 50 samples is too slow then you can always take less samples  with get_temp(ser,5) to only take 5 samples for example  ... if you want the mode or median instead of the mean then i would recommend just using numpy.mode or numpy.median instead of calculating it (its probably faster to use numpy.mean than calculating the average manually)

Body:
Good day everyone I'm sorry I'm new to python programming sorry if I'm asking this even this is basic or not. Someone can help me with this? The problem is I want to put the data that has been read by my Pyserial from my Arduino temperature sensor but I don't know how.

Here code for the Temperature to pyserial:

def tempe():
    import serial
    import time

    ser = serial.Serial('COM5', 9600)
    time.sleep(2)

    data =[]                       # empty list to store the data
    for i in range(50):
        b = ser.readline()         # read a byte string
        string = b.rstrip()        # remove \n and \r

        temp =  string             <= this data here I want to show to my opencv

        data.append(string)        # add to the end of data list
        time.sleep(0.1)            # wait (sleep) 0.1 seconds

    ser.close()

And here's the whole code that I want to show in my PutText on opencv:

def offrecog():

screen2.destroy() <=dont mind this
screen.destroy()  <= dont mind this
def recog2(img, classifier, scaleFactor,miNeighbors, color, text, clf):
    image =  cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    features = classifier.detectMultiScale(image, scaleFactor, miNeighbors)

    for (x,y,w,h) in features:
        cv2.rectangle(img, (x,y),(x+w,y+h), color, 2)

        id, pred = clf.predict(image [y:y+h, x:x+w])
        confidence = int(100*(1-pred/300))

        databases = mysql.connector.connect(
        host ="localhost",
        user = "userdata",
        password = "",
        database = "facerecog"
        )

        mycursor = databases.cursor()

        mycursor.execute("SELECT names FROM record WHERE ids= " + str(id))
        datas = mycursor.fetchone()
        datas = "+".join(datas)

        cursor2 = databases.cursor()
        cursor2.execute("SELECT course_year FROM record WHERE ids= " + str(id))
        datas1 = mycursor.fetchone()
        datas1 = "+".join(datas1)

        cursor3 = databases.cursor()
        cursor3.execute("SELECT positions FROM record WHERE ids= " + str(id))
        datas2 = mycursor.fetchone()
        datas2 = "+".join(datas2)

        if confidence>70:
            cv2.putText(img, datas, (x,y+205), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
            cv2.putText(img, datas1, (x,y+230), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
            cv2.putText(img, datas2, (x,y+250), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
            cv2.putText(img, tempe, (x,y+280), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
            markattend(datas,datas1,datas2)

        else:

            cv2.putText(img, "UNKNOWN", (x,y+205), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,0,255), 1, cv2.LINE_AA)

    return img

faceCascade = cv2.CascadeClassifier("C:\\Users\\So_Low\\Desktop\\final_recog\\haarcascade_frontalface_default.xml")

clf = cv2.face.LBPHFaceRecognizer_create()
clf.read("trained.xml")

video_capture = cv2.VideoCapture(0)

while True:
    ret, img = video_capture.read()
    img = recog2(img, faceCascade, 1.3, 4, (255,255,255), "Face", clf)
    cv2.imshow("FACE RECOGNITION", img)

    if cv2.waitKey(1) & 0xFF == ord('!'):
        break
video_capture.release()
cv2.destroyAllWindows()
screen2.destroy()

and I got this error when I run it:

File "c:\Users\So_Low\Desktop\Offrecog\offrecog.py", line 97, in recog2
    cv2.putText(img, wew, (x,y+280), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
cv2.error: OpenCV(4.5.3) :-1: error: (-5:Bad argument) in function 'putText'
> Overload resolution failed:
>  - Can't convert object of type 'function' to 'str' for 'text'
>  - Can't convert object of type 'function' to 'str' for 'text'

[ WARN:0] global C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-u4kjpz2z\opencv\modules\videoio\src\cap_msmf.cpp (438) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback

[Done] exited with code=0 in 14.22 seconds

[Running] python -u "c:\Users\So_Low\Desktop\Offrecog\offrecog.py"
Exception in Tkinter callback
Traceback (most recent call last):
  File "I:\Python\lib\tkinter\__init__.py", line 1883, in __call__
    return self.func(*args)
  File "c:\Users\So_Low\Desktop\Offrecog\offrecog.py", line 136, in login_verify
    offrecog()
  File "c:\Users\So_Low\Desktop\Offrecog\offrecog.py", line 113, in offrecog
    img = recog2(img, faceCascade, 1.3, 4, (255,255,255), "Face", clf)
  File "c:\Users\So_Low\Desktop\Offrecog\offrecog.py", line 95, in recog2
    cv2.putText(img, temps, (x,y+280), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
cv2.error: OpenCV(4.5.3) :-1: error: (-5:Bad argument) in function 'putText'
> Overload resolution failed:
>  - Can't convert object of type 'module' to 'str' for 'text'
>  - Can't convert object of type 'module' to 'str' for 'text'

Even If I don't put the temperature code into function It run the pyserial 1st before the opencv.
Please Help I don't know what to do. Please

Body:
presumably you want to sample your temperature 50 times and then return a single value?

def get_temp(ser, num_samples=50):
    float_vals = [float(ser.readline()) for _ in range(num_samples)]
    avg_val = sum(float_vals)/len(float_vals)
    return str(avg_val) # convert to string for open cv

then in your opencv call use get_temp(ser) instead of tempe

where ser is a serial instance thats already open

if taking 50 samples is too slow then you can always take less samples  with get_temp(ser,5) to only take 5 samples for example  ... if you want the mode or median instead of the mean then i would recommend just using numpy.mode or numpy.median instead of calculating it (its probably faster to use numpy.mean than calculating the average manually)


问:
Mixed content jQuery ajax HTTPS request has been blocked on Laravel
I think this question will be easy for someone and will be a face-palm situation for me.

I have a Laravel 5.3 site, and various pages have ajax requests. Because I use the csrf_field() feature, they work fine.

But there is one page where the ajax produces this error:

```<code>Mixed Content: The page at 'https://example.com/fb/reports' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://example.com/fb/json?levelType=&id=&aggLevel=ad&start=&end='. This request has been blocked; the content must be served over HTTPS.
</code>```

My javascript looks like this:

```<code>    var relUrl = '/fb/json/';
    var payload = {
        levelType: levelType,
        id: id,
        aggLevel: aggLevel,
        start: start,
        end: end
    };
    console.log(relUrl);
    return $.ajax({
        type: 'GET',
        dataType: 'json',
        data: payload,
        url: relUrl,
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
</code>```

I've read tons of articles about this error. I've tried tons of suggested solutions, including changing the relative URL to the full https URL, or starting it with 2 slashes.

I've even tried changing the way my Laravel routes work and am now using just querystring parameters.

I've studied all of the articles below (and more).

Also, since this one ajax query is in a password-protect part of the site (and the ajax queries that work are in a public/open part of the site), I figured maybe that was related to the problem. But then I used SSH to log into the production server and vim to temporarily remove the line that required any authentication, and the https error still happens.

What steps can I take to debug further from here?  What logs can I 'tail' on my Cloudways server?

Is there anything that Cloudflare might be interfering with (which I doubt, since other ajax queries work, all on https)?

Thanks!

jQuery AJAX Request to HTTPS getting served to HTTP with Laravel and Select2

This request has been blocked; the content must be served over HTTPS

Mixed content issue - insecure XMLHttpRequest endpoint

XHR response blocked by Chrome, because of mixed content issue (http/https)

Forcing AJAX call to be HTTPS from HTTPS Page

MixedContent when I'm loading https page through ajax, but browser still thinks it's http

jQuery ajax won't make HTTPS requests

Laravel 5.1 ajax url parameter is url

答:
When changing from HTTP to HTTPS, it's possible to get the problem Mixed content issue - Content must be served as HTTPS.

So, first, modify APP_URL in the .env file, if we use the assets helper, this shouldn't give any problem with the URL.

```<code>APP_URL=https://url.net
</code>```

Finally, add the following to the beginning of **api.php** or **web.php**:

```<code>if (App::environment('production')) {
    URL::forceScheme('https');
}
</code>```

Body:
I think this question will be easy for someone and will be a face-palm situation for me.

I have a Laravel 5.3 site, and various pages have ajax requests. Because I use the csrf_field() feature, they work fine.

But there is one page where the ajax produces this error:

Mixed Content: The page at 'https://example.com/fb/reports' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://example.com/fb/json?levelType=&id=&aggLevel=ad&start=&end='. This request has been blocked; the content must be served over HTTPS.

My javascript looks like this:

    var relUrl = '/fb/json/';
    var payload = {
        levelType: levelType,
        id: id,
        aggLevel: aggLevel,
        start: start,
        end: end
    };
    console.log(relUrl);
    return $.ajax({
        type: 'GET',
        dataType: 'json',
        data: payload,
        url: relUrl,
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

I've read tons of articles about this error. I've tried tons of suggested solutions, including changing the relative URL to the full https URL, or starting it with 2 slashes.

I've even tried changing the way my Laravel routes work and am now using just querystring parameters.

I've studied all of the articles below (and more).

Also, since this one ajax query is in a password-protect part of the site (and the ajax queries that work are in a public/open part of the site), I figured maybe that was related to the problem. But then I used SSH to log into the production server and vim to temporarily remove the line that required any authentication, and the https error still happens.

What steps can I take to debug further from here?  What logs can I 'tail' on my Cloudways server?

Is there anything that Cloudflare might be interfering with (which I doubt, since other ajax queries work, all on https)?

Thanks!

jQuery AJAX Request to HTTPS getting served to HTTP with Laravel and Select2

This request has been blocked; the content must be served over HTTPS

Mixed content issue - insecure XMLHttpRequest endpoint

XHR response blocked by Chrome, because of mixed content issue (http/https)

Forcing AJAX call to be HTTPS from HTTPS Page

MixedContent when I'm loading https page through ajax, but browser still thinks it's http

jQuery ajax won't make HTTPS requests

Laravel 5.1 ajax url parameter is url

Body:
When changing from HTTP to HTTPS, it's possible to get the problem Mixed content issue - Content must be served as HTTPS.

So, first, modify APP_URL in the .env file, if we use the assets helper, this shouldn't give any problem with the URL.

APP_URL=https://url.net

Finally, add the following to the beginning of **api.php** or **web.php**:

if (App::environment('production')) {
    URL::forceScheme('https');
}


问:
SQL request for filter change produtc price. Rails app with PostgreSQL
Please tell me how you can make a query using SQL or ActiveRecord. I have table price_history: id, product_id, price, date . I need to sort those products whose price has changed more than 2 times. I am new to SQL. My application uses Ruby-on-Rails and PostgreSQL . I will be glad for any help. Thank you.

I probably didn't formulate my question clearly. I need to get something like the following:

```<code>table: prices_history
id  | product | price | date
--------------------------------
1     milk      2.0     01/01/2022
2     milk      2.5     10/01/2022
3     milk      6.0     20/02/2022
4     bread     2.0     01/01/2022
5     bread     2.1     10/01/2022
6     bread     3.0     20/02/2022

SQL request =>
milk: min_price = 2.0, max_price = 6.0, max_price/min_price = 3 > 2? it`s true
bread: min_price = 2.0, max_price = 3.0, max_price/min_price = 1,5 > 2? it`s false

result SQL request = > milk
</code>```

答:
As per Rails,

In your application, define below association in Product, PriceHistory model

```<code>class Product
  has_many :price_histories
end

class PriceHostory
  belongs_to :product_id
end
</code>```

Then below query to find the products having more than 2 price histories

```<code>Product.joins(:price_histories).group('products.id').having('count(price_histories) > 2')
</code>```

Body:
Please tell me how you can make a query using SQL or ActiveRecord. I have table price_history: id, product_id, price, date . I need to sort those products whose price has changed more than 2 times. I am new to SQL. My application uses Ruby-on-Rails and PostgreSQL . I will be glad for any help. Thank you.

I probably didn't formulate my question clearly. I need to get something like the following:

table: prices_history
id  | product | price | date
--------------------------------
1     milk      2.0     01/01/2022
2     milk      2.5     10/01/2022
3     milk      6.0     20/02/2022
4     bread     2.0     01/01/2022
5     bread     2.1     10/01/2022
6     bread     3.0     20/02/2022

SQL request =>
milk: min_price = 2.0, max_price = 6.0, max_price/min_price = 3 > 2? it`s true
bread: min_price = 2.0, max_price = 3.0, max_price/min_price = 1,5 > 2? it`s false

result SQL request = > milk

Body:
As per Rails,

In your application, define below association in Product, PriceHistory model

class Product
  has_many :price_histories
end

class PriceHostory
  belongs_to :product_id
end

Then below query to find the products having more than 2 price histories

Product.joins(:price_histories).group('products.id').having('count(price_histories) > 2')


问:
Firebase logs out user when reloading Expo
Firebase screen

```<code>import  firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';

const firebaseConfig = {
    apiKey: "xxxxx",
    authDomain: "xxxx",
    projectId: "xxxxx",
    storageBucket: "xxxxx",
    messagingSenderId: "xxxxxxx",
    appId: "xxxxxxxx",
    measurementId: "xxxxxx"
};

let app;

if (firebase.apps.length === 0) {
  app = firebase.initializeApp(firebaseConfig)
} else {
  app = firebase.app();
}

const db = app.firestore();
const auth = firebase.auth();
const api = firebase.app();
const phoneAuth = firebase.auth;

export { db, auth, api, phoneAuth};
</code>```

App Screen

```<code>//redux
import {Provider} from 'react-redux';
import { createStore, applyMiddleware } from "redux";
import rootReducer from "./redux/reducers";
import thunk from "redux-thunk";
import { auth } from './src/config/firebase';

const store = createStore(rootReducer, applyMiddleware(thunk));

const Stack = createNativeStackNavigator();

export class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loaded: false,
    };
  }

   componentDidMount() {
     auth.onAuthStateChanged((user) => {
      console.log(user)<------------------------------------------
      if (!user) {
        this.setState({
          loggedIn: false,
          loaded: true,
        });
      } else {
        this.setState({
          loggedIn: true,
          loaded: true
        });
      }
    });
  }

    render() {
      const { loggedIn, loaded } = this.state;

      if (!loaded) {
        return (
          <SafeAreaView>
              <Text>Template</Text>
              <ActivityIndicator  size='large' color='white'/>
          </SafeAreaView>
        );
      }
      if(!loggedIn) {
        return (
          <Provider store={store}>
            <NavigationContainer>
              <Stack.Navigator>
                <Stack.Screen name="Landing" component={LandingScreen}/>
                <Stack.Screen name="Register" component={RegisterScreen}/>
                <Stack.Screen name="SignGuest" component={SignGuestScreen}/>
                <Stack.Screen name="VerifyPhoneNumber" component={VerifyPhoneNumberScreen} />
                <Stack.Screen name="AddressSearchPage" component={AddressSearchPageScreen} />
                <Stack.Screen name="AddressSearch" component={AddressSearchScreen} />
              </Stack.Navigator>
            </NavigationContainer>
          </Provider>
        )
      }
        return (
          <Provider store={store}>
            <NavigationContainer>
              <Stack.Navigator>
                <Stack.Screen name="TabNavigator" component={TabNavigatorScreen} />
                <Stack.Screen name="Account" component={AccountScreen}/>
                <Stack.Screen name="Cart" component={CartScreen}/>
                <Stack.Screen name="RegisterModal" component={RegisterModalScreen} />
                <Stack.Screen name="AddressSearch" component={AddressSearchScreen} />
                <Stack.Screen name="DisplayItem" component={DisplayItemScreen} />
              </Stack.Navigator>
            </NavigationContainer>
        </Provider>
      )}
  }

  export default App;
</code>```

Firebase logs out user when reloading expo. I put a console.log in the componentDidMount to see the problem and it returns null after the app reloads.

To be honest I don't understand where the problem is.

I would like for the user to stay logged in. I've tried many methods and read a lot of tutorials, but it just doesn't seem to work.

答:
To add a workaround for your issue with the auth, You can apply a modular approach instead of using the compat approach from the firebase.

As per the documentation, Compat is a temporary workaround if you are already using the firebase v8 SDK.

It should work but I also don't know why it is not working.

For This, I created a demo and used the modular approach from firebase and it is working properly.

Check the Doc: Firebase Modular Update documentation

You can use the Modular approach from firebase to implement the auth functionality.

Code.

```<code>import React, { useEffect } from "react";
import { View, Button } from 'react-native'
import { initializeApp } from 'firebase/app'
import { getAuth, signInWithEmailAndPassword } from "firebase/auth";

const App = () => {
  async function logIn() {
    try {
      const loginRes = await signInWithEmailAndPassword(getAuth(), 'user@gmail.com', 'xxxxxx')
      console.log('loginRes : ', loginRes.user?.email)
    } catch ({ message }) {
      console.log('[Error] logIn : ', message)
    }
  }

  useEffect(() => {
    const firebaseConfig = {
      apiKey: "xxxxxx",
      authDomain: "xxxxx",
      projectId: "xxxxxx",
      storageBucket: "xxxxxx",
      messagingSenderId: "xxxxxx",
      appId: "xxxxxx",
      measurementId: "xxxxxx"
    };

    // Initialize Firebase
    initializeApp(firebaseConfig);

    // Adding listener for firebase auth
    const unsubscribe = getAuth().onAuthStateChanged((user) => {
      if (user) {
        console.log('user already loggen in')
      } else {
        console.log('user not logged in')
      }
    });

    return unsubscribe
  }, [])

  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Button title="Button" onPress={logIn} />
    </View>
  )
}

export default App
</code>```

Body:
Firebase screen

import  firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';

const firebaseConfig = {
    apiKey: "xxxxx",
    authDomain: "xxxx",
    projectId: "xxxxx",
    storageBucket: "xxxxx",
    messagingSenderId: "xxxxxxx",
    appId: "xxxxxxxx",
    measurementId: "xxxxxx"
};

let app;

if (firebase.apps.length === 0) {
  app = firebase.initializeApp(firebaseConfig)
} else {
  app = firebase.app();
}

const db = app.firestore();
const auth = firebase.auth();
const api = firebase.app();
const phoneAuth = firebase.auth;

export { db, auth, api, phoneAuth};

App Screen

//redux
import {Provider} from 'react-redux';
import { createStore, applyMiddleware } from "redux";
import rootReducer from "./redux/reducers";
import thunk from "redux-thunk";
import { auth } from './src/config/firebase';

const store = createStore(rootReducer, applyMiddleware(thunk));

const Stack = createNativeStackNavigator();

export class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loaded: false,
    };
  }

   componentDidMount() {
     auth.onAuthStateChanged((user) => {
      console.log(user)<------------------------------------------
      if (!user) {
        this.setState({
          loggedIn: false,
          loaded: true,
        });
      } else {
        this.setState({
          loggedIn: true,
          loaded: true
        });
      }
    });
  }

    render() {
      const { loggedIn, loaded } = this.state;

      if (!loaded) {
        return (
          <SafeAreaView>
              <Text>Template</Text>
              <ActivityIndicator  size='large' color='white'/>
          </SafeAreaView>
        );
      }
      if(!loggedIn) {
        return (
          <Provider store={store}>
            <NavigationContainer>
              <Stack.Navigator>
                <Stack.Screen name="Landing" component={LandingScreen}/>
                <Stack.Screen name="Register" component={RegisterScreen}/>
                <Stack.Screen name="SignGuest" component={SignGuestScreen}/>
                <Stack.Screen name="VerifyPhoneNumber" component={VerifyPhoneNumberScreen} />
                <Stack.Screen name="AddressSearchPage" component={AddressSearchPageScreen} />
                <Stack.Screen name="AddressSearch" component={AddressSearchScreen} />
              </Stack.Navigator>
            </NavigationContainer>
          </Provider>
        )
      }
        return (
          <Provider store={store}>
            <NavigationContainer>
              <Stack.Navigator>
                <Stack.Screen name="TabNavigator" component={TabNavigatorScreen} />
                <Stack.Screen name="Account" component={AccountScreen}/>
                <Stack.Screen name="Cart" component={CartScreen}/>
                <Stack.Screen name="RegisterModal" component={RegisterModalScreen} />
                <Stack.Screen name="AddressSearch" component={AddressSearchScreen} />
                <Stack.Screen name="DisplayItem" component={DisplayItemScreen} />
              </Stack.Navigator>
            </NavigationContainer>
        </Provider>
      )}
  }

  export default App;

Firebase logs out user when reloading expo. I put a console.log in the componentDidMount to see the problem and it returns null after the app reloads.

To be honest I don't understand where the problem is.

I would like for the user to stay logged in. I've tried many methods and read a lot of tutorials, but it just doesn't seem to work.

Body:
To add a workaround for your issue with the auth, You can apply a modular approach instead of using the compat approach from the firebase.

As per the documentation, Compat is a temporary workaround if you are already using the firebase v8 SDK.

It should work but I also don't know why it is not working.

For This, I created a demo and used the modular approach from firebase and it is working properly.

Check the Doc: Firebase Modular Update documentation

You can use the Modular approach from firebase to implement the auth functionality.

Code.

import React, { useEffect } from "react";
import { View, Button } from 'react-native'
import { initializeApp } from 'firebase/app'
import { getAuth, signInWithEmailAndPassword } from "firebase/auth";

const App = () => {
  async function logIn() {
    try {
      const loginRes = await signInWithEmailAndPassword(getAuth(), 'user@gmail.com', 'xxxxxx')
      console.log('loginRes : ', loginRes.user?.email)
    } catch ({ message }) {
      console.log('[Error] logIn : ', message)
    }
  }

  useEffect(() => {
    const firebaseConfig = {
      apiKey: "xxxxxx",
      authDomain: "xxxxx",
      projectId: "xxxxxx",
      storageBucket: "xxxxxx",
      messagingSenderId: "xxxxxx",
      appId: "xxxxxx",
      measurementId: "xxxxxx"
    };

    // Initialize Firebase
    initializeApp(firebaseConfig);

    // Adding listener for firebase auth
    const unsubscribe = getAuth().onAuthStateChanged((user) => {
      if (user) {
        console.log('user already loggen in')
      } else {
        console.log('user not logged in')
      }
    });

    return unsubscribe
  }, [])

  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Button title="Button" onPress={logIn} />
    </View>
  )
}

export default App


问:
Download file with FileContentResult and store it client side using javascript
I've an MVC route as this:

```<code>public FileContentResult GetMedia(string media_md5)
{
    // get media from DB here
    processed_file_doc file_doc = getMediaFromDb(media_md5);

    string filename = file_doc.Filename;
    string filepath = file_doc.File_path;

    byte[] fileBytes = System.IO.File.ReadAllBytes(filepath);
    string fileName = filename;

    FileContentResult file_result = File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);

    return file_result;
}
</code>```

This method is called by javascript in this way:

```<code>function DownloadMedia(row_id) {

    filetable = $('#mytable').DataTable();
    var data = filetable.row('#' + row_id).data();
    filename = data['Filename'];

    var handleSuccess = function (file) {
        var a = document.createElement("a"),
            file = new Blob([file], { type: "application/octect-stream" });

            var url = URL.createObjectURL(file);
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            setTimeout(function () {
                document.body.removeChild(a);
                window.URL.revokeObjectURL(url);
            }, 0);
    }

    $.post("/MyController/GetMedia", { media_md5: row_id }, handleSuccess);
}
</code>```

The problem is that using this code I can correctly download only .txt files, if for example I try to download a .jpg, the image can't be opened. I've checked the two file downloaded and they are really different:

I've verified that the file is open and read correctly, but I can't understand why once received from client it is all messed up.

答: Use octet-stream instead of octect-stream</p>

Body:
I've an MVC route as this:

public FileContentResult GetMedia(string media_md5)
{
    // get media from DB here
    processed_file_doc file_doc = getMediaFromDb(media_md5);

    string filename = file_doc.Filename;
    string filepath = file_doc.File_path;

    byte[] fileBytes = System.IO.File.ReadAllBytes(filepath);
    string fileName = filename;

    FileContentResult file_result = File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);

    return file_result;
}

This method is called by javascript in this way:

function DownloadMedia(row_id) {

    filetable = $('#mytable').DataTable();
    var data = filetable.row('#' + row_id).data();
    filename = data['Filename'];

    var handleSuccess = function (file) {
        var a = document.createElement("a"),
            file = new Blob([file], { type: "application/octect-stream" });

            var url = URL.createObjectURL(file);
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            setTimeout(function () {
                document.body.removeChild(a);
                window.URL.revokeObjectURL(url);
            }, 0);
    }

    $.post("/MyController/GetMedia", { media_md5: row_id }, handleSuccess);
}

The problem is that using this code I can correctly download only .txt files, if for example I try to download a .jpg, the image can't be opened. I've checked the two file downloaded and they are really different:

I've verified that the file is open and read correctly, but I can't understand why once received from client it is all messed up.


问:
Unconstrained Optimization using Gradient and (sparse) Hessian
I'm looking for a C++ optimization package that can do multivariate unconstrained optimization using gradient and Hessian information.  I'm doing it now in Matlab using fminunc with the 'GradObj', 'Hessian', and 'HessPattern' options.  My Hessian is very sparse so a package that takes that into account would be preferable.

Are there any alternatives to Matlab for this?  Open-source or closed-source are both fine.  C++ is preferable but I'm flexible.

答: Have you considered compiling the MATLAB library into a .dll or .exe that R can reference? MATLAB has this capability.</p>

OwnerDisplayName: eglaser

OwnerDisplayName: Quant Guy


问:
How do I create a GUID / UUID?
How do I create GUIDs (globally-unique identifiers) in JavaScript? The GUID / UUID should be at least 32 characters and should stay in the ASCII range to avoid trouble when passing them around.

I'm not sure what routines are available on all browsers, how "random" and seeded the built-in random number generator is, etc.

答:
Easy to do with a simple uuid package
https://www.npmjs.com/package/uuid</p>
```<code>const { v4: uuidv4 } = require('uuid');
uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'
</code>```

OwnerDisplayName: Jason Cohen

Title: How do I create a GUID / UUID?

Body:
Easy to do with a simple uuid package
https://www.npmjs.com/package/uuid

const { v4: uuidv4 } = require('uuid');
uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'


问:
Finding difference between column from select statement
I'm trying to output the difference between my calculation in a SQL statement.

Let's say I have the following select statement and tables:

'''
Select SUM(a) as A, case as B, 0 as diff
where ......
'''

the thing I'm trying to do is to use A - B as diff but currently have no luck on it.

Anything is appreciated!

答:
For your case a Common Table Expression could be helpful:

WITH
  cte AS (Select SUM(a) as A, case as B where ...)
SELECT A, B, (A-B) ar diff FROM cte
```

https://dev.mysql.com/doc/refman/8.0/en/with.html

Body:
For your case a Common Table Expression could be helpful:

WITH
  cte AS (Select SUM(a) as A, case as B where ...)
SELECT A, B, (A-B) ar diff FROM cte

https://dev.mysql.com/doc/refman/8.0/en/with.html


问:
Cleaning Scraped Table Data
all I'm attempting to pull table data from a site that is displayed from a search box. I'm having trouble cleaning up the data in excel. Are there any tricks to get this a little neater? here is the code and screenshot below.

I need it to display the headers of  Case Number, Style/Defendant,
File Date and then the case numbers below, description of the defendant
case, and file date.

```<code>soup = BeautifulSoup(driver.page_source,'html.parser')
df = pd.read_html(str(soup))[0]
df.dropna(inplace=True)

print(df)
datatoexcel = pd.ExcelWriter('Case_Files.xlsx')

df.to_excel(datatoexcel)

datatoexcel.save()
print('DataFrame is Written to Excel Successfully.')
</code>```

This is what the table looks like from the print(df) screen

```<code> Unnamed: 0_level_0                                               Name Date of Birth
         Case Number                                  Style / Defendant     File Date
         Case Number                                  Style / Defendant     File Date
2        Case Number                                  Style / Defendant     File Date
3          08A575873  In the Matter of Petition for Compromise of Mi...    11/17/2008
6        Case Number                                  Style / Defendant     File Date
7          08A575874  In the Matter of Petition for Compromise of Mi...    11/17/2008
DataFrame is Written to Excel Successfully.
</code>```

答:
IIUC, drop the first two levels of column index then filter out your rows:</p>
```<code>>>> df.droplevel(level=[0, 1], axis=1).query("`Case Number` != 'Case Number'")

  Case Number                                  Style / Defendant   File Date
3   08A575873  In the Matter of Petition for Compromise of Mi...  11/17/2008
7   08A575874  In the Matter of Petition for Compromise of Mi...  11/17/2008
</code>```

Title: Cleaning Scraped Table Data

Body:
all I'm attempting to pull table data from a site that is displayed from a search box. I'm having trouble cleaning up the data in excel. Are there any tricks to get this a little neater? here is the code and screenshot below.

I need it to display the headers of  Case Number, Style/Defendant,
File Date and then the case numbers below, description of the defendant
case, and file date.

soup = BeautifulSoup(driver.page_source,'html.parser')
df = pd.read_html(str(soup))[0]
df.dropna(inplace=True)

print(df)
datatoexcel = pd.ExcelWriter('Case_Files.xlsx')

df.to_excel(datatoexcel)

datatoexcel.save()
print('DataFrame is Written to Excel Successfully.')

This is what the table looks like from the print(df) screen

 Unnamed: 0_level_0                                               Name Date of Birth
         Case Number                                  Style / Defendant     File Date
         Case Number                                  Style / Defendant     File Date
2        Case Number                                  Style / Defendant     File Date
3          08A575873  In the Matter of Petition for Compromise of Mi...    11/17/2008
6        Case Number                                  Style / Defendant     File Date
7          08A575874  In the Matter of Petition for Compromise of Mi...    11/17/2008
DataFrame is Written to Excel Successfully.

Body:
IIUC, drop the first two levels of column index then filter out your rows:

>>> df.droplevel(level=[0, 1], axis=1).query("`Case Number` != 'Case Number'")

  Case Number                                  Style / Defendant   File Date
3   08A575873  In the Matter of Petition for Compromise of Mi...  11/17/2008
7   08A575874  In the Matter of Petition for Compromise of Mi...  11/17/2008


问:
Call two UIGestureRecognizer at the same time
Here's the question: I have an UIScrollView with an UIButton as a subView. Both the UIScrollView and the UIButton have an UILongPressGestureRecognizer assigned to them. Is it possible that if the UILongPressGestureRecognizer of the UIButton is called the one of the UIScrollView gets called too?</p>

答: A simple way to do this would be to manually call the long-press handling function for your scrollview when the button is long-pressed. You shouldn't try and run more than one thing on your interface at the same time, because interface code needs to be executed only on the main thread.</p>


问:
How to pass a dynamic column name in a pipe in custom function in R
I've created a dynamic column name w/ dplyr::mutate() based on this thread Use dynamic variable names in `dplyr` and now I want to sort the new column.... but I'm not correctly passing the column name</p>
```<code>library(glue)
library(dplyr)

# data
set.seed(123)
df <- data.frame(distance = sample(1:100, size = 10))

# custom function
multiply_function <- function(df, metric, multiplier){

  df %>%
    mutate(., "{{metric}}_x{{multiplier}}" := {{metric}} * multiplier) %>%
    arrange(desc("{{metric}}_x{{multiplier}}")) # <--- this is not working
}

df %>%
  multiply_function(., metric = distance, multiplier = 3)

   distance distance_x3
1        31          93
2        79         237
3        51         153
4        14          42
5        67         201
6        42         126
7        50         150
8        43         129
9        97         291
10       25          75
</code>```

答:
Unfortunately I don't know if any way to use that nice glue syntax with anything that's not on the left side of a :=. That's there the magic happens. You can get something to work if you take care of the explicity conversion to sumbol your self and do the string building manually. It's not pretty, but this works

```<code>multiply_function <- function(df, metric, multiplier){
  metric <- ensym(metric)
  newname <- glue::glue("{rlang::as_string(metric)}_x{as.character(multiplier)}")
  df %>%
    mutate("{newname}" := !!metric * multiplier) %>%
    arrange(desc(.data[[newname]]))
}
</code>```

Body:
I've created a dynamic column name w/ dplyr::mutate() based on this thread Use dynamic variable names in `dplyr` and now I want to sort the new column.... but I'm not correctly passing the column name

library(glue)
library(dplyr)

# data
set.seed(123)
df <- data.frame(distance = sample(1:100, size = 10))

# custom function
multiply_function <- function(df, metric, multiplier){

  df %>%
    mutate(., "{{metric}}_x{{multiplier}}" := {{metric}} * multiplier) %>%
    arrange(desc("{{metric}}_x{{multiplier}}")) # <--- this is not working
}

df %>%
  multiply_function(., metric = distance, multiplier = 3)

   distance distance_x3
1        31          93
2        79         237
3        51         153
4        14          42
5        67         201
6        42         126
7        50         150
8        43         129
9        97         291
10       25          75

Body:
Unfortunately I don't know if any way to use that nice glue syntax with anything that's not on the left side of a :=. That's there the magic happens. You can get something to work if you take care of the explicity conversion to sumbol your self and do the string building manually. It's not pretty, but this works

multiply_function <- function(df, metric, multiplier){
  metric <- ensym(metric)
  newname <- glue::glue("{rlang::as_string(metric)}_x{as.character(multiplier)}")
  df %>%
    mutate("{newname}" := !!metric * multiplier) %>%
    arrange(desc(.data[[newname]]))
}


问:
update specific field data on sql database
so i have a table of data in web ui

as soon as I click the button. all of the field data in "Status Email" changed. not just selected field that i meant.
this is the sintaks sql

```<code>if($mail->Send())
{
    $query = "UPDATE nearly_inactive SET EmailSent = 'Sudah Kirim Email' WHERE  EmailSent = 'Belum Kirim Email'";
    $update = $con->prepare($query);
    $update->execute();
}
</code>```

how can i get the "update" only the data that I click on the button??

答:
you need to determine which record need to be changed based on their unique ID. usually it's the primary key of the table. so, If your primary key is enroller_id, then pass the value of enroller_id, and put it inside your sql.

```<code>if($mail->Send())
{
    //prepare your query
    $statement = $this->mysqli->prepare("UPDATE nearly_inactive SET EmailSent = 'Sudah Kirim Email' WHERE enroller_id = ?");

    //check for statement preparation
    if ($statement === false) {
        trigger_error($this->mysqli->error, E_USER_ERROR);
        return;
    }

    //bind the value
    $statement->bindParam("i", $id);

    //get id for the query
    $id = your_field_enroller_id;

    //execute the statement
    $statement->execute();
}
</code>```

where enroller_id is your table primary key, and $id is the value of that field primary key.

Body:
so i have a table of data in web ui

as soon as I click the button. all of the field data in "Status Email" changed. not just selected field that i meant.
this is the sintaks sql

if($mail->Send())
{
    $query = "UPDATE nearly_inactive SET EmailSent = 'Sudah Kirim Email' WHERE  EmailSent = 'Belum Kirim Email'";
    $update = $con->prepare($query);
    $update->execute();
}

how can i get the "update" only the data that I click on the button??

Body:
you need to determine which record need to be changed based on their unique ID. usually it's the primary key of the table. so, If your primary key is enroller_id, then pass the value of enroller_id, and put it inside your sql.

if($mail->Send())
{
    //prepare your query
    $statement = $this->mysqli->prepare("UPDATE nearly_inactive SET EmailSent = 'Sudah Kirim Email' WHERE enroller_id = ?");

    //check for statement preparation
    if ($statement === false) {
        trigger_error($this->mysqli->error, E_USER_ERROR);
        return;
    }

    //bind the value
    $statement->bindParam("i", $id);

    //get id for the query
    $id = your_field_enroller_id;

    //execute the statement
    $statement->execute();
}

where enroller_id is your table primary key, and $id is the value of that field primary key.


问:
How to disable some weights in keras?
Imagine I am trying to fit a model the following way:

```<code>import tensorflow as tf

x_in=tf.keras.layers.Input(shape=n)
x_out = tf.keras.layers.Dense(m, use_bias=False)(x_in)

model = tf.keras.Model(inputs=x_in, outputs=x_out)
</code>```

Now the problem is that this will create nxm weights - in my model, however, I want most of the weights to be zero (in fact, only m weights are non-zero); So far, I implemented it by a custom weight constraint function; This however, proved to be extremely slow as the weights that I want to be 0 are nevertheless updated in every iteration and then manually set to 0 which takes a lot of time;

Is there a better way to do it? So a way to say something like "Disable weight w[i,j] whenever i!=(j+1)" such that only these m weights that are not disabled will really be updated in every iteration?

答:
Could the following applied in suitable format solve your problem:

```<code>import tensorflow as tf
import numpy as np

n=1
m=1

x_in=tf.keras.layers.Input(shape=n)
x_out = tf.keras.layers.Dense(m, use_bias=False,trainable=True)(x_in)
x_out_disabledweights = tf.keras.layers.Dense(m, use_bias=False,trainable=False)(x_in)

model_A = tf.keras.Model(inputs=x_in, outputs=x_out)
model_B = tf.keras.Model(inputs=x_in, outputs=x_out_disabledweights)

print(model_A.summary())
print(model_B.summary())

#by following the idea above, you are able to freeze the weights you want...
weights_before_update=model_B.get_weights()

#fix the weigth to desired value e.g. 0.12345
weights_before_update[0][0][0]=0.12345

#and set the weigths to the model:
model_B.set_weights(weights_before_update)

#and this way you can verify the weight has been updated...
weights_after_update=model_B.get_weights()

print("The weights after manual update...")
print(weights_after_update)
print("And the result of model with test input of one...")
test_result=model_B(np.ones(1))
print(test_result)
</code>```

...please note the possibility to handle trainability of selected layers. You can design several different layers ... having individual characteristics of weights and their features.

Title: How to disable some weights in keras?

Body:
Imagine I am trying to fit a model the following way:

import tensorflow as tf

x_in=tf.keras.layers.Input(shape=n)
x_out = tf.keras.layers.Dense(m, use_bias=False)(x_in)

model = tf.keras.Model(inputs=x_in, outputs=x_out)

Now the problem is that this will create nxm weights - in my model, however, I want most of the weights to be zero (in fact, only m weights are non-zero); So far, I implemented it by a custom weight constraint function; This however, proved to be extremely slow as the weights that I want to be 0 are nevertheless updated in every iteration and then manually set to 0 which takes a lot of time;

Is there a better way to do it? So a way to say something like "Disable weight w[i,j] whenever i!=(j+1)" such that only these m weights that are not disabled will really be updated in every iteration?

Body:
Could the following applied in suitable format solve your problem:

import tensorflow as tf
import numpy as np

n=1
m=1

x_in=tf.keras.layers.Input(shape=n)
x_out = tf.keras.layers.Dense(m, use_bias=False,trainable=True)(x_in)
x_out_disabledweights = tf.keras.layers.Dense(m, use_bias=False,trainable=False)(x_in)

model_A = tf.keras.Model(inputs=x_in, outputs=x_out)
model_B = tf.keras.Model(inputs=x_in, outputs=x_out_disabledweights)

print(model_A.summary())
print(model_B.summary())

#by following the idea above, you are able to freeze the weights you want...
weights_before_update=model_B.get_weights()

#fix the weigth to desired value e.g. 0.12345
weights_before_update[0][0][0]=0.12345

#and set the weigths to the model:
model_B.set_weights(weights_before_update)

#and this way you can verify the weight has been updated...
weights_after_update=model_B.get_weights()

print("The weights after manual update...")
print(weights_after_update)
print("And the result of model with test input of one...")
test_result=model_B(np.ones(1))
print(test_result)

...please note the possibility to handle trainability of selected layers. You can design several different layers ... having individual characteristics of weights and their features.


问:
Does anyone know of a way of hiding a column in an asp.net listview?
I know you can put <% if %> statements in the ItemTemplate to hide controls but the column is still there.
You cannot put <% %> statements into the LayoutTemplate which is where the column headings are declared, hence the problem.
Does anyone know of a better way?</p>

答:
The listview doesn't really have a concept of 'column' since it is intended just to be, well, a list.

I'm going to assume that you are using databinding to attach a list of 'somethings' to the ListView. If that is the case then you will just have a list of items and the html in the LayoutTemplate will decide on just how those items are displayed. If you are then talking about creating a table-style array of columns and rows then maybe a DataGrid would be a better choice since this gives much more programmatic control of specific columns.

It may be that you are hoping to create the table layout entirely through CSS, which is an admirable decision if it is purely for layout purposes. However, your requirement to specifically hide one column indicates to me that a table is better placed to suit your needs. It's fine to use tables for tabular data...IMHO...

If you really do need to use a ListView then you could always try binding against something in your data which determines whether an element should be shown or not, e.g.:

```<code>style='display: <%#Eval("DisplayStyle") %>;'
</code>```

Place this code within the html element that you want to control (in the LayoutTemplate). Then in the object you are binding to you would need a property 'DisplayStyle' which was either set to 'block' or 'none'.

Body:
The listview doesn't really have a concept of 'column' since it is intended just to be, well, a list.

I'm going to assume that you are using databinding to attach a list of 'somethings' to the ListView. If that is the case then you will just have a list of items and the html in the LayoutTemplate will decide on just how those items are displayed. If you are then talking about creating a table-style array of columns and rows then maybe a DataGrid would be a better choice since this gives much more programmatic control of specific columns.

It may be that you are hoping to create the table layout entirely through CSS, which is an admirable decision if it is purely for layout purposes. However, your requirement to specifically hide one column indicates to me that a table is better placed to suit your needs. It's fine to use tables for tabular data...IMHO...

If you really do need to use a ListView then you could always try binding against something in your data which determines whether an element should be shown or not, e.g.:

style='display: <%#Eval("DisplayStyle") %>;'

Place this code within the html element that you want to control (in the LayoutTemplate). Then in the object you are binding to you would need a property 'DisplayStyle' which was either set to 'block' or 'none'.