答:
I would suggest to take a look at the ThreadPoolExecutor or ProcessPoolExecutor: https://docs.python.org/3/library/concurrent.futures.html

You can create a pool with an arbitrary amount of workers, submit the work while collecting the futures, and then waiting on them until they are all completed.

Refactor your convert function to process a single file (meaning, extract the for-loop form the function), then loop over the items while submitting the work.

Example code

from concurrent.futures import ProcessPoolExecutor

executor = ProcessPoolExecutor(max_workers=10)

futures = []
for f in files:
    futures.append(executor.submit(convert, f)

for future in futures:
    future.result()

```

Title: How to implement Python's multiprocessing Pool to convert thousands of files

Body:
I have a Python script that reads in a directory containing over 10,000 DBF files so they can be converted to CSV. I would like to parellelize this task rather than converting each file individually. I have read up on Python's multiprocessing module, though I am having a little bit of trouble implementing it for this task. Specifically, I wanted to use the Pool class to distribute the workload across the CPU cores.

Here is my code thus far:

import os
from dbfread import DBF
import pandas as pd
import multiprocessing

directory = 'C:\\Path_to_DBF_Files' #define file directory

files_in = os.listdir(directory) #store files in directory to list

def convert():

    for file in files_in:

        if file.startswith('D') and file.endswith('.DBF'): #define parameters of filenames to convert
            file_path = os.path.join(files_in, file)
            print(f'\nReading in {file}...')
            dbf = DBF(file_path) #create DBF object
            dbf.encoding = 'utf-8' #set encoding attribute to utf-8 instead of acsii
            dbf.char_decode_errors = 'ignore' #set decoding errors attribute to ignore any errors and read in DBF file as is
            print('\nConverting to DataFrame...')
            df = pd.DataFrame(iter(dbf)) #convert to Pandas dataframe
            df.columns.astype(str) #convert column datatypes to string
            print(df)
            print('\nWriting to CSV...')
            dest_directory = 'C:\\Path_to_output_directory\\%s.csv' % ('D' + file.strip('.DBF')) #define destination directory and names for output files
            df.to_csv(dest_directory, index = False)
            print(f'\nConverted {file} to CSV. Moving to next file...')

        elif file.startswith('B') and file.endswith('.DBF'): #define parameters for unnecessary files
            print('\nB file not needed.')
            continue

        elif file.endswith('.FPT'): #skip FPT files
            print('Skipping FPT file.')
            continue

        elif file.startswith('ID') and file.endswith('.DB~'): #stop iteration when this file is reached in the directory
            print('All files converted to CSV.')
            break

        else:
            print('\nFile not found or error.')
            print(f'Last file read in was {file}.')

pool = multiprocessing.Pool(processes = len(in_files)) #create Pool to run across the length of the input directory
result = pool.map(convert, files_in) #reference convert function and list of DBF files to be passed through
print(result)

I've read a few answers here on StackOverflow that are somewhat similar to my question; however, I've not seen anything that applies to my specific task. How could I improve my code so that instead of reading and converting just one file at a time, the script will process multiple files simultaneously?

Thank you for any help provided.


来源: stackexchange

问:
Function to add character between concatenation of strings
Is there a more simplistic way to add characters throughout an string at the time of concatenation? I'm thinking of utilizing an function to do this and can achieve it by doing a concatenation; however, is there an kind of alternative that can be done other than concatenation?

Here is what I need to do...There is Table A which has 8 columns, for this example col1, col2, col3, etc.

```<code>;WITH
 TABLE_A
 AS
 (
  SELECT 'ABC' AS Col1
         , 'COM' AS Col2
         , 'SMALL' AS Col3
         , '1234' AS Col4
         , 'ABC INC.' AS Col5
         , '123456789' AS Col6
         , 'ABC Of New England' AS Col7
         , 'NC123456' AS Col8
 )
  SELECT *
  FROM TABLE_A
</code>```

I need to concatenate the values within the columns with an > between each. I can accomplish this by doing something along the lines of...

```<code>CONCAT(Col1,'>',Col2,'>',Col3,'>',Col4,'^',Col5,'>',Col6,'>',Col7,'>',Col8)
</code>```

but I need it to be dynamic, so for example if col1 - Col3 has a value then the concatenation has to occur for only those CONCAT(Col1,'>',Col2,'>',Col3) and if Col1 - Col5 has values then CONCAT(Col1,'>',Col2,'>',Col3,'>',Col4,'^',Col5) and so on, the concatenation should only go as far as there are values.

Also to add another wrinkle, instead of an > between Col4 and Col5, I need to have a carrot ^ as the delimiter.

Is there an alternative method to do this without using CONCAT? Maybe a loop?

答:
Using cross apply with nested replace. This will take care of your requirement to have ^ between col4 and col5 when they are not null and also any leading > character.

```<code>select case when left(txt,1)='>' then right(txt, len(txt)-1) else txt end as str
from your_table
cross apply
(select replace(replace(replace(concat(col1,'>'
                                      ,col2,'>'
                                      ,col3,'>'
                                      ,col4, case when col4 is not null and col5 is not null then '^' else '>' end
                                      ,col5,'>'
                                      ,col6,'>'
                                      ,col7,'>'
                                      ,col8),'>>>>','>'),'>>>','>'),'>>','>') as txt) t;
</code>```

DEMO

ContentLicense: CC BY-SA 4.0

Body:
Is there a more simplistic way to add characters throughout an string at the time of concatenation? I'm thinking of utilizing an function to do this and can achieve it by doing a concatenation; however, is there an kind of alternative that can be done other than concatenation?

Here is what I need to do...There is Table A which has 8 columns, for this example col1, col2, col3, etc.

;WITH
 TABLE_A
 AS
 (
  SELECT 'ABC' AS Col1
         , 'COM' AS Col2
         , 'SMALL' AS Col3
         , '1234' AS Col4
         , 'ABC INC.' AS Col5
         , '123456789' AS Col6
         , 'ABC Of New England' AS Col7
         , 'NC123456' AS Col8
 )
  SELECT *
  FROM TABLE_A

I need to concatenate the values within the columns with an > between each. I can accomplish this by doing something along the lines of...

CONCAT(Col1,'>',Col2,'>',Col3,'>',Col4,'^',Col5,'>',Col6,'>',Col7,'>',Col8)

but I need it to be dynamic, so for example if col1 - Col3 has a value then the concatenation has to occur for only those CONCAT(Col1,'>',Col2,'>',Col3) and if Col1 - Col5 has values then CONCAT(Col1,'>',Col2,'>',Col3,'>',Col4,'^',Col5) and so on, the concatenation should only go as far as there are values.

Also to add another wrinkle, instead of an > between Col4 and Col5, I need to have a carrot ^ as the delimiter.

Is there an alternative method to do this without using CONCAT? Maybe a loop?

Body:
Using cross apply with nested replace. This will take care of your requirement to have ^ between col4 and col5 when they are not null and also any leading > character.

select case when left(txt,1)='>' then right(txt, len(txt)-1) else txt end as str
from your_table
cross apply
(select replace(replace(replace(concat(col1,'>'
                                      ,col2,'>'
                                      ,col3,'>'
                                      ,col4, case when col4 is not null and col5 is not null then '^' else '>' end
                                      ,col5,'>'
                                      ,col6,'>'
                                      ,col7,'>'
                                      ,col8),'>>>>','>'),'>>>','>'),'>>','>') as txt) t;

DEMO


问:
Login system with password_verify()
I'm trying to make a login system with hashed passwords.
What is supposed to happen is after I click on the submit button a session should be created and I should be redirected to home.php. If input data doesn't match the data inside the database I should get "Error 1" or "Error 2" alerts.

My problem is that when I click on a submit button all that happens is that I get redirected to login.php. I get no errors and no alerts, only blank screen with login.php URL.

I'm trying to figure how to make the password_verify() part work.  Any kind of help is appreciated.

Picture of database: https://imgur.com/a/BXiHBN4

Picture of what happens after a login attempt: https://imgur.com/a/qKZ1tsi

Form code:

```<code><html>

<head>

<title> Login now! </title>

<meta charset="UTF-8">

<link rel="stylesheet" type="text/css" href="css/style.css"/>

</head>

<body>

<header>

  <div class="alignRight">
    <a href="registration.html"> Register </a>
  </div>

  <div class="alignLeft">
    <a href="contact.html"> Contact us </a>
    <a href="aboutus.html"> About us </a>
    <a href="news.html"> News </a>
  </div>

</header>

<h1> Welcome back! </h1>

<h2> Log in to continue with your work. </h2>

<form name="login-form" id="login-form" action="login.php" method="post">

    <input class="_40" type="text" name="username"  pattern="[a-zA-Z0-9_]{1,15}"
placeholder="Username"  required />

    <br />

    <input class="_40" type="password" name="pwd"  placeholder="Password"  required />

    <br />

    <input id="loginSubmitButton" type="submit" value="Submit"  />

</form>

</body>

</html>
</code>```

PHP code:

```<code><?php

session_start();

$servername ="localhost";
$username = "root";
$password = "";

$link = mysqli_connect($servername, $username, $password);

mysqli_select_db($link, "users");

$username = mysqli_real_escape_string($link, $_POST["username"]);
$pwd = mysqli_real_escape_string($link, $_POST["pwd"]);
$query = "SELECT * FROM users WHERE Username = '$username'";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_assoc($result);

if(($result->num_rows > 0))
{
    while($row = mysqli_fetch_array($result))
    {
        if(password_verify($pwd, $row["Hash"]))
        {
            $_SESSION["username"] = $username;
            header("location:home.php");
        }
        else
        {
            echo '<script>alert("Error 1")</script>';
        }
    }
}
else
{
    echo '<script>alert("Error2")</script>';
}

?>
</code>```

答:
I think I see the problem.

It looks like you're probably fetching the only row from the results before the if

```<code>$row = mysqli_fetch_assoc($result);
</code>```

Then when you fetch again here, there's nothing left to fetch.

```<code>if(($result->num_rows > 0))
{
    while($row = mysqli_fetch_array($result))
</code>```

(I'm assuming the query will only return one row since username is unique.)

Title: Login system with password_verify()

Body:
I'm trying to make a login system with hashed passwords.
What is supposed to happen is after I click on the submit button a session should be created and I should be redirected to home.php. If input data doesn't match the data inside the database I should get "Error 1" or "Error 2" alerts.

My problem is that when I click on a submit button all that happens is that I get redirected to login.php. I get no errors and no alerts, only blank screen with login.php URL.

I'm trying to figure how to make the password_verify() part work.  Any kind of help is appreciated.

Picture of database: https://imgur.com/a/BXiHBN4

Picture of what happens after a login attempt: https://imgur.com/a/qKZ1tsi

Form code:

<title> Login now! </title>

<meta charset="UTF-8">

<link rel="stylesheet" type="text/css" href="css/style.css"/>

     Register

     Contact us
     About us
     News

 Welcome back!

 Log in to continue with your work.

<form name="login-form" id="login-form" action="login.php" method="post">

    <input class="_40" type="text" name="username"  pattern="[a-zA-Z0-9_]{1,15}"
placeholder="Username"  required />

    <input class="_40" type="password" name="pwd"  placeholder="Password"  required />

    <input id="loginSubmitButton" type="submit" value="Submit"  />

</form>

PHP code:

<?php

session_start();

$servername ="localhost";
$username = "root";
$password = "";

$link = mysqli_connect($servername, $username, $password);

mysqli_select_db($link, "users");

$username = mysqli_real_escape_string($link, $_POST["username"]);
$pwd = mysqli_real_escape_string($link, $_POST["pwd"]);
$query = "SELECT * FROM users WHERE Username = '$username'";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_assoc($result);

if(($result->num_rows > 0))
{
    while($row = mysqli_fetch_array($result))
    {
        if(password_verify($pwd, $row["Hash"]))
        {
            $_SESSION["username"] = $username;
            header("location:home.php");
        }
        else
        {
            echo '';
        }
    }
}
else
{
    echo '';
}

?>

Body:
I think I see the problem.

It looks like you're probably fetching the only row from the results before the if

$row = mysqli_fetch_assoc($result);

Then when you fetch again here, there's nothing left to fetch.

if(($result->num_rows > 0))
{
    while($row = mysqli_fetch_array($result))

(I'm assuming the query will only return one row since username is unique.)


问:
ng test requires me to fix all linting before running any unit tests
The output of my ng test is as follows:

```<code>> ng test

24 12 2019 14:20:07.854:WARN [karma]: No captured browser, open http://localhost:9876/
24 12 2019 14:20:07.860:INFO [karma-server]: Karma v4.4.1 server started at http://0.0.0.0:9876/
24 12 2019 14:20:07.860:INFO [launcher]: Launching browsers ChromeNoSandbox with concurrency unlimited
24 12 2019 14:20:07.865:INFO [launcher]: Starting browser ChromeHeadless

app/shared/forms/templates/templates.component.ts:11:1 - error TS6133: 'MatDialog' is declared but its value is never read.

11 import { MatDialog } from '@angular/material';
   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
24 12 2019 14:20:11.633:INFO [HeadlessChrome 79.0.3945 (Mac OS X 10.15.2)]: Connected on socket 9OfTSV7nahQakrDOAAAA with id 85821004
HeadlessChrome 79.0.3945 (Mac OS X 10.15.2): Executed 0 of 0 SUCCESS (0 secs / 0 secs)
HeadlessChrome 79.0.3945 (Mac OS X 10.15.2): Executed 0 of 0 SUCCESS (0.002 secs / 0 secs)
TOTAL: 0 SUCCESS
TOTAL: 0 SUCCESS
</code>```

The issue I am having is that if I have any linting errors in my src code, then unit tests will not run, which is extremely inconvenient when I just want to try things here and there for test-driven development. I would much rather just get the warnings for these linting errors and I can fix them all at once.

I am on Angular version, "@angular/core": "8.1.2" and Karma versions:

```<code>"karma": "4.4.1",
"karma-chrome-launcher": "3.1.0",
"karma-cli": "2.0.0",
"karma-coverage-istanbul-reporter": "2.1.1",
"karma-jasmine": "2.0.1",
"karma-jasmine-html-reporter": "1.4.2",
"karma-junit-reporter": "2.0.1",
"karma-verbose-reporter": "0.0.6",
</code>```

On Angular 7 I did not have a problem with this, my unit tests would execute regardless of linting errors. I am not sure what has changed or which configuration I should be checking to stop this from occurring.

The end goal is for unit tests to be able to run regardless of any frequency of linting errors.

angular.json contains the configuration for tests:

```<code>    "test": {
      "builder": "@angular-devkit/build-angular:karma",
      "options": {
        "main": "src/test.ts",
        "karmaConfig": "./karma.conf.js",
        "polyfills": "src/polyfills.ts",
        "tsConfig": "src/tsconfig.spec.json",
    ...etc...
</code>```

karma.conf

```<code>// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-junit-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma'),
      require('karma-verbose-reporter')
    ],
    client:{
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, 'coverage'), reports: [ 'html', 'lcovonly' ],
      fixWebpackSourcePaths: true
    },

    reporters: config.angularCli && config.angularCli.codeCoverage ? ['progress', 'coverage-istanbul', 'junit'] : ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['ChromeNoSandbox'],
    singleRun: false,
    junitReporter: {
      outputDir: process.env.JUNIT_REPORT_PATH,
      outputFile: process.env.JUNIT_REPORT_NAME,
      useBrowserName: false
    },
    customLaunchers: {
      ChromeNoSandbox: {
        base: 'ChromeHeadless',
        flags: ['--no-sandbox']
      }
    }
  });
};
</code>```

答:
This is TypeScript error, it means that noUnusedLocals is set to true in tsconfig.spec.json.

I think you can create inherited config i.e. tsconfig.spec.dev.json (use "extends": "./tsconfig.spec.json") and override noUnusedLocals value with false. Then you need to add configurations section:

```<code>    "test": {
      "builder": "@angular-devkit/build-angular:karma",
      "options": {
        "main": "src/test.ts",
        "polyfills": "src/polyfills.ts",
        "tsConfig": "tsconfig.spec.dev.json",
        "karmaConfig": "karma.conf.js",
        "assets": [
          "src/favicon.ico",
          "src/assets"
        ],
        "styles": [
          "src/styles.css"
        ],
        "scripts": []
      },
      "configurations": {
        "production": {
          "tsConfig": "tsconfig.spec.json"
        }
      }
    }
