答:
You can use the function filter along with the function includes in order to select those lines which have a third letter within the array D.

let A = [ "B,C,D", "W,F,G", "M,S,E" ],
    D = ["E"],
    result = A.filter(s => {
      let [,,C] = s.split(",");
      return D.includes(C);
    });

console.log(result);```

Body:
If I have two array

A = [ "B,C,D"
      "W,F,G"
      "M,S,E"
    ]
D = [E]

and want to compare D OR G with E (I mean the third one in each line)and If they are equal can show all the line for me. The third one in each line a part of each line and I want just compare the third one If it is equal show that line have equal variable .
I wrote this code but didn't give me the response that I need have :

 for(var k=0 ; k<A.length ; k++){
    if(A[k].split(",")[2] === E) {
       finalSuccessServices = A;
       console.log(finalSuccessServices );
     }

How can I improve my code to get that line that have my equal variable?


来源: stackexchange

问:
load a php image using src
Is it possible to load a image using:

```<code><img src="image.php?image_id=1">
</code>```

?

for image.php:

```<code>$image_id = $_GET['image_id'];
echo "image".$image_id.".png";
</code>```

答: If you have the png contents in the database, follow the other answers. If all you need is the id from the database, simply <img src="image<?=$image_id?>.png">

ContentLicense: CC BY-SA 3.0

Title: load a php image using src

Body:
Is it possible to load a image using:

?

for image.php:

$image_id = $_GET['image_id'];
echo "image".$image_id.".png";


问:
Slow SELECT with LEFT JOIN over 4 tables
My database has 4 tables: org_addresses, org_main, zipcodes and cities.

The table org_addresses contains address data for organizations, the table org_main contains the main data for these organizations, the table zipcodes contains city zipcodes, and the table cities contains city names.

org_addresses:

```<code>| id | org_id | address_line | zipcode |
</code>```

org_main:

```<code>| id | name |
</code>```

zipcodes

```<code>| id | city_id | zipcode |
</code>```

cities

```<code>| id | name |
</code>```

In my query, I join all 4 tables using LEFT JOIN together to output complete data as a list with 1600 organizations.

As soon as I join the table zipcodes via LEFT JOIN and then join to the table cities, the request slows down to 4 seconds. Without the table zipcodes, the query takes 0.009 seconds.

```<code>SELECT a.org_id
     , a.address_line2
     , a.zipcode
     , m.name
  FROM org_addresses a
  LEFT
  JOIN org_main m
    ON a.org_id = m.id
  LEFT
  JOIN zipcodes z
    ON a.zipcode = z.zipcode
  LEFT
  JOIN cities c
    ON z.city_id = c.id
</code>```

What am I doing wrong?

答:
You should look at the execution plans of the queries to see what is happening.

My guess would be that zipcodes(zipcode) is not indexed (and probably not cities(city).  It is curious that you are not joining on the tables id instead.

ContentLicense: CC BY-SA 4.0

Body:
My database has 4 tables: org_addresses, org_main, zipcodes and cities.

The table org_addresses contains address data for organizations, the table org_main contains the main data for these organizations, the table zipcodes contains city zipcodes, and the table cities contains city names.

org_addresses:

| id | org_id | address_line | zipcode |

org_main:

| id | name |

zipcodes

| id | city_id | zipcode |

cities

| id | name |

In my query, I join all 4 tables using LEFT JOIN together to output complete data as a list with 1600 organizations.

As soon as I join the table zipcodes via LEFT JOIN and then join to the table cities, the request slows down to 4 seconds. Without the table zipcodes, the query takes 0.009 seconds.

SELECT a.org_id
     , a.address_line2
     , a.zipcode
     , m.name
  FROM org_addresses a
  LEFT
  JOIN org_main m
    ON a.org_id = m.id
  LEFT
  JOIN zipcodes z
    ON a.zipcode = z.zipcode
  LEFT
  JOIN cities c
    ON z.city_id = c.id

What am I doing wrong?


问:
In Octopus Deploy, how to require an approval when a major or minor version is deployed to an environment the first time?
Imagine you had five environments, Dev, Test, UAT, Stage and Production.

For those environments you have the following lifecycles:
- Sprint: Dev -> Test
- Test To Prod: Test -> UAT -> Stage -> Prod
- UAT to Prod: UAT -> Stage -> Prod
- Hotfix: Stage -> Prod

The release versioning looks like 2020.1.3.  When a new release is cut it will either update the major (2020) or minor (1) in the version number.  For example 2020.1.3 goes to 2020.2.1 or 2021.1.1.  A bug fix or minor release will update the last number (3).

The concern is if a release is deployed to Test, UAT or Stage at the wrong time or by accident and it stops our testers.  For example, QA is in the middle of testing the 2020.1.3 release in Test.  A developer accidentally pushes 2020.2 up to Test.  That includes new code QA wasn't expecting.  While QA is in the middle of testing 2020.1.x they only want to see 2020.1.x releases.

We don't want to use version rules in our channels.  Each time a new release is cut the version rules would have to be updated.

Is it possible to require an approval when a major or minor version is deploy to an environment the first time?

答:
Yes, that is possible.  To do this, we will use output variables and run conditions.

First, two new steps were added to the start of the process.

Both steps skip development and production because they are not affected by this problem.  Having to approve a deployment to dev every time a major/minor version changes will get old really fast.  And all production releases must at least go to staging first.

The first step runs this PowerShell script.  It will compare the previous release number for this specific environment with the current release number.  It will set the output variable "RequiresApproval" to true if either the major or minor version is different.

```<code>$releaseNumber = $OctopusParameters["Octopus.Release.Number"]
$releaseNumberArray = $releaseNumber.Split('.')

$lastVersion = $OctopusParameters["Octopus.Release.PreviousForEnvironment.Number"]
$lastVersionArray = $lastVersion.Split('.')

Write-Highlight "The previous version deployed to this environment was $lastVersion"

$requiresApproval = $false
if ($lastVersionArray[0] -ne $releaseNumberArray[0])
{
    Write-Highlight "The previous major version $($lastVersionArray[0]) in $lastVersion is different than the one being deployed $($releaseNumberArray[0]) in $releaseNumber, this requires someone to approve"
    $requiresApproval = $true
}
elseif ($lastVersionArray[1] -ne $releaseNumberArray[1])
{
    Write-Highlight "The previous minor version $($lastVersionArray[1]) in $lastVersion is different than the one being deployed $($releaseNumberArray[1]) in $releaseNumber, this requires someone to approve"
    $requiresApproval = $true
}
else
{
    Write-Highlight "The previous version's major and minor versions are the same, skipping approval"
}

Set-OctopusVariable -name "RequiresApproval" -value $requiresApproval
</code>```

Output variables are a little verbose and can be tricky to use.  To make that easier, create a project variable to reference it.

In the manual intervention step, set the run condition to that project variable.

Now it is time to test this.  UAT currently has 2020.1.2 while Test has 2020.2.3.  When 2020.2.4 is deployed to to Test the manual intervention shouldn't appear.

Success, the manual intervention is skipped.

UAT currently has 2020.1.2. 2020.2.4 has a new minor version, a deployment to UAT will prompt the user for a manual intervention.

This YouTube Video shows this in action.

Body:
Yes, that is possible.  To do this, we will use output variables and run conditions.

First, two new steps were added to the start of the process.

Both steps skip development and production because they are not affected by this problem.  Having to approve a deployment to dev every time a major/minor version changes will get old really fast.  And all production releases must at least go to staging first.

The first step runs this PowerShell script.  It will compare the previous release number for this specific environment with the current release number.  It will set the output variable "RequiresApproval" to true if either the major or minor version is different.

$releaseNumber = $OctopusParameters["Octopus.Release.Number"]
$releaseNumberArray = $releaseNumber.Split('.')

$lastVersion = $OctopusParameters["Octopus.Release.PreviousForEnvironment.Number"]
$lastVersionArray = $lastVersion.Split('.')

Write-Highlight "The previous version deployed to this environment was $lastVersion"

$requiresApproval = $false
if ($lastVersionArray[0] -ne $releaseNumberArray[0])
{
    Write-Highlight "The previous major version $($lastVersionArray[0]) in $lastVersion is different than the one being deployed $($releaseNumberArray[0]) in $releaseNumber, this requires someone to approve"
    $requiresApproval = $true
}
elseif ($lastVersionArray[1] -ne $releaseNumberArray[1])
{
    Write-Highlight "The previous minor version $($lastVersionArray[1]) in $lastVersion is different than the one being deployed $($releaseNumberArray[1]) in $releaseNumber, this requires someone to approve"
    $requiresApproval = $true
}
else
{
    Write-Highlight "The previous version's major and minor versions are the same, skipping approval"
}

Set-OctopusVariable -name "RequiresApproval" -value $requiresApproval

Output variables are a little verbose and can be tricky to use.  To make that easier, create a project variable to reference it.

In the manual intervention step, set the run condition to that project variable.

Now it is time to test this.  UAT currently has 2020.1.2 while Test has 2020.2.3.  When 2020.2.4 is deployed to to Test the manual intervention shouldn't appear.

Success, the manual intervention is skipped.

UAT currently has 2020.1.2. 2020.2.4 has a new minor version, a deployment to UAT will prompt the user for a manual intervention.

This YouTube Video shows this in action.


问:
Management.Azure.com REST API Call with Odata $expand and $filter | body results not filtering
I am unable to get the desired results using a $expand and $filter in Odata on a REST API GET call. Basically looking to filter results so only properties.status = 'Closed' are returned on the GET API call. So far the expand and filters receive 200 OK but are not honoring the filtering in the body results.

https://management.azure.com/subscriptions/{SUBID}/resourceGroups/{RGNAME}/providers/Microsoft.OperationalInsights/workspaces/{WorkspaceName}/providers/Microsoft.SecurityInsights/Cases?api-version=2019-01-01-preview&$expand=properties($filter=status eq 'Closed')

eventually adding a 2nd filter like:

&$expand=properties($filter=status eq 'Closed' and relatedalertproductnames eq 'Azure Security Center')

答:
I believe you're specifying the $filter criteria incorrectly. Please try something like the following:

```<code>$expand=properties&$filter=properties/status eq 'New'
</code>```

Body:
I believe you're specifying the $filter criteria incorrectly. Please try something like the following:

$expand=properties&$filter=properties/status eq 'New'


问:
how to show array in Toast
i have an app to show a toast with specific duration time and specific time to show next toast and show randomly on display,
 thath's work safe but don't show array items in toast.
how do it?
tnx</p>

```<code> //MyReceive
public void onReceive(Context con, Intent mIntent) {

    mContext = con;
    final String[] array = { "1", "3", "4", "5", "6", "ffff","END"};

        final Handler mHandler = new Handler();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {

                Random r = new Random();
                int i1 = r.nextInt(Activity_Main.w);

                r = new Random();
                int i2 = r.nextInt(Activity_Main.h);
                Log.d("tag : ", i1 + "   :   " + i2);

                for (String arr : array) {
                    t1 = Toast.makeText(mContext, arr, Toast.LENGTH_SHORT);

                }

                //delay in show toast duration 100ms
                Handler h = new Handler();
                h.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        t1.cancel();
                    }

                }, 100);
                //random location on screen
                t1.setGravity(Gravity.TOP, i1, i2);
                t1.show();

                //delay in show next toast
                int min = 3;
                int max = 8;
                Random random = new Random();
                int d = random.nextInt(max - min + 1) + min;
                Log.d("random ", String.valueOf(d));

                mHandler.postDelayed(this, d * 1000);

            }

        }, 100);
