问:
How can I print this query result on my show.blade.php?
How can I print the result of this query on my show.blade.php? This is what I did on my Controller:

```<code>public function getRating(Request $request){
            $results = DB::select('SELECT AVG(stars) FROM reviews WHERE stars>1', [1])->get();
        }
</code>```

And this is what I tried on my show.blade.php

```<code><li class="nav-item">
     <form action="{{ action('CatalogController@getRating')}}" method="GET">
       <div>
         {{$results}}
       </div>
     </form>
</li>
</code>```

I'm still learning and I looked for this before making this question but I don't know if I couldn't find it or if I wasn't searching for the right thing, thanks.

答:
try this

in your controller

```<code>public function getRating()
{
    $results = DB::select('SELECT AVG(stars) FROM reviews WHERE stars>1', [1])->get();

    return view('show', ['results' => $results]);
}
</code>```

you should pass variable to view
see this link

Body:
How can I print the result of this query on my show.blade.php? This is what I did on my Controller:

public function getRating(Request $request){
            $results = DB::select('SELECT AVG(stars) FROM reviews WHERE stars>1', [1])->get();
        }

And this is what I tried on my show.blade.php

     <form action="{{ action('CatalogController@getRating')}}" method="GET">

         {{$results}}

     </form>

I'm still learning and I looked for this before making this question but I don't know if I couldn't find it or if I wasn't searching for the right thing, thanks.

Body:
try this

in your controller

public function getRating()
{
    $results = DB::select('SELECT AVG(stars) FROM reviews WHERE stars>1', [1])->get();

    return view('show', ['results' => $results]);
}

you should pass variable to view
see this link


来源: stackexchange

问:
React TypeError: teams.map is not a function
I getting the TypeError: teams.map is not a function while trying to fetch and paint elements from an api. I haven't been able to find the error.

I'm trying to build a simple app with premier league teams and details about them. I'm still writing because stack overflow won't let me publish my question

leagueTeams Component

import React, { useState } from 'react';

function LeagueTeams() {
  const url = 'https://www.thesportsdb.com/api/v1/json/1/search_all_teams.php?l=English%20Premier%20League'

  const [teams, setTeams] = useState(null)

  fetch(url)
    .then(res => res.json())
    .then(data => setTeams(data))

  return (

    {teams && teams.map((team, index)=>(

{team.strTeam}

)

    )}

  )
}

export default LeagueTeams```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script></code>```

App.js

import React from 'react';
import './App.css';
import LeagueTeams from './components/leagueTeams'

function App() {

return(
  <>

Premier League Teams!

  <LeagueTeams />
  </>
)
  }