</code>```

Now you can run dev as ng test or prod as ng test --prod.

Body:
The output of my ng test is as follows:

> ng test

24 12 2019 14:20:07.854:WARN [karma]: No captured browser, open http://localhost:9876/
24 12 2019 14:20:07.860:INFO [karma-server]: Karma v4.4.1 server started at http://0.0.0.0:9876/
24 12 2019 14:20:07.860:INFO [launcher]: Launching browsers ChromeNoSandbox with concurrency unlimited
24 12 2019 14:20:07.865:INFO [launcher]: Starting browser ChromeHeadless

app/shared/forms/templates/templates.component.ts:11:1 - error TS6133: 'MatDialog' is declared but its value is never read.

11 import { MatDialog } from '@angular/material';
   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
24 12 2019 14:20:11.633:INFO [HeadlessChrome 79.0.3945 (Mac OS X 10.15.2)]: Connected on socket 9OfTSV7nahQakrDOAAAA with id 85821004
HeadlessChrome 79.0.3945 (Mac OS X 10.15.2): Executed 0 of 0 SUCCESS (0 secs / 0 secs)
HeadlessChrome 79.0.3945 (Mac OS X 10.15.2): Executed 0 of 0 SUCCESS (0.002 secs / 0 secs)
TOTAL: 0 SUCCESS
TOTAL: 0 SUCCESS

The issue I am having is that if I have any linting errors in my src code, then unit tests will not run, which is extremely inconvenient when I just want to try things here and there for test-driven development. I would much rather just get the warnings for these linting errors and I can fix them all at once.

I am on Angular version, "@angular/core": "8.1.2" and Karma versions:

"karma": "4.4.1",
"karma-chrome-launcher": "3.1.0",
"karma-cli": "2.0.0",
"karma-coverage-istanbul-reporter": "2.1.1",
"karma-jasmine": "2.0.1",
"karma-jasmine-html-reporter": "1.4.2",
"karma-junit-reporter": "2.0.1",
"karma-verbose-reporter": "0.0.6",

On Angular 7 I did not have a problem with this, my unit tests would execute regardless of linting errors. I am not sure what has changed or which configuration I should be checking to stop this from occurring.

The end goal is for unit tests to be able to run regardless of any frequency of linting errors.

angular.json contains the configuration for tests:

    "test": {
      "builder": "@angular-devkit/build-angular:karma",
      "options": {
        "main": "src/test.ts",
        "karmaConfig": "./karma.conf.js",
        "polyfills": "src/polyfills.ts",
        "tsConfig": "src/tsconfig.spec.json",
    ...etc...

karma.conf

// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-junit-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma'),
      require('karma-verbose-reporter')
    ],
    client:{
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, 'coverage'), reports: [ 'html', 'lcovonly' ],
      fixWebpackSourcePaths: true
    },

    reporters: config.angularCli && config.angularCli.codeCoverage ? ['progress', 'coverage-istanbul', 'junit'] : ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['ChromeNoSandbox'],
    singleRun: false,
    junitReporter: {
      outputDir: process.env.JUNIT_REPORT_PATH,
      outputFile: process.env.JUNIT_REPORT_NAME,
      useBrowserName: false
    },
    customLaunchers: {
      ChromeNoSandbox: {
        base: 'ChromeHeadless',
        flags: ['--no-sandbox']
      }
    }
  });
};

Body:
This is TypeScript error, it means that noUnusedLocals is set to true in tsconfig.spec.json.

I think you can create inherited config i.e. tsconfig.spec.dev.json (use "extends": "./tsconfig.spec.json") and override noUnusedLocals value with false. Then you need to add configurations section:

    "test": {
      "builder": "@angular-devkit/build-angular:karma",
      "options": {
        "main": "src/test.ts",
        "polyfills": "src/polyfills.ts",
        "tsConfig": "tsconfig.spec.dev.json",
        "karmaConfig": "karma.conf.js",
        "assets": [
          "src/favicon.ico",
          "src/assets"
        ],
        "styles": [
          "src/styles.css"
        ],
        "scripts": []
      },
      "configurations": {
        "production": {
          "tsConfig": "tsconfig.spec.json"
        }
      }
    }

Now you can run dev as ng test or prod as ng test --prod.


问:
Find all indices of each letter in a string
I'm trying to get a list consisting of the indexes for each item of another sequence.
Sounds easy enough in theory.

```<code>a = 'string of letters'
b = [a.index(x) for x in a]
</code>```

But it doesn't work. I've tried list comprehensions, simple for loops, using enumerate etc, but every time b will return the same index for duplicates in a.
That is, 's' in a, for example, will return '0' in b for both the first and last item because they're the same character.
I'm guessing is cache or something like that as a way for Python to speed things up.

In any case, I can't figure this out and I'd appreciate some help as to how I can get this working as well as maybe an explanation of why this happens.

答:
I refactored the code you posted as an answer, let me know if I understood things correctly.

from typing import List

def copy_case(a: str, b: str) -> str:
    res_chars: List[str] = []
    curr_a: str
    curr_b: str

    for curr_a, curr_b in zip(a, b):
        if curr_a.isupper():
            curr_b = curr_b.upper()
        else:
            curr_b = curr_b.lower()
        res_chars.append(curr_b)

    return ''.join(res_chars)

print(copy_case('tEXt', 'xTTe'))
```