</code>```

答:
In kotlin:

```<code> var allItems = "" //used to display in the toast
 for (str in messageArray)
    {
       allItems = allItems + "\n" + str //adds a new line between items
     }
 Toast.makeText(this,allItems, Toast.LENGTH_SHORT).show()
</code>```

In Java:

```<code>String allItems = ""; //used to display in the toast

for(String str : messageArray){

    allItems = allItems + "\n" + str; //adds a new line between items

 }

  Toast.makeText(getApplicationContext(),allItems, Toast.LENGTH_LONG).show();
</code>```

Title: how to show array in Toast

Body:
i have an app to show a toast with specific duration time and specific time to show next toast and show randomly on display,
 thath's work safe but don't show array items in toast.
how do it?
tnx

 //MyReceive
public void onReceive(Context con, Intent mIntent) {

    mContext = con;
    final String[] array = { "1", "3", "4", "5", "6", "ffff","END"};

        final Handler mHandler = new Handler();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {

                Random r = new Random();
                int i1 = r.nextInt(Activity_Main.w);

                r = new Random();
                int i2 = r.nextInt(Activity_Main.h);
                Log.d("tag : ", i1 + "   :   " + i2);

                for (String arr : array) {
                    t1 = Toast.makeText(mContext, arr, Toast.LENGTH_SHORT);

                }

                //delay in show toast duration 100ms
                Handler h = new Handler();
                h.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        t1.cancel();
                    }

                }, 100);
                //random location on screen
                t1.setGravity(Gravity.TOP, i1, i2);
                t1.show();

                //delay in show next toast
                int min = 3;
                int max = 8;
                Random random = new Random();
                int d = random.nextInt(max - min + 1) + min;
                Log.d("random ", String.valueOf(d));

                mHandler.postDelayed(this, d * 1000);

            }

        }, 100);

Body:
In kotlin:

 var allItems = "" //used to display in the toast
 for (str in messageArray)
    {
       allItems = allItems + "\n" + str //adds a new line between items
     }
 Toast.makeText(this,allItems, Toast.LENGTH_SHORT).show()

In Java:

String allItems = ""; //used to display in the toast

for(String str : messageArray){

    allItems = allItems + "\n" + str; //adds a new line between items

 }

  Toast.makeText(getApplicationContext(),allItems, Toast.LENGTH_LONG).show();


问:
Google Amp 403 Forbidden error when testing endpoint from playground
I keep getting a 403 forbidden error when trying to test my api endpoint from the Google amp playground. I tried adding all of the response headers that amp requires but I still get the error. These are the headers i have on the api response, am I missing anything?

```<code>access-control-allow-credentials: true
access-control-allow-origin: https://amp.gmail.dev
access-control-allow-source-origin: https://www.example.com
access-control-expose-headers: AMP-Access-Control-Allow-Source-Origin
amp-access-control-allow-source-origin: amp@gmail.dev
Content-Type: application/json;charset=UTF-8
</code>```

And the form submission error in the console:

```<code>log.js:251 [amp-form] Form submission failed: Error: HTTP error 403
    at bb (https://cdn.ampproject.org/v0.js:28:169)
    at Ya.f.createError (https://cdn.ampproject.org/v0.js:23:257)
    at https://cdn.ampproject.org/v0.js:141:409
    at new Promise (<anonymous>)
    at jg (https://cdn.ampproject.org/v0.js:141:344)
    at https://cdn.ampproject.org/v0.js:143:267
</code>```

答: Try turning off recaptcha, most likely it returns the status of 'spam' which causes an error.</p>

Body:
I keep getting a 403 forbidden error when trying to test my api endpoint from the Google amp playground. I tried adding all of the response headers that amp requires but I still get the error. These are the headers i have on the api response, am I missing anything?

access-control-allow-credentials: true
access-control-allow-origin: https://amp.gmail.dev
access-control-allow-source-origin: https://www.example.com
access-control-expose-headers: AMP-Access-Control-Allow-Source-Origin
amp-access-control-allow-source-origin: amp@gmail.dev
Content-Type: application/json;charset=UTF-8

And the form submission error in the console:

log.js:251 [amp-form] Form submission failed: Error: HTTP error 403
    at bb (https://cdn.ampproject.org/v0.js:28:169)
    at Ya.f.createError (https://cdn.ampproject.org/v0.js:23:257)
    at https://cdn.ampproject.org/v0.js:141:409
    at new Promise (<anonymous>)
    at jg (https://cdn.ampproject.org/v0.js:141:344)
    at https://cdn.ampproject.org/v0.js:143:267


问:
Using bindingsource stored in the ifs
Is there any possible way to create a serviceprogramm (crtsqlrpgi OBJTYPE(*SRVPGM)) using a .bnd file stored in the ifs as bindingsource?</p>

答:
According to the docs, Create Service Program (CRTSRVPGM) has a SRCSTMF (Export source stream file) parameter.

Appears to have been added at v7.3.

Title: Using bindingsource stored in the ifs


问:
How to make sure code has no data races in Go?
I'm writing a microservice that calls other microservices, for data that rarely updates (once in a day or once in a month). So I decided to create cache, and implemented this interface:

```<code>type StringCache interface {
    Get(string) (string, bool)
    Put(string, string)
}
</code>```

internally it's just map[string]cacheItem, where

```<code>type cacheItem struct {
    data      string
    expire_at time.Time
}
</code>```

My coworker says that it's unsafe, and I need add mutex locks in my methods, because it will be used in parallel by different instances of http handler functions. I have a test for it, but it detects no data races, because it uses cache in one goroutine:

```<code>func TestStringCache(t *testing.T) {
    testDuration := time.Millisecond * 10
    cache := NewStringCache(testDuration / 2)

    cache.Put("here", "this")

    // Value put in cache should be in cache
    res, ok := cache.Get("here")
    assert.Equal(t, res, "this")
    assert.True(t, ok)

    // Values put in cache will eventually expire
    time.Sleep(testDuration)

    res, ok = cache.Get("here")
    assert.Equal(t, res, "")
    assert.False(t, ok)
}
</code>```

So, my question is: how to rewrite this test that it detects data race (if it is present) when running with go test -race?

答:
First thing first, the data race detector in Go is not some sort of formal prover which uses static code analysis but is rather a dynamic tool which instruments the compiled code in a special way to try to detect data races at runtime.

What this means is that if the race detector is lucky and it spots a data race, you ought to be sure there is a data race at the reported spot. But this also means that if the actual program flow did not make certain existing data race condition happen, the race detector won't spot and report it.

In oher words, the race detector does not have false positives but it is merely a best-effort tool.

So, in order to write race-free code you really have to rethink your approach.

It's best to start with this classic essay on the topic written by the author of the Go race detector, and once you have absorbed that there is no benign data races, you basically just train yourself to think about concurrently running theads of execution accessing your data each time you're architecting the data and the algorithms to manipulate it.

For instance, you know (at least you should know if you have read the docs) that each incoming request to an HTTP server implemented using net/http is handled by a separate goroutine.

This means, that if you have a central (shared) data structure such as a cache which is to be accessed by the code which processes client requests, you do have multiple goroutines potentially accessing that shared data concurrently.

Now if you have another goroutine which updates that data, you do have a potential for a classic data race: while one goroutine is updating the data, another may read it.

As to the question at hand, two things:

First, Never ever use timers to test stuff. This does not work.

Second, for such a simple case as yours, using merely two goroutines completely suffices:

package main

import (
    "testing"
    "time"
)

type cacheItem struct {
    data      string
    expire_at time.Time
}

type stringCache struct {
    m   map[string]cacheItem
    exp time.Duration
}

func (sc *stringCache) Get(key string) (string, bool) {
    if item, ok := sc.m[key]; !ok {
        return "", false
    } else {
        return item.data, true
    }
}

func (sc *stringCache) Put(key, data string) {
    sc.m[key] = cacheItem{
        data:      data,
        expire_at: time.Now().Add(sc.exp),
    }
}

func NewStringCache(d time.Duration) *stringCache {
    return &stringCache{
        m:   make(map[string]cacheItem),
        exp: d,
    }
}

func TestStringCache(t *testing.T) {
    cache := NewStringCache(time.Minute)

    ch := make(chan struct{})

    go func() {
        cache.Put("here", "this")
        close(ch)
    }()

    _, _ = cache.Get("here")

    <-ch
}
```
<p>Save this as <code>sc_test.go</code> and then</p>
```tmp$ go test -race -c -o sc_test ./sc_test.go
tmp$ ./sc_test
==================
WARNING: DATA RACE
Write at 0x00c00009e270 by goroutine 8:
  runtime.mapassign_faststr()
      /home/kostix/devel/golang-1.13.6/src/runtime/map_faststr.go:202 +0x0
  command-line-arguments.(*stringCache).Put()
      /home/kostix/tmp/sc_test.go:27 +0x144
  command-line-arguments.TestStringCache.func1()
      /home/kostix/tmp/sc_test.go:46 +0x62

Previous read at 0x00c00009e270 by goroutine 7:
  runtime.mapaccess2_faststr()
      /home/kostix/devel/golang-1.13.6/src/runtime/map_faststr.go:107 +0x0
  command-line-arguments.TestStringCache()
      /home/kostix/tmp/sc_test.go:19 +0x125
  testing.tRunner()
      /home/kostix/devel/golang-1.13.6/src/testing/testing.go:909 +0x199

Goroutine 8 (running) created at:
  command-line-arguments.TestStringCache()
      /home/kostix/tmp/sc_test.go:45 +0xe4
  testing.tRunner()
      /home/kostix/devel/golang-1.13.6/src/testing/testing.go:909 +0x199

Goroutine 7 (running) created at:
  testing.(*T).Run()
      /home/kostix/devel/golang-1.13.6/src/testing/testing.go:960 +0x651
  testing.runTests.func1()
      /home/kostix/devel/golang-1.13.6/src/testing/testing.go:1202 +0xa6
  testing.tRunner()
      /home/kostix/devel/golang-1.13.6/src/testing/testing.go:909 +0x199
  testing.runTests()
      /home/kostix/devel/golang-1.13.6/src/testing/testing.go:1200 +0x521
  testing.(*M).Run()
      /home/kostix/devel/golang-1.13.6/src/testing/testing.go:1117 +0x2ff
  main.main()
      _testmain.go:44 +0x223
==================
--- FAIL: TestStringCache (0.00s)
    testing.go:853: race detected during execution of test
FAIL
```

Body:
I'm writing a microservice that calls other microservices, for data that rarely updates (once in a day or once in a month). So I decided to create cache, and implemented this interface:

type StringCache interface {
    Get(string) (string, bool)
    Put(string, string)
}

internally it's just map[string]cacheItem, where

type cacheItem struct {
    data      string
    expire_at time.Time
}

My coworker says that it's unsafe, and I need add mutex locks in my methods, because it will be used in parallel by different instances of http handler functions. I have a test for it, but it detects no data races, because it uses cache in one goroutine:

func TestStringCache(t *testing.T) {
    testDuration := time.Millisecond * 10
    cache := NewStringCache(testDuration / 2)

    cache.Put("here", "this")

    // Value put in cache should be in cache
    res, ok := cache.Get("here")
    assert.Equal(t, res, "this")
    assert.True(t, ok)

    // Values put in cache will eventually expire
    time.Sleep(testDuration)

    res, ok = cache.Get("here")
    assert.Equal(t, res, "")
    assert.False(t, ok)
}

So, my question is: how to rewrite this test that it detects data race (if it is present) when running with go test -race?

Body:
First thing first, the data race detector in Go is not some sort of formal prover which uses static code analysis but is rather a dynamic tool which instruments the compiled code in a special way to try to detect data races at runtime.

What this means is that if the race detector is lucky and it spots a data race, you ought to be sure there is a data race at the reported spot. But this also means that if the actual program flow did not make certain existing data race condition happen, the race detector won't spot and report it.

In oher words, the race detector does not have false positives but it is merely a best-effort tool.

So, in order to write race-free code you really have to rethink your approach.

It's best to start with this classic essay on the topic written by the author of the Go race detector, and once you have absorbed that there is no benign data races, you basically just train yourself to think about concurrently running theads of execution accessing your data each time you're architecting the data and the algorithms to manipulate it.

For instance, you know (at least you should know if you have read the docs) that each incoming request to an HTTP server implemented using net/http is handled by a separate goroutine.

This means, that if you have a central (shared) data structure such as a cache which is to be accessed by the code which processes client requests, you do have multiple goroutines potentially accessing that shared data concurrently.

Now if you have another goroutine which updates that data, you do have a potential for a classic data race: while one goroutine is updating the data, another may read it.

As to the question at hand, two things:

First, Never ever use timers to test stuff. This does not work.

Second, for such a simple case as yours, using merely two goroutines completely suffices:

package main

import (
    "testing"
    "time"
)

type cacheItem struct {
    data      string
    expire_at time.Time
}

type stringCache struct {
    m   map[string]cacheItem
    exp time.Duration
}

func (sc *stringCache) Get(key string) (string, bool) {
    if item, ok := sc.m[key]; !ok {
        return "", false
    } else {
        return item.data, true
    }
}

func (sc *stringCache) Put(key, data string) {
    sc.m[key] = cacheItem{
        data:      data,
        expire_at: time.Now().Add(sc.exp),
    }
}

func NewStringCache(d time.Duration) *stringCache {
    return &stringCache{
        m:   make(map[string]cacheItem),
        exp: d,
    }
}

func TestStringCache(t *testing.T) {
    cache := NewStringCache(time.Minute)

    ch := make(chan struct{})

    go func() {
        cache.Put("here", "this")
        close(ch)
    }()

    _, _ = cache.Get("here")

    <-ch
}

Save this as sc_test.go and then

tmp$ go test -race -c -o sc_test ./sc_test.go
tmp$ ./sc_test
==================
WARNING: DATA RACE
Write at 0x00c00009e270 by goroutine 8:
  runtime.mapassign_faststr()
      /home/kostix/devel/golang-1.13.6/src/runtime/map_faststr.go:202 +0x0
  command-line-arguments.(*stringCache).Put()
      /home/kostix/tmp/sc_test.go:27 +0x144
  command-line-arguments.TestStringCache.func1()
      /home/kostix/tmp/sc_test.go:46 +0x62

Previous read at 0x00c00009e270 by goroutine 7:
  runtime.mapaccess2_faststr()
      /home/kostix/devel/golang-1.13.6/src/runtime/map_faststr.go:107 +0x0
  command-line-arguments.TestStringCache()
      /home/kostix/tmp/sc_test.go:19 +0x125
  testing.tRunner()
      /home/kostix/devel/golang-1.13.6/src/testing/testing.go:909 +0x199

Goroutine 8 (running) created at:
  command-line-arguments.TestStringCache()
      /home/kostix/tmp/sc_test.go:45 +0xe4
  testing.tRunner()
      /home/kostix/devel/golang-1.13.6/src/testing/testing.go:909 +0x199

Goroutine 7 (running) created at:
  testing.(*T).Run()
      /home/kostix/devel/golang-1.13.6/src/testing/testing.go:960 +0x651
  testing.runTests.func1()
      /home/kostix/devel/golang-1.13.6/src/testing/testing.go:1202 +0xa6
  testing.tRunner()
      /home/kostix/devel/golang-1.13.6/src/testing/testing.go:909 +0x199
  testing.runTests()
      /home/kostix/devel/golang-1.13.6/src/testing/testing.go:1200 +0x521
  testing.(*M).Run()
      /home/kostix/devel/golang-1.13.6/src/testing/testing.go:1117 +0x2ff
  main.main()
      _testmain.go:44 +0x223
==================
--- FAIL: TestStringCache (0.00s)
    testing.go:853: race detected during execution of test
FAIL


问:
PowerShell function not running as expected
I have a curious case that I cannot fathom the reason for...

Please know I am a novice to PowerShell.

I am working on a PowerShell menu system to help automate building out new computers in my environment. I have a PS1 file that holds the script for an app install. When I use the script to reference this I am able to run it and have no issue. However, when I try inserting this into a function and referencing it does not.

This works:

```<code>4       #   Microsoft Office 32-bit
            {
                Write-Host "`nMicrosoft Office 32-bit..." -ForegroundColor Yellow

                # {installMS32Bit}
                Invoke-Expression "cmd /c start powershell -NoExit -File '\\**SERVERPATH**\menuItems\ms_office\32-bit\install.ps1'"

                Start-Sleep -seconds 2
            }
</code>```

This does not:

```<code>function installMS32Bit(){

Invoke-Expression "cmd /c start powershell -NoExit -File '\\**SERVERPATH**\menuItems\ms_office\32-bit\install.ps1'"
}
</code>```

}

```<code>4       #   Microsoft Office 32-bit
            {
                Write-Host "`nMicrosoft Office 32-bit..." -ForegroundColor Yellow

                {installMS32Bit}

                Start-Sleep -seconds 2}
</code>```

install.ps1 file:

```<code>    # Copy MS Office uninstall and setup to local then run and install 32-bit Office
Copy-Item -Path '\\**SERVERPATH**\menuItems\ms_office\setup.exe' -Destination 'C:\temp\' -Force
Copy-Item -Path '\\**SERVERPATH**\menuItems\ms_office\uninstall.xml' -Destination 'C:\temp\' -Force
Copy-Item -Path '\\**SERVERPATH**\menuItems\ms_office\32-bit\Setup.exe' -Destination 'C:\temp' -Force

Invoke-Expression ("cmd /c 'C:\temp\setup.exe' /configure 'C:\temp\uninstall.xml'")

Start-Process -FilePath 'C:\temp\Setup.exe'
</code>```

Secondary question and a little explanation for Invoke-Expression...

I like to see progress and like to have secondary windows open to monitor the new process being run. I was unable to find a solution with a persistent window that worked for me to do this without Invoke-Expression.

If there is a better way to do this in PowerShell I am all ears!

答:
{installMS32Bit}

As Mathias points out in a comment on the question, this statement doesn't call your function, it wraps it in a script block ({ ... })[1], which is a piece of reusable code (like a function pointer, loosely speaking), for later execution via &, the call (execute) operator.

To call your function, just use its name (by itself here, given that there are no arguments to pass): installMS32Bit

Invoke-Expression should generally be avoided; definitely don't use it to invoke an external program, as in your attempts.

Additionally, there's generally no need to call an external program via cmd.exe (cmd /c ...), just invoke it directly.

For instance, replace the last Invoke-Epression call from your question with:

```<code># If the EXE path weren't quoted, you wouldn't need the &
& 'C:\temp\setup.exe' /configure 'C:\temp\uninstall.xml'
</code>```

I like to see progress and like to have secondary windows open to monitor the new process being run. I was unable to find a solution with a persistent window that worked for me to do this without Invoke-Expression.

(On Windows), Start-Process by default executes a console application in a new window (unless you specify -NoNewWindow), asynchronously (unless you specify -Wait).

You cannot pass a .ps1 script directly to Start-Process (it will be treated like a document to open rather than an executable to call), but you can pass it to PowerShell's CLI via the -File parameter:

```<code>Start-Process powershell.exe '-File install.ps1'
</code>```

The above is short for:

```<code>Start-Process -FilePath powershell.exe -ArgumentList '-File install.ps1'
</code>```

That is, PowerShell will execute the following in a new window:

powershell.exe -File install.ps1

[1] Since you're not assigning the script block being created to a variable, it is implicitly output (printed to the display, in the absence of a redirection); a script block stringifies by its literal contents, excluding the enclosing { and }, so string installMS32Bit will print to the display.

Body:
I have a curious case that I cannot fathom the reason for...

Please know I am a novice to PowerShell.

I am working on a PowerShell menu system to help automate building out new computers in my environment. I have a PS1 file that holds the script for an app install. When I use the script to reference this I am able to run it and have no issue. However, when I try inserting this into a function and referencing it does not.

This works:

4       #   Microsoft Office 32-bit
            {
                Write-Host "`nMicrosoft Office 32-bit..." -ForegroundColor Yellow

                # {installMS32Bit}
                Invoke-Expression "cmd /c start powershell -NoExit -File '\\**SERVERPATH**\menuItems\ms_office\32-bit\install.ps1'"

                Start-Sleep -seconds 2
            }

This does not:

function installMS32Bit(){

Invoke-Expression "cmd /c start powershell -NoExit -File '\\**SERVERPATH**\menuItems\ms_office\32-bit\install.ps1'"
}

}