export default App;```

答:
as teams is going to be array, write state as

```<code>const [teams, setTeams] = useState([])
</code>```

and write fetch() function in useEffect like this

```<code>    useEffect(()=>{
 fetch(url)
    .then(res => res.json())
    .then(data => setTeams(data))
},[])
</code>```

this will fetch data when components mounts .

and in map function write it as

```<code>{teams.length && teams.map((team, index)
</code>```

hope it works

ContentLicense: CC BY-SA 4.0

Body:
I getting the TypeError: teams.map is not a function while trying to fetch and paint elements from an api. I haven't been able to find the error.

I'm trying to build a simple app with premier league teams and details about them. I'm still writing because stack overflow won't let me publish my question

leagueTeams Component

import React, { useState } from 'react';

function LeagueTeams() {
  const url = 'https://www.thesportsdb.com/api/v1/json/1/search_all_teams.php?l=English%20Premier%20League'

  const [teams, setTeams] = useState(null)

  fetch(url)
    .then(res => res.json())
    .then(data => setTeams(data))

  return (

    {teams && teams.map((team, index)=>(

{team.strTeam}

)

    )}

  )
}

export default LeagueTeams

App.js

import React from 'react';
import './App.css';
import LeagueTeams from './components/leagueTeams'

function App() {

return(
  <>

Premier League Teams!

  <LeagueTeams />
  </>
)
  }

export default App;

Body:
as teams is going to be array, write state as

const [teams, setTeams] = useState([])

and write fetch() function in useEffect like this

    useEffect(()=>{
 fetch(url)
    .then(res => res.json())
    .then(data => setTeams(data))
},[])

this will fetch data when components mounts .

and in map function write it as

{teams.length && teams.map((team, index)

hope it works


问:
conv2d(): argument 'input' (position 1) must be Tensor, not str in loop function
I am trying to write a loop function to extract features from my data and save it in the list.

And here is my code:

```<code>import pickle

output_features = []

with torch.no_grad():
    for (inputs, labels) in dataloaders.items():
        x=feature_extractor(inputs)
        output_features.append(x)
        output_features = torch.cat(output_features).numpy

pickle.dump(output_features, open("features.pkl", "w"))
</code>```

But i have an error.

```<code>conv2d(): argument 'input' (position 1) must be Tensor, not str
</code>```

Then I changed again it to

```<code>with torch.no_grad():
    for i, (inputs, labels) in enumerate(dataloaders['val']):
        x=feature_extractor(inputs)
        output_features.append(x)
        output_features = torch.cat(output_features).numpy

pickle.dump(output_features, open("features.pkl", "wb"))

</code>```

Then I got this error

```<code>'builtin_function_or_method' object has no attribute 'append'
</code>```

Please, someone, explain to me why I got this error and how to get features from each input with its label and save them in an array. Thank you

答:
For the first issue, it really depends on how the data is saved into the dataloader. But according to convention, I'm guessing it holds tuples of (input tensor, label), which can simply be accessed by for (inputs, labels) in dataloader:. The enumeration isn't compulsory, unless you would like to keep count of each iteration.

As for the second error, this is because you accidentally wrote output_features = torch.cat(output_features).numpy, which calls a built-in method, instead of applying it to the output tensor. You can correct this to output_features = torch.cat(output_features).numpy() and you should be able to get the output features fine!

Body:
I am trying to write a loop function to extract features from my data and save it in the list.

And here is my code:

import pickle

output_features = []

with torch.no_grad():
    for (inputs, labels) in dataloaders.items():
        x=feature_extractor(inputs)
        output_features.append(x)
        output_features = torch.cat(output_features).numpy

pickle.dump(output_features, open("features.pkl", "w"))

But i have an error.

conv2d(): argument 'input' (position 1) must be Tensor, not str

Then I changed again it to

with torch.no_grad():
    for i, (inputs, labels) in enumerate(dataloaders['val']):
        x=feature_extractor(inputs)
        output_features.append(x)
        output_features = torch.cat(output_features).numpy

pickle.dump(output_features, open("features.pkl", "wb"))

Then I got this error

'builtin_function_or_method' object has no attribute 'append'

Please, someone, explain to me why I got this error and how to get features from each input with its label and save them in an array. Thank you


问:
JDBC is refusing to use a specified password
I'm getting an SQLInvalidAuthorizationSpecException with "Access denied for user 'someuser'@'localhost' (using password: NO)"

```<code>mysql = DriverManager.getConnection(
    "jdbc:mysql://localhost:3306/somedb/",
    "someuser",
    "somepassword"
);
</code>```

As you can see, the password is indeed specified and yet the driver thinks it shouldn't use it. What am I doing wrong? I'm 100% sure the credentials are correct.

I've also tried specifying everything in the connection string like so:

```<code>mysql = DriverManager.getConnection("jdbc:mysql://localhost:3306/somedb?user=someuser&password=somepassword");
</code>```

to no avail.

MySQL Community version 8.0.17

mysql-connector-java version 8.0.19

答: Run this in your MySQL workbench (or command line) : ALTER USER 'someuser'@'localhost' IDENTIFIED WITH mysql_native_password BY 'somepassword'

Body:
I'm getting an SQLInvalidAuthorizationSpecException with "Access denied for user 'someuser'@'localhost' (using password: NO)"

mysql = DriverManager.getConnection(
    "jdbc:mysql://localhost:3306/somedb/",
    "someuser",
    "somepassword"
);

As you can see, the password is indeed specified and yet the driver thinks it shouldn't use it. What am I doing wrong? I'm 100% sure the credentials are correct.

I've also tried specifying everything in the connection string like so:

mysql = DriverManager.getConnection("jdbc:mysql://localhost:3306/somedb?user=someuser&password=somepassword");

to no avail.

MySQL Community version 8.0.17

mysql-connector-java version 8.0.19


问:
Stop the audio from playing in pydub
Is there something like terminate or stop feature in pydub such that the stream after started by play() can be stopped abruptly while it is still playing instead of the audio being played to it's full length and then stopping.</p>

答:
As far as I've seen, and I am using the whole sound processing for the first time, you could use pyaudio to play a wav-file as a stream. pyaudio is not pydub. :)

First, convert your anydata-file to a wav-file with pydub/ffmpeg, see below, and then use pyaudio to play it as a stream with logic between.

Because, when I play an MP3 with pydub, it waits some seconds and then states that the file has been converted to wav in a /tmp-folder. So, why not convert it just once and save it to your own location? It lasts some seconds both ways, anyway, but the latter converting has just to be done once (assuming you have tons of Gigabytes :) ), and then you can just check if the file already exists.

-> converting

Python convert mp3 to wav with Pydub

-> playing and recording sound with python -> pyaudio (comprehensive guide)

https://realpython.com/playing-and-recording-sound-python/#pyaudio

As you see in the code, you could put your own logic into the while loop where the stream is played.

I will try to use that combination in a project I make. Hope it works. :)

ContentLicense: CC BY-SA 3.0

Title: Stop the audio from playing in pydub


问:
An assembly specified in the application dependencies manifest (MyApp.deps.json) was not found:
My project is built in Azure Pipelines using SDK 3.1.101, without any errors/warnings, but after deployment to the host (Ubuntu 18.04), I'm getting error:

```<code>Error:
    An assembly specified in the application dependencies manifest (MyApp.deps.json) was not found:
        package: 'Microsoft.Data.SqlClient', version: '1.0.19269.1'
        path: 'runtimes/unix/lib/netcoreapp2.1/Microsoft.Data.SqlClient.dll'
</code>```

Little bit of investigation pointed me that problem comes from Microsoft.EntityFrameworkCore.SqlServer which references Microsoft.Data.SqlClient.

Looks like it tries to find library from v2.1, somehow strange to me - but it's LST, so maybe...

Initially on the hosting had only aspnetcore-runtime-3.1, so, I thought that by installing v2.1 may fix the problem, and installed aspnetcore-runtime-2.1, then SDKs for both versions but nothing helped so far :(

Any thoughts how to fix it?

答:
I fixed it by changing

```<code><PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.1" PrivateAssets="All" />
</code>```

into

```<code><PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.1" />
</code>```

Body:
My project is built in Azure Pipelines using SDK 3.1.101, without any errors/warnings, but after deployment to the host (Ubuntu 18.04), I'm getting error:

Error:
    An assembly specified in the application dependencies manifest (MyApp.deps.json) was not found:
        package: 'Microsoft.Data.SqlClient', version: '1.0.19269.1'
        path: 'runtimes/unix/lib/netcoreapp2.1/Microsoft.Data.SqlClient.dll'

Little bit of investigation pointed me that problem comes from Microsoft.EntityFrameworkCore.SqlServer which references Microsoft.Data.SqlClient.

Looks like it tries to find library from v2.1, somehow strange to me - but it's LST, so maybe...

Initially on the hosting had only aspnetcore-runtime-3.1, so, I thought that by installing v2.1 may fix the problem, and installed aspnetcore-runtime-2.1, then SDKs for both versions but nothing helped so far :(

Any thoughts how to fix it?

Body:
I fixed it by changing

<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.1" PrivateAssets="All" />

into

<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.1" />


问:
onPrimaryClipchanged() called multiple times in Android
I have implemented Background Service to listen to clipboard events system wide..

Service Implementation:

```<code>public class ClipService extends Service {
ClipboardManager cm;

@Override
public void onCreate() {
    Log.d("FRAG","onCreate called...");
    super.onCreate();
    cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
    cm.addPrimaryClipChangedListener(new ClipboardListener());
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onDestroy() {
    super.onDestroy();
    cm.removePrimaryClipChangedListener(new ClipboardListener());
}

class ClipboardListener implements ClipboardManager.OnPrimaryClipChangedListener{

     @Override
     public void onPrimaryClipChanged() {
        Log.d("FRAG","onPrimaryClipChanged called..");
        if(cm!=null) {
            String s1 = cm.getPrimaryClip().getItemAt(0).coerceToText(ClipService.this).toString();
            ContentValues cv = new ContentValues();
            cv.put(DatabaseHelper.CONTENT,s1);
            getContentResolver().insert(DataProvider.CONTENT_URI, cv);//Insert using Content provider
        }
     }
}
}
</code>```

Now my concern is that for every text copied to clipboard three entries are getting inserted for single copy event...i.e. onPrimaryClipChanged is getting called three times..

i am using `Log.d("FRAG","onPrimaryClipChanged called.."); and it is getting logged 3 times so problem seems to be with function being called 3 times for each clipboard change event and not insert part of the code.

What might be the cause of it getting called 3 times?

答:
This is a known issue with WebView/Chrome. I got around it by ignoring the duplicated events within a certain threshold (e.g. 50ms)</p>

```<code>ClipboardManager.OnPrimaryClipChangedListener primaryClipChangedListener = new ClipboardManager.OnPrimaryClipChangedListener() {
    private static final long THRESHOLD_MS = 50;
    private long lastChangedTime = 0;
    private String lastString = "";
    @Override
    public void onPrimaryClipChanged() {
        try {
            String str = clipMan.getText().toString();

            // Copying text from certain places will trigger multiple events (e.g. Chrome/WebView generates 3 events)
            // Ignore the duplicated events
            if (System.currentTimeMillis() - lastChangedTime < THRESHOLD_MS && Objects.equals(lastString, str)) {
                return;
            }

            lastChangedTime = System.currentTimeMillis();
            lastString = str;

            // Rest of the logic
            ...
        }
    }
}
</code>```

Body:
I have implemented Background Service to listen to clipboard events system wide..

Service Implementation:

public class ClipService extends Service {
ClipboardManager cm;

@Override
public void onCreate() {
    Log.d("FRAG","onCreate called...");
    super.onCreate();
    cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
    cm.addPrimaryClipChangedListener(new ClipboardListener());
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onDestroy() {
    super.onDestroy();
    cm.removePrimaryClipChangedListener(new ClipboardListener());
}

class ClipboardListener implements ClipboardManager.OnPrimaryClipChangedListener{

     @Override
     public void onPrimaryClipChanged() {
        Log.d("FRAG","onPrimaryClipChanged called..");
        if(cm!=null) {
            String s1 = cm.getPrimaryClip().getItemAt(0).coerceToText(ClipService.this).toString();
            ContentValues cv = new ContentValues();
            cv.put(DatabaseHelper.CONTENT,s1);
            getContentResolver().insert(DataProvider.CONTENT_URI, cv);//Insert using Content provider
        }
     }
}
}

Now my concern is that for every text copied to clipboard three entries are getting inserted for single copy event...i.e. onPrimaryClipChanged is getting called three times..

i am using `Log.d("FRAG","onPrimaryClipChanged called.."); and it is getting logged 3 times so problem seems to be with function being called 3 times for each clipboard change event and not insert part of the code.

What might be the cause of it getting called 3 times?

Body:
This is a known issue with WebView/Chrome. I got around it by ignoring the duplicated events within a certain threshold (e.g. 50ms)

ClipboardManager.OnPrimaryClipChangedListener primaryClipChangedListener = new ClipboardManager.OnPrimaryClipChangedListener() {
    private static final long THRESHOLD_MS = 50;
    private long lastChangedTime = 0;
    private String lastString = "";
    @Override
    public void onPrimaryClipChanged() {
        try {
            String str = clipMan.getText().toString();

            // Copying text from certain places will trigger multiple events (e.g. Chrome/WebView generates 3 events)
            // Ignore the duplicated events
            if (System.currentTimeMillis() - lastChangedTime < THRESHOLD_MS && Objects.equals(lastString, str)) {
                return;
            }

            lastChangedTime = System.currentTimeMillis();
            lastString = str;

            // Rest of the logic
            ...
        }
    }
}


问:
read 2-D binary data in Python and write in NetCDF format
I have binary data with following header information:

```<code>DSET ../prcp/cmorph_test
OPTIONS template little_endian
UNDEF  -999.0
TITLE  Precipitation estimates
XDEF 1440 LINEAR    0.125  0.25
YDEF  480 LINEAR  -59.875  0.25
ZDEF   01 LEVELS 1
TDEF 999999 LINEAR  00z01jan2014  3hr
VARS 1
cmorph   1   99 RAW CMORPH integrated satellite precipitation estimates [mm/3hr]
ENDVARS
</code>```

Please suggest if it is possible to read (and any sample code snippet would be really helpful) and convert it into NetCDF using Python?

答:
The Nasa guys don't seem to respond any emails.

It downloads the data and plots it to compare what can be found in
ftp://ftp.cpc.ncep.noaa.gov/precip/global_CMORPH/3-hourly_025deg/cmorph-precip_3hrly-025deg.gif

```<code>import numpy as np
import os
import datetime
import bz2
import urllib.request as request
from contextlib import closing
import shutil
import matplotlib.pyplot as plt

def get_closest_file_index(hour=None, dataHours=np.array([0,3,6,9,12,15,18,21,24])):
    """
    hour is in decimal format: that is 7:40 am is 7.66666
    assuming here we have 8 data files/ 24h == 0,3,6,9,12,15,18,21
    (24 is with to get datapoints from the next 24h period)
    """
    return (np.argmin(np.abs(float(hour)-dataHours)))

def cmorph_download(year=None, month=None, day=None, hour=None,
                    urlStart='ftp://ftp.cpc.ncep.noaa.gov/precip/CMORPH_V1.0/CRT/0.25deg-3HLY/',
                    ext='.bz2'):
    """
    Returns rain-rate in single grid, first dimension is lat, second lon
    first data is from data[lat=-59.875, lon=0.125] , step is 0.25

    download cmorph water data from
    ftp://ftp.cpc.ncep.noaa.gov/precip/CMORPH_V1.0/CRT/0.25deg-3HLY/

    data is real*4 little endian binary

    ftp://ftp.cpc.ncep.noaa.gov/precip/CMORPH_V1.0/CTL/CMORPH_V1.0_CRT_0.25deg-3HLY.ctl
    There it says:
    OPTIONS template little_endian
    UNDEF  -999.0
    TITLE  Precipitation estimates
    XDEF 1440 LINEAR    0.125  step 0.25 last is 359.875
    YDEF  480 LINEAR   59.875  step 0.25 last is -59.875
    ZDEF   01 LEVELS 1

    motivation:

    The CMORPH technique provides a passive
    microwave (PMW) rain-rate dataset that is derived from
    low-Earth-orbit microwave satellite observations, and
    these observations are translated via spatial propagation
    information obtained from geostationary IR1 data.
    """
    fileNumber = get_closest_file_index(hour=hour)
    if fileNumber == 8:
        # data is from the next day...
        # so we take it next day at 0am
        fileNumber = 0
        minute = round((float(hour) - int(hour)) * 60.)
        dataDate = datetime.datetime(int(year), int(month), int(day), int(hour), int(minute))
        year = dataDate.year
        month = dataDate.month
        day = dataDate.day
    print("fileNumber:", fileNumber)
    file = 'CMORPH_V1.0_ADJ_0.25deg-3HLY_' \
           + str(year) + str(month).rjust(2,'0') + str(day).rjust(2,'0') \
           + ext

    ftppath = urlStart \
              + '/' + str(year) \
              + '/' + str(year) + str(month).rjust(2,'0') \
              + '/' + file

    fileName = file
    if not os.path.exists(fileName):
        with closing(request.urlopen(ftppath)) as r:
            print(f"Downloading... {ftppath}")
            with open(fileName, 'wb') as f:
                shutil.copyfileobj(r, f)
    else:
        print("using old file:", fileName)

    with bz2.open(fileName, "rb") as f:
        # Decompress data from file
        data = f.read()
    data = np.fromstring(data, dtype='<f4')
    data = np.reshape(data, (8, (120 * 4), (360 * 4)))
    data = data[fileNumber, ...]
    data = np.squeeze(data)

    return data

data = cmorph_download(year=2012, month=3, day=19, hour=3)
# to compare with
# ftp://ftp.cpc.ncep.noaa.gov/precip/global_CMORPH/3-hourly_025deg/cmorph-precip_3hrly-025deg.gif
plt.contour(data)
plt.show()

</code>```

Body:
I have binary data with following header information:

DSET ../prcp/cmorph_test
OPTIONS template little_endian
UNDEF  -999.0
TITLE  Precipitation estimates
XDEF 1440 LINEAR    0.125  0.25
YDEF  480 LINEAR  -59.875  0.25
ZDEF   01 LEVELS 1
TDEF 999999 LINEAR  00z01jan2014  3hr
VARS 1
cmorph   1   99 RAW CMORPH integrated satellite precipitation estimates [mm/3hr]
ENDVARS

Please suggest if it is possible to read (and any sample code snippet would be really helpful) and convert it into NetCDF using Python?

Body:
The Nasa guys don't seem to respond any emails.

It downloads the data and plots it to compare what can be found in
ftp://ftp.cpc.ncep.noaa.gov/precip/global_CMORPH/3-hourly_025deg/cmorph-precip_3hrly-025deg.gif

import numpy as np
import os
import datetime
import bz2
import urllib.request as request
from contextlib import closing
import shutil
import matplotlib.pyplot as plt

def get_closest_file_index(hour=None, dataHours=np.array([0,3,6,9,12,15,18,21,24])):
    """
    hour is in decimal format: that is 7:40 am is 7.66666
    assuming here we have 8 data files/ 24h == 0,3,6,9,12,15,18,21
    (24 is with to get datapoints from the next 24h period)
    """
    return (np.argmin(np.abs(float(hour)-dataHours)))

def cmorph_download(year=None, month=None, day=None, hour=None,
                    urlStart='ftp://ftp.cpc.ncep.noaa.gov/precip/CMORPH_V1.0/CRT/0.25deg-3HLY/',
                    ext='.bz2'):
    """
    Returns rain-rate in single grid, first dimension is lat, second lon
    first data is from data[lat=-59.875, lon=0.125] , step is 0.25

    download cmorph water data from
    ftp://ftp.cpc.ncep.noaa.gov/precip/CMORPH_V1.0/CRT/0.25deg-3HLY/

    data is real*4 little endian binary

    ftp://ftp.cpc.ncep.noaa.gov/precip/CMORPH_V1.0/CTL/CMORPH_V1.0_CRT_0.25deg-3HLY.ctl
    There it says:
    OPTIONS template little_endian
    UNDEF  -999.0
    TITLE  Precipitation estimates
    XDEF 1440 LINEAR    0.125  step 0.25 last is 359.875
    YDEF  480 LINEAR   59.875  step 0.25 last is -59.875
    ZDEF   01 LEVELS 1

    motivation:

    The CMORPH technique provides a passive
    microwave (PMW) rain-rate dataset that is derived from
    low-Earth-orbit microwave satellite observations, and
    these observations are translated via spatial propagation
    information obtained from geostationary IR1 data.
    """
    fileNumber = get_closest_file_index(hour=hour)
    if fileNumber == 8:
        # data is from the next day...
        # so we take it next day at 0am
        fileNumber = 0
        minute = round((float(hour) - int(hour)) * 60.)
        dataDate = datetime.datetime(int(year), int(month), int(day), int(hour), int(minute))
        year = dataDate.year
        month = dataDate.month
        day = dataDate.day
    print("fileNumber:", fileNumber)
    file = 'CMORPH_V1.0_ADJ_0.25deg-3HLY_' \
           + str(year) + str(month).rjust(2,'0') + str(day).rjust(2,'0') \
           + ext

    ftppath = urlStart \
              + '/' + str(year) \
              + '/' + str(year) + str(month).rjust(2,'0') \
              + '/' + file

    fileName = file
    if not os.path.exists(fileName):
        with closing(request.urlopen(ftppath)) as r:
            print(f"Downloading... {ftppath}")
            with open(fileName, 'wb') as f:
                shutil.copyfileobj(r, f)
    else:
        print("using old file:", fileName)

    with bz2.open(fileName, "rb") as f:
        # Decompress data from file
        data = f.read()
    data = np.fromstring(data, dtype='<f4')
    data = np.reshape(data, (8, (120 * 4), (360 * 4)))
    data = data[fileNumber, ...]
    data = np.squeeze(data)

    return data

data = cmorph_download(year=2012, month=3, day=19, hour=3)
# to compare with
# ftp://ftp.cpc.ncep.noaa.gov/precip/global_CMORPH/3-hourly_025deg/cmorph-precip_3hrly-025deg.gif
plt.contour(data)
plt.show()


问:
Scoping issue occurring when looping through a tryCatch block in R
I'm trying to loop through a vector, evaluate each member in a conditional statement, and record any false evaluations onto an external csv. However, the argument i keeps triggering an error in the code below. Specifically, my output is "1234567891011" and then the error "Error in cat(i) : object 'i' not found" interrupts execution. I suspect that there is some sort of scoping issue, but I'm baffled as to what it could be. A reproducible example is included below. Any help would be greatly appreciated.

```<code>library('utils')

tryBlock <- function(i){
  cat(i)
  if(i>10)
     stop("condition is false")
}

work <- function(list){
  for(i in list){
    tryCatch(tryBlock(i),
             error= function(err){write.table(as.data.frame(c(i,err)), "falseOutput.csv")})
}}

work(1:20)
</code>```

答:
The problem is when trying to write an object of class

```<code>c("simpleError", "error", "condition")
</code>```

to a CSV file. Or even to a text file with write.table. When I tried to use writeLines I forgot that there is no append argument so only the last error, with i == 20, would be written.

The solution I found is to output to file with cat.

Note that err is coerced to "character".

```<code>work <- function(list){
  for(i in list){
    tryCatch(tryBlock(i),
             error = function(err){
               msg <- paste("iter:", i, "\n")
               msg <- c(msg, paste("error:", as.character(err), "\n"))
               cat(msg, file = "falseOutput.txt", append = TRUE)
             }
    )
  }
}

work(1:20)
#1234567891011121314151617181920
</code>```

The first lines of the file are:

iter: 11

  error: Error in tryBlock(i): condition is false

iter: 12

  error: Error in tryBlock(i): condition is false

iter: 13

  error: Error in tryBlock(i): condition is false

Body:
I'm trying to loop through a vector, evaluate each member in a conditional statement, and record any false evaluations onto an external csv. However, the argument i keeps triggering an error in the code below. Specifically, my output is "1234567891011" and then the error "Error in cat(i) : object 'i' not found" interrupts execution. I suspect that there is some sort of scoping issue, but I'm baffled as to what it could be. A reproducible example is included below. Any help would be greatly appreciated.

library('utils')

tryBlock <- function(i){
  cat(i)
  if(i>10)
     stop("condition is false")
}

work <- function(list){
  for(i in list){
    tryCatch(tryBlock(i),
             error= function(err){write.table(as.data.frame(c(i,err)), "falseOutput.csv")})
}}

work(1:20)

Body:
The problem is when trying to write an object of class

c("simpleError", "error", "condition")

to a CSV file. Or even to a text file with write.table. When I tried to use writeLines I forgot that there is no append argument so only the last error, with i == 20, would be written.

The solution I found is to output to file with cat.

Note that err is coerced to "character".

work <- function(list){
  for(i in list){
    tryCatch(tryBlock(i),
             error = function(err){
               msg <- paste("iter:", i, "\n")
               msg <- c(msg, paste("error:", as.character(err), "\n"))
               cat(msg, file = "falseOutput.txt", append = TRUE)
             }
    )
  }
}

work(1:20)
#1234567891011121314151617181920

The first lines of the file are:

iter: 11

  error: Error in tryBlock(i): condition is false

iter: 12

  error: Error in tryBlock(i): condition is false

iter: 13

  error: Error in tryBlock(i): condition is false


问:
pywintypes.error: (50, 'GetFileSecurity', 'The request is not supported.') while using Jupyter Notebook on network drive
I am currently trying to use a combination of miniconda + jupyter (installed with pip) on a network drive and I get the following error:

pywintypes.error: (50, 'GetFileSecurity', 'The request is not supported.')

I am currently working in a corporate set-up, so we are working with some limitations regarding access rights. Unfortunately, I can only try jupyter on network drives, changes to the local hard drive requires admin rights which I don't have.

The full error output:

```<code>Traceback (most recent call last):
 File "c:\programs\miniconda3_64\lib\site-packages\tornado\web.py", line 1699, in _execute
   result = await result
 File "c:\programs\miniconda3_64\lib\site-packages\tornado\gen.py", line 742, in run
   yielded = self.gen.throw(*exc_info)  # type: ignore
 File "c:\programs\miniconda3_64\lib\site-packages\notebook\services\sessions\handlers.py", line 72, in post
   type=mtype))
 File "c:\programs\miniconda3_64\lib\site-packages\tornado\gen.py", line 735, in run
   value = future.result()
 File "c:\programs\miniconda3_64\lib\site-packages\tornado\gen.py", line 742, in run
   yielded = self.gen.throw(*exc_info)  # type: ignore
 File "c:\programs\miniconda3_64\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 88, in create_session
   kernel_id = yield self.start_kernel_for_session(session_id, path, name, type, kernel_name)
 File "c:\programs\miniconda3_64\lib\site-packages\tornado\gen.py", line 735, in run
   value = future.result()
 File "c:\programs\miniconda3_64\lib\site-packages\tornado\gen.py", line 742, in run
   yielded = self.gen.throw(*exc_info)  # type: ignore
 File "c:\programs\miniconda3_64\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 101, in start_kernel_for_session
   self.kernel_manager.start_kernel(path=kernel_path, kernel_name=kernel_name)
 File "c:\programs\miniconda3_64\lib\site-packages\tornado\gen.py", line 735, in run
   value = future.result()
 File "c:\programs\miniconda3_64\lib\site-packages\tornado\gen.py", line 209, in wrapper
   yielded = next(result)
 File "c:\programs\miniconda3_64\lib\site-packages\notebook\services\kernels\kernelmanager.py", line 168, in start_kernel
   super(MappingKernelManager, self).start_kernel(**kwargs)
 File "c:\programs\miniconda3_64\lib\site-packages\jupyter_client\multikernelmanager.py", line 110, in start_kernel
   km.start_kernel(**kwargs)
 File "c:\programs\miniconda3_64\lib\site-packages\jupyter_client\manager.py", line 240, in start_kernel
   self.write_connection_file()
 File "c:\programs\miniconda3_64\lib\site-packages\jupyter_client\connect.py", line 547, in write_connection_file
   kernel_name=self.kernel_name
 File "c:\programs\miniconda3_64\lib\site-packages\jupyter_client\connect.py", line 212, in write_connection_file
   with secure_write(fname) as f:
 File "c:\programs\miniconda3_64\lib\contextlib.py", line 82, in __enter__
   return next(self.gen)
 File "c:\programs\miniconda3_64\lib\site-packages\jupyter_client\connect.py", line 100, in secure_write
   win32_restrict_file_to_user(fname)
 File "c:\programs\miniconda3_64\lib\site-packages\jupyter_client\connect.py", line 61, in win32_restrict_file_to_user
   sd = win32security.GetFileSecurity(fname, win32security.DACL_SECURITY_INFORMATION)
ywintypes.error: (50, 'GetFileSecurity', 'The request is not supported.')
</code>```

Any ideas or experience with this type of error?

答:
The problem you have may be due to access rights for the browser as well as for jupyter lab to run as I have painfully just found.

My original answer can be found here: https://github.com/jupyter/jupyter_client/issues/481

But here is my story for others who want to continue to use the latest Jupyter lab/Notebook version:

(I run Anconda which comes pre installed with Jupyter):

1- When checking the environment paths by using this command: jupyter --paths I get two roaming locations one for runtime and one for data! This is because I use a corporate laptop and Windows is setup to store user data files in a roaming location on the network!

```<code>(base) C:\>jupyter --paths
config:
    C:\Users\user_x\.jupyter
    C:\ProgramData\Anaconda3\etc\jupyter
    C:\ProgramData\jupyter
data:
    \\A-FILEDATA-P\Profile\use_x\AppData\Roaming\jupyter
    C:\ProgramData\Anaconda3\share\jupyter
    C:\ProgramData\jupyter
runtime:
    \\A-FILEDATA-P\Profile\use_x\AppData\Roaming\jupyter\runtime

(base) C:\>
</code>```

2- So, I tried modifying C:\Users\user_xxx.jupyter\jupyter_notebook_config.py by adding
JUPYTER_RUNTIME_DIR = 'C:\Users\user_x\AppData\Roaming\jupyter\runtime'
but it did not work!

2- However, Big note here: I noticed that jupyter lab command fire a "stand alone" Chrome I have on a removable usb harddisk! which under the corporate Windows setup does not have any rights to write to other folder location on the laptop, thus the security error!

3- The solution was to setup two folders on my usb disk, where stand alone Chrome is found and set the environment variables to point to those locations like this:

```<code>set JUPYTER_RUNTIME_DIR=D:\jupyter\runtime
set JUPYTER_DATA_DIR=D:\jupyter
</code>```

4- The only catch is that you have to do these two commands at the start of every new session as they don't persist say when you restart Jupyter lab! and as @Shongololo  pointed out you can only run other programs like Spyder from the command line only for it to read the correct settings!

It remains to be found out how this could be resolved permanently.

Body:
I am currently trying to use a combination of miniconda + jupyter (installed with pip) on a network drive and I get the following error:

pywintypes.error: (50, 'GetFileSecurity', 'The request is not supported.')

I am currently working in a corporate set-up, so we are working with some limitations regarding access rights. Unfortunately, I can only try jupyter on network drives, changes to the local hard drive requires admin rights which I don't have.

The full error output:

Traceback (most recent call last):
 File "c:\programs\miniconda3_64\lib\site-packages\tornado\web.py", line 1699, in _execute
   result = await result
 File "c:\programs\miniconda3_64\lib\site-packages\tornado\gen.py", line 742, in run
   yielded = self.gen.throw(*exc_info)  # type: ignore
 File "c:\programs\miniconda3_64\lib\site-packages\notebook\services\sessions\handlers.py", line 72, in post
   type=mtype))
 File "c:\programs\miniconda3_64\lib\site-packages\tornado\gen.py", line 735, in run
   value = future.result()
 File "c:\programs\miniconda3_64\lib\site-packages\tornado\gen.py", line 742, in run
   yielded = self.gen.throw(*exc_info)  # type: ignore
 File "c:\programs\miniconda3_64\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 88, in create_session
   kernel_id = yield self.start_kernel_for_session(session_id, path, name, type, kernel_name)
 File "c:\programs\miniconda3_64\lib\site-packages\tornado\gen.py", line 735, in run
   value = future.result()
 File "c:\programs\miniconda3_64\lib\site-packages\tornado\gen.py", line 742, in run
   yielded = self.gen.throw(*exc_info)  # type: ignore
 File "c:\programs\miniconda3_64\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 101, in start_kernel_for_session
   self.kernel_manager.start_kernel(path=kernel_path, kernel_name=kernel_name)
 File "c:\programs\miniconda3_64\lib\site-packages\tornado\gen.py", line 735, in run
   value = future.result()
 File "c:\programs\miniconda3_64\lib\site-packages\tornado\gen.py", line 209, in wrapper
   yielded = next(result)
 File "c:\programs\miniconda3_64\lib\site-packages\notebook\services\kernels\kernelmanager.py", line 168, in start_kernel
   super(MappingKernelManager, self).start_kernel(**kwargs)
 File "c:\programs\miniconda3_64\lib\site-packages\jupyter_client\multikernelmanager.py", line 110, in start_kernel
   km.start_kernel(**kwargs)
 File "c:\programs\miniconda3_64\lib\site-packages\jupyter_client\manager.py", line 240, in start_kernel
   self.write_connection_file()
 File "c:\programs\miniconda3_64\lib\site-packages\jupyter_client\connect.py", line 547, in write_connection_file
   kernel_name=self.kernel_name
 File "c:\programs\miniconda3_64\lib\site-packages\jupyter_client\connect.py", line 212, in write_connection_file
   with secure_write(fname) as f:
 File "c:\programs\miniconda3_64\lib\contextlib.py", line 82, in __enter__
   return next(self.gen)
 File "c:\programs\miniconda3_64\lib\site-packages\jupyter_client\connect.py", line 100, in secure_write
   win32_restrict_file_to_user(fname)
 File "c:\programs\miniconda3_64\lib\site-packages\jupyter_client\connect.py", line 61, in win32_restrict_file_to_user
   sd = win32security.GetFileSecurity(fname, win32security.DACL_SECURITY_INFORMATION)
ywintypes.error: (50, 'GetFileSecurity', 'The request is not supported.')

Any ideas or experience with this type of error?

Body:
The problem you have may be due to access rights for the browser as well as for jupyter lab to run as I have painfully just found.

My original answer can be found here: https://github.com/jupyter/jupyter_client/issues/481

But here is my story for others who want to continue to use the latest Jupyter lab/Notebook version:

(I run Anconda which comes pre installed with Jupyter):

1- When checking the environment paths by using this command: jupyter --paths I get two roaming locations one for runtime and one for data! This is because I use a corporate laptop and Windows is setup to store user data files in a roaming location on the network!

(base) C:\>jupyter --paths
config:
    C:\Users\user_x\.jupyter
    C:\ProgramData\Anaconda3\etc\jupyter
    C:\ProgramData\jupyter
data:
    \\A-FILEDATA-P\Profile\use_x\AppData\Roaming\jupyter
    C:\ProgramData\Anaconda3\share\jupyter
    C:\ProgramData\jupyter
runtime:
    \\A-FILEDATA-P\Profile\use_x\AppData\Roaming\jupyter\runtime

(base) C:\>

2- So, I tried modifying C:\Users\user_xxx.jupyter\jupyter_notebook_config.py by adding
JUPYTER_RUNTIME_DIR = 'C:\Users\user_x\AppData\Roaming\jupyter\runtime'
but it did not work!

2- However, Big note here: I noticed that jupyter lab command fire a "stand alone" Chrome I have on a removable usb harddisk! which under the corporate Windows setup does not have any rights to write to other folder location on the laptop, thus the security error!

3- The solution was to setup two folders on my usb disk, where stand alone Chrome is found and set the environment variables to point to those locations like this:

set JUPYTER_RUNTIME_DIR=D:\jupyter\runtime
set JUPYTER_DATA_DIR=D:\jupyter

4- The only catch is that you have to do these two commands at the start of every new session as they don't persist say when you restart Jupyter lab! and as @Shongololo  pointed out you can only run other programs like Spyder from the command line only for it to read the correct settings!

It remains to be found out how this could be resolved permanently.


问:
C# DataTable ItemArray returns '{}' - how can I test for null value?
I have a DataTable resultSet; - I'm trying to check fields for null, but get an '{}' (empty-set ?) object back. Searches involving "{}" aren't yielding any appropriate solutions.

This is the code that isn't working as expected when the "fk_id" field is null:

```<code>if (resultSet.Rows[0].ItemArray[resultSet.Columns.IndexOf("fk_id")] == null)
{
   //never reaches here
}
</code>```

Note: using an int index instead of the Columns.IndexOf() isn't the issue.

Also does the "{}" have some other name in C#?

答:
```<code>try
{
    if (DT.Rows[0][0] != null)
    {
      //your code
    }
}
catch
{
    MessageBox.Show("AUTHANICATION FAILED.");
}
</code>```

OwnerDisplayName: Nick Josevski

ContentLicense: CC BY-SA 2.5

Body:
I have a DataTable resultSet; - I'm trying to check fields for null, but get an '{}' (empty-set ?) object back. Searches involving "{}" aren't yielding any appropriate solutions.

This is the code that isn't working as expected when the "fk_id" field is null:

if (resultSet.Rows[0].ItemArray[resultSet.Columns.IndexOf("fk_id")] == null)
{
   //never reaches here
}

Note: using an int index instead of the Columns.IndexOf() isn't the issue.

Also does the "{}" have some other name in C#?


答:
Use this connection string</p>

```<code>mysql = DriverManager.getConnection("jdbc:mysql://localhost:3306/somedb","someuser","somepassword");
</code>```

Title: JDBC is refusing to use a specified password

Body:
Use this connection string

mysql = DriverManager.getConnection("jdbc:mysql://localhost:3306/somedb","someuser","somepassword");


问:
Why does Laravel group RESTful methods the way they do?
I'm brand new to Laravel and am working my way through the Laravel 6 from Scratch course over at Laracasts. The course is free but I can't afford a Laracasts membership so I can't ask questions there.

I've finished the first several sections of the course and am a little confused about some of the concepts around the whole RESTful idea. The instructor, who seems very good and experienced with Laravel, describes 7 methods that are going to be part of pretty much any CRUD (Create Read Update Delete) application (and most applications are CRUD in nature.) He says naming of these 7 methods should be consistent with this:

index - a list of all the resources in a collection e.g. all articles in a blog

show - display a specific resource from a collection e.g. a specific article in a blog

create - create a new instance of a resource e.g. add a new article to a blog

store - save a new instance of a resource to a data store like a database

edit - modify the contents of an existing resource e.g. change the title of an article

update - save the modified resource to a data store

destroy - remove a resource from a collection e.g. delete a blog article

I'm a little puzzled by this division of work into 7 separate methods. It seems to me that Create and Store belong together in a single method; ditto for Edit and Update. Creating a new record has two phases: displaying an empty form to gather up the data needed to construct a new article, then validating the data and storing it on the database. By the same token, changing an existing record consists of two phases: displaying the current data in a form and letting the user change what needs changing, then validating it and sending it to the database (or back to the user for corrections).

I would also argue that to be consistent with the approach they've used for create/store and edit/update, destroy should be divided into two methods, Destroy and Remove, where Destroy displays the full record that the user wants to remove with two buttons at the bottom: Delete and Cancel. Then, if the user clicks on Delete, they go to a Remove method that actually deletes the record f from the database.

I've been coding for a fair while and I've never seen a system where the user was allowed to delete any important record without first being shown the record and being asked if they're sure they want to delete it. Now, maybe that's fallen out of fashion and I didn't notice but it seems a pretty prudent thing to do.

So why are the methods what they are, at least as RESTful is implemented in Laravel?

答:
It seems to me that Create and Store belong together in a single method

Well, Laravel generate all those methods thinking in a server-side rendered app. So in a SSR, before you store your data, you must be able to see a creation form.. that's why this create() function exists. The create(), normally, should return a view that will show the user the valid fields to create a resource, this is all done in a GET request. Then, when the users hit the "create"/"add" button, it will reach the store() method that will implement the logic to persist this data storing a new record in your database, this is done in a POST request.

The same goes for edit()/update().

I've been coding for a fair while and I've never seen a system where the user was allowed to delete any important record without first being shown the record and being asked if they're sure they want to delete it

That is because those validations are commonly implemented in the client-side, so, you do this with JS in  your front-end, for validations of that kind you shouldn't hit the server.

So why are the methods what they are, at least as RESTful is implemented in Laravel?

Finally, for a RESTful API you don't need all of those methods. Just index, show, store, update and delete ones. If you just need this kind of methods in your controller, you could exclude the create/edit ones by adding the --api flag when creating your controller through Artisan. From the documentation:

API Resource Routes

// ...

To quickly generate an API resource controller that does not include the create or edit methods, use the --api switch when executing the make:controller command:

```<code>php artisan make:controller API/PhotoController --api
</code>```

Body:
It seems to me that Create and Store belong together in a single method

Well, Laravel generate all those methods thinking in a server-side rendered app. So in a SSR, before you store your data, you must be able to see a creation form.. that's why this create() function exists. The create(), normally, should return a view that will show the user the valid fields to create a resource, this is all done in a GET request. Then, when the users hit the "create"/"add" button, it will reach the store() method that will implement the logic to persist this data storing a new record in your database, this is done in a POST request.

The same goes for edit()/update().

I've been coding for a fair while and I've never seen a system where the user was allowed to delete any important record without first being shown the record and being asked if they're sure they want to delete it

That is because those validations are commonly implemented in the client-side, so, you do this with JS in  your front-end, for validations of that kind you shouldn't hit the server.

So why are the methods what they are, at least as RESTful is implemented in Laravel?

Finally, for a RESTful API you don't need all of those methods. Just index, show, store, update and delete ones. If you just need this kind of methods in your controller, you could exclude the create/edit ones by adding the --api flag when creating your controller through Artisan. From the documentation:

API Resource Routes

// ...

To quickly generate an API resource controller that does not include the create or edit methods, use the --api switch when executing the make:controller command:

php artisan make:controller API/PhotoController --api


问:
Serilog serializing fields
If I have the following class

```<code>public class Customer
{
    public string Name;
}
</code>```

and then have the following log command in Serilog

```<code>Log.Logger = new LoggerConfiguration()
    .WriteTo.Console()
    .WriteTo.Seq("http://localhost:5341")
    .CreateLogger();

var item = new Customer();
item.Name = "John";
Serilog.Log.Information("Customer {@item}", item);
</code>```

The log just displays in Seq as

```<code>Customer {}
</code>```

If I change the Name field to a property it works but I would prefer not to do that at this stage. Is there any way around it?

答:
Thanks to Nicholas Blumhardt for a good starting point. I just have a small tweak.

my class:

```<code>public class Dummy
{
    public string Field = "the field";
    public string Property { get; set; } = "the property";
}
</code>```

log call:

```<code>Log.Information("Dummy = {@Dummy}", new Dummy());
</code>```

IDestructuringPolicy implementation includes both fields and properties:

```<code>internal class IncludePublicFieldsPolicy : IDestructuringPolicy
{
    public bool TryDestructure(object value, ILogEventPropertyValueFactory propertyValueFactory, out LogEventPropertyValue result)
    {
        var typeInfo = value.GetType().GetTypeInfo();

        var fieldsWithValues = typeInfo
            .DeclaredFields
            .Where(f => f.IsPublic)
            .Select(f =>
            {
                var val = f.GetValue(value);
                var propval = propertyValueFactory.CreatePropertyValue(val);
                var ret = new LogEventProperty(f.Name, propval);
                return ret;
            })
        ;

        var propertiesWithValues = typeInfo
            .DeclaredProperties
            .Where(f => f.CanRead)
            .Select(f =>
            {
                var val = f.GetValue(value);
                var propval = propertyValueFactory.CreatePropertyValue(val);
                var ret = new LogEventProperty(f.Name, propval);
                return ret;
            })
        ;

        result = new StructureValue(fieldsWithValues.Union(propertiesWithValues));
        return true;
    }
}
</code>```

Title: Serilog serializing fields

Body:
If I have the following class

public class Customer
{
    public string Name;
}

and then have the following log command in Serilog

Log.Logger = new LoggerConfiguration()
    .WriteTo.Console()
    .WriteTo.Seq("http://localhost:5341")
    .CreateLogger();

var item = new Customer();
item.Name = "John";
Serilog.Log.Information("Customer {@item}", item);

The log just displays in Seq as

Customer {}

If I change the Name field to a property it works but I would prefer not to do that at this stage. Is there any way around it?

Body:
Thanks to Nicholas Blumhardt for a good starting point. I just have a small tweak.

my class:

public class Dummy
{
    public string Field = "the field";
    public string Property { get; set; } = "the property";
}

log call:

Log.Information("Dummy = {@Dummy}", new Dummy());

IDestructuringPolicy implementation includes both fields and properties:

internal class IncludePublicFieldsPolicy : IDestructuringPolicy
{
    public bool TryDestructure(object value, ILogEventPropertyValueFactory propertyValueFactory, out LogEventPropertyValue result)
    {
        var typeInfo = value.GetType().GetTypeInfo();

        var fieldsWithValues = typeInfo
            .DeclaredFields
            .Where(f => f.IsPublic)
            .Select(f =>
            {
                var val = f.GetValue(value);
                var propval = propertyValueFactory.CreatePropertyValue(val);
                var ret = new LogEventProperty(f.Name, propval);
                return ret;
            })
        ;

        var propertiesWithValues = typeInfo
            .DeclaredProperties
            .Where(f => f.CanRead)
            .Select(f =>
            {
                var val = f.GetValue(value);
                var propval = propertyValueFactory.CreatePropertyValue(val);
                var ret = new LogEventProperty(f.Name, propval);
                return ret;
            })
        ;

        result = new StructureValue(fieldsWithValues.Union(propertiesWithValues));
        return true;
    }
}


问:
How to find word with en dash within it?
I need to find and highlight all words combinations with en dash within it in MS Word document.
For example in the sentence: "In the years 1993–1996 the economic situation was difficult." macro should result with highlighting "1993–1996".

I tried to use several text combinations with wildcards but it was not successful.

```<code>Sub DSFinder()

Dim r As Range

'highlights incorrect'
Set r = ActiveDocument.Range
With r.Find
.MatchWildcards = True
.Text = "*(^0150)*"
Do While .Execute(Forward:=True) = True
r.HighlightColorIndex = wdPink
Loop
End With

End Sub
</code>```

答:
Use a wildcard Find with:

```<code>.Text = "<[! ]@^=*>"
</code>```

PS: The following code is much more efficient than what you're using:

```<code>Sub DSFinder()
Application.ScreenUpdating = False
Dim iDx As Long
iDx = Options.DefaultHighlightColorIndex
Options.DefaultHighlightColorIndex = wdPink
With ActiveDocument.Range.Find
  .MatchWildcards = True
  .Text = "<[! ]@^=*>"
  .Replacement.Text = "^&"
  .Replacement.Highlight = True
  .Execute Replace:=wdReplaceAll
End With
Options.DefaultHighlightColorIndex = iDx
Application.ScreenUpdating = True
End Sub
</code>```

Body:
I need to find and highlight all words combinations with en dash within it in MS Word document.
For example in the sentence: "In the years 1993–1996 the economic situation was difficult." macro should result with highlighting "1993–1996".

I tried to use several text combinations with wildcards but it was not successful.

Sub DSFinder()

Dim r As Range

'highlights incorrect'
Set r = ActiveDocument.Range
With r.Find
.MatchWildcards = True
.Text = "*(^0150)*"
Do While .Execute(Forward:=True) = True
r.HighlightColorIndex = wdPink
Loop
End With

End Sub

Body:
Use a wildcard Find with:

.Text = "<[! ]@^=*>"

PS: The following code is much more efficient than what you're using:

Sub DSFinder()
Application.ScreenUpdating = False
Dim iDx As Long
iDx = Options.DefaultHighlightColorIndex
Options.DefaultHighlightColorIndex = wdPink
With ActiveDocument.Range.Find
  .MatchWildcards = True
  .Text = "<[! ]@^=*>"
  .Replacement.Text = "^&"
  .Replacement.Highlight = True
  .Execute Replace:=wdReplaceAll
End With
Options.DefaultHighlightColorIndex = iDx
Application.ScreenUpdating = True
End Sub


问:
Woocommerce optional product attributes
The custom attributes of a variable product are required. How can I make some of those attributes optional?

I've searched in woocommerce for the optional option, but there is none. So I'm wondering if there is an option to add this trough the Wordpress functions.php

What I actually want is an option to select if the attribute is optional or required.

答:
I've just had the same issue where I have a list of dropdown attributes for a product, where only some of these attributes need to be selected. I understand what LoicTheAztec is saying and must assume this is how WooCommerce think as well which is why I don't think there's an elegant answer in code. However, the simplest answers are the best.

What I did is just add a --NONE-- attribute value at the start of the list. Set this as the default value and Robert's your mother's brother.

Title: Woocommerce optional product attributes


问:
How does Windows find the installed location when uninstalling software
When I run an installer that allows a custom install location/path, the files will be correctly placed at the location that I select.

When I run the same MSI and select remove (or uninstall from add/remove programs), how does it know the install location so the correct files are removed?

I thought it would be stored at 'Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall{GUID}', but when I look at that location for my installed software, the 'InstallLocation' key is empty.

However, no matter how I uninstall it, it knows which folder to go remove, no matter where I put it. Is that information stored elsewhere in the registry, or in the MSI file itself?

答:
UPDATE:

Find Component's Installation Location: Is there way to detect install location without uninstall registry nor C:\Windows\Installer?

Implementation Details: How MSI stores these things are implementation details that should not be meddled with, attempted modified or used directly for any purpose - just so that is clear. You should go through the MSI API which is implemented as Win32 functions with complementary COM wrappers for access via scripting languages.

Registry: The MSI database is stored mostly in the registry, but there also components on disk - some of which you refer to - for example %SystemDrive%\Windows\Installer (a super-hidden folder that should not be modified in any way). The MSI database is stored in numerous locations throughout the registry:

HKCR\Installer

HKCU\Software\Microsoft\Installer

HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer

HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall

HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall

HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Installer

Etc...

Some of these are real, some are aliases, some are merges. It is all a bit fuzzy. Again: implementation details - a well-known euphemism for all of us to: "give up right now, will you"? :-). Just apply the MSI API to acquire the information you need.

MSI API: A lot of stuff to read above to get to the point, go via the MSI API to get your information on directory resolution. What we have to do is a bit exotic, we have to spin up a session object for the installed product and run two standard actions (built-in MSI actions from Microsoft) in order to resolve the directory table and installation directories of the MSI in question (about "costing"). Below is a practical sample:

For the record:

How can I find the product GUID of an installed MSI setup?

How can I compare the content of two (or more) MSI files? (on Orca and other, free MSI tools)

Uninstalling an MSI file from the command line without using msiexec (a myriad of ways to uninstall MSI packages)

Set installer = CreateObject("WindowsInstaller.Installer")

' Other test product codes: {2F73A7B2-E50E-39A6-9ABC-EF89E4C62E36}

productcode = Trim(InputBox("Please paste or type in the product code you want to look up details for:", _
              "Find Product Details (test GUID provided):", "{766AD270-A684-43D6-AF9A-74165C9B5796}"))
If search = vbCancel Or Trim(productcode) = "" Then
   WScript.Quit(0)
End If

Set session = installer.OpenProduct(productcode)

' Crucially, resolve the directory table and properties by running "MSI Costing"
session.DoAction("CostInitialize")
session.DoAction("CostFinalize")

' Can be any directory property from the Directory table in the MSI:
MsgBox session.Property("INSTALLFOLDER")

' Open the MSI in Orca to find the directory folder property names
```
<hr />
<p>Throwing in a link to an old answer on how to list tables inside an MSI file.</p>
<hr />
<p><em><strong>Resolve All</strong></em>: Got a bit carried away and made one more update to resolve ALL directories for any installed package. Here is a script (not tested much):</p>
<pre class="lang-vb prettyprint-override"><code>' https://stackoverflow.com/questions/17543132/how-can-i-resolve-msi-paths-in-vbscript
' On Error resume Next

Set installer = CreateObject("WindowsInstaller.Installer")

' Other test product codes: {2F73A7B2-E50E-39A6-9ABC-EF89E4C62E36}

const READONLY = 0
Dim DirList

productcode = Trim(InputBox("Please paste or type in the product code you want to look up details for:", _
              "Find Product Details (test GUID provided):", "{766AD270-A684-43D6-AF9A-74165C9B5796}"))
If search = vbCancel Or Trim(productcode) = "" Then
   WScript.Quit(0)
End If

Set session = installer.OpenProduct(productcode)
session.DoAction("CostInitialize")
session.DoAction("CostFinalize")

set view = session.Database.OpenView("SELECT * FROM Directory")
view.Execute
set record = view.Fetch

Do until record is Nothing

    ResolvedDir = session.Property(record.StringData(1))
    DirList = DirList + record.StringData(1) + " => " + ResolvedDir + vbCrLf
    set record = view.Fetch

Loop

' Dismiss dialog with ESC key if it falls off screen
WScript.Echo DirList ' Use WScript.Echo due to MsgBox restrictions (number of characters)
</code>```

Links:

How can I resolve MSI paths in VBScript?

Body:
UPDATE:

Find Component's Installation Location: Is there way to detect install location without uninstall registry nor C:\Windows\Installer?

Implementation Details: How MSI stores these things are implementation details that should not be meddled with, attempted modified or used directly for any purpose - just so that is clear. You should go through the MSI API which is implemented as Win32 functions with complementary COM wrappers for access via scripting languages.

Registry: The MSI database is stored mostly in the registry, but there also components on disk - some of which you refer to - for example %SystemDrive%\Windows\Installer (a super-hidden folder that should not be modified in any way). The MSI database is stored in numerous locations throughout the registry:

HKCR\Installer

HKCU\Software\Microsoft\Installer

HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer

HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall

HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall

HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Installer

Etc...

Some of these are real, some are aliases, some are merges. It is all a bit fuzzy. Again: implementation details - a well-known euphemism for all of us to: "give up right now, will you"? :-). Just apply the MSI API to acquire the information you need.

MSI API: A lot of stuff to read above to get to the point, go via the MSI API to get your information on directory resolution. What we have to do is a bit exotic, we have to spin up a session object for the installed product and run two standard actions (built-in MSI actions from Microsoft) in order to resolve the directory table and installation directories of the MSI in question (about "costing"). Below is a practical sample:

For the record:

How can I find the product GUID of an installed MSI setup?

How can I compare the content of two (or more) MSI files? (on Orca and other, free MSI tools)

Uninstalling an MSI file from the command line without using msiexec (a myriad of ways to uninstall MSI packages)

Set installer = CreateObject("WindowsInstaller.Installer")

' Other test product codes: {2F73A7B2-E50E-39A6-9ABC-EF89E4C62E36}

productcode = Trim(InputBox("Please paste or type in the product code you want to look up details for:", _
              "Find Product Details (test GUID provided):", "{766AD270-A684-43D6-AF9A-74165C9B5796}"))
If search = vbCancel Or Trim(productcode) = "" Then
   WScript.Quit(0)
End If

Set session = installer.OpenProduct(productcode)

' Crucially, resolve the directory table and properties by running "MSI Costing"
session.DoAction("CostInitialize")
session.DoAction("CostFinalize")

' Can be any directory property from the Directory table in the MSI:
MsgBox session.Property("INSTALLFOLDER")

' Open the MSI in Orca to find the directory folder property names

Throwing in a link to an old answer on how to list tables inside an MSI file.

Resolve All: Got a bit carried away and made one more update to resolve ALL directories for any installed package. Here is a script (not tested much):

' https://stackoverflow.com/questions/17543132/how-can-i-resolve-msi-paths-in-vbscript
' On Error resume Next

Set installer = CreateObject("WindowsInstaller.Installer")

' Other test product codes: {2F73A7B2-E50E-39A6-9ABC-EF89E4C62E36}

const READONLY = 0
Dim DirList

productcode = Trim(InputBox("Please paste or type in the product code you want to look up details for:", _
              "Find Product Details (test GUID provided):", "{766AD270-A684-43D6-AF9A-74165C9B5796}"))
If search = vbCancel Or Trim(productcode) = "" Then
   WScript.Quit(0)
End If

Set session = installer.OpenProduct(productcode)
session.DoAction("CostInitialize")
session.DoAction("CostFinalize")

set view = session.Database.OpenView("SELECT * FROM Directory")
view.Execute
set record = view.Fetch

Do until record is Nothing

    ResolvedDir = session.Property(record.StringData(1))
    DirList = DirList + record.StringData(1) + " => " + ResolvedDir + vbCrLf
    set record = view.Fetch

Loop

' Dismiss dialog with ESC key if it falls off screen
WScript.Echo DirList ' Use WScript.Echo due to MsgBox restrictions (number of characters)

Links:

How can I resolve MSI paths in VBScript?


问:
Trouble with merging tsv files using pandas
So I have been having an issue using pandas where it simply does not merge certain lines. For example, when trying to merge the following two excerpts together:

```<code>Haggai  1:1 In the second year of Darius the king, in the sixth month, in the first day of the month, the Word of Yahweh came by Haggai, the prophet, to Zerubbabel, the son of Shealtiel, governor of Judah, and to Joshua, the son of Jehozadak, the high priest, saying,
Haggai  1:2 "This is what Yahweh of Hosts says: These people say, 'The time hasn't yet come, the time for Yahweh's house to be built.'"
Haggai  1:3 Then the Word of Yahweh came by Haggai, the prophet, saying,
Haggai  1:4 "Is it a time for you yourselves to dwell in your paneled houses, while this house lies waste?
Haggai  1:5 Now therefore this is what Yahweh of Hosts says: Consider your ways.
Haggai  1:6 You have sown much, and bring in little. You eat, but you don't have enough. You drink, but you aren't filled with drink. You clothe yourselves, but no one is warm, and he who earns wages earns wages to put them into a bag with holes in it."
</code>```

and

```<code>Haggai  1:1 ΕΝ τῷ δευτέρῳ ἔτει ἐπὶ Δαρίου τοῦ βασιλέως ἐν τῷ μηνὶ τῷ ἕκτῳ μιᾷ τοῦ μηνὸς ἐγένετο λόγος Κυρίου ἐν χειρὶ Ἀγγαίου τοῦ προφήτου λέγων Εἰπὸν πρὸς Ζοροβάβελ τὸν τοῦ Σαλαθιὴλ ἐκ φυλῆς Ἰούδα καὶ πρὸς Ἰησοῦν τὸν τοῦ Ἰωσεδὲκ τὸν ἱερέα τὸν μέγαν λέγων
Haggai  1:2 Τάδε λέγει Κύριος Παντοκράτωρ λέγων Ὁ λαὸς οὗτος λέγουσιν Οὐχ ἤκει ὁ καιρὸς τοῦ οἰκοδομῆσαι τὸν οἶκον Κυρίου.
Haggai  1:3 καὶ ἐγένετο λόγος Κυρίου ἐν χειρὶ Ἀγγαίου τοῦ προφήτου λέγων
Haggai  1:4 Εἰ καιρὸς μέν ὑμῖν ἐστιν τοῦ οἰκεῖν ἐν οἴκοις ὑμῶν κοιλοστάθμοις, ὁ δὲ οἶκος ὑμῶν ἐξηρήμωται;
Haggai  1:5 καὶ νῦν τάδε λέγει Κύριος Παντοκράτωρ Τάξατε δὴ τὰς καρδίας ὑμῶν εἰς τὰς ὁδοὺς ὑμῶν·
Haggai  1:6 ἐσπείρατε πολλὰ καὶ εἰσηνέγκατε ὀλίγα, ἐφάγετε καὶ οὐκ εἰς πλησμονήν, ἐπίετε καὶ οὐκ εἰς μέθην, περιεβάλεσθε καὶ οὐκ ἐθερμάνθητε ἐν αὐτοῖς, καὶ ὁ τοὺς μισθοὺς συνάγων συνήγαγεν εἰς δεσμὸν τετρυπημένον.
</code>```

I get:

```<code>21  Haggai  1:1 ΕΝ τῷ δευτέρῳ ἔτει ἐπὶ Δαρίου τοῦ βασιλέως ἐν τῷ μηνὶ τῷ ἕκτῳ μιᾷ τοῦ μηνὸς ἐγένετο λόγος Κυρίου ἐν χειρὶ Ἀγγαίου τοῦ προφήτου λέγων Εἰπὸν πρὸς Ζοροβάβελ τὸν τοῦ Σαλαθιὴλ ἐκ φυλῆς Ἰούδα καὶ πρὸς Ἰησοῦν τὸν τοῦ Ἰωσεδὲκ τὸν ἱερέα τὸν μέγαν λέγων In the second year of Darius the king, in the sixth month, in the first day of the month, the Word of Yahweh came by Haggai, the prophet, to Zerubbabel, the son of Shealtiel, governor of Judah, and to Joshua, the son of Jehozadak, the high priest, saying,
22  Haggai  1:2 Τάδε λέγει Κύριος Παντοκράτωρ λέγων Ὁ λαὸς οὗτος λέγουσιν Οὐχ ἤκει ὁ καιρὸς τοῦ οἰκοδομῆσαι τὸν οἶκον Κυρίου.   This is what Yahweh of Hosts says: These people say, 'The time hasn't yet come, the time for Yahweh's house to be built.'
23  Haggai  1:3 καὶ ἐγένετο λόγος Κυρίου ἐν χειρὶ Ἀγγαίου τοῦ προφήτου λέγων    Then the Word of Yahweh came by Haggai, the prophet, saying,
24  Haggai  1:4 Εἰ καιρὸς μέν ὑμῖν ἐστιν τοῦ οἰκεῖν ἐν οἴκοις ὑμῶν κοιλοστάθμοις, ὁ δὲ οἶκος ὑμῶν ἐξηρήμωται;   "Is it a time for you yourselves to dwell in your paneled houses, while this house lies waste?
Haggai  1:5 Now therefore this is what Yahweh of Hosts says: Consider your ways.
Haggai  1:6 You have sown much, and bring in little. You eat, but you don't have enough. You drink, but you aren't filled with drink. You clothe yourselves, but no one is warm, and he who earns wages earns wages to put them into a bag with holes in it."
</code>```

Where clearly Haggai 1:5 and Haggai 1:6 do not merge correctly.

The code I am using is:

```<code>import pandas as pd

df1 = pd.read_table('greekBible.txt')
df2 = pd.read_table('englishBible.txt')

df3 = pd.merge(df1, df2, on=['Book', 'Chapter:Verse'])

df3.to_csv('test.txt', sep="\t")
</code>```

Keep in mind, this is only a small excerpt. Further, the two bibles are not totally aligned — there are entries in one that are not in the other and vice versa. However, this shouldn’t be a problem to my understanding.

Thank you very much for your help with this problem!

答: There appear to be missing quotes in your file, probably due to how the text was split. It is most obvious on the line Haggai  1:4 "Is it a time for you yourselves to dwell in your paneled houses, while this house lies waste?

Body:
So I have been having an issue using pandas where it simply does not merge certain lines. For example, when trying to merge the following two excerpts together:

Haggai  1:1 In the second year of Darius the king, in the sixth month, in the first day of the month, the Word of Yahweh came by Haggai, the prophet, to Zerubbabel, the son of Shealtiel, governor of Judah, and to Joshua, the son of Jehozadak, the high priest, saying,
Haggai  1:2 "This is what Yahweh of Hosts says: These people say, 'The time hasn't yet come, the time for Yahweh's house to be built.'"
Haggai  1:3 Then the Word of Yahweh came by Haggai, the prophet, saying,
Haggai  1:4 "Is it a time for you yourselves to dwell in your paneled houses, while this house lies waste?
Haggai  1:5 Now therefore this is what Yahweh of Hosts says: Consider your ways.
Haggai  1:6 You have sown much, and bring in little. You eat, but you don't have enough. You drink, but you aren't filled with drink. You clothe yourselves, but no one is warm, and he who earns wages earns wages to put them into a bag with holes in it."

and

Haggai  1:1 ΕΝ τῷ δευτέρῳ ἔτει ἐπὶ Δαρίου τοῦ βασιλέως ἐν τῷ μηνὶ τῷ ἕκτῳ μιᾷ τοῦ μηνὸς ἐγένετο λόγος Κυρίου ἐν χειρὶ Ἀγγαίου τοῦ προφήτου λέγων Εἰπὸν πρὸς Ζοροβάβελ τὸν τοῦ Σαλαθιὴλ ἐκ φυλῆς Ἰούδα καὶ πρὸς Ἰησοῦν τὸν τοῦ Ἰωσεδὲκ τὸν ἱερέα τὸν μέγαν λέγων
Haggai  1:2 Τάδε λέγει Κύριος Παντοκράτωρ λέγων Ὁ λαὸς οὗτος λέγουσιν Οὐχ ἤκει ὁ καιρὸς τοῦ οἰκοδομῆσαι τὸν οἶκον Κυρίου.
Haggai  1:3 καὶ ἐγένετο λόγος Κυρίου ἐν χειρὶ Ἀγγαίου τοῦ προφήτου λέγων
Haggai  1:4 Εἰ καιρὸς μέν ὑμῖν ἐστιν τοῦ οἰκεῖν ἐν οἴκοις ὑμῶν κοιλοστάθμοις, ὁ δὲ οἶκος ὑμῶν ἐξηρήμωται;
Haggai  1:5 καὶ νῦν τάδε λέγει Κύριος Παντοκράτωρ Τάξατε δὴ τὰς καρδίας ὑμῶν εἰς τὰς ὁδοὺς ὑμῶν·
Haggai  1:6 ἐσπείρατε πολλὰ καὶ εἰσηνέγκατε ὀλίγα, ἐφάγετε καὶ οὐκ εἰς πλησμονήν, ἐπίετε καὶ οὐκ εἰς μέθην, περιεβάλεσθε καὶ οὐκ ἐθερμάνθητε ἐν αὐτοῖς, καὶ ὁ τοὺς μισθοὺς συνάγων συνήγαγεν εἰς δεσμὸν τετρυπημένον.

I get:

21  Haggai  1:1 ΕΝ τῷ δευτέρῳ ἔτει ἐπὶ Δαρίου τοῦ βασιλέως ἐν τῷ μηνὶ τῷ ἕκτῳ μιᾷ τοῦ μηνὸς ἐγένετο λόγος Κυρίου ἐν χειρὶ Ἀγγαίου τοῦ προφήτου λέγων Εἰπὸν πρὸς Ζοροβάβελ τὸν τοῦ Σαλαθιὴλ ἐκ φυλῆς Ἰούδα καὶ πρὸς Ἰησοῦν τὸν τοῦ Ἰωσεδὲκ τὸν ἱερέα τὸν μέγαν λέγων In the second year of Darius the king, in the sixth month, in the first day of the month, the Word of Yahweh came by Haggai, the prophet, to Zerubbabel, the son of Shealtiel, governor of Judah, and to Joshua, the son of Jehozadak, the high priest, saying,
22  Haggai  1:2 Τάδε λέγει Κύριος Παντοκράτωρ λέγων Ὁ λαὸς οὗτος λέγουσιν Οὐχ ἤκει ὁ καιρὸς τοῦ οἰκοδομῆσαι τὸν οἶκον Κυρίου.   This is what Yahweh of Hosts says: These people say, 'The time hasn't yet come, the time for Yahweh's house to be built.'
23  Haggai  1:3 καὶ ἐγένετο λόγος Κυρίου ἐν χειρὶ Ἀγγαίου τοῦ προφήτου λέγων    Then the Word of Yahweh came by Haggai, the prophet, saying,
24  Haggai  1:4 Εἰ καιρὸς μέν ὑμῖν ἐστιν τοῦ οἰκεῖν ἐν οἴκοις ὑμῶν κοιλοστάθμοις, ὁ δὲ οἶκος ὑμῶν ἐξηρήμωται;   "Is it a time for you yourselves to dwell in your paneled houses, while this house lies waste?
Haggai  1:5 Now therefore this is what Yahweh of Hosts says: Consider your ways.
Haggai  1:6 You have sown much, and bring in little. You eat, but you don't have enough. You drink, but you aren't filled with drink. You clothe yourselves, but no one is warm, and he who earns wages earns wages to put them into a bag with holes in it."

Where clearly Haggai 1:5 and Haggai 1:6 do not merge correctly.

The code I am using is:

import pandas as pd

df1 = pd.read_table('greekBible.txt')
df2 = pd.read_table('englishBible.txt')

df3 = pd.merge(df1, df2, on=['Book', 'Chapter:Verse'])

df3.to_csv('test.txt', sep="\t")

Keep in mind, this is only a small excerpt. Further, the two bibles are not totally aligned — there are entries in one that are not in the other and vice versa. However, this shouldn’t be a problem to my understanding.

Thank you very much for your help with this problem!


问:
Finding data ending in ___ in SQL?
Trying to get get this information from a database: number of Zip codes where the city name ends in ‘boro’ or 'town' and has an average house value at or below $250,000.

This is what I put:

```<code>select count(*)
from zip_codes
where city like ’%boro’ and city like ‘%town’ and average_house_value <= 250000;
</code>```

and keep getting this message: ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%boro’ OR city like ‘%town’) and average_house_value <= 250000' at line 1

help?

答:
where city like ’%boro’ and city like ‘%town’ and average_house_value <= 250000

Issues with your query:

You should use standard single quotes instead of these funky ’ characters; likely, this is the reason why you are getting a syntax error

You want cities that end with 'boro' or 'town', but you phrased a query that searches for cityes that end with both: this is guaranteed to return no rows, as no value can end with both strings at once

Consider:

```<code>select count(*)
from zip_codes
where (city like '%boro' or city like '%tow') and average_house_value <= 250000
</code>```

Title: Finding data ending in ___ in SQL?

Body:
Trying to get get this information from a database: number of Zip codes where the city name ends in ‘boro’ or 'town' and has an average house value at or below $250,000.

This is what I put:

select count(*)
from zip_codes
where city like ’%boro’ and city like ‘%town’ and average_house_value <= 250000;

and keep getting this message: ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%boro’ OR city like ‘%town’) and average_house_value <= 250000' at line 1

help?

Body:
where city like ’%boro’ and city like ‘%town’ and average_house_value <= 250000

Issues with your query:

You should use standard single quotes instead of these funky ’ characters; likely, this is the reason why you are getting a syntax error

You want cities that end with 'boro' or 'town', but you phrased a query that searches for cityes that end with both: this is guaranteed to return no rows, as no value can end with both strings at once

Consider:

select count(*)
from zip_codes
where (city like '%boro' or city like '%tow') and average_house_value <= 250000


问:
is this correct re returning a date re memory management?
is this correct re returning a date re memory management?

The assumption here I have is I want to return a date back to the caller, but I don't want the caller to be able to be change the date and impact the method's date, hence I thought I would return a copy.

So the code in the method I have is:

```<code>- (NSDate*)dateForMyTest {
     return [[self.endDate copy] autorelease];
}
</code>```

I was assuming I have to autorelease it so the caller doesn't have to, as they would not have called an init/copy/etc themselves.

答:
The copy autorelease may be needed if the app is using nsoperations/threads, etc. But you may be already thread safer - or not: When you use

```<code>return self.endDate
</code>```

any number of things could be happening, depending on how the property was set up. Was it

```<code> @property (retain) endDate;
</code>```

, or the more common, faster and less thread safe

```<code> @property (nonatomic, retain) endDate;
</code>```

It is as complicated as you like!

What's the difference between the atomic and nonatomic attributes?

Body:
is this correct re returning a date re memory management?

The assumption here I have is I want to return a date back to the caller, but I don't want the caller to be able to be change the date and impact the method's date, hence I thought I would return a copy.

So the code in the method I have is:

- (NSDate*)dateForMyTest {
     return [[self.endDate copy] autorelease];
}

I was assuming I have to autorelease it so the caller doesn't have to, as they would not have called an init/copy/etc themselves.

Body:
The copy autorelease may be needed if the app is using nsoperations/threads, etc. But you may be already thread safer - or not: When you use

return self.endDate

any number of things could be happening, depending on how the property was set up. Was it

 @property (retain) endDate;

, or the more common, faster and less thread safe

 @property (nonatomic, retain) endDate;

It is as complicated as you like!

What's the difference between the atomic and nonatomic attributes?


问:
Module exports for Express Router / Functions
Hi I am trying to export both a function (so that other routes may use this function to verify certs and also a the express router so that I can add it to my main class to mount the route on. This is because I believe the function and the route both serve the same sort of "functionality" and I want to encapsulate it in one file, so I want to export both the function and the router to use! Here is the following code of which I get an error... Note I WANT to do verifytoken.router to refer to the router and then verifytoken.verify to refer to the function in other files

/routes/verifytoken.js file

```<code>const router = require('express').Router();
const jwt = require('jsonwebtoken');

function verify (req, res, next) {
    const token = req.header("auth-token");
    if (!token) return res.status(401).send("Access Denied");

    try {
        const verified = jwt.verify(token, process.env.TOKEN_SECRET);
        req.user = verified;
        next();
    } catch (error) {
        res.status(400).send("Invalid Token")
    }
}

router.get("/tester", (req, res) => {
    res.status(200).send("validation please work bro");
});

module.exports = {
    verify:verify,
    router:router
}
</code>```

my main index.js file

```<code>const express = require('express');

//import routes
const verifytoken = require('./routes/verifytoken')

const app = express();

//route middlewares
app.use("/api/user". verifytoken.router);

app.listen(3000 , () => console.log('Server Running...'))
</code>```

The stack trace is :

```<code>app.use("/api/user". verifytoken.router);
                                 ^

TypeError: Cannot read property 'router' of undefined
</code>```

答:
1) Another typo:

app.use("/api/user". verifytoken.router);
```

<p>Should be: (note dot . instead of comma ,)</p>

<pre class="lang-js prettyprint-override"><code>app.use("/api/user", verifytoken.router);
</code>```

2) You're using the wrong filename in the imported module:

```<code>const verifytoken = require('./routes/verifytoken');
</code>```

Should be:

const verifytoken = require('./routes/verify');

```

The required file is named verify.js not verifytoken.js

Body:
Hi I am trying to export both a function (so that other routes may use this function to verify certs and also a the express router so that I can add it to my main class to mount the route on. This is because I believe the function and the route both serve the same sort of "functionality" and I want to encapsulate it in one file, so I want to export both the function and the router to use! Here is the following code of which I get an error... Note I WANT to do verifytoken.router to refer to the router and then verifytoken.verify to refer to the function in other files

/routes/verifytoken.js file

const router = require('express').Router();
const jwt = require('jsonwebtoken');

function verify (req, res, next) {
    const token = req.header("auth-token");
    if (!token) return res.status(401).send("Access Denied");

    try {
        const verified = jwt.verify(token, process.env.TOKEN_SECRET);
        req.user = verified;
        next();
    } catch (error) {
        res.status(400).send("Invalid Token")
    }
}

router.get("/tester", (req, res) => {
    res.status(200).send("validation please work bro");
});

module.exports = {
    verify:verify,
    router:router
}

my main index.js file

const express = require('express');

//import routes
const verifytoken = require('./routes/verifytoken')

const app = express();

//route middlewares
app.use("/api/user". verifytoken.router);

app.listen(3000 , () => console.log('Server Running...'))

The stack trace is :

app.use("/api/user". verifytoken.router);
                                 ^

TypeError: Cannot read property 'router' of undefined

Body:
1) Another typo:

app.use("/api/user". verifytoken.router);

Should be: (note dot . instead of comma ,)

app.use("/api/user", verifytoken.router);

2) You're using the wrong filename in the imported module:

const verifytoken = require('./routes/verifytoken');

Should be:

const verifytoken = require('./routes/verify');

The required file is named verify.js not verifytoken.js


问:
How to identify a dependent entity in one to one relationship Entity Framework Core?
I have studied many articles about how to config one to one relationships. I have learned it.

But I couldn't understand how to find a dependent entity in one to one relationship?

For instance, we have two entities User and Developer. How to understand which of them is a dependent entity? Because I think we must add a foreign key to a dependent entity. So the first things to do, we need to find a dependent entity.

```<code>public class User
{
    public int Id {get;set;}
    public string PasswordHash { get; set; }
    public string FullName { get { return FirstName + " " +LastName;}}
    public GenderType Gender { get; set; }
    public bool IsActive { get; set; }
    public DateTimeOffset LastLoginDate { get; set; }
    public string FirstName { get ; set ; }
    public string LastName { get; set; }
}

public class Developer
{
    public int Id { get; set; }
    public byte Image { get; set; }
    public int Age { get; set; }
    public string Resume { get; set; }
}
</code>```

答:
A dependent is something that depends on something else. A baby is dependent on its mother for food etc. Identify which entity can stand alone, without the other.

For example, you may decide that a User might not be a Developer but a Developer is always a User - in this case your relationship is actually 1:0..1 (user:developer) and you're looking at Developer being a subclass of a User. If. You could alternatively arrange things in a has-a fashion, and Developer has a User property (but User doesn't have a Developer property because not every User is a developer)