Body:
I'm trying to get a list consisting of the indexes for each item of another sequence.
Sounds easy enough in theory.

a = 'string of letters'
b = [a.index(x) for x in a]

But it doesn't work. I've tried list comprehensions, simple for loops, using enumerate etc, but every time b will return the same index for duplicates in a.
That is, 's' in a, for example, will return '0' in b for both the first and last item because they're the same character.
I'm guessing is cache or something like that as a way for Python to speed things up.

In any case, I can't figure this out and I'd appreciate some help as to how I can get this working as well as maybe an explanation of why this happens.


问:
Multi provider relational user table in laravel
I am new in laravel and trying to create an auth system where user can login/register using multiple providers and whenever user logins using any of providers the user avatar and profile data must be shown accordingly. When using Auth::user()->providers the result is array of all registered providers for that user.

What I want is to fetch only provider data for current login method (i.e local account, facebook account provider, google account provider etc) so I can show data from that exact provider for user.

User.php

```<code>...
    public function providers()
    {
        return $this->hasMany("App\UserProvider");
    }
...
</code>```

UserProvider.php

```<code>class UserProvider Extends Model
{
    protected $table = 'user_providers';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_id', 'provider', 'provider_id','avatar_url', 'token', 'token_secret',
    ];

}
</code>```

Please let me know if I am on the right way or is there any other way to do this.
Thanks!

答:
You could also include a boolean column in your user_providers table to know which of the providers is the last used (so this will be the current login method). Let's call this column is_current.

So, when a user access the system, you update the login method setting this field to true. You can do this by overriding the authenticated() method of the app\Http\Controllers\LoginController controller:

```<code># app\Http\Controllers\LoginController.php

protected function authenticated(Request $request, $user)
{
    Auth::user()
          ->providers()
          ->where('provider', $request->provider) // Change this to make it work
          ->update('is_current', true);
}
</code>```

This way, you can access your current login method wherever you want, doing this:

```<code>Auth::user()->providers()->whereTrue('is_current')->first();
</code>```

Of course, you could make an accessor in your model to shorten this:

```<code># User.php

public function getCurrentProviderAttribute()
{
    return $this->providers()->where('is_current', true)->first();
}
</code>```

So now, you can do simply:

```<code>Auth::user()->current_provider;
</code>```

Body:
I am new in laravel and trying to create an auth system where user can login/register using multiple providers and whenever user logins using any of providers the user avatar and profile data must be shown accordingly. When using Auth::user()->providers the result is array of all registered providers for that user.

What I want is to fetch only provider data for current login method (i.e local account, facebook account provider, google account provider etc) so I can show data from that exact provider for user.

User.php

...
    public function providers()
    {
        return $this->hasMany("App\UserProvider");
    }
...

UserProvider.php

class UserProvider Extends Model
{
    protected $table = 'user_providers';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_id', 'provider', 'provider_id','avatar_url', 'token', 'token_secret',
    ];

}

Please let me know if I am on the right way or is there any other way to do this.
Thanks!

Body:
You could also include a boolean column in your user_providers table to know which of the providers is the last used (so this will be the current login method). Let's call this column is_current.

So, when a user access the system, you update the login method setting this field to true. You can do this by overriding the authenticated() method of the app\Http\Controllers\LoginController controller:

# app\Http\Controllers\LoginController.php

protected function authenticated(Request $request, $user)
{
    Auth::user()
          ->providers()
          ->where('provider', $request->provider) // Change this to make it work
          ->update('is_current', true);
}

This way, you can access your current login method wherever you want, doing this:

Auth::user()->providers()->whereTrue('is_current')->first();

Of course, you could make an accessor in your model to shorten this:

# User.php

public function getCurrentProviderAttribute()
{
    return $this->providers()->where('is_current', true)->first();
}

So now, you can do simply:

Auth::user()->current_provider;


问:
How to fix supportFragmentManager?
Im trying to put google maps into SupportMapFragment on my MainActivity file like these ways:

```<code>val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as? SupportMapFragment
        mapFragment?.getMapAsync(this)
</code>```

and

```<code>val mapFragment = supportFragmentManager
            .findFragmentById(R.id.map) as SupportMapFragment
        mapFragment.getMapAsync(this)
</code>```

And modifying my content_main.xml like:

```<code> <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal"
                android:gravity="center_vertical">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/app_name"
                    android:textColor="#FFFFFF"
                    style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"/>
            </LinearLayout>
</code>```

and

```<code><LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_weight="13"
                android:orientation="horizontal"
                android:gravity="center_vertical">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/app_name"
                    android:textColor="#FFFFFF"
                    style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"/>
            </LinearLayout>
</code>```

but the application is working like the next way:

Any advice?

EDIT
This is my Activity_Main.xml:

```<code><include
        xmlns:tools="http://schemas.android.com/tools"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        layout="@layout/content_main"
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

<!--<fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />-->
</code>```

ps. I removed the <fragment> tag to debug some parts.

答:
I solved it; as the guys taugh me in the comments, I'm going to post for future references if someone has same situation:

```<code>val mapFragment = SupportMapFragment.newInstance()
        supportFragmentManager.beginTransaction().add(R.id.map, mapFragment)
            .commit()
        mapFragment.getMapAsync(this)
</code>```

Thank you.

Title: How to fix supportFragmentManager?

Body:
Im trying to put google maps into SupportMapFragment on my MainActivity file like these ways:

val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as? SupportMapFragment
        mapFragment?.getMapAsync(this)

and

val mapFragment = supportFragmentManager
            .findFragmentById(R.id.map) as SupportMapFragment
        mapFragment.getMapAsync(this)

And modifying my content_main.xml like:

 <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal"
                android:gravity="center_vertical">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/app_name"
                    android:textColor="#FFFFFF"
                    style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"/>
            </LinearLayout>

and

<LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_weight="13"
                android:orientation="horizontal"
                android:gravity="center_vertical">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/app_name"
                    android:textColor="#FFFFFF"
                    style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"/>
            </LinearLayout>

but the application is working like the next way:

Any advice?

EDIT
This is my Activity_Main.xml:

<include
        xmlns:tools="http://schemas.android.com/tools"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        layout="@layout/content_main"
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

ps. I removed the <fragment> tag to debug some parts.

Body:
I solved it; as the guys taugh me in the comments, I'm going to post for future references if someone has same situation:

val mapFragment = SupportMapFragment.newInstance()
        supportFragmentManager.beginTransaction().add(R.id.map, mapFragment)
            .commit()
        mapFragment.getMapAsync(this)

Thank you.


问:
JavaFX WebView: how to block resources from a specific website?
Is there a way to block resources (images, scripts, css sheets, etc) from either a specific website or all websites when using the JavaFX WebView?

Basically, I would like to stop the src attribute and href attribute from working depending on their content.

答:
An easy way is to add a content security policy via a meta tag at the very beginning of the document:

<meta http-equiv="Content-Security-Policy" content=style-src 'unsafe-inline'; script-src 'unsafe-inline' 'unsafe-eval'">
```


问:
Changing the AcceptButton depending on active control
I have a working WinForm that handles the search functionality in my customer database. It contains the following controls:

A textBox where you type your search string (A)

A "search" button (B)

A DataGridView (C) that returns the result of the search

An "OK" button (D) and a "Cancel" button (E)

What I am trying to accieve next is this:

When A is active the AcceptButton (enter) should be linked to B

When B or enter is pressed C should become active

When C is active the AcceptButton should be linked to D

I realise this is a somewhat big question so don't hesitate to answer just one of the bullet marks if you know the answer.

EDIT: I have solved the implementation of requirement 1 and 3 above, but I am still looking for an answer to the second one. To clarify, when the search is initiated (meaning i have pressed enter on the keyboard or the search button with the mouse) I want focus to shift to the first line in the DataGridView.

答:
```<code>private void WhateverControl_Enter(...)
{
    this.AcceptButton = myButton;
}
</code>```

OwnerDisplayName: Sakkle

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Sakkle

OwnerDisplayName: SnOrfus

ContentLicense: CC BY-SA 3.0


问:
The picture shown on google search
When I googled my website on mobile, google showed the picture next to my website. The picture is on my site, but I want another picture to be shown. Is there any way to change it?</p>

答:
You can indicate to Google which image you'd like used for your property using Schema.org markup. Here's a quick company website example:</p>

```<code><script type="application/ld+json">
{"@context" : "http://schema.org",
 "@type" : "Organization",
  "name" : "Example Company",
  "url" : "https://www.example.org",
  "logo": "https://www.example.org/images/my-logo.png" }