4       #   Microsoft Office 32-bit
            {
                Write-Host "`nMicrosoft Office 32-bit..." -ForegroundColor Yellow

                {installMS32Bit}

                Start-Sleep -seconds 2}

install.ps1 file:

    # Copy MS Office uninstall and setup to local then run and install 32-bit Office
Copy-Item -Path '\\**SERVERPATH**\menuItems\ms_office\setup.exe' -Destination 'C:\temp\' -Force
Copy-Item -Path '\\**SERVERPATH**\menuItems\ms_office\uninstall.xml' -Destination 'C:\temp\' -Force
Copy-Item -Path '\\**SERVERPATH**\menuItems\ms_office\32-bit\Setup.exe' -Destination 'C:\temp' -Force

Invoke-Expression ("cmd /c 'C:\temp\setup.exe' /configure 'C:\temp\uninstall.xml'")

Start-Process -FilePath 'C:\temp\Setup.exe'

Secondary question and a little explanation for Invoke-Expression...

I like to see progress and like to have secondary windows open to monitor the new process being run. I was unable to find a solution with a persistent window that worked for me to do this without Invoke-Expression.

If there is a better way to do this in PowerShell I am all ears!

Body:
{installMS32Bit}

As Mathias points out in a comment on the question, this statement doesn't call your function, it wraps it in a script block ({ ... })[1], which is a piece of reusable code (like a function pointer, loosely speaking), for later execution via &, the call (execute) operator.

To call your function, just use its name (by itself here, given that there are no arguments to pass): installMS32Bit

Invoke-Expression should generally be avoided; definitely don't use it to invoke an external program, as in your attempts.

Additionally, there's generally no need to call an external program via cmd.exe (cmd /c ...), just invoke it directly.

For instance, replace the last Invoke-Epression call from your question with:

# If the EXE path weren't quoted, you wouldn't need the &
& 'C:\temp\setup.exe' /configure 'C:\temp\uninstall.xml'

I like to see progress and like to have secondary windows open to monitor the new process being run. I was unable to find a solution with a persistent window that worked for me to do this without Invoke-Expression.

(On Windows), Start-Process by default executes a console application in a new window (unless you specify -NoNewWindow), asynchronously (unless you specify -Wait).

You cannot pass a .ps1 script directly to Start-Process (it will be treated like a document to open rather than an executable to call), but you can pass it to PowerShell's CLI via the -File parameter:

Start-Process powershell.exe '-File install.ps1'

The above is short for:

Start-Process -FilePath powershell.exe -ArgumentList '-File install.ps1'