You may decide that you can never have one without the other- in which case they would probably be a good candidate for being in the same table/same client side entity

To some extent the question can be academic; there may be situations where you want to treat one as dependent, and others where it's the inverse way round. It'll probably help you overall though if you make a decision about how your entities are related on the client side and this will drive how you map them on the database side

Body:
I have studied many articles about how to config one to one relationships. I have learned it.

But I couldn't understand how to find a dependent entity in one to one relationship?

For instance, we have two entities User and Developer. How to understand which of them is a dependent entity? Because I think we must add a foreign key to a dependent entity. So the first things to do, we need to find a dependent entity.

public class User
{
    public int Id {get;set;}
    public string PasswordHash { get; set; }
    public string FullName { get { return FirstName + " " +LastName;}}
    public GenderType Gender { get; set; }
    public bool IsActive { get; set; }
    public DateTimeOffset LastLoginDate { get; set; }
    public string FirstName { get ; set ; }
    public string LastName { get; set; }
}

public class Developer
{
    public int Id { get; set; }
    public byte Image { get; set; }
    public int Age { get; set; }
    public string Resume { get; set; }
}


问:
reference LONG variable to cell in a sheet
How to link a Long variable to a value entered in an excel sheet? I want to create large number of rows and although I am able to change the variable directly in the code (e.g. x=100000) but as soon as I link the variable x to a cell (e.g. x = Cells(1,1) no value seems to be recognized and printed to the range.</p>

答:
In order to simulate the cell being linked to the variable, you would have to add some code that gets triggered by something to write it to the cell.

Dim the variable as Public or Global (outside of the routine that sets it), so that other subroutines can "see" its value:

```<code>Public x as Long
</code>```

and then add the code that sets its value to the worksheet in the Worksheet_SelectionChange event or the Worksheet_Change event (depending on how you want it to work):

```<code>Cells(1, 1) = x
</code>```

If you are trying to set the variable automatically, then here's the opposite. Add this to the WorkSheet_Change event:

```<code>If Target.Row = 1 and Target.Column = 1 Then
    x = Cells(Target.Row, Target.Column)
End If
</code>```

Body:
In order to simulate the cell being linked to the variable, you would have to add some code that gets triggered by something to write it to the cell.

Dim the variable as Public or Global (outside of the routine that sets it), so that other subroutines can "see" its value:

Public x as Long

and then add the code that sets its value to the worksheet in the Worksheet_SelectionChange event or the Worksheet_Change event (depending on how you want it to work):

Cells(1, 1) = x

If you are trying to set the variable automatically, then here's the opposite. Add this to the WorkSheet_Change event:

If Target.Row = 1 and Target.Column = 1 Then
    x = Cells(Target.Row, Target.Column)
End If


问:
Import CSV Error Exception: Cannot convert ',' to char
I created a script based off this one which takes a CSV attachment from Gmail and then pastes it into a Google Sheet, and when I try use the script again on a new sheet it gives me an error:

Exception: Cannot convert ',' to char. (line 22, file "Code")

Line of code:

```<code>  var csvData = Utilities.parseCsv(attachment.getDataAsString(), ',');
</code>```

The thing I find really weird I have the exact same line of code in other scripts and they work without issue. I've even tried copy/pasting the line of code from the working scripts.

function importCSVFromGmail() {
  var threads = GmailApp.search("redacted");
  var message = threads[0].getMessages().pop();

  var attachment = message.getAttachments()[0];

  if (attachment != null) {
    var attachName = attachment.getName();

    // Is the attachment a CSV file
    if (attachName.substring(attachName.length-4) === ".csv") {
      var id = "redacted";
      var name = "Data Sheet";
      var sheet = SpreadsheetApp.openById(id);
      var tab = sheet.getSheetByName(name);

      // Clear the content of the sheet
      var csvData = Utilities.parseCsv(attachment.getDataAsString(), ",");
      tab.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
    }
  }
}```

Any help would be appreciated, I can't figure out why I'm getting the error only in new scripts.

答:
I don't think removing the parameter is the best solution.

Here is the definition from Google:
parseCsv(csv, delimiter)

Here is my solution:

```<code>var csvData = Utilities.parseCsv(attachment.getDataAsString(), ','.charCodeAt(0));
</code>```

Note: Removing the parameter in your example may have no difference as ',' is the default delimiter in this function. It may make a lot more sense on a situation that you need another delimiter like ';'

Body:
I created a script based off this one which takes a CSV attachment from Gmail and then pastes it into a Google Sheet, and when I try use the script again on a new sheet it gives me an error:

Exception: Cannot convert ',' to char. (line 22, file "Code")

Line of code:

  var csvData = Utilities.parseCsv(attachment.getDataAsString(), ',');

The thing I find really weird I have the exact same line of code in other scripts and they work without issue. I've even tried copy/pasting the line of code from the working scripts.

function importCSVFromGmail() {
  var threads = GmailApp.search("redacted");
  var message = threads[0].getMessages().pop();

  var attachment = message.getAttachments()[0];

  if (attachment != null) {
    var attachName = attachment.getName();

    // Is the attachment a CSV file
    if (attachName.substring(attachName.length-4) === ".csv") {
      var id = "redacted";
      var name = "Data Sheet";
      var sheet = SpreadsheetApp.openById(id);
      var tab = sheet.getSheetByName(name);

      // Clear the content of the sheet
      var csvData = Utilities.parseCsv(attachment.getDataAsString(), ",");
      tab.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
    }
  }
}

Any help would be appreciated, I can't figure out why I'm getting the error only in new scripts.

Body:
I don't think removing the parameter is the best solution.

Here is the definition from Google:
parseCsv(csv, delimiter)

Here is my solution:

var csvData = Utilities.parseCsv(attachment.getDataAsString(), ','.charCodeAt(0));

Note: Removing the parameter in your example may have no difference as ',' is the default delimiter in this function. It may make a lot more sense on a situation that you need another delimiter like ';'


问:
Android AsyncTask blocks back key dispatch Event
The Problem is:

My Activity starts an AsyncTask in onStart().
In the doInBackground Method I make a short webrequest, and depending on your network connetion, this may take a little, so I want this task cancelable...

BUT..

After hours of searching, testing and debugging I noticed now, when the user presses the back button during the doInBackground Method, the Keyevent ist always dispatched AFTER my doInBackground method is finished.

So I dont have to wonder why the asynctask never is cancelled when the users presses the backbutton,
the AsyncTask.cancel(true) is invoked too late..... (even if I am not sure if cancel(true) will help)

So is this normal behavoiur with asynctask and backbutton?

This cant be normal, because how should the user ever get back from the activity on slow connection?

wait for timeout?

I am Begging for Help, cancel an async webrequest SHOULD be possible :)

答:
when the user presses the back button during the doInBackground Method, the Keyevent is always dispatched AFTER my doInBackground method is finished.

No, this isn't true.

If I hit the BACK button on my device when an AsyncTask is running in my main Activity (downloading files from my server), the Activity is immediately closed.

What IS true, however, is the AsyncTask will continue to run whatever code is in its doInBackground() method UNLESS I explicitly cancel it (but you kind of know that already).

As far as I can tell, your 'webrequest' (whatever that may be) is blocking your doInBackground() method and because of that, any attempt to cancel it in onPause(), onStop, onDestroy() etc will never work.

As advantej points out, the way the AsyncTask.cancel(...) method works is that it causes isCancelled to be set to 'true'. In order to successfully cancel the AsyncTask's doInBackground() method you need to periodically check isCancelled. Example...

```<code>@Override
protected Void doInBackground(String... params) {

    while (!isCancelled) {
        DoSomething();
    }
}
</code>```

The problem is if DoSomething() (for example your 'webrequest') is blocking the while loop then isCancelled won't be checked until it completes.

Body:
when the user presses the back button during the doInBackground Method, the Keyevent is always dispatched AFTER my doInBackground method is finished.

No, this isn't true.

If I hit the BACK button on my device when an AsyncTask is running in my main Activity (downloading files from my server), the Activity is immediately closed.

What IS true, however, is the AsyncTask will continue to run whatever code is in its doInBackground() method UNLESS I explicitly cancel it (but you kind of know that already).

As far as I can tell, your 'webrequest' (whatever that may be) is blocking your doInBackground() method and because of that, any attempt to cancel it in onPause(), onStop, onDestroy() etc will never work.

As advantej points out, the way the AsyncTask.cancel(...) method works is that it causes isCancelled to be set to 'true'. In order to successfully cancel the AsyncTask's doInBackground() method you need to periodically check isCancelled. Example...

@Override
protected Void doInBackground(String... params) {

    while (!isCancelled) {
        DoSomething();
    }
}

The problem is if DoSomething() (for example your 'webrequest') is blocking the while loop then isCancelled won't be checked until it completes.