</script>
</code>```

Title: The picture shown on google search

Body:
You can indicate to Google which image you'd like used for your property using Schema.org markup. Here's a quick company website example:

<script type="application/ld+json">
{"@context" : "http://schema.org",
 "@type" : "Organization",
  "name" : "Example Company",
  "url" : "https://www.example.org",
  "logo": "https://www.example.org/images/my-logo.png" }
</script>


问:
ffmpeg: no matches found: -map[v]
I am trying to merge 4 videos in split-screen with their audio together.

```<code>./ffmpeg -i ./clip11.mp4 -i ./clip21.mp4 -i ./clip31.mp4 -i ./clip41.mp4  -filter_complex "[0:v][1:v]hstack=inputs=2[top];[2:v][3:v]hstack=inputs=2[bottom];[top][bottom]vstack=inputs=2[v];amerge=inputs=4[a]" -map[v] -map[a] ./split21.mp4
</code>```

I try tried and run the code, but it shows this as an error.

```<code>zsh: no matches found: -map[v]
</code>```

I don't know whether my machine cannot configure the "map" because it happens the same thing when I tried to do "concat". I do not know what else to change about. I typed it out on the latest Mac, but surprisingly my friend that have an older version of Mac got the code working. Help.

答: Looks like it's zsh that complains that a file pattern is not matching any file. Try to add a space and put quotes around the patterns like this -map "[v]" -map "[a]" to no expand them.

Title: ffmpeg: no matches found: -map[v]

Body:
I am trying to merge 4 videos in split-screen with their audio together.

./ffmpeg -i ./clip11.mp4 -i ./clip21.mp4 -i ./clip31.mp4 -i ./clip41.mp4  -filter_complex "[0:v][1:v]hstack=inputs=2[top];[2:v][3:v]hstack=inputs=2[bottom];[top][bottom]vstack=inputs=2[v];amerge=inputs=4[a]" -map[v] -map[a] ./split21.mp4

I try tried and run the code, but it shows this as an error.

zsh: no matches found: -map[v]

I don't know whether my machine cannot configure the "map" because it happens the same thing when I tried to do "concat". I do not know what else to change about. I typed it out on the latest Mac, but surprisingly my friend that have an older version of Mac got the code working. Help.


问:
Automatically suspend process
I saw that Windows/Linux has the ability to suspend a process.
It is wired for me why background applications are not suspended automatically.

For example, lots of resources are used by Chrome when it is in the background. Easily it can be suspended. So it will stay in RAM and it can unsuspend quickly but it will not use CPU and GPU.

My question contains two parts:

Why Windows/Linux (or applications) don't use suspend feature? (sth similar to pause in Android but in the different way)

Is there any way to suspend a background task and unsuspend it when it gets focus (when it goes to foreground)?

答:
A process like Chrome might not have input focus on the user interface but still be "running."  (Chrome consists of a set of related processes and threads.)

Yes, Linux does have the ability to actually "suspend" a process using the STOP/CONT signals, but this would be disruptive to the user interface because Chrome, now being literally frozen, could no longer respond to messages sent to it by the user interface.

Processes and threads only consume CPU resources when they actually need to (they are "runnable"), and then only when the operating system gives them a time-slice.  If a thread or process is, say, "waiting for the user interface to send it a message," it's not considered to be "runnable" until a message arrives.

It's also typical that, when a process doesn't have input focus, its priority is slightly reduced so that it always gives-way to the process that does.  In some systems, the priority is even more reduced when you minimize the window.  (When several processes are "runnable," the operating system uses "priority" to help it to decide which one to run next.)

Title: Automatically suspend process


问:
bootstrap-vue : how to recognize hover event over b-tab
I'm trying to change the active tab of a bootstrap-vue b-tabs when the tab title is hovered over, not only when clicked on. I'm having trouble isolating this event.

In the following Codepen example, I can isolate the event when the image is being hovered over, however I want to isolate the event when the title ('Tubes and Vials' for example) is being hovered over.

I'm fairly new to Vue so I apologize if this is a simple answer, but I haven't struggled with this for a while now and haven't been able to figure this out. Thanks!

Component File

```<code><template>
    <b-container class="px-3" fluid>
        <div>
            <h3>Range Of Glass Products We Inspect</h3>
            <p>Anything formed from tubular glass</p>
        </div>
        <div>
            <b-tabs content-class="mt-3" align="left" class="vial-types" vertical>
                <b-tab
                        v-for="glassItem in productRange"
                        v-bind:key="glassItem.type"
                        v-bind:ref="glassItem"
                        v-bind:title="glassItem.type"
                        @mouseover.native="greet()"
                        @mouseleave.native="greet()"
                >
                    <b-img
                            v-bind:src="glassItem.image"
                            alt="Factory Image">
                    </b-img>
                </b-tab>
            </b-tabs>
        </div>
    </b-container>
</template>

<script>
    export default {
        name: "ProductRange",
        data() {
            return {
                productRange: [
                    {type: "Screw & Flanged Head", image:"https://picsum.photos/600/400/", hover: false},
                    {type: "Tubes and Vials", image:"https://picsum.photos/600/400/", hover: false},
                    {type: "Pipettes, Syringes, Filling Needles", image:"https://picsum.photos/400/400/",hover: false},
                    {type: "Ampoules", image:"https://picsum.photos/600/400/", hover: false},
                    {type: "Custom Geometries Per Customer Specification", image:"https://picsum.photos/600/400/", hover: false}
                ]
            }
        },
        methods: {
            greet: function () {
                console.log("Hovering");
            }
        }
    }
</script>

<style lang="sass">

</style>
</code>```

答:
You could also use the b-tab's title slot, and then add a hover/unhover listener in there:

    <template v-slot:title>

        {{ glassItem.type }}

    </template>

```

Body:
I'm trying to change the active tab of a bootstrap-vue b-tabs when the tab title is hovered over, not only when clicked on. I'm having trouble isolating this event.

In the following Codepen example, I can isolate the event when the image is being hovered over, however I want to isolate the event when the title ('Tubes and Vials' for example) is being hovered over.

I'm fairly new to Vue so I apologize if this is a simple answer, but I haven't struggled with this for a while now and haven't been able to figure this out. Thanks!

Component File

<template>

Range Of Glass Products We Inspect

Anything formed from tubular glass

</template>

Body:
You could also use the b-tab's title slot, and then add a hover/unhover listener in there:

<b-tabs content-class="mt-3" align="left" class="vial-types" vertical>
  <b-tab
    v-for="glassItem in productRange"
    v-bind:key="glassItem.type"
    v-bind:ref="glassItem"
  >
    <template v-slot:title>
      <div
        @mouseover="hovered"
        @mouseleave="unHovered"
      >
        {{ glassItem.type }}
      </div>
    </template>
    <b-img
      v-bind:src="glassItem.image"
      alt="Factory Image">
    </b-img>
  </b-tab>
</b-tabs>


问:
Is Laravel blade '@include()' case-sensitive?
I'm getting a "blade not found shop.cart.favorites" error when running in Docker on Ubuntu.  (Therefore: "case-sensitive file system.")

I suspect that the culprit is case-sensitivity.  The path to the blade file is:

```<code> resources/views/Shop/Cart/favorites.blade.php
                 ^    ^
</code>```

Did I guess correctly?

答:
You have made a little mistake bro...

Change in your Controller/Function where you defined the View .Like this.....

```<code>return View('Shop.Cart.favorites');
</code>```

It will work..  Check it out..

Thank you.

Body:
I'm getting a "blade not found shop.cart.favorites" error when running in Docker on Ubuntu.  (Therefore: "case-sensitive file system.")

I suspect that the culprit is case-sensitivity.  The path to the blade file is:

 resources/views/Shop/Cart/favorites.blade.php
                 ^    ^

Did I guess correctly?

Body:
You have made a little mistake bro...

Change in your Controller/Function where you defined the View .Like this.....

return View('Shop.Cart.favorites');

It will work..  Check it out..

Thank you.


问:
How to Split Image Into Multiple Pieces in Python
I'm trying to split a photo into multiple pieces using PIL.

```<code>def crop(Path,input,height,width,i,k,x,y,page):
    im = Image.open(input)
    imgwidth = im.size[0]
    imgheight = im.size[1]
    for i in range(0,imgheight-height/2,height-2):
        print i
        for j in range(0,imgwidth-width/2,width-2):
            print j
            box = (j, i, j+width, i+height)
            a = im.crop(box)
            a.save(os.path.join(Path,"PNG","%s" % page,"IMG-%s.png" % k))
            k +=1
</code>```

but it doesn't seem to be working. It splits the photo but not in an exact way (you can try it).

答:
I tried the solutions above, but sometimes you just gotta do it yourself.
Might be off by a pixel in some cases but works fine in general.

```<code>import matplotlib.pyplot as plt
import numpy as np
def image_to_tiles(im, number_of_tiles = 4, plot=False):
    """
    Function that splits SINGLE channel images into tiles
    :param im: image: single channel image (NxN matrix)
    :param number_of_tiles: squared number
    :param plot:
    :return tiles:
    """
    n_slices = np.sqrt(number_of_tiles)
    assert int(n_slices + 0.5) ** 2 == number_of_tiles, "Number of tiles is not a perfect square"

    n_slices = n_slices.astype(np.int)
    [w, h] = cropped_npy.shape

    r = np.linspace(0, w, n_slices+1)
    r_tuples = [(np.int(r[i]), np.int(r[i+1])) for i in range(0, len(r)-1)]
    q = np.linspace(0, h, n_slices+1)
    q_tuples = [(np.int(q[i]), np.int(q[i+1])) for i in range(0, len(q)-1)]

    tiles = []
    for row in range(n_slices):
        for column in range(n_slices):
            [x1, y1, x2, y2] = *r_tuples[row], *q_tuples[column]
            tiles.append(im[x1:y1, x2:y2])

    if plot:
        fig, axes = plt.subplots(n_slices, n_slices, figsize=(10,10))
        c = 0
        for row in range(n_slices):
            for column in range(n_slices):
                axes[row,column].imshow(tiles[c])
                axes[row,column].axis('off')
                c+=1

    return tiles
</code>```

Hope it helps.

Body:
I'm trying to split a photo into multiple pieces using PIL.

def crop(Path,input,height,width,i,k,x,y,page):
    im = Image.open(input)
    imgwidth = im.size[0]
    imgheight = im.size[1]
    for i in range(0,imgheight-height/2,height-2):
        print i
        for j in range(0,imgwidth-width/2,width-2):
            print j
            box = (j, i, j+width, i+height)
            a = im.crop(box)
            a.save(os.path.join(Path,"PNG","%s" % page,"IMG-%s.png" % k))
            k +=1

but it doesn't seem to be working. It splits the photo but not in an exact way (you can try it).

Body:
I tried the solutions above, but sometimes you just gotta do it yourself.
Might be off by a pixel in some cases but works fine in general.

import matplotlib.pyplot as plt
import numpy as np
def image_to_tiles(im, number_of_tiles = 4, plot=False):
    """
    Function that splits SINGLE channel images into tiles
    :param im: image: single channel image (NxN matrix)
    :param number_of_tiles: squared number
    :param plot:
    :return tiles:
    """
    n_slices = np.sqrt(number_of_tiles)
    assert int(n_slices + 0.5) ** 2 == number_of_tiles, "Number of tiles is not a perfect square"

    n_slices = n_slices.astype(np.int)
    [w, h] = cropped_npy.shape

    r = np.linspace(0, w, n_slices+1)
    r_tuples = [(np.int(r[i]), np.int(r[i+1])) for i in range(0, len(r)-1)]
    q = np.linspace(0, h, n_slices+1)
    q_tuples = [(np.int(q[i]), np.int(q[i+1])) for i in range(0, len(q)-1)]

    tiles = []
    for row in range(n_slices):
        for column in range(n_slices):
            [x1, y1, x2, y2] = *r_tuples[row], *q_tuples[column]
            tiles.append(im[x1:y1, x2:y2])

    if plot:
        fig, axes = plt.subplots(n_slices, n_slices, figsize=(10,10))
        c = 0
        for row in range(n_slices):
            for column in range(n_slices):
                axes[row,column].imshow(tiles[c])
                axes[row,column].axis('off')
                c+=1

    return tiles