That is, PowerShell will execute the following in a new window:

powershell.exe -File install.ps1

[1] Since you're not assigning the script block being created to a variable, it is implicitly output (printed to the display, in the absence of a redirection); a script block stringifies by its literal contents, excluding the enclosing { and }, so string installMS32Bit will print to the display.


问:
Can I optimize a standalone battery with MIP and output the charge/discharge pattern?
I am a beginner in Python.  I'm using the mip package to optimize a standalone battery given hourly power price in a year.  I need the program to pick 5 lowest price hours to charge the battery and 4 highest price hours to discharge it every day for a year.  But first I'm trying out the solver for 24 hours.

Data:

time, month, day, hour, power price (24 entries)

Q:

Solve for a standalone battery's optimal charging and discharging pattern

Battery rating: 1MW with 4MWh storage capability (4-hour storage)

Output: two columns of binary variables

Battery needs 4.7 hours to fully charge, and discharges for 4 hours

Round-trip efficiency 85%, charging 1 hour enables discharging of 0.85 hour

Constraints:

Battery state: available power >0 (cumulative charge - cumulative discharge) > 0

0 < cumulative discharge < 4

0 < cumulative charge < 4.7

Below is my code:

```<code>import numpy as np
import pandas as pd
import mip
from mip import Model, xsum, maximize, BINARY, CONTINUOUS, OptimizationStatus

# Define model and var
m = mip.Model(sense=maximize)
maxdischargepower = 4
maxchargepower = 4.7
H = 24
charge = [m.add_var(var_type = BINARY) for i in range(H)]
discharge = [m.add_var(var_type = BINARY) for i in range(H)]

batterystate = np.cumsum(charge) - np.cumsum(discharge)

# Define objective function
m.objective = xsum(discharge[i]*price[i] for i in range(H)) - xsum(charge[i]*price[i] for i in range (H))

# Constraints
m += np.cumsum(discharge) <= maxdischargepower
m += np.cumsum(charge) <= maxchargepower
m += np.cumsum(discharge) >= 0
m += batterystate >= 0
</code>```

I have several questions:

I get a result of -1277, which is the opposite number of the sum of power price in 24 hours.  There must be something wrong with the optimizing code but I cannot find it.

How do I save the charge and discharge binaries in the input data file?

Should I iterate the optimization model for 365 days for year-round data?

Thank you.

---------------------Edit 2/19-------------------------

Here's some sample data I've been running the code on:

Or in fact, 24 random numbers would also work but these are the actual prices I've been using.

I have an entire year of the data and once I figure out how to optimize within a day should I iterate the optimization for 366 days?

sample data

答:
Seems like the main part of the algorithm is to ask these questions at the top of each hour:

At what time will the battery be discharged?

Which hour between now and then will be the cheapest for recharging?

IF that is the current hour, then turn on recharging.

It seems like that would be optimal if you can recharge in less than an hour.  I don't understand the numbers you have -- 4 and 4.7 -- sounds like you need to be recharging almost all the time.

If that is the case, the algorithm can be turned around to "avoid recharging during costly hours".

You can't wait too long to decide whether to charge or not.  I assume the cost of making the decision is essentially zero.  So, recompute every hour (at least) and don't reach forward too far.  It sounds like you have less than 5 hours before the battery will die; trying to optimize further into the future will be useless if it is dead.

Body:
I am a beginner in Python.  I'm using the mip package to optimize a standalone battery given hourly power price in a year.  I need the program to pick 5 lowest price hours to charge the battery and 4 highest price hours to discharge it every day for a year.  But first I'm trying out the solver for 24 hours.

Data:

time, month, day, hour, power price (24 entries)

Q:

Solve for a standalone battery's optimal charging and discharging pattern

Battery rating: 1MW with 4MWh storage capability (4-hour storage)

Output: two columns of binary variables

Battery needs 4.7 hours to fully charge, and discharges for 4 hours

Round-trip efficiency 85%, charging 1 hour enables discharging of 0.85 hour

Constraints:

Battery state: available power >0 (cumulative charge - cumulative discharge) > 0

0 < cumulative discharge < 4

0 < cumulative charge < 4.7

Below is my code:

import numpy as np
import pandas as pd
import mip
from mip import Model, xsum, maximize, BINARY, CONTINUOUS, OptimizationStatus

# Define model and var
m = mip.Model(sense=maximize)
maxdischargepower = 4
maxchargepower = 4.7
H = 24
charge = [m.add_var(var_type = BINARY) for i in range(H)]
discharge = [m.add_var(var_type = BINARY) for i in range(H)]

batterystate = np.cumsum(charge) - np.cumsum(discharge)

# Define objective function
m.objective = xsum(discharge[i]*price[i] for i in range(H)) - xsum(charge[i]*price[i] for i in range (H))

# Constraints
m += np.cumsum(discharge) <= maxdischargepower
m += np.cumsum(charge) <= maxchargepower
m += np.cumsum(discharge) >= 0
m += batterystate >= 0

I have several questions:

I get a result of -1277, which is the opposite number of the sum of power price in 24 hours.  There must be something wrong with the optimizing code but I cannot find it.

How do I save the charge and discharge binaries in the input data file?

Should I iterate the optimization model for 365 days for year-round data?

Thank you.

---------------------Edit 2/19-------------------------

Here's some sample data I've been running the code on:

Or in fact, 24 random numbers would also work but these are the actual prices I've been using.

I have an entire year of the data and once I figure out how to optimize within a day should I iterate the optimization for 366 days?

sample data


问:
SQL LIKE query to C# code
I need to use the following query in my C# code:

```<code>SELECT AVG(Percent)
From Table1
Where code Like "Sport" and Year Like"2011" and Sitting Like"June";
</code>```

I did it like this:

```<code>"SELECT AVG(Percentage) FROM MasterTable WHERE Code LIKE " + comboBoxSubject.Text +
"AND Year LIKE "+dateTimePicker1 +" AND Sitting LIKE June"
</code>```

but i get an exception probably because the parameters are extracted from different controls and are not placed in inverted commas.

Can anyone help me ?

ANSWER

That is the query that worked for me:

```<code>"SELECT AVG(Percent) FROM MasterTable WHERE Code LIKE '" + comboBoxSubject.Text + "' AND Year LIKE '" + dateTimePicker1.Value.Year + "' AND Sitting LIKE 'June'"
</code>```

答:
MySqlCommand cmd = new MySqlCommand("SELECT Employee_No, Image, Last_Name, First_Name, Middle_Name, Suffix, Sex, Birthdate, Contact_No, Address, Username FROM user_tbl WHERE Employee_No LIKE '%" + searchemployeeno + "%' OR Last_Name LIKE '%" + searchemployeeno + "%' ", SQLConn.conn);
```

Title: SQL LIKE query to C# code

Body:
I need to use the following query in my C# code:

SELECT AVG(Percent)
From Table1
Where code Like "Sport" and Year Like"2011" and Sitting Like"June";

I did it like this:

"SELECT AVG(Percentage) FROM MasterTable WHERE Code LIKE " + comboBoxSubject.Text +
"AND Year LIKE "+dateTimePicker1 +" AND Sitting LIKE June"

but i get an exception probably because the parameters are extracted from different controls and are not placed in inverted commas.

Can anyone help me ?

ANSWER

That is the query that worked for me:

"SELECT AVG(Percent) FROM MasterTable WHERE Code LIKE '" + comboBoxSubject.Text + "' AND Year LIKE '" + dateTimePicker1.Value.Year + "' AND Sitting LIKE 'June'"


问:
How to auto reload next.js running with static site generation?
next dev allows you view websites while developing when you're using server-side generation.

When you're using static site generation, you first have to next build, and then do next start every time you want to refresh your changes.

Is there a next dev alternative for static sites? Something I can use while development.

答:
Next.js will pre-render the pages that don't have blocking data requirements - Static Generation.

You decide per-page if it will be statically rendered at build time or if will be server-rendered on-demand.

The way that Pre-rendering works in Next.js is that the page is rendered to HTML either at build-time or on-demand, this generated HTML will be optimized automatically.

When you're using static site generation, you first have to next build, and then do next start every time you want to refresh your changes.

This is wrong.

next build simply builds the application for production usage and next start starts a Next.js production server

Just run next if you are in development mode and next build + next start if you are in production.


问:
Python Pandas Regex
I have a pandas dataframe like in the example below.
Column 0 has many HTML tags, from which I need to extract all URLs and add them as columns in this DataFrame, while respecting the row order.

In this case, column 2, row 0 would have the: "https://sco...". In reality, this column could have as many as 10 URLs, which should be added to individual columns of the Dataframe.
I've tried using Beautiful Soup, but I couldn't make it work accurately with a Dataframe like this.

I've tried extracting using the Regex below to extract all those URLs, but I couldn't plug it to the Dataframe.

```<code>postsOnlyURL = re.findall('"(http.*?)"',all_text,re.IGNORECASE|re.DOTALL)

                                                    0                                                  1
0   src="https://sco ...                               publicado a 23/10/2019Ident...
1   Ativo</div></div><div class="_7jwu">Começou a ...  AtivoComeçou a ser publicado a 23/10/2019Ident...
2   Ativo</div></div><div class="_7jwu">Começou a ...  AtivoComeçou a ser publicado a 23/10/2019Ident...
</code>```

Is there a way to make this work?

答:
I can't access your dataset, but in general this is a way to extract urls from strings in dataframe with regex and create new columns dynamically according to the number of urls extracted:</p>

```<code>df = pd.DataFrame({'Col1': ['check my blog http://example.com/blah or this is an example of https://google.com or http://facebook.com',
                             'get url from https://facebook.com', 'You can find answers at https://stackoverflow.com/']})

pattern = r'(https?://[^\s]+)'

df['urls'] = df['Col1'].str.findall(pattern)
df['urls'] = [','.join(map(str, l)) for l in df['urls']]
df = pd.concat([df, df['urls'].str.split(',', expand=True)], axis=1)
</code>```

Title: Python Pandas Regex

Body:
I have a pandas dataframe like in the example below.
Column 0 has many HTML tags, from which I need to extract all URLs and add them as columns in this DataFrame, while respecting the row order.

In this case, column 2, row 0 would have the: "https://sco...". In reality, this column could have as many as 10 URLs, which should be added to individual columns of the Dataframe.
I've tried using Beautiful Soup, but I couldn't make it work accurately with a Dataframe like this.

I've tried extracting using the Regex below to extract all those URLs, but I couldn't plug it to the Dataframe.

postsOnlyURL = re.findall('"(http.*?)"',all_text,re.IGNORECASE|re.DOTALL)

                                                    0                                                  1
0   src="https://sco ...                               publicado a 23/10/2019Ident...
1   Ativo

Começou a ...  AtivoComeçou a ser publicado a 23/10/2019Ident...
2   Ativo

Começou a ...  AtivoComeçou a ser publicado a 23/10/2019Ident...

Is there a way to make this work?

Body:
I can't access your dataset, but in general this is a way to extract urls from strings in dataframe with regex and create new columns dynamically according to the number of urls extracted:

df = pd.DataFrame({'Col1': ['check my blog http://example.com/blah or this is an example of https://google.com or http://facebook.com',
                             'get url from https://facebook.com', 'You can find answers at https://stackoverflow.com/']})

pattern = r'(https?://[^\s]+)'

df['urls'] = df['Col1'].str.findall(pattern)
df['urls'] = [','.join(map(str, l)) for l in df['urls']]
df = pd.concat([df, df['urls'].str.split(',', expand=True)], axis=1)


问:
How to transform categorical column using one hot encoder in sklearn
I have a dataframe with a categorical column and am trying to one hot encode it using sklearn using the below snippit

```<code>oneEncoder= OneHotEncoder()
features['COL2'] = features['COL2'].apply(lambda col :  oneEncoder.fit_transform(col))
</code>```

but it keep throwing
ValueError: Expected 2D array, got scalar array instead:
array=1771. Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

I also tried

```<code>oneEncoder= OneHotEncoder() #initializing an object of class LabelEncoder
oneEncoder.fit_transform( features['COL2'])
</code>```

but it throws
ValueError: Expected 2D array, got 1D array instead:

答:
you could do directly </p>

```<code>categories = pd.get_dummies(features['COL2'])
</code>```

<p>otherwise you could pass a 2d array instead </p>

```<code>oneEncoder.fit_transform( features[['COL2']].values)
</code>```

Body:
I have a dataframe with a categorical column and am trying to one hot encode it using sklearn using the below snippit

oneEncoder= OneHotEncoder()
features['COL2'] = features['COL2'].apply(lambda col :  oneEncoder.fit_transform(col))

but it keep throwing
ValueError: Expected 2D array, got scalar array instead:
array=1771. Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

I also tried

oneEncoder= OneHotEncoder() #initializing an object of class LabelEncoder
oneEncoder.fit_transform( features['COL2'])

but it throws
ValueError: Expected 2D array, got 1D array instead:

Body:
you could do directly

categories = pd.get_dummies(features['COL2'])

otherwise you could pass a 2d array instead

oneEncoder.fit_transform( features[['COL2']].values)


问:
How to configure gitlab-runner workflow to run continuously two job of one project in two individual stages
I'm using Gitlab-runner 12.4.1.

I have a project using Gitlab-ci like:

```<code>stages:
- build
- deploy

build_a:
    stage: build

deploy_a:
    stage: deploy

build_b:
    stage: build

deploy_b:
    stage: deploy

build_c:
    stage: build

deploy_c:
    stage: deploy
</code>```

I want to set my project workflow as build_a > deploy_a > build_b > deploy_b > build_c > deploy_c.

But it actually does as build_a > build_b > build_c > deploy_a > deploy_b > deploy_c.

How to configure .gitlab-ci.yml for the jobs work like my expectation?

答:
Like that:

```<code>stages:
    - build_a
    - deploy_a
    - build_b
    - deploy_b
    - build_c
    - deploy_c

build_a:
    stage: build_a

deploy_a:
    stage: deploy_a

build_b:
    stage: build_b

deploy_b:
    stage: deploy_b

build_c:
    stage: build_c

deploy_c:
    stage: deploy_c
</code>```

Gitlab-CI will follow the order in "stages".
https://docs.gitlab.com/ee/ci/yaml/#stages

Body:
I'm using Gitlab-runner 12.4.1.

I have a project using Gitlab-ci like:

stages:
- build
- deploy

build_a:
    stage: build

deploy_a:
    stage: deploy

build_b:
    stage: build

deploy_b:
    stage: deploy

build_c:
    stage: build

deploy_c:
    stage: deploy

I want to set my project workflow as build_a > deploy_a > build_b > deploy_b > build_c > deploy_c.

But it actually does as build_a > build_b > build_c > deploy_a > deploy_b > deploy_c.

How to configure .gitlab-ci.yml for the jobs work like my expectation?

Body:
Like that:

stages:
    - build_a
    - deploy_a
    - build_b
    - deploy_b
    - build_c
    - deploy_c

build_a:
    stage: build_a

deploy_a:
    stage: deploy_a

build_b:
    stage: build_b

deploy_b:
    stage: deploy_b

build_c:
    stage: build_c

deploy_c:
    stage: deploy_c

Gitlab-CI will follow the order in "stages".
https://docs.gitlab.com/ee/ci/yaml/#stages


问:
Multi style sheet with jQuery cookies (Issue with pop up box)
```<code>$(function() {
    $('#yes a').click(function() {
        $.cookie('AutoPlayTrue', '1', {
            expires: 999
        });
        $('.disableAutoPlay').hide('slow');
        $.cookie('ccss_remembered_style', null);
        $.cookie('AutoPlayFalse', null);
    });
    $('#ccss-no a').click(function() {
        $.cookie('AutoPlayFalse', '1', {
            expires: 999
        });
        $('.disableAutoPlay').hide('slow');
        $.cookie('AutoPlayTrue', null);
    });
    if ($.cookie('AutoPlayFalse') === null) {
        $('.disableAutoPlay').show();
    }
    else {
        $('.disableAutoPlay').hide();
    }

    if ($.cookie('AutoPlayTrue') === null) {
        $('.disableAutoPlay').show();
    }
    else {
        $('.disableAutoPlay').hide();
    }
});
</code>```

I have a pop up box with the HTML:

```<code><li class="widget ccss" id="ccss-widget-3"><h2 class="widgettitle">Should HipHop97.com Automatically Start Playing Music?</h2>
    <ul id="ccss-list">

        <li id="ccss-no"><a href="http://hiphop97.com/wp-content/themes/hiphop/noAutoPlayCSS.css">No</a></li><li id="yes"><a href="#">Yes</a></li>
    </ul>

</li>
</code>```

I need when the 'yes' button is selected just act as a 'close' and with cookies 'don't show me again' and the 'no' button I've already got the style sheet and stuff code worked out I just need it to not display the box again with cookies. (The element is in the theme, just marked as display:none; it's at the top of the main container.)

I tried this, it's a good concept I suppose, it just doesn't work:

```<code><script type="text/javascript">
jQuery(document).ready(function($) {
    if ($.cookie('AutoPlayFalse')) {
        $('.displayAutoPlay').css('display','none !important');
    }
    if ($.cookie('AutoPlayTrue')) {
        $('.displayAutoPlay').css('display','none !important');
    }
});
</script>
</code>```

答:
```<code>if(!$.cookie('autoplay')){
   //display box
}else{
   $.cookie('autoplay',1);
}
</code>```

I dont understand why do you over complicate it as much :)

Body:
$(function() {
    $('#yes a').click(function() {
        $.cookie('AutoPlayTrue', '1', {
            expires: 999
        });
        $('.disableAutoPlay').hide('slow');
        $.cookie('ccss_remembered_style', null);
        $.cookie('AutoPlayFalse', null);
    });
    $('#ccss-no a').click(function() {
        $.cookie('AutoPlayFalse', '1', {
            expires: 999
        });
        $('.disableAutoPlay').hide('slow');
        $.cookie('AutoPlayTrue', null);
    });
    if ($.cookie('AutoPlayFalse') === null) {
        $('.disableAutoPlay').show();
    }
    else {
        $('.disableAutoPlay').hide();
    }

    if ($.cookie('AutoPlayTrue') === null) {
        $('.disableAutoPlay').show();
    }
    else {
        $('.disableAutoPlay').hide();
    }
});

I have a pop up box with the HTML:

Should HipHop97.com Automatically Start Playing Music?

No

Yes

I need when the 'yes' button is selected just act as a 'close' and with cookies 'don't show me again' and the 'no' button I've already got the style sheet and stuff code worked out I just need it to not display the box again with cookies. (The element is in the theme, just marked as display:none; it's at the top of the main container.)

I tried this, it's a good concept I suppose, it just doesn't work:

Body:
if(!$.cookie('autoplay')){
   //display box
}else{
   $.cookie('autoplay',1);
}

I dont understand why do you over complicate it as much :)


问:
Update all dictionary values with different ids
I want to design an auto-generated dictionary template.

The format of dictionary is like: {'google_drive': {'services': []}, 'dropbox': {'services': []}, 'test': {'services': []}}

All keys have same value {'services': []} and their value ids/addresses should be different. The problem now is all values are the same.

```<code># init function has an array ["google_drive", "dropbox", "test"]
# so that all the key-value pairs can be created automatically
test = CloudInfo().init().config_info
print(id(test["google_drive"]["services"]))
print(id(test["dropbox"]["services"]))
print(id(test["test"]["services"]))
</code>```

Output

```<code>2382756081216
2382756081216
2382756081216
</code>```

And I have found the problem in my encapsulated method:

```<code>def update_all_value(self, keys, value):
    __keys = keys
    __dict = self.__dict
    __value = value
    if __keys is not None:
        for key in __keys:
            if key in __dict:
                __dict.update({key: __value})
        self.__dict = __dict
    return self
</code>```

All keys have pointed to single variable __value.

If I changed __dict.update({key: __value}) as __dict.update({key: {'services': []}}),  dictionary value are different ids. But the function is not reusable.

Is there any good solution that can update all dictionary values with different ids and keep the input parameter value working?

答:
You can use a defaultdict:

from collections import defaultdict
import copy

template = {'services': []}
test = defaultdict(lambda: copy.deepcopy(template))
print(id(test["google_drive"]["services"]))
# 2546846465416
print(id(test["dropbox"]["services"]))
# 2546847840648
print(id(test["test"]["services"]))
# 2545171504392
```

Body:
I want to design an auto-generated dictionary template.

The format of dictionary is like: {'google_drive': {'services': []}, 'dropbox': {'services': []}, 'test': {'services': []}}

All keys have same value {'services': []} and their value ids/addresses should be different. The problem now is all values are the same.

# init function has an array ["google_drive", "dropbox", "test"]
# so that all the key-value pairs can be created automatically
test = CloudInfo().init().config_info
print(id(test["google_drive"]["services"]))
print(id(test["dropbox"]["services"]))
print(id(test["test"]["services"]))

Output

2382756081216
2382756081216
2382756081216

And I have found the problem in my encapsulated method:

def update_all_value(self, keys, value):
    __keys = keys
    __dict = self.__dict
    __value = value
    if __keys is not None:
        for key in __keys:
            if key in __dict:
                __dict.update({key: __value})
        self.__dict = __dict
    return self

All keys have pointed to single variable __value.

If I changed __dict.update({key: __value}) as __dict.update({key: {'services': []}}),  dictionary value are different ids. But the function is not reusable.

Is there any good solution that can update all dictionary values with different ids and keep the input parameter value working?


问:
Two expressions to get an answer (If X = Y and A = B then the answer is D)
Struggling on what should be a simple expression Google Sheets: Two expressions to get an answer (If X = Y and A = B then the answer is D)

You can see copy of the doc here.
https://docs.google.com/spreadsheets/d/1ufFZfXQb0st4bWP_fcw50FKZSx-tRL58ELTClLsIMQs/edit?usp=sharing

Body:
you need nested IF:

=IF((A13="BMW") *(B13="SUV"),       B17,
 IF((A13="Ford")*(B13="hatchback"), B20, ))


问:
Validate dependant data of 4 comboboxes at once c#
Im learning MVVM C# with WPF and I need to validate 4 Combo Boxes at once. The logic behind is that the selections must be of the same type ad family (2 properties of the objects that populate those comboboxes). The problem is that they must be evaluated in conjunction and I have been reaching posts from this site, MSDN and even udemy courses where I haven't been able to find answer to these questions.

In first place, where should I put my evaluation code?
Currently the code is in the ViewModel file for the window I have built. A fragment of this validation code says the following.

```<code>    //Temperature Check
    private void CheckTemperature()
    {
      if (Temperature < -273.15)
      {
        MessageBox.Show("You can't use temperatures below 0ºK", "It's freezing");
        Temperature = -273.15;
      }
      else if (Temperature > 100)
      {
        MessageBox.Show("Surface temperature can't be that hot", "Hotter than hell");
        Temperature = 100;
      }
      CanObtainHarm();
    }
</code>```