Hope it helps.


问:
Append multiple dummy objects to json array with jq
Lets say this is my array :

```<code>[
  {
    "name": "Matias",
    "age": "33"
  }
]
</code>```

I can do this :

```<code>echo "$response" | jq '[ .[] | select(.name | test("M.*"))] | . += [.[]]'
</code>```

And it will output :

```<code>[
  {
    "name": "Matias",
    "age": "33"
  },
  {
    "name": "Matias",
    "age": "33"
  }
]
</code>```

But I cant do this :

```<code>echo "$response" | jq '[ .[] | select(.name | test("M.*"))] | . += [.[] * 3]'
jq: error (at <stdin>:7): object ({"name":"Ma...) and number (3) cannot be multiplied
</code>```

I need to extend an array to create a dummy array with 100 values. And I cant do it. Also, I would like to have a random age on the objects. ( So later on I can filter the file to measure performance of an app .

答:
Currently jq does not have a built-in randomization function, but it's easy enough to generate random numbers that jq can use.  The following solution uses awk but in a way that some other PRNG can easily be used.

```<code>#!/bin/bash

function template {
    cat<<EOF
[
  {
    "name": "Matias",
    "age": "33"
  }
]

EOF
}

function randoms {
    awk -v n=$1 'BEGIN { for(i=0;i<n;i++) {print int(100*rand())} }'
}

randoms 100 | jq -n --argfile template <(template) '
  first($template[] | select(.name | test("M.*"))) as $t
  | [ $t | .age = inputs]
'
</code>```

Note on performance

Even though the above uses awk and jq together, this combination is about 10 times faster than the posted jtc solution using -eu:

jq+awk:          u+s = 0.012s

jtc with -eu:    u+s = 0.192s

Using jtc in conjunction with awk as above, however, gives u+s == 0.008s on the same machine.

Body:
Lets say this is my array :

[
  {
    "name": "Matias",
    "age": "33"
  }
]

I can do this :

echo "$response" | jq '[ .[] | select(.name | test("M.*"))] | . += [.[]]'

And it will output :

[
  {
    "name": "Matias",
    "age": "33"
  },
  {
    "name": "Matias",
    "age": "33"
  }
]

But I cant do this :

echo "$response" | jq '[ .[] | select(.name | test("M.*"))] | . += [.[] * 3]'
jq: error (at <stdin>:7): object ({"name":"Ma...) and number (3) cannot be multiplied

I need to extend an array to create a dummy array with 100 values. And I cant do it. Also, I would like to have a random age on the objects. ( So later on I can filter the file to measure performance of an app .

Body:
Currently jq does not have a built-in randomization function, but it's easy enough to generate random numbers that jq can use.  The following solution uses awk but in a way that some other PRNG can easily be used.

#!/bin/bash

function template {
    cat<<EOF
[
  {
    "name": "Matias",
    "age": "33"
  }
]

EOF
}

function randoms {
    awk -v n=$1 'BEGIN { for(i=0;i<n;i++) {print int(100*rand())} }'
}

randoms 100 | jq -n --argfile template <(template) '
  first($template[] | select(.name | test("M.*"))) as $t
  | [ $t | .age = inputs]
'

Note on performance

Even though the above uses awk and jq together, this combination is about 10 times faster than the posted jtc solution using -eu:

jq+awk:          u+s = 0.012s

jtc with -eu:    u+s = 0.192s

Using jtc in conjunction with awk as above, however, gives u+s == 0.008s on the same machine.


问:
Add class when (...) with jQuery
I've this simple code:

HTML:

```<code><input type="text" name="name" class="required" />

<select id="options" name="options" size="1">
  <option value="0"> YES </option>
  <option value="1"> NO </option>
</select>

<input type="text" name="email" />
<input type="text" name="city" />
</code>```

Question:

I want to add class = "required"  to email and city fields when options is equal to 1

答:
```<code>if( $('#options').val() == "1"){
   $('#email, #city').addClass('required');
}
</code>```

Title: Add class when (...) with jQuery

Body:
I've this simple code:

HTML:

<input type="text" name="name" class="required" />

<select id="options" name="options" size="1">
  <option value="0"> YES </option>
  <option value="1"> NO </option>
</select>

<input type="text" name="email" />
<input type="text" name="city" />

Question:

I want to add class = "required"  to email and city fields when options is equal to 1


问:
How can I add content:"NEW" to paragraphs 2 & 3 using only CSS?

help me put content="NEW" with css, but only in paragraf 2 and 3.

i mustn't change html code.

if possible pls wiht pseudo classes.

```<code><div id="first-div">
  <h2>Subheading</h2>
  <p>Paragraph 2</p> <!-- i need to add content here-->
  <p>Paragraph 3</p> <!--and here -->
  <div id="second-div">
     <h3>Sub subheading</h3>
     <p>Paragraph 4</p>
     <p>Paragraph 5</p>
     <p>Paragraph 6</p>
     <p>Paragraph 7</p>
     <p>Paragraph 8</p>
  </div>
</div>
<p>Paragraph 9</p>
<p>Paragraph 10</p>
</code>```

答:
What you want to do is first look at #first-div and drill down on its children using the direct descendant operator (>).

In case you need 2 specific elements, you can use the direct child operator along with the nth-child function.

```<code>#first-div > p:nth-child(2):after,
#first-div > p:nth-child(3):after {
  color: red;
  content: "NEW";
}
</code>```

If you need all p tags under #first-div, just select all of them

```<code>#first-div > p:after {
  color: red;
  content: "NEW";
}
</code>```

Body:
help me put content="NEW" with css, but only in paragraf 2 and 3.

i mustn't change html code.

if possible pls wiht pseudo classes.

Subheading

Paragraph 2

Paragraph 3

Sub subheading

Paragraph 4

Paragraph 5

Paragraph 6

Paragraph 7

Paragraph 8

Paragraph 9

Paragraph 10

Body:
What you want to do is first look at #first-div and drill down on its children using the direct descendant operator (>).

In case you need 2 specific elements, you can use the direct child operator along with the nth-child function.

#first-div > p:nth-child(2):after,
#first-div > p:nth-child(3):after {
  color: red;
  content: "NEW";
}

If you need all p tags under #first-div, just select all of them

#first-div > p:after {
  color: red;
  content: "NEW";
}


问:
How to add a timestamp of a prepared stmt to mysql database when code is run?
```<code>$stmt = $conn->prepare("INSERT INTO users (username,created) VALUES (?,?)");
$stmt->bind_param("ss", $_POST['username-reg','whatdoiputhere?']);
$stmt->execute();
</code>```

I want to add a "now" date/timestamp that can also be inserted simultaneously so that i can keep track of when users create accounts. is there a function that i need to write/reference to get the current date? or is there an already known function that i just need to reference? i am new to php, sorry

答:
You can use NOW() :

```<code>$stmt = $conn->prepare("INSERT INTO users (username,created) VALUES (?, NOW())");
$stmt->bind_param("s", $_POST['username-reg']);
$stmt->execute();
</code>```

Body:
$stmt = $conn->prepare("INSERT INTO users (username,created) VALUES (?,?)");
$stmt->bind_param("ss", $_POST['username-reg','whatdoiputhere?']);
$stmt->execute();

I want to add a "now" date/timestamp that can also be inserted simultaneously so that i can keep track of when users create accounts. is there a function that i need to write/reference to get the current date? or is there an already known function that i just need to reference? i am new to php, sorry

Body:
You can use NOW() :

$stmt = $conn->prepare("INSERT INTO users (username,created) VALUES (?, NOW())");
$stmt->bind_param("s", $_POST['username-reg']);
$stmt->execute();


答:
You can leverage MySQL's timestamp initialization feature.

This works by adding a timestamp column to the table with the default current_timestamp option:

```<code>create table users (
    user_id int primary key auto_increment,
    username varchar(50),
    ts_created timestamp default current_timestamp
);
</code>```

With this set-up in place, you don't have to worry about that column anymore. Just ignore it when you insert, and the database will automatically set it as needed:

```<code>$stmt = $conn->prepare("INSERT INTO users (username) VALUES (?)");
$stmt->bind_param("ss", $_POST['username-reg']);
$stmt->execute();
</code>```

Note: if you also want the timestamp to be updated when the record is modified, you can add the on update current_timestamp to the definition of the column.

Title: How to add a timestamp of a prepared stmt to mysql database when code is run?

Body:
You can leverage MySQL's timestamp initialization feature.

This works by adding a timestamp column to the table with the default current_timestamp option:

create table users (
    user_id int primary key auto_increment,
    username varchar(50),
    ts_created timestamp default current_timestamp
);

With this set-up in place, you don't have to worry about that column anymore. Just ignore it when you insert, and the database will automatically set it as needed:

$stmt = $conn->prepare("INSERT INTO users (username) VALUES (?)");
$stmt->bind_param("ss", $_POST['username-reg']);
$stmt->execute();

Note: if you also want the timestamp to be updated when the record is modified, you can add the on update current_timestamp to the definition of the column.


问:
How to conditionally render a React component that uses hooks
The following (albeit contrived) component violates react-hooks/rules-of-hooks (via eslint)

```<code>function Apple(props){
  const {seeds} = props;
  if(!seeds){
    return null;
  }
  const [bitesTaken, setBitesTaken] = useState(0);
  return <div>{bitesTaken}</div>
}

</code>```

with the following error
React Hook "useState" is called conditionally. React Hooks must be called in the exact same order in every component render. Did you accidentally call a React Hook after an early return?

I understand that hooks need to be called in the same order, but this kind of conditional rendering (so long as no hooks are invoked before the return, does not prevent the hooks from being called in the same order.  I think the eslint rule is too strict, but maybe there's a better way.

What is the best way to conditionally render a component which uses hooks?

答:
Another option is to split the component.

```<code>import React,{useState} from 'react';

const Apple = (props) => {
    const {seeds} = props;
    return !!seeds && <AppleWithSeeds />;
};

const AppleWithSeeds =(props) => {
    const [bitesTaken] = useState(0);
    return <div>{bitesTaken}</div>
};

export default Apple;
</code>```

Advantage of this method is that your components stay small and logical.

And in your case you might have something more than '0' in the useState initializer which you don't want unnecessary at the top before the condition.

Body:
The following (albeit contrived) component violates react-hooks/rules-of-hooks (via eslint)

function Apple(props){
  const {seeds} = props;
  if(!seeds){
    return null;
  }
  const [bitesTaken, setBitesTaken] = useState(0);
  return
{bitesTaken}

}

with the following error
React Hook "useState" is called conditionally. React Hooks must be called in the exact same order in every component render. Did you accidentally call a React Hook after an early return?

I understand that hooks need to be called in the same order, but this kind of conditional rendering (so long as no hooks are invoked before the return, does not prevent the hooks from being called in the same order.  I think the eslint rule is too strict, but maybe there's a better way.

What is the best way to conditionally render a component which uses hooks?

Body:
Another option is to split the component.

import React,{useState} from 'react';

const Apple = (props) => {
    const {seeds} = props;
    return !!seeds && <AppleWithSeeds />;
};

const AppleWithSeeds =(props) => {
    const [bitesTaken] = useState(0);
    return <div>{bitesTaken}</div>
};

export default Apple;

Advantage of this method is that your components stay small and logical.

And in your case you might have something more than '0' in the useState initializer which you don't want unnecessary at the top before the condition.


问:
CSS Backround Autosizing Issues
I am very new to web development and am in need of some help. I have built a login page using JavaScript, html, and CSS. I want my background to autosize to fit the screen of whatever device is accessing the page. I've researched how to do this and have implemented it through this CSS styling:

```<code>    body, html {
      background: url("/images/Test.jpg"), #2d2d2d;
      height: 100%;
      width: 100%;
      background-repeat: no-repeat;
    }
</code>```

Any ideas on how I can fix this? Thanks.

答: background-size: cover; might be your hero in css ;)

Title: CSS Backround Autosizing Issues

Body:
I am very new to web development and am in need of some help. I have built a login page using JavaScript, html, and CSS. I want my background to autosize to fit the screen of whatever device is accessing the page. I've researched how to do this and have implemented it through this CSS styling:

    body, html {
      background: url("/images/Test.jpg"), #2d2d2d;
      height: 100%;
      width: 100%;
      background-repeat: no-repeat;
    }

Any ideas on how I can fix this? Thanks.


问:
Don't start every fragment at once in ViewPager
I have implemented a View Pager in my app. It slides between to fragments, the problem is, even if only the first fragment is being display, the other fragment gets created.
That causes problems because, in the second fragment I'm displaying a Loading Bar and this way it shows in the first fragment instead of the second one.

This is my ViewPager code:

```<code>
class FragmentViewPagerAdapter(fm: FragmentManager) : FragmentStatePagerAdapter(fm) {

    override fun getItem(position: Int): Fragment {
        if (position == 0){
            return VentFragment()
        }
        return ConversationsFragment()
    }

    override fun getCount(): Int {
        return 2
    }

}
</code>```

In the second fragment I call the Loading Bar this way in onCreateView:

```<code> loading = ProgressDialog(context)

        loading.setTitle(getString(R.string.loading))
        loading.setMessage(getString(R.string.fetching_your_data))
        loading.setCanceledOnTouchOutside(false)
        loading.show()
</code>```

Is it because of the context? I can't seem to find the bug...

答:
the problem is, even if only the first fragment is being display, the other fragment gets created

That is the way ViewPager works. It needs the second fragment to be available in order to transition to it when the user swipes, rather than wait for you to create it after the user has started swiping.

in the second fragment I'm displaying a Loading Bar and this way it shows in the first fragment instead of the second one

Your second fragment has a bug. A fragment — particularly one a ViewPager — should not be modifying UI that lives outside of the fragment itself. If you fix this bug, your problem with ViewPager should go away.

Body:
I have implemented a View Pager in my app. It slides between to fragments, the problem is, even if only the first fragment is being display, the other fragment gets created.
That causes problems because, in the second fragment I'm displaying a Loading Bar and this way it shows in the first fragment instead of the second one.

This is my ViewPager code:

class FragmentViewPagerAdapter(fm: FragmentManager) : FragmentStatePagerAdapter(fm) {

    override fun getItem(position: Int): Fragment {
        if (position == 0){
            return VentFragment()
        }
        return ConversationsFragment()
    }

    override fun getCount(): Int {
        return 2
    }

}

In the second fragment I call the Loading Bar this way in onCreateView:

 loading = ProgressDialog(context)

        loading.setTitle(getString(R.string.loading))
        loading.setMessage(getString(R.string.fetching_your_data))
        loading.setCanceledOnTouchOutside(false)
        loading.show()

Is it because of the context? I can't seem to find the bug...


问:
sscanf_s doesn't return first character of string
I'm trying to find the first string (max 4 characters) in a comma-separated list of strings inside a C char-array.

I'm trying to achieve this by using sscanf_s (under Windows) and the format-control string %[^,]:

```<code>char mystring[] = "STR1,STR2";
char temp[5];

if (sscanf_s(mystring, "%[^,]", temp, 5) != 0) {
    if (strcmp(temp, "STR1") == 0) { return 0; }
    else if (strcmp(temp, "STR2") == 0) { return 1; }
    else { return -1; }
}
</code>```

After calling sscanf_s the content of temp is not STR1 but \0TR1 (\0 being the ASCII-interpretation of 0). And the value -1 is returned.

Why do I get that behavior and how do I fix my code to get the right result (return of 0)?

EDIT: changed char mystring to mystring[] (I should have made sure I typed it correcly here)

答:
There are multiple problems in your code:

mystring is defined as a char, not a string pointer.

the argument 5 following temp in sscanf_s() should have type rsize_t, which is the same as size_t. You should specify it as sizeof(temp).

you should specify the maximum number of characters to store into the destination array in the format string, to avoid the counter-intuitive behavior of sscanf_s in case of overflow.

sscanf_s returns 1 if it can convert and store the string. Testing != 0 will also accept EOF which is an input failure, for which the contents of temp is indeterminate.

Here is a modified version:

const char *mystring = "STR1,STR2";
char temp[5];

if (sscanf_s(mystring, "%4[^,]", temp, sizeof temp) == 1) {
    if (strcmp(temp, "STR1") == 0) {
        return 0;
    } else
    if (strcmp(temp, "STR2") == 0) {
        return 1;
    } else {
        return -1;
    }
}
```
<p><strong>UPDATE:</strong> The OP uses Microsoft Visual Studio, which seems to have a non-conforming implementation of the so-called <em>secure</em> stream functions. Here is a citation from their documentation page:</p>
<blockquote>
<p>The <code>sscanf_s</code> function reads data from buffer into the location that's given by each argument. The arguments after the format string specify pointers to variables that have a type that corresponds to a type specifier in format. Unlike the less secure version <code>sscanf</code>, a buffer size parameter is required when you use the type field characters <code>c</code>, <code>C</code>, <code>s</code>, <code>S</code>, or string control sets that are enclosed in <code>[]</code>. The buffer size in characters must be supplied as an additional parameter immediately after each buffer parameter that requires it. For example, if you are reading into a string, the buffer size for that string is passed as follows:</p>
```wchar_t ws[10];
swscanf_s(in_str, L"%9s", ws, (unsigned)_countof(ws)); // buffer size is 10, width specification is 9
```
<p>The buffer size includes the terminating null. A width specification field may be used to ensure that the token that's read in will fit into the buffer. If no width specification field is used, and the token read in is too big to fit in the buffer, nothing is written to that buffer.</p>
<p>In the case of characters, a single character may be read as follows:</p>
```wchar_t wc;
swscanf_s(in_str, L"%c", &wc, 1);
```
<p>This example reads a single character from the input string and then stores it in a wide-character buffer. When you read multiple characters for non-null terminated strings, unsigned integers are used as the width specification and the buffer size.</p>
```char c[4];
sscanf_s(input, "%4c", &c, (unsigned)_countof(c)); // not null terminated
```
<p>This example reads a single character from the input string and then stores it in a wide-character buffer. When you read multiple characters for non-null terminated strings, unsigned integers are used as the width specification and the buffer size.</p>
```char c[4];
sscanf_s(input, "%4c", &c, (unsigned)_countof(c)); // not null terminated
```
</blockquote>
<p>This specification is incompatible with the C Standard, that specifies the type of the width arguments to be <code>rsize_t</code> and type <code>rsize_t</code> to be the same type as <code>size_t</code>.</p>
<p>As a conclusion, for improved portability, one should avoid using these <em>secure</em> functions and use the standard functions correctly, with the length prefix to prevent buffer overruns.</p>
<p>You can prevent the Visual Studio warning about deprecation of <code>sscanf</code> by inserting this definition before including <code><stdio.h></code>:</p>
```#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS  // let me use standard functions
#endif
```

Body:
I'm trying to find the first string (max 4 characters) in a comma-separated list of strings inside a C char-array.

I'm trying to achieve this by using sscanf_s (under Windows) and the format-control string %[^,]:

char mystring[] = "STR1,STR2";
char temp[5];

if (sscanf_s(mystring, "%[^,]", temp, 5) != 0) {
    if (strcmp(temp, "STR1") == 0) { return 0; }
    else if (strcmp(temp, "STR2") == 0) { return 1; }
    else { return -1; }
}

After calling sscanf_s the content of temp is not STR1 but \0TR1 (\0 being the ASCII-interpretation of 0). And the value -1 is returned.

Why do I get that behavior and how do I fix my code to get the right result (return of 0)?

EDIT: changed char mystring to mystring[] (I should have made sure I typed it correcly here)

Body:
There are multiple problems in your code:

mystring is defined as a char, not a string pointer.

the argument 5 following temp in sscanf_s() should have type rsize_t, which is the same as size_t. You should specify it as sizeof(temp).

you should specify the maximum number of characters to store into the destination array in the format string, to avoid the counter-intuitive behavior of sscanf_s in case of overflow.

sscanf_s returns 1 if it can convert and store the string. Testing != 0 will also accept EOF which is an input failure, for which the contents of temp is indeterminate.

Here is a modified version:

const char *mystring = "STR1,STR2";
char temp[5];

if (sscanf_s(mystring, "%4[^,]", temp, sizeof temp) == 1) {
    if (strcmp(temp, "STR1") == 0) {
        return 0;
    } else
    if (strcmp(temp, "STR2") == 0) {
        return 1;
    } else {
        return -1;
    }
}

UPDATE: The OP uses Microsoft Visual Studio, which seems to have a non-conforming implementation of the so-called secure stream functions. Here is a citation from their documentation page:

The sscanf_s function reads data from buffer into the location that's given by each argument. The arguments after the format string specify pointers to variables that have a type that corresponds to a type specifier in format. Unlike the less secure version sscanf, a buffer size parameter is required when you use the type field characters c, C, s, S, or string control sets that are enclosed in []. The buffer size in characters must be supplied as an additional parameter immediately after each buffer parameter that requires it. For example, if you are reading into a string, the buffer size for that string is passed as follows:

wchar_t ws[10];
swscanf_s(in_str, L"%9s", ws, (unsigned)_countof(ws)); // buffer size is 10, width specification is 9

The buffer size includes the terminating null. A width specification field may be used to ensure that the token that's read in will fit into the buffer. If no width specification field is used, and the token read in is too big to fit in the buffer, nothing is written to that buffer.

In the case of characters, a single character may be read as follows:

wchar_t wc;
swscanf_s(in_str, L"%c", &wc, 1);

This example reads a single character from the input string and then stores it in a wide-character buffer. When you read multiple characters for non-null terminated strings, unsigned integers are used as the width specification and the buffer size.

char c[4];
sscanf_s(input, "%4c", &c, (unsigned)_countof(c)); // not null terminated

This example reads a single character from the input string and then stores it in a wide-character buffer. When you read multiple characters for non-null terminated strings, unsigned integers are used as the width specification and the buffer size.

char c[4];
sscanf_s(input, "%4c", &c, (unsigned)_countof(c)); // not null terminated

This specification is incompatible with the C Standard, that specifies the type of the width arguments to be rsize_t and type rsize_t to be the same type as size_t.

As a conclusion, for improved portability, one should avoid using these secure functions and use the standard functions correctly, with the length prefix to prevent buffer overruns.

You can prevent the Visual Studio warning about deprecation of sscanf by inserting this definition before including <stdio.h>:

#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS  // let me use standard functions
#endif


答:
Something like:

```<code>$('#options').change(function() {
    $('input[name="email"], input[name="city"]')
       .toggleClass('required', this.value === '1');
});
</code>```

Reference: change, toggleClass

Title: Add class when (...) with jQuery

Body:
Something like:

$('#options').change(function() {
    $('input[name="email"], input[name="city"]')
       .toggleClass('required', this.value === '1');
});

Reference: change, toggleClass


问:
Trigger: Inserted table column value cannot be referenced inside condition
I have the following trigger:

```<code>    GO
ALTER TRIGGER [dbo].[FooTrigger]
ON [dbo].[Foo]
FOR INSERT
AS
DECLARE @Url nvarchar(MAX)
SELECT @Url  = ins.Url from INSERTED ins;

IF EXISTS (SELECT *
           FROM [dbo].[Foo]  p
           where p.Url =  @Url)
BEGIN
RAISERROR ( 'error %s' , 16, 1, @Url)
ROLLBACK TRANSACTION;
RETURN
END;
PRINT 'Executed Trigger Insert.'
GO
</code>```

It works without an issue if I hardcode the condition like

```<code>IF EXISTS(SELECT * FROM [dbo].[Foo] foo WHERE foo.Url = 'test.com')
</code>```

But the original one does not work. It throws the message:

It looks like there is an error referencing the inserted table data using @Url inside the condition. But RAISERROR ( @Url , 16, 1); correctly printing the value, so I think inside the condition the referencing is somehow not permitted. Are there any workarounds?

答:
First, if you are trying to ensure that urls are unique, then use a unique constraint:

```<code>alter table foo add constraint unq_foo_url unique (url);
</code>```

Second, NEVER assume that inserted has only one row.  This code:

```<code>SELECT @Url  = ins.Url from INSERTED ins;
</code>```

is a bug waiting to happen.

EDIT:

You have a messy problem if you have a table that already violates the unique constraint.  You can fix this problem.  The issue with your code is that a FOR INSERT trigger is really an AFTER INSERT trigger -- the new data is already visible.

But, you can handle this.  Here is one way:

```<code>CREATE TRIGGER [dbo].[FooInsertTrigger]
ON [dbo].[Foo]
AFTER INSERT
AS
BEGIN
    IF (SELECT TOP (1) COUNT(*)
        FROM inserted i JOIN
             [dbo].[Foo] f
             on i.url = f.url
        GROUP BY i.url
        ORDER BY COUNT(*) DESC
       ) > 1
    BEGIN
        RAISERROR('Duplicate URL found' , 16, 1);
        ROLLBACK TRANSACTION;
        RETURN
    END;
    PRINT 'Executed Trigger Insert.'
END;
</code>```

The maximum count(*) is greater than 1 in the following cases:

inserted.url matches 1 row in foo.  This is the normal case.

inserted.url matches multiple rows in foo.  This is caught.

This will also catch the case where there are multiples in inserted.

By making the code safe for multiple inserts, it is harder to pull out the offending URLs.  But the error is handled correctly.

Here is a db<>fiddle.

Body:
I have the following trigger:

    GO
ALTER TRIGGER [dbo].[FooTrigger]
ON [dbo].[Foo]
FOR INSERT
AS
DECLARE @Url nvarchar(MAX)
SELECT @Url  = ins.Url from INSERTED ins;

IF EXISTS (SELECT *
           FROM [dbo].[Foo]  p
           where p.Url =  @Url)
BEGIN
RAISERROR ( 'error %s' , 16, 1, @Url)
ROLLBACK TRANSACTION;
RETURN
END;
PRINT 'Executed Trigger Insert.'
GO

It works without an issue if I hardcode the condition like

IF EXISTS(SELECT * FROM [dbo].[Foo] foo WHERE foo.Url = 'test.com')

But the original one does not work. It throws the message:

It looks like there is an error referencing the inserted table data using @Url inside the condition. But RAISERROR ( @Url , 16, 1); correctly printing the value, so I think inside the condition the referencing is somehow not permitted. Are there any workarounds?

Body:
First, if you are trying to ensure that urls are unique, then use a unique constraint:

alter table foo add constraint unq_foo_url unique (url);

Second, NEVER assume that inserted has only one row.  This code:

SELECT @Url  = ins.Url from INSERTED ins;

is a bug waiting to happen.

EDIT:

You have a messy problem if you have a table that already violates the unique constraint.  You can fix this problem.  The issue with your code is that a FOR INSERT trigger is really an AFTER INSERT trigger -- the new data is already visible.

But, you can handle this.  Here is one way:

CREATE TRIGGER [dbo].[FooInsertTrigger]
ON [dbo].[Foo]
AFTER INSERT
AS
BEGIN
    IF (SELECT TOP (1) COUNT(*)
        FROM inserted i JOIN
             [dbo].[Foo] f
             on i.url = f.url
        GROUP BY i.url
        ORDER BY COUNT(*) DESC
       ) > 1
    BEGIN
        RAISERROR('Duplicate URL found' , 16, 1);
        ROLLBACK TRANSACTION;
        RETURN
    END;
    PRINT 'Executed Trigger Insert.'
END;

The maximum count(*) is greater than 1 in the following cases:

inserted.url matches 1 row in foo.  This is the normal case.

inserted.url matches multiple rows in foo.  This is caught.

This will also catch the case where there are multiples in inserted.

By making the code safe for multiple inserts, it is harder to pull out the offending URLs.  But the error is handled correctly.

Here is a db<>fiddle.


问:
how to solve an exponential with e base function in python?
I have this equation that I want to solve in python but I'm not sure if I'm following the right procedure, the equation is ((e^x)* a + b=0) where a and b are constants this my code the output is [-0.916290731874155 + 3.14159265358979*I] which I'm not sure what it means</p>

```<code>import sympy as sp

T_final= 70.0
T_intial= 75.0
T_diff= T_final - T_intial

T_now= 72.0
T_d= T_final - T_now
x = Symbol('x')

z= (sp.exp(x)* T_diff)+ T_d
sp.solve(z, x)
</code>```

答:
I stands for sqrt(-1), e.g. solve(x**2+1) -> [-I, I]. When solving the equation f(x) = a you have to pass this to solve as solve(f(x) - a, x) (note the minus on a) or as solve(Eq(f(x), a), x).

In your case do you mean

```<code>>>> solve((sp.exp(x)* T_diff) - T_d, x)  # i.e. Tdiff*e^x = Td
[-0.916290731874155]
</code>```

Body:
I have this equation that I want to solve in python but I'm not sure if I'm following the right procedure, the equation is ((e^x)* a + b=0) where a and b are constants this my code the output is [-0.916290731874155 + 3.14159265358979*I] which I'm not sure what it means

import sympy as sp

T_final= 70.0
T_intial= 75.0
T_diff= T_final - T_intial

T_now= 72.0
T_d= T_final - T_now
x = Symbol('x')

z= (sp.exp(x)* T_diff)+ T_d
sp.solve(z, x)

Body:
I stands for sqrt(-1), e.g. solve(x**2+1) -> [-I, I]. When solving the equation f(x) = a you have to pass this to solve as solve(f(x) - a, x) (note the minus on a) or as solve(Eq(f(x), a), x).

In your case do you mean

>>> solve((sp.exp(x)* T_diff) - T_d, x)  # i.e. Tdiff*e^x = Td
[-0.916290731874155]


问:
BACnet segmentation-not-supported on mobile
I'm implementing a bacnet library to read and write some object instances.
But I don't understand, why with a PC and with an application like Yabe if I ask to a common controller to read more than 300 objects, the segmentation is supported, instead with a mobile phone and on the same request to the same controller the segmentation is not supported.
Both the PC and the smartphone are in the same network on Wifi.
So what is the problem/difference?</p>

答:
It is nothing to take with a PC or a mobile phone. Any IP compatible devices mobile phone, desktop, laptop, Arduino chips will work with BACnet.
Your problem is segmentation. You will have to handle the segmented messages coming from the Controller.
Every BACnet controller vendor specifies the MaxApduLength (i.e max length of data to be transferred within one UDP packet). The standard APDU length is 1476 bytes. So a BACnet controller cannot send the data more than the length of APDU specified within it.

Requesting 300 objects from a controller results definitely in a large APDU than the controller's limit. In this case Controller will send you segmented messages each with sequence number. You will have to handle this all segmented messages and combine them in one message then only you will get exact response. This is same with Yabe and other BACnet clients.

I have also written BACnet libraries for our mobile applications in Java and Swift 4.0 and both can read any number of objects from controller with segmentation support added. I have tested these with controllers having more than 400 objects.


问:
Complex Minimum of Rolling Values
I'm working on a complex statistical function that requires finding the minimum of 10 previous computed values. The computed values for each of the previous rows are dependent not only on the average from current row, but the previous rows calculations as well. The below illustration shows the desired query result:

I am able to get the 10 day average, but am stumped on how to apply the other calculations without the use of a window function for every individual scenario which would be very inefficient. Below is the code I have so far:

```<code>CREATE TABLE #TBL(
[id]    int IDENTITY(1,1) NOT NULL,
[price] numeric(20,10)
)

INSERT INTO #TBL ([price])
VALUES (93.02),(90.56),(88.63),(90.3),(91.58),(90.42),(89.5),(89.23),(87.07),(85.88),(86.04),(87.26),(87.67),(84.37),(84.13),(83.3),(82.4),(81.73),(82),(80.69),(82.13)

SELECT
    [id], [price],
    CASE WHEN [id] >= 10 THEN
    avg([price]) OVER(ORDER BY ID ASC ROWS BETWEEN 9 PRECEDING AND CURRENT ROW)
    END  AS [average (last 10)]
FROM #TBL
</code>```

Any help on creating an efficient query would be greatly appreciated.

答:
```<code>CREATE TABLE #TBL(
[id]    int IDENTITY(1,1) NOT NULL primary key clustered, --!!!!
[price] numeric(20,10)
)

INSERT INTO #TBL ([price])
VALUES (93.02),(90.56),(88.63),(90.3),(91.58),(90.42),(89.5),(89.23),(87.07),(85.88),(86.04),(87.26),(87.67),(84.37),(84.13),(83.3),(82.4),(81.73),(82),(80.69),(82.13)

select *
from
(
  select *, avg([price]) OVER(ORDER BY ID ASC ROWS BETWEEN 9 PRECEDING AND CURRENT ROW) as avg10
  from #TBL
) as a
outer apply
(

   select min(r.runningdiff) as mindiff
   from
   (
      select sum(l10.diff) over (order by l10.id) as runningdiff
      from
      (
        select TOP (10) b.id, a.avg10 - b.price as diff
        from #Tbl as b
        where 1=1
        and a.Id >= 10
        and b.Id between a.id-9 and a.Id
      ) as l10
   ) as r
) as rt
</code>```

Title: Complex Minimum of Rolling Values

Body:
I'm working on a complex statistical function that requires finding the minimum of 10 previous computed values. The computed values for each of the previous rows are dependent not only on the average from current row, but the previous rows calculations as well. The below illustration shows the desired query result:

I am able to get the 10 day average, but am stumped on how to apply the other calculations without the use of a window function for every individual scenario which would be very inefficient. Below is the code I have so far:

CREATE TABLE #TBL(
[id]    int IDENTITY(1,1) NOT NULL,
[price] numeric(20,10)
)

INSERT INTO #TBL ([price])
VALUES (93.02),(90.56),(88.63),(90.3),(91.58),(90.42),(89.5),(89.23),(87.07),(85.88),(86.04),(87.26),(87.67),(84.37),(84.13),(83.3),(82.4),(81.73),(82),(80.69),(82.13)

SELECT
    [id], [price],
    CASE WHEN [id] >= 10 THEN
    avg([price]) OVER(ORDER BY ID ASC ROWS BETWEEN 9 PRECEDING AND CURRENT ROW)
    END  AS [average (last 10)]
FROM #TBL

Any help on creating an efficient query would be greatly appreciated.


问:
Exact math with big numbers in Python 3
I'm trying to implement a system for encryption similar to Shamir's Secret Sharing using Python. Essentially, I have code that will generate a list of points that can be used to find a password at the y-intercept of the gradient formed by these points. The password is a number in ASCII (using two digits per ASCII character), thus is gets to be a pretty big number with larger passwords. For example, the password ThisIsAPassword will generate a list of points that looks like this:

```<code>x    y
9556 66707086867915126140753213946756441607861037300900
4083 28502040182447127964404994111341362715565457349000
9684 67600608880657662915204624898507424633297513499300
9197 64201036847801292531159022293017356403707170463200
</code>```

To be clear, these points are generated upon a randomly chosen slope (this is fine since it's the y-intercept that matters).

The problem arises in trying to make a program to decode a password. Using normal math, Python is unable to accurately find the password because of the size of the numbers. Here's the code I have:

```<code>def findYint(x,y):
    slope = (y[1] - y[0]) / (x[1] - x[0])
    yint = int(y[0] - slope * x[0])
    return yint

def asciiToString(num):
    chars = [num[i:i+3] for i in range(0, len(num), 3)]

    return ''.join(chr(int(i)) for i in chars)

def main():
    fi = open('pass.txt','r')
    x,y = [], []
    for i in fi:
        row = i.split()
        x.append(int(row[0]))
        y.append(int(row[1]))
    fi.close()
    yint = findYint(x,y)
    pword = asciiToString(str(yint))

    print(pword)

main()
</code>```

Output (with the password "ThisIsAPassword"):

```<code>͉)3 ǢΜĩũć»¢ǔ¼
</code>```

Typically my code will work with shorter passwords such as "pass" or "word", but the bigger numbers presumably aren't computed with the exact accuracy needed to convert them into ASCII. Any solutions for using either precise math or something else?

Also here's the code for generating points in case it's important:

```<code>import random

def encryptWord(word):
    numlist = []
    for i in range(len(word)):
        numlist.append(str(ord(word[i])).zfill(3))
    num = int("".join(numlist))
    return num

def createPoints(pwd, pts):
    yint = pwd
    gradient = pwd*random.randint(10,100)
    xvals = []
    yvals = []
    for i in range(pts):
        n = random.randint(1000,10000)
        xvals.append(n)
        yvals.append(((n) * gradient) + pwd)

    return xvals, yvals

def main():
    pword = input("Enter a password to encrypt: ")
    pword = encryptWord(pword)
    numpoints = int(input("How many points to generate? "))
    if numpoints < 2:
        numpoints = 2
    xpts, ypts = createPoints(pword, numpoints)

    fi = open("pass.txt","w")
    for i in range(len(xpts)):
        fi.write(str(xpts[i]))
        fi.write(' ')
        fi.write(str(ypts[i]))
        fi.write('\n')
    fi.close()
    print("Sent to file (pass.txt)")
main()
</code>```

答:
As you may know, Python's built-in int type can handle arbitrarily large integers, but the float type which has limited precision. The only part of your code which deals with numbers that aren't ints seems to be this function:

def findYint(x,y):
    slope = (y[1] - y[0]) / (x[1] - x[0])
    yint = int(y[0] - slope * x[0])
    return yint
```