And it gets executed everytime that...

```<code>private double _temperature;

    public double Temperature
    {
      get { return _temperature; }
      set {
        _temperature = value;
        CheckTemperature();
        OnPropertyChanged("Temperature");
      }
    }
</code>```

My common sense says me that this is not the place to be of this validation code.
For this example I will make it a validation rule but the case of the 4 comboboxes that must be validated and if they are not properly set, they should be left void makes me crazy.
Since I haven't found how can I validate user's ComboBox input and left it void if it is not valid, I am jumping from video to post desperately.
Additional information:
There is no button to press validation, it should be performed everytime a value of these comboboxes is changed

答:
i boil this task down like:

Validate dependant data of 4 comboboxes at once c#

when any of these 4 properties change, run some validation logic

on property changed, if propertyName = one of the 4, run some validation logic

INotifyPropertyChanged.PropertyChanged, switch statement, validation logic

so somewhere where we have a reference to our view model, we need to add an event handler to its PropertyChanged event, to check that the property name is one of the 4 and if so then run some validation logic.

given our view model is a dependency property on our view, i'd wire all of this up in the view's Loaded event.

ANotifyPropertyChanged - base implementation for all of our view models

```<code>using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace SO60283924
{
    public abstract class ANotifyPropertyChanged : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void SetProperty<T>(ref T backingStore, T newValue, [CallerMemberName] string propertyName = "")
        {
            var areEqual = ReferenceEquals(backingStore, newValue);
            if (areEqual)
                return;
            backingStore = newValue;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
</code>```

SomeViewModel - a view model with 5 properties, 4 of which we want to validate in conjunction

```<code>namespace SO60283924
{
    public class SomeViewModel : ANotifyPropertyChanged
    {
        private string someString;
        private int someInt;
        private object someObject;
        private decimal someDecimal;
        private object somePropertyNotPartOfValidation;

        public string SomeString { get => someString; set => SetProperty(ref someString, value); }
        public int SomeInt { get => someInt; set => SetProperty(ref someInt, value); }
        public object SomeObject { get => someObject; set => SetProperty(ref someObject, value); }
        public decimal SomeDecimal { get => someDecimal; set => SetProperty(ref someDecimal, value); }
        public object SomePropertyNotPartOfValidation { get => somePropertyNotPartOfValidation; set => SetProperty(ref somePropertyNotPartOfValidation, value); }
    }
}
</code>```

MainWindow - a view for some view model

```<code><Window
    x:Class="SO60283924.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Loaded="Window_Loaded">
    <Grid>

    </Grid>
</Window>
</code>```

MainWindow code behind - where we add the property changed handler with the validation logic

```<code>using System.Windows;

namespace SO60283924
{
    public partial class MainWindow : Window
    {
        public SomeViewModel SomeViewModel
        {
            get { return (SomeViewModel)GetValue(SomeViewModelProperty); }
            set { SetValue(SomeViewModelProperty, value); }
        }
        public static readonly DependencyProperty SomeViewModelProperty =
            DependencyProperty.Register(nameof(SomeViewModel), typeof(SomeViewModel), typeof(MainWindow), new PropertyMetadata(new SomeViewModel()));
        public MainWindow()
        {
            InitializeComponent();
        }
        void Window_Loaded(object sender, RoutedEventArgs e)
        {
            SomeViewModel.PropertyChanged += (_, propertyChangedEventArgs) =>
            {
                switch (propertyChangedEventArgs.PropertyName)
                {
                    case nameof(SomeViewModel.SomeDecimal):
                    case nameof(SomeViewModel.SomeInt):
                    case nameof(SomeViewModel.SomeObject):
                    case nameof(SomeViewModel.SomeString):
                        //TODO add validation code
                        break;
                }
            };
        }
    }
}
</code>```

this accomplishes our goal: on property changed, if one of our 4 properties changed, run some validation logic.

Body:
Im learning MVVM C# with WPF and I need to validate 4 Combo Boxes at once. The logic behind is that the selections must be of the same type ad family (2 properties of the objects that populate those comboboxes). The problem is that they must be evaluated in conjunction and I have been reaching posts from this site, MSDN and even udemy courses where I haven't been able to find answer to these questions.

In first place, where should I put my evaluation code?
Currently the code is in the ViewModel file for the window I have built. A fragment of this validation code says the following.

    //Temperature Check
    private void CheckTemperature()
    {
      if (Temperature < -273.15)
      {
        MessageBox.Show("You can't use temperatures below 0ºK", "It's freezing");
        Temperature = -273.15;
      }
      else if (Temperature > 100)
      {
        MessageBox.Show("Surface temperature can't be that hot", "Hotter than hell");
        Temperature = 100;
      }
      CanObtainHarm();
    }

And it gets executed everytime that...

private double _temperature;

    public double Temperature
    {
      get { return _temperature; }
      set {
        _temperature = value;
        CheckTemperature();
        OnPropertyChanged("Temperature");
      }
    }

My common sense says me that this is not the place to be of this validation code.
For this example I will make it a validation rule but the case of the 4 comboboxes that must be validated and if they are not properly set, they should be left void makes me crazy.
Since I haven't found how can I validate user's ComboBox input and left it void if it is not valid, I am jumping from video to post desperately.
Additional information:
There is no button to press validation, it should be performed everytime a value of these comboboxes is changed

Body:
i boil this task down like:

Validate dependant data of 4 comboboxes at once c#

when any of these 4 properties change, run some validation logic

on property changed, if propertyName = one of the 4, run some validation logic

INotifyPropertyChanged.PropertyChanged, switch statement, validation logic

so somewhere where we have a reference to our view model, we need to add an event handler to its PropertyChanged event, to check that the property name is one of the 4 and if so then run some validation logic.

given our view model is a dependency property on our view, i'd wire all of this up in the view's Loaded event.

ANotifyPropertyChanged - base implementation for all of our view models

using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace SO60283924
{
    public abstract class ANotifyPropertyChanged : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void SetProperty<T>(ref T backingStore, T newValue, [CallerMemberName] string propertyName = "")
        {
            var areEqual = ReferenceEquals(backingStore, newValue);
            if (areEqual)
                return;
            backingStore = newValue;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

SomeViewModel - a view model with 5 properties, 4 of which we want to validate in conjunction

namespace SO60283924
{
    public class SomeViewModel : ANotifyPropertyChanged
    {
        private string someString;
        private int someInt;
        private object someObject;
        private decimal someDecimal;
        private object somePropertyNotPartOfValidation;

        public string SomeString { get => someString; set => SetProperty(ref someString, value); }
        public int SomeInt { get => someInt; set => SetProperty(ref someInt, value); }
        public object SomeObject { get => someObject; set => SetProperty(ref someObject, value); }
        public decimal SomeDecimal { get => someDecimal; set => SetProperty(ref someDecimal, value); }
        public object SomePropertyNotPartOfValidation { get => somePropertyNotPartOfValidation; set => SetProperty(ref somePropertyNotPartOfValidation, value); }
    }
}

MainWindow - a view for some view model

<Window
    x:Class="SO60283924.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Loaded="Window_Loaded">
    <Grid>

    </Grid>
</Window>

MainWindow code behind - where we add the property changed handler with the validation logic

using System.Windows;

namespace SO60283924
{
    public partial class MainWindow : Window
    {
        public SomeViewModel SomeViewModel
        {
            get { return (SomeViewModel)GetValue(SomeViewModelProperty); }
            set { SetValue(SomeViewModelProperty, value); }
        }
        public static readonly DependencyProperty SomeViewModelProperty =
            DependencyProperty.Register(nameof(SomeViewModel), typeof(SomeViewModel), typeof(MainWindow), new PropertyMetadata(new SomeViewModel()));
        public MainWindow()
        {
            InitializeComponent();
        }
        void Window_Loaded(object sender, RoutedEventArgs e)
        {
            SomeViewModel.PropertyChanged += (_, propertyChangedEventArgs) =>
            {
                switch (propertyChangedEventArgs.PropertyName)
                {
                    case nameof(SomeViewModel.SomeDecimal):
                    case nameof(SomeViewModel.SomeInt):
                    case nameof(SomeViewModel.SomeObject):
                    case nameof(SomeViewModel.SomeString):
                        //TODO add validation code
                        break;
                }
            };
        }
    }
}

this accomplishes our goal: on property changed, if one of our 4 properties changed, run some validation logic.


问:
What does the filter parameter to createScaledBitmap do?
The declaration of android.graphics.Bitmap.createScaledBitmap is

```<code>public static Bitmap createScaledBitmap
  (Bitmap src, int dstWidth, int dstHeight, boolean filter)
</code>```

However, the documentation doesn't explain any of the parameters.  All of them are pretty obvious except for boolean filter.  Does anyone know what it does?

答:
A bit late to the party, but I thought some sample images might clarify the issue.

There is a more general question about whether and how to filter on superuser.

Says Jeff Atwood:

In general you want a mild sharpening effect when making a larger image into a smaller one, and a mild blurring effect when making a smaller image into a larger one.

Android's API does not specify what kind of filter would be applied, so I guess the question is: do you want your pixels to remain as they are (as you would want in 8-bit art) or is it okay to apply a transformation to make the image more palatable (as you would want in photographs).

ContentLicense: CC BY-SA 2.5

Body:
The declaration of android.graphics.Bitmap.createScaledBitmap is

public static Bitmap createScaledBitmap
  (Bitmap src, int dstWidth, int dstHeight, boolean filter)

However, the documentation doesn't explain any of the parameters.  All of them are pretty obvious except for boolean filter.  Does anyone know what it does?


问:
Printing the output rounded to 3 decimals in SymPy
I got a SymPy matrix M

```<code>In [1]: from sympy import *
In [2]: M = 1/10**6 * Matrix(([1, 10, 100], [1000, 10000, 100000]))
In [3]: M
Out[3]:
Matrix([
[1.0e-6, 1.0e-5, 0.0001],
[ 0.001,   0.01,    0.1]])
</code>```

I want to print the output rounded to 3 decimals, as follows:

```<code>In [3]: M
Out[3]:
Matrix([
[ 0.000, 0.000, 0.000],
[ 0.001, 0.010, 0.100]])
</code>```

In normal Python, I would go like this:

```<code>In [5]: '{:.3f}'.format(1/10**6)
Out[5]: '0.000'
</code>```

But how to do in a SymPy matrix?

Moreover, a more general case would be an expression containing also Symbols

```<code>x = symbols('x')
M = 1/10**6 * Matrix(([1, 10*x, 100], [1000, 10000*x, 100000]))
</code>```

The preferred output is

```<code>In [3]: M
Out[3]:
Matrix([
[ 0.000, 0.000*x, 0.000],
[ 0.001, 0.010*x, 0.100]])
</code>```

答:
I needed to improve these 2 solutions (Space47 already improved the accepted solution) because my numbers were very big, and Sympy just send "123456789.123 x"

```<code>def printM(expr, num_digits):
     return expr.xreplace({n.evalf() : n if type(n)==int else Float(n, num_digits) for n in expr.atoms(Number)})
</code>```

so "123456789.123 x" will be displayed 1.23 * 10^8
and the function does NOT change representation of integers (previously, "1" was replaced by "1.0")

Body:
I got a SymPy matrix M

In [1]: from sympy import *
In [2]: M = 1/10**6 * Matrix(([1, 10, 100], [1000, 10000, 100000]))
In [3]: M
Out[3]:
Matrix([
[1.0e-6, 1.0e-5, 0.0001],
[ 0.001,   0.01,    0.1]])

I want to print the output rounded to 3 decimals, as follows:

In [3]: M
Out[3]:
Matrix([
[ 0.000, 0.000, 0.000],
[ 0.001, 0.010, 0.100]])

In normal Python, I would go like this:

In [5]: '{:.3f}'.format(1/10**6)
Out[5]: '0.000'

But how to do in a SymPy matrix?

Moreover, a more general case would be an expression containing also Symbols

x = symbols('x')
M = 1/10**6 * Matrix(([1, 10*x, 100], [1000, 10000*x, 100000]))

The preferred output is

In [3]: M
Out[3]:
Matrix([
[ 0.000, 0.000*x, 0.000],
[ 0.001, 0.010*x, 0.100]])

Body:
I needed to improve these 2 solutions (Space47 already improved the accepted solution) because my numbers were very big, and Sympy just send "123456789.123 x"

def printM(expr, num_digits):
     return expr.xreplace({n.evalf() : n if type(n)==int else Float(n, num_digits) for n in expr.atoms(Number)})

so "123456789.123 x" will be displayed 1.23 * 10^8
and the function does NOT change representation of integers (previously, "1" was replaced by "1.0")


问:
How can I set a state with react native and typescript?
I'm just started with react native and I'm trying to use typescript. I am trying to set my state but it gives me the following error.

```<code>Argument of type '{ pickerData: PickerData; }' is not assignable to parameter of type 'IRegisterScreenState | ((prevState: Readonly<IRegisterScreenState>, props: Readonly<IRegisterScreenProps>) => IRegisterScreenState | Pick<...>) | Pick<...>'.
  Type '{ pickerData: PickerData; }' is not assignable to type 'Pick<IRegisterScreenState, "pickerData">'.
    Types of property 'pickerData' are incompatible.
      Type 'PickerData' is missing the following properties from type 'ReactNativePhoneInput<typeof TextInput>': isValidNumber, getNumberType, getValue, getFlag, and 14 more.
</code>```

I looked up on how to set a state using typescript an I found the following https://facebook.github.io/react-native/blog/2018/05/07/using-typescript-with-react-native#adding-a-component where they use the interface State and Props. Can I not make my own interface for this component? I've seen others do IState and IProps. Otherwise I woul not know what is causing my error. The error comes from the following line this.setState({pickerData: this.phoneInputRef.current.getPickerData()});

```<code>import * as React from 'react';
import { StyleSheet, Text, View, } from 'react-native';
import {Button} from 'react-native-elements';

import PhoneInput from 'react-native-phone-input';
import ReactNativePhoneInput from 'react-native-phone-input';
import PickerData from 'react-native-phone-input';
// import CountryPicker from 'react-native-country-picker-modal';

export interface IRegisterScreenProps {

}

export interface IRegisterScreenState{
  cca2? : string;
  pickerData? : PickerData;
}

export default class RegisterScreen extends React.Component<IRegisterScreenProps, IRegisterScreenState> {

  private phoneInputRef = React.createRef<ReactNativePhoneInput>();

  constructor(props:IRegisterScreenProps) {
    super(props);
    this.onPressFlag = this.onPressFlag.bind(this);
    this.selectCountry = this.selectCountry.bind(this);
    this.submitPhoneNumber = this.submitPhoneNumber.bind(this);
    this.state = {
      cca2: 'US',
    };
  }

  componentDidMount() {
    if (this.phoneInputRef.current)
      this.setState({pickerData: this.phoneInputRef.current.getPickerData()});
  }

  onPressFlag() {
    // this.countryPicker.openModal();
    console.log(this.phoneInputRef.current);
  }

  selectCountry(country:IRegisterScreenState) {
    if(this.phoneInputRef.current)
      this.phoneInputRef.current.selectCountry(country.cca2.toLowerCase());
    // this.setState({ cca2: country.cca2 });
  }

  public render(): JSX.Element
  {
    return (
      <View style={styles.container}>
        <Text style={styles.title}>Tempp</Text>
        <PhoneInput ref={this.phoneInputRef} onPressFlag={this.onPressFlag}/>
        <Button title="Submit" onPress={this.submitPhoneNumber} containerStyle={styles.submitButton} />
      </View>
    );
  }

  private submitPhoneNumber() : void
  {
    console.log(this.phoneInputRef);
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  title: {
    fontSize: 50,
    margin: 30,
  },
  phoneNumberInput:{
    width: 300,
  },
  submitButton:{
    width: 150,
    margin: 25,
  },
});
</code>```

答:
PickerData type is probably wrong. Where is that type coming from? I looked at the plugin issues and someone was asking for TypeScript support for the lib.

Anyways maybe change pickerData to

```<code>export interface IRegisterScreenState{
  cca2? : string;
  pickerData? : any;
}
</code>```

and see what the getPickerData function returns. You can then define a proper type for whatever that function returns.

Also i noticed you called

```<code>this.phoneInputRef.current.getPickerData()
</code>```

and the documentation says

```<code>this.phone.getPickerData()
</code>```

but i'm not sure if that matters

Body:
I'm just started with react native and I'm trying to use typescript. I am trying to set my state but it gives me the following error.

Argument of type '{ pickerData: PickerData; }' is not assignable to parameter of type 'IRegisterScreenState | ((prevState: Readonly<IRegisterScreenState>, props: Readonly<IRegisterScreenProps>) => IRegisterScreenState | Pick<...>) | Pick<...>'.
  Type '{ pickerData: PickerData; }' is not assignable to type 'Pick<IRegisterScreenState, "pickerData">'.
    Types of property 'pickerData' are incompatible.
      Type 'PickerData' is missing the following properties from type 'ReactNativePhoneInput<typeof TextInput>': isValidNumber, getNumberType, getValue, getFlag, and 14 more.

I looked up on how to set a state using typescript an I found the following https://facebook.github.io/react-native/blog/2018/05/07/using-typescript-with-react-native#adding-a-component where they use the interface State and Props. Can I not make my own interface for this component? I've seen others do IState and IProps. Otherwise I woul not know what is causing my error. The error comes from the following line this.setState({pickerData: this.phoneInputRef.current.getPickerData()});

import * as React from 'react';
import { StyleSheet, Text, View, } from 'react-native';
import {Button} from 'react-native-elements';

import PhoneInput from 'react-native-phone-input';
import ReactNativePhoneInput from 'react-native-phone-input';
import PickerData from 'react-native-phone-input';
// import CountryPicker from 'react-native-country-picker-modal';

export interface IRegisterScreenProps {

}

export interface IRegisterScreenState{
  cca2? : string;
  pickerData? : PickerData;
}

export default class RegisterScreen extends React.Component<IRegisterScreenProps, IRegisterScreenState> {

  private phoneInputRef = React.createRef<ReactNativePhoneInput>();

  constructor(props:IRegisterScreenProps) {
    super(props);
    this.onPressFlag = this.onPressFlag.bind(this);
    this.selectCountry = this.selectCountry.bind(this);
    this.submitPhoneNumber = this.submitPhoneNumber.bind(this);
    this.state = {
      cca2: 'US',
    };
  }

  componentDidMount() {
    if (this.phoneInputRef.current)
      this.setState({pickerData: this.phoneInputRef.current.getPickerData()});
  }

  onPressFlag() {
    // this.countryPicker.openModal();
    console.log(this.phoneInputRef.current);
  }

  selectCountry(country:IRegisterScreenState) {
    if(this.phoneInputRef.current)
      this.phoneInputRef.current.selectCountry(country.cca2.toLowerCase());
    // this.setState({ cca2: country.cca2 });
  }

  public render(): JSX.Element
  {
    return (
      <View style={styles.container}>
        <Text style={styles.title}>Tempp</Text>
        <PhoneInput ref={this.phoneInputRef} onPressFlag={this.onPressFlag}/>
        <Button title="Submit" onPress={this.submitPhoneNumber} containerStyle={styles.submitButton} />
      </View>
    );
  }

  private submitPhoneNumber() : void
  {
    console.log(this.phoneInputRef);
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  title: {
    fontSize: 50,
    margin: 30,
  },
  phoneNumberInput:{
    width: 300,
  },
  submitButton:{
    width: 150,
    margin: 25,
  },
});

Body:
PickerData type is probably wrong. Where is that type coming from? I looked at the plugin issues and someone was asking for TypeScript support for the lib.

Anyways maybe change pickerData to

export interface IRegisterScreenState{
  cca2? : string;
  pickerData? : any;
}

and see what the getPickerData function returns. You can then define a proper type for whatever that function returns.

Also i noticed you called

this.phoneInputRef.current.getPickerData()

and the documentation says

this.phone.getPickerData()

but i'm not sure if that matters


问:
PDO Join, avoid overwriting keys with the same name in the resulted array
I am doing a join with PDO like this:

```<code>SELECT users.*,images.*, sessions.*,social.*,videos.*,teams.*,achievements.*,_achievements_list.* FROM users LEFT JOIN images ON users.user_id=images.user_id LEFT JOIN sessions ON users.user_id=sessions.user_id LEFT JOIN social ON users.user_id=social.user_id LEFT JOIN videos ON users.user_id=videos.user_id LEFT JOIN teams ON users.user_id=teams.user_id LEFT JOIN achievements ON users.user_id=achievements.user_id LEFT JOIN _achievements_list ON achievements.achievement_id=_achievements_list.parent_id WHERE users.nickname = 'something'
</code>```

The problem is that some tables have the same names for some columns, so in the array that PDO gives me back, many things are overwritten.

I am using this:

```<code>   $statement = $this->pdo->prepare($query);

    if ($statement->execute($param))
        return $statement->fetchAll(PDO::FETCH_ASSOC);
    return false;
</code>```

PDO returns an associative array, but how do I do in order to avoid overwriting columns with the same names but from different tables?

答: you can use PDO::FETCH_NAMED, see https://phpdelusions.net/pdo/fetch_modes#FETCH_NAMED

Body:
I am doing a join with PDO like this:

SELECT users.*,images.*, sessions.*,social.*,videos.*,teams.*,achievements.*,_achievements_list.* FROM users LEFT JOIN images ON users.user_id=images.user_id LEFT JOIN sessions ON users.user_id=sessions.user_id LEFT JOIN social ON users.user_id=social.user_id LEFT JOIN videos ON users.user_id=videos.user_id LEFT JOIN teams ON users.user_id=teams.user_id LEFT JOIN achievements ON users.user_id=achievements.user_id LEFT JOIN _achievements_list ON achievements.achievement_id=_achievements_list.parent_id WHERE users.nickname = 'something'

The problem is that some tables have the same names for some columns, so in the array that PDO gives me back, many things are overwritten.

I am using this:

   $statement = $this->pdo->prepare($query);

    if ($statement->execute($param))
        return $statement->fetchAll(PDO::FETCH_ASSOC);
    return false;

PDO returns an associative array, but how do I do in order to avoid overwriting columns with the same names but from different tables?


问:
How to run jboss server in windows?
I am new in jboss and now i am configuring jboss server with windows. I am setting env. variable as:

```<code>JBOSS_HOME= C:\jboss-4.2.0.GA
Path = C:\jboss-4.2.0.GA\bin
</code>```

and while starting jboss through run.bat, it will do nothing just blinking once and disable the prompt.

It will gives me out as

The filename, directory name, or volume label syntax is incorrect.
  'findstr' is not recognized as an internal or external command,
  operable program or batch file.

答:
If you take a look in run.bat you will see that it uses findstr command.

```<code>"%JAVA%" -version 2>&1 | findstr /I hotspot > nul
</code>```

You modified your PATH environment and it cannot find findstr which is a native Windows command.

You don't need to modify PATH to use JBOSS. If you do keep old PATH values, like

```<code>set PATH = C:\jboss-4.2.0.GA\bin;%PATH%
</code>```

Title: How to run jboss server in windows?

Body:
I am new in jboss and now i am configuring jboss server with windows. I am setting env. variable as:

JBOSS_HOME= C:\jboss-4.2.0.GA
Path = C:\jboss-4.2.0.GA\bin

and while starting jboss through run.bat, it will do nothing just blinking once and disable the prompt.

It will gives me out as

The filename, directory name, or volume label syntax is incorrect.
  'findstr' is not recognized as an internal or external command,
  operable program or batch file.

Body:
If you take a look in run.bat you will see that it uses findstr command.

"%JAVA%" -version 2>&1 | findstr /I hotspot > nul

You modified your PATH environment and it cannot find findstr which is a native Windows command.

You don't need to modify PATH to use JBOSS. If you do keep old PATH values, like

set PATH = C:\jboss-4.2.0.GA\bin;%PATH%


问:
In Cypress, how do I check if a button has an attribute or not?
I want to put an if condition if an attribute exist on a button or else do some other things. How can I do it in Cypress?
I have done this till now but not working...
'''

```<code>if(cy.get('button[type="button"]').should('have.attr','disabled')==true){
       doTaskA()
   }else{
        doTaskB()
    }
</code>```

'''
This fails the whole test and not just the condition.

答:
Two ideas come to mind:

Maybe checkout the Cypress guide on conditional testing. They have a bit about element existence. You might be able to do something similar : https://docs.cypress.io/guides/core-concepts/conditional-testing.html#Element-existence

Or maybe, perform the condition check manually using jquery:

let $el = Cypress.$("myselector");
if ($el.attr("myattr") === "myvalue") {
    do.A();
} else {
    do.B();
}
```

Body:
I want to put an if condition if an attribute exist on a button or else do some other things. How can I do it in Cypress?
I have done this till now but not working...
'''

if(cy.get('button[type="button"]').should('have.attr','disabled')==true){
       doTaskA()
   }else{
        doTaskB()
    }

'''
This fails the whole test and not just the condition.


问:
SQL Server 2012 PERCENT_RANK() Exclude NULLS
```<code>SELECT [Cole_Crops],
       PERCENT_RANK() OVER (PARTITION BY HUC02
                            ORDER BY [Cole_Crops]) AS Cole_Crops_PCT_RANK],
       [Row_Crops],
       PERCENT_RANK() OVER (PARTITION BY HUC02
                            ORDER BY [Row_Crops]) AS Row_Crops_PCT_RANK]