<p>Here the division results in a <code>float</code>, even if the result would be exact as an <code>int</code>. Moreover, we can't safely do integer division here with the <code>//</code> operator, because <code>slope</code> will get multiplied by <code>x[0]</code> before the truncation is supposed to happen.</p>

<p>So either you need to do some algebra in order to get the same result using only <code>int</code>s, or you need to represent the fraction (y<sub>1</sub> - y<sub>0</sub>) / (x<sub>1</sub> - x<sub>0</sub>) with an exact non-integer number type instead of <code>float</code>. Fortunately, Python's standard library has a class named Fraction which will do what you want:</p>

<pre class="lang-py prettyprint-override"><code>from fractions import Fraction

def findYint(x,y):
    slope = Fraction(y[1] - y[0], x[1] - x[0])
    yint = int(y[0] - slope * x[0])
    return yint
</code>```

Title: Exact math with big numbers in Python 3

Body:
I'm trying to implement a system for encryption similar to Shamir's Secret Sharing using Python. Essentially, I have code that will generate a list of points that can be used to find a password at the y-intercept of the gradient formed by these points. The password is a number in ASCII (using two digits per ASCII character), thus is gets to be a pretty big number with larger passwords. For example, the password ThisIsAPassword will generate a list of points that looks like this:

x    y
9556 66707086867915126140753213946756441607861037300900
4083 28502040182447127964404994111341362715565457349000
9684 67600608880657662915204624898507424633297513499300
9197 64201036847801292531159022293017356403707170463200

To be clear, these points are generated upon a randomly chosen slope (this is fine since it's the y-intercept that matters).

The problem arises in trying to make a program to decode a password. Using normal math, Python is unable to accurately find the password because of the size of the numbers. Here's the code I have:

def findYint(x,y):
    slope = (y[1] - y[0]) / (x[1] - x[0])
    yint = int(y[0] - slope * x[0])
    return yint

def asciiToString(num):
    chars = [num[i:i+3] for i in range(0, len(num), 3)]

    return ''.join(chr(int(i)) for i in chars)

def main():
    fi = open('pass.txt','r')
    x,y = [], []
    for i in fi:
        row = i.split()
        x.append(int(row[0]))
        y.append(int(row[1]))
    fi.close()
    yint = findYint(x,y)
    pword = asciiToString(str(yint))

    print(pword)

main()

Output (with the password "ThisIsAPassword"):

͉)3 ǢΜĩũć»¢ǔ¼

Typically my code will work with shorter passwords such as "pass" or "word", but the bigger numbers presumably aren't computed with the exact accuracy needed to convert them into ASCII. Any solutions for using either precise math or something else?

Also here's the code for generating points in case it's important:

import random

def encryptWord(word):
    numlist = []
    for i in range(len(word)):
        numlist.append(str(ord(word[i])).zfill(3))
    num = int("".join(numlist))
    return num

def createPoints(pwd, pts):
    yint = pwd
    gradient = pwd*random.randint(10,100)
    xvals = []
    yvals = []
    for i in range(pts):
        n = random.randint(1000,10000)
        xvals.append(n)
        yvals.append(((n) * gradient) + pwd)

    return xvals, yvals

def main():
    pword = input("Enter a password to encrypt: ")
    pword = encryptWord(pword)
    numpoints = int(input("How many points to generate? "))
    if numpoints < 2:
        numpoints = 2
    xpts, ypts = createPoints(pword, numpoints)

    fi = open("pass.txt","w")
    for i in range(len(xpts)):
        fi.write(str(xpts[i]))
        fi.write(' ')
        fi.write(str(ypts[i]))
        fi.write('\n')
    fi.close()
    print("Sent to file (pass.txt)")
main()

Body:
As you may know, Python's built-in int type can handle arbitrarily large integers, but the float type which has limited precision. The only part of your code which deals with numbers that aren't ints seems to be this function:

def findYint(x,y):
    slope = (y[1] - y[0]) / (x[1] - x[0])
    yint = int(y[0] - slope * x[0])
    return yint

Here the division results in a float, even if the result would be exact as an int. Moreover, we can't safely do integer division here with the // operator, because slope will get multiplied by x[0] before the truncation is supposed to happen.

So either you need to do some algebra in order to get the same result using only ints, or you need to represent the fraction (y1 - y0) / (x1 - x0) with an exact non-integer number type instead of float. Fortunately, Python's standard library has a class named Fraction which will do what you want:

from fractions import Fraction

def findYint(x,y):
    slope = Fraction(y[1] - y[0], x[1] - x[0])
    yint = int(y[0] - slope * x[0])
    return yint