FROM V012_CDLMAX_09
</code>```

How do you exclude NULL values from affecting the PERCENT_RANK in a query with multiple columns to be ranked?

SQL Server 2012 PERCENT_RANK() treats NULLS as a real value in the distribution. If there were one column to be ranked, you can simply add a where clause (i.e., where Cole_Crops IS NOT NULL).

答:
You can try adding a condition in PARTITION BY clause:</p>

```<code>SELECT [Cole_Crops],
   PERCENT_RANK() OVER (PARTITION BY [Cole_Crops] is not null, HUC02
                        ORDER BY [Cole_Crops]) AS Cole_Crops_PCT_RANK],
   [Row_Crops],
   PERCENT_RANK() OVER (PARTITION BY [Row_Crops] is not null, HUC02
                        ORDER BY [Row_Crops]) AS Row_Crops_PCT_RANK]
FROM V012_CDLMAX_09
</code>```

Body:
SELECT [Cole_Crops],
       PERCENT_RANK() OVER (PARTITION BY HUC02
                            ORDER BY [Cole_Crops]) AS Cole_Crops_PCT_RANK],
       [Row_Crops],
       PERCENT_RANK() OVER (PARTITION BY HUC02
                            ORDER BY [Row_Crops]) AS Row_Crops_PCT_RANK]
FROM V012_CDLMAX_09

How do you exclude NULL values from affecting the PERCENT_RANK in a query with multiple columns to be ranked?

SQL Server 2012 PERCENT_RANK() treats NULLS as a real value in the distribution. If there were one column to be ranked, you can simply add a where clause (i.e., where Cole_Crops IS NOT NULL).

Body:
You can try adding a condition in PARTITION BY clause:

SELECT [Cole_Crops],
   PERCENT_RANK() OVER (PARTITION BY [Cole_Crops] is not null, HUC02
                        ORDER BY [Cole_Crops]) AS Cole_Crops_PCT_RANK],
   [Row_Crops],
   PERCENT_RANK() OVER (PARTITION BY [Row_Crops] is not null, HUC02
                        ORDER BY [Row_Crops]) AS Row_Crops_PCT_RANK]
FROM V012_CDLMAX_09


问:
Word Cloud making error in Python: string indices must be integers
I'm trying to make a Word Cloud out of a txt file with this code:

```<code>import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from wordcloud import WordCloud, STOPWORDS
from IPython.display import Image as im

file = open("T.txt", encoding='utf-8')
FR = file.read()

raw_file = []

for line in FR:
    raw_file.append(line['text'])

words = raw_file.split(" ")
words = [w for w in words if len(w) > 2]
words = [w.lower() for w in words]
words = [w for w in words if w not in STOPWORDS]

word_list = (words)
word_counter = {}
for word in word_list:
     if word in word_counter:
         word_counter[word] += 1
     else:
         word_counter[word] = 1

popular_words = sorted(word_counter, key = word_counter.get, reverse = True)

topp = popular_words

topp.remove('https')

mask = np.array(Image.open('/Users/x/Downloads/B.png'))

wc = WordCloud(background_color="black", max_words=2000, mask=mask)
clean_string = ','.join(topp)
wc.generate(clean_string)

plt.imshow(wc, interpolation='bilinear')
plt.title("Title", size=40)
plt.axis("off")
plt.show()
</code>```

As in the title, it gives me Error: string indices must be integers on raw_file.append(line['text']).
I tried a few different methods to make it work but it didn't, so I'm asking here for help.

Thanks in advance.

答:
line from file.read() reads a single char. You want to use file.readlines() and iterate over that.
I don't know why you are trying to use line as a dictionary line['text'].
This is what throws the error, since you cant access the text key.

Body:
I'm trying to make a Word Cloud out of a txt file with this code:

import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from wordcloud import WordCloud, STOPWORDS
from IPython.display import Image as im

file = open("T.txt", encoding='utf-8')
FR = file.read()

raw_file = []

for line in FR:
    raw_file.append(line['text'])

words = raw_file.split(" ")
words = [w for w in words if len(w) > 2]
words = [w.lower() for w in words]
words = [w for w in words if w not in STOPWORDS]

word_list = (words)
word_counter = {}
for word in word_list:
     if word in word_counter:
         word_counter[word] += 1
     else:
         word_counter[word] = 1

popular_words = sorted(word_counter, key = word_counter.get, reverse = True)

topp = popular_words

topp.remove('https')

mask = np.array(Image.open('/Users/x/Downloads/B.png'))

wc = WordCloud(background_color="black", max_words=2000, mask=mask)
clean_string = ','.join(topp)
wc.generate(clean_string)

plt.imshow(wc, interpolation='bilinear')
plt.title("Title", size=40)
plt.axis("off")
plt.show()

As in the title, it gives me Error: string indices must be integers on raw_file.append(line['text']).
I tried a few different methods to make it work but it didn't, so I'm asking here for help.

Thanks in advance.


问:
How to remove spaces only before the First letter
How to remove spaces only before the First letter and do not change to other words / text in line.

答:
Ctrl+H

Find what: ^\h+

Replace with: LEAVE EMPTY

CHECK Wrap around

CHECK Regular expression

Replace all

Explanation:

```<code>^           # beginning of line
  \h+       # 1 or more horizontal spaces
</code>```

Body:
Ctrl+H

Find what: ^\h+

Replace with: LEAVE EMPTY

CHECK Wrap around

CHECK Regular expression

Replace all

Explanation:

^           # beginning of line
  \h+       # 1 or more horizontal spaces


问:
Python function import not working in Django using Spyder
My Django project has the following folder structure where controllers is where I keep all custom .py files:

```<code>C:.
│   db.sqlite3
│   manage.py
│
├───myApp
│   │   admin.py
│   │   apps.py
│   │   forms.py
│   │   models.py
│   │   tests.py
│   │   urls.py
│   │   views.py
│   │   widgets.py
│   │   __init__.py
│   │
│   ├───controllers
│   │   │   helpers.py
│   │   │   function.py
│   │   │   __init__.py
│   │   │
</code>```

Inside controllers/function.py I want to import the file helpers.py.

Scenario 1: If I type from .helpers import foo and run this in Django, then I am able to import helpers.py, but if I run this same import in Spyder then I get: ImportError: attempted relative import with no known parent package

Scenario 2: If I type from helpers import foo (without the "dot") and run this in Django, then I get: ModuleNotFoundError: No module named 'helpers' but it works in Spyder!

What am I missing here with the paths (or relative paths). I need to be able to have one python script that works in Django and Spyder without having to remove the . everywhere.

答:
A Try Except clause should do it:</p>

```<code>try:
    from .helpers import foo
except ImportError:
    from helpers import foo
</code>```

Body:
My Django project has the following folder structure where controllers is where I keep all custom .py files:

C:.
│   db.sqlite3
│   manage.py
│
├───myApp
│   │   admin.py
│   │   apps.py
│   │   forms.py
│   │   models.py
│   │   tests.py
│   │   urls.py
│   │   views.py
│   │   widgets.py
│   │   __init__.py
│   │
│   ├───controllers
│   │   │   helpers.py
│   │   │   function.py
│   │   │   __init__.py
│   │   │

Inside controllers/function.py I want to import the file helpers.py.

Scenario 1: If I type from .helpers import foo and run this in Django, then I am able to import helpers.py, but if I run this same import in Spyder then I get: ImportError: attempted relative import with no known parent package

Scenario 2: If I type from helpers import foo (without the "dot") and run this in Django, then I get: ModuleNotFoundError: No module named 'helpers' but it works in Spyder!

What am I missing here with the paths (or relative paths). I need to be able to have one python script that works in Django and Spyder without having to remove the . everywhere.

Body:
A Try Except clause should do it:

try:
    from .helpers import foo
except ImportError:
    from helpers import foo


问:
What does whitelisted mean for WRITE_EXTERNAL_STORAGE?
The docs for WRITE_EXTERNAL_STORAGE permission say:

If this permission is not whitelisted for an app that targets an API
  level before Build.VERSION_CODES.Q this permission cannot be granted
  to apps.

What does that mean and how can a permission be "whitelisted"?

答:
In the context to which you are speaking, some apps that target certain permissions get "grandfathered".
Per the permission docs:

Over time, new restrictions may be added to the platform such that, in order to use certain APIs, your app must request a permission that it previously did not need. Because existing apps assume access to those APIs is freely available, Android may apply the new permission request to the app's manifest to avoid breaking the app on the new platform version (thereby, "grandfathering" your app for the permission). Android makes the decision as to whether an app might need the permission based on the value provided for the targetSdkVersion attribute. If the value is lower than the version in which the permission was added, then Android adds the permission.

For example, the READ_EXTERNAL_STORAGE permission is enforced beginning with API level 19 to restrict access to the shared storage space. If your targetSdkVersion is 18 or lower, this permission is added to your app on newer versions of Android.