问:
Pure SQL checklist format
I'm not sure if this is possible in SQL

I have the following tables

Below shows the list of all the food

Below shows who bought the items

Basically the user wants to display it as below

I want to use pure SQL because there is a function on my web api service to convert sqldatareader => datatable => CSV. So I don't have to manipulate the data on the api level.

答:
If you are dealing with a fixed list of fruits, then a database-independent solution is conditional aggregation:

```<code>select
    buyer,
    max(case when food = 'apple'  then 'X' end) apple,
    max(case when food = 'banana' then 'X' end) banana,
    max(case when food = 'grapes' then 'X' end) grapes,
    max(case when food = 'lemon'  then 'X' end) lemon
from mytable
group by buyer
order by buyer
</code>```

If the list is not fixed, then you need dynamic SQL. I would not consider that this meets the description of pure SQL that is described in the question.

Title: Pure SQL checklist format

Body:
If you are dealing with a fixed list of fruits, then a database-independent solution is conditional aggregation:

select
    buyer,
    max(case when food = 'apple'  then 'X' end) apple,
    max(case when food = 'banana' then 'X' end) banana,
    max(case when food = 'grapes' then 'X' end) grapes,
    max(case when food = 'lemon'  then 'X' end) lemon
from mytable
group by buyer
order by buyer

If the list is not fixed, then you need dynamic SQL. I would not consider that this meets the description of pure SQL that is described in the question.


来源: stackexchange

问:
Pydicom.read_file is only working with some Dicom images
I am making a python application that can convert a .dcm image to .jpg using the pydicom library. This is my code:

```<code>import pydicom
import cv2
import numpy as np

filename = 'testDicom.dcm'

#get pixel data from image
ds = pydicom.read_file(filename, force=True)
image = ds.pixel_array

new_img = []
max_value = None
min_value = None

#get maximum and minimum pixel values
for i in image:
    for l in i:
        if max_value:
            if l > max_value:
                max_value = l
        else:
            max_value = l

        if min_value:
            if l < min_value:
                min_value = l
        else:
            min_value = l

#use maximum and minimum pixel values to map pixel values between 0 and 255
for i in image:
    row = []
    for pixel in i:
        row.append((pixel - min_value) / (max_value / 255.0))
    new_img.append(row)

#convert to numpy array
new_img = np.array(new_img)

#save image
cv2.imwrite(filename.replace('.dcm', '.jpg'), new_img)
</code>```

I have tested it on two files. The first one,

```<code>https://github.com/MaxwellMarcus/Training-Data-Creator/blob/master/testDicom.dcm
</code>```

worked fine.

The second one,

```<code>https://github.com/MaxwellMarcus/Training-Data-Creator/blob/master/testDicom2.dcm
</code>```

gave an error:

```<code>Traceback (most recent call last):
  File "C:\Users\Max Marcus\github\Training-Data-Creator\creator.py", line 6, in <module>
    image = ds.pixel_array
  File "C:\Python38\lib\site-packages\pydicom\dataset.py", line 1615, in pixel_array
    self.convert_pixel_data()
  File "C:\Python38\lib\site-packages\pydicom\dataset.py", line 1324, in convert_pixel_data
    self._convert_pixel_data_without_handler()
  File "C:\Python38\lib\site-packages\pydicom\dataset.py", line 1409, in _convert_pixel_data_without_handler
    raise RuntimeError(msg + ', '.join(pkg_msg))
RuntimeError: The following handlers are available to decode the pixel data however they are missing required dependencies: GDCM (req. GDCM)
</code>```

Does anybody know why this is happening on only one of the two files, or how to fix it?

答:
Second image is compressed dicom image and pydicom uses different packages such as GDCM and Pillow(for jpg, jpeg) for processing these images.

Installing one of the packages would solve the problem.

ContentLicense: CC BY-SA 4.0

Body:
I am making a python application that can convert a .dcm image to .jpg using the pydicom library. This is my code:

import pydicom
import cv2
import numpy as np

filename = 'testDicom.dcm'

#get pixel data from image
ds = pydicom.read_file(filename, force=True)
image = ds.pixel_array

new_img = []
max_value = None
min_value = None

#get maximum and minimum pixel values
for i in image:
    for l in i:
        if max_value:
            if l > max_value:
                max_value = l
        else:
            max_value = l

        if min_value:
            if l < min_value:
                min_value = l
        else:
            min_value = l

#use maximum and minimum pixel values to map pixel values between 0 and 255
for i in image:
    row = []
    for pixel in i:
        row.append((pixel - min_value) / (max_value / 255.0))
    new_img.append(row)

#convert to numpy array
new_img = np.array(new_img)

#save image
cv2.imwrite(filename.replace('.dcm', '.jpg'), new_img)

I have tested it on two files. The first one,

https://github.com/MaxwellMarcus/Training-Data-Creator/blob/master/testDicom.dcm

worked fine.

The second one,

https://github.com/MaxwellMarcus/Training-Data-Creator/blob/master/testDicom2.dcm

gave an error:

Traceback (most recent call last):
  File "C:\Users\Max Marcus\github\Training-Data-Creator\creator.py", line 6, in <module>
    image = ds.pixel_array
  File "C:\Python38\lib\site-packages\pydicom\dataset.py", line 1615, in pixel_array
    self.convert_pixel_data()
  File "C:\Python38\lib\site-packages\pydicom\dataset.py", line 1324, in convert_pixel_data
    self._convert_pixel_data_without_handler()
  File "C:\Python38\lib\site-packages\pydicom\dataset.py", line 1409, in _convert_pixel_data_without_handler
    raise RuntimeError(msg + ', '.join(pkg_msg))
RuntimeError: The following handlers are available to decode the pixel data however they are missing required dependencies: GDCM (req. GDCM)

Does anybody know why this is happening on only one of the two files, or how to fix it?


问:
Facebook JSON badly encoded
I downloaded my Facebook messenger data (in your Facebook account, go to settings, then to Your Facebook information, then Download your information, then create a file with at least the Messages box checked) to do some cool statistics

However there is a small problem with encoding. I'm not sure, but it looks like Facebook used bad encoding for this data. When I open it with text editor I see something like this: Rados\u00c5\u0082aw. When I try to open it with python (UTF-8) I get RadosÅ\x82aw. However I should get: Radosław.

My python script:

```<code>text = open(os.path.join(subdir, file), encoding='utf-8')
conversations.append(json.load(text))
</code>```

I tried a few most common encodings. Example data is:

```<code>{
  "sender_name": "Rados\u00c5\u0082aw",
  "timestamp": 1524558089,
  "content": "No to trzeba ostatnie treningi zrobi\u00c4\u0087 xD",
  "type": "Generic"
}
</code>```

答:
I would like to extend @Geekmoss' answer with the following recursive code snippet, I used to decode my facebook data.

```<code>import json

def parse_obj(obj):
    if isinstance(obj, str):
        return obj.encode('latin_1').decode('utf-8')

    if isinstance(obj, list):
        return [parse_obj(o) for o in obj]

    if isinstance(obj, dict):
        return {key: parse_obj(item) for key, item in obj.items()}

    return obj

decoded_data = parse_obj(json.loads(file))
</code>```

I noticed this works better, because the facebook data you download might contain list of dicts, in which case those dicts would be just returned 'as is' because of the lambda identity function.

ContentLicense: CC BY-SA 3.0

Title: Facebook JSON badly encoded

Body:
I downloaded my Facebook messenger data (in your Facebook account, go to settings, then to Your Facebook information, then Download your information, then create a file with at least the Messages box checked) to do some cool statistics

However there is a small problem with encoding. I'm not sure, but it looks like Facebook used bad encoding for this data. When I open it with text editor I see something like this: Rados\u00c5\u0082aw. When I try to open it with python (UTF-8) I get RadosÅ\x82aw. However I should get: Radosław.

My python script:

text = open(os.path.join(subdir, file), encoding='utf-8')
conversations.append(json.load(text))

I tried a few most common encodings. Example data is:

{
  "sender_name": "Rados\u00c5\u0082aw",
  "timestamp": 1524558089,
  "content": "No to trzeba ostatnie treningi zrobi\u00c4\u0087 xD",
  "type": "Generic"
}

Body:
I would like to extend @Geekmoss' answer with the following recursive code snippet, I used to decode my facebook data.

import json

def parse_obj(obj):
    if isinstance(obj, str):
        return obj.encode('latin_1').decode('utf-8')

    if isinstance(obj, list):
        return [parse_obj(o) for o in obj]

    if isinstance(obj, dict):
        return {key: parse_obj(item) for key, item in obj.items()}

    return obj

decoded_data = parse_obj(json.loads(file))

I noticed this works better, because the facebook data you download might contain list of dicts, in which case those dicts would be just returned 'as is' because of the lambda identity function.


问:
iterating value over java 8
I have the following code in Java 8

```<code>List<CategoryTranslation> categoriesTranslation = categoriesRepository.findByLanguageId(languageId);
List<CategoryDTO> categoryList = categoriesTranslation
.stream()
.map(x -> categoriesAdapter.category2DTO(x))
.collect(Collectors.toList());
</code>```

This works correctly , but I need to convert like this.

```<code>   List<CategoryTranslation> categoriesTranslation = categoriesRepository.findByLanguageId(languageId);
    List<CategoryDTO> categoryList = new ArrayList<CategoryDTO>();
   for (CategoryTranslation categoryTranslation : categoriesTranslation) {
                    CategoryDTO categoryDTO = categoriesAdapter.category2DTO(categoryTranslation);
                    categoryDTO.setTotal(categoryRepository.countTotalArticlesByCategory(categoryDTO.getCategoryId(), languageId));
                    categoryList.add(categoryDTO);
                }
</code>```

I know that I could use the adapter but I don't like to use a JPA in Adapter.

答:
Just create a method categorty2DTOWithTotal(CategoryTranslation ct, Long? languiageId).
Otherwise you'd have to call forEach, but it's a terminating method so you couldn't group it into a list. In theory if setting total would result in sensible mapping, you could introduce a method which does that, but here it seems like a bit of a stretch.

```<code>void aMethod(Long? languageId) {
    List<CategoryTranslation> categoriesTranslation = categoriesRepository
        .findByLanguageId(languageId);
    List<CategoryDTO> categoryList = categoriesTranslation
        .stream()
        .map(x -> category2DTOWithTotal(x, languageId))
        .collect(Collectors.toList());
}

CategoryDTO category2DTOWithTotal(CategoryTranslation ct, Long? languageId) {
    CategoryDTO categoryDTO = categoriesAdapter.category2DTO(categoryTranslation);
    categoryDTO.setTotal(
        categoryRepository.countTotalArticlesByCategory(
            categoryDTO.getCategoryId(), languageId
        )
    );
    return categoryDTO;
}
</code>```

Or, you could set total later:

```<code>void aMethod(Long? languageId) {
    List<CategoryDTO> categoryList = categoriesTranslation
        .stream()
        .map(categoriesAdapter::category2DTO)
        .collect(Collectors.toList());

    categoryList.forEach(dto -> dto.setTotal(
        categoryRepository.countTotalArticlesByCategory(
            categoryDTO.getCategoryId(), languageId
        )
    );
}
</code>```

And for completeness, a mappable version of setting total:

```<code>void aMethod(Long? languageId) {
    List<CategoryTranslation> categoriesTranslation = categoriesRepository
        .findByLanguageId(languageId);
    List<CategoryDTO> categoryList = categoriesTranslation
        .stream()
        .map(categoriesAdapter::category2DTO)
        .map(x -> setTotal(x, languageId))
        .collect(Collectors.toList());
}

CategoryDTO setTotal(CategoryDTO ctd, Long? languageId) {
    ctd.setTotal(
        categoryRepository.countTotalArticlesByCategory(ctd.getCategoryId(), languageId)
    );
    return ctd;
}
</code>```

Title: iterating value over java 8

Body:
I have the following code in Java 8

List<CategoryTranslation> categoriesTranslation = categoriesRepository.findByLanguageId(languageId);
List<CategoryDTO> categoryList = categoriesTranslation
.stream()
.map(x -> categoriesAdapter.category2DTO(x))
.collect(Collectors.toList());

This works correctly , but I need to convert like this.

   List<CategoryTranslation> categoriesTranslation = categoriesRepository.findByLanguageId(languageId);
    List<CategoryDTO> categoryList = new ArrayList<CategoryDTO>();
   for (CategoryTranslation categoryTranslation : categoriesTranslation) {
                    CategoryDTO categoryDTO = categoriesAdapter.category2DTO(categoryTranslation);
                    categoryDTO.setTotal(categoryRepository.countTotalArticlesByCategory(categoryDTO.getCategoryId(), languageId));
                    categoryList.add(categoryDTO);
                }

I know that I could use the adapter but I don't like to use a JPA in Adapter.

Body:
Just create a method categorty2DTOWithTotal(CategoryTranslation ct, Long? languiageId).
Otherwise you'd have to call forEach, but it's a terminating method so you couldn't group it into a list. In theory if setting total would result in sensible mapping, you could introduce a method which does that, but here it seems like a bit of a stretch.

void aMethod(Long? languageId) {
    List<CategoryTranslation> categoriesTranslation = categoriesRepository
        .findByLanguageId(languageId);
    List<CategoryDTO> categoryList = categoriesTranslation
        .stream()
        .map(x -> category2DTOWithTotal(x, languageId))
        .collect(Collectors.toList());
}

CategoryDTO category2DTOWithTotal(CategoryTranslation ct, Long? languageId) {
    CategoryDTO categoryDTO = categoriesAdapter.category2DTO(categoryTranslation);
    categoryDTO.setTotal(
        categoryRepository.countTotalArticlesByCategory(
            categoryDTO.getCategoryId(), languageId
        )
    );
    return categoryDTO;
}

Or, you could set total later:

void aMethod(Long? languageId) {
    List<CategoryDTO> categoryList = categoriesTranslation
        .stream()
        .map(categoriesAdapter::category2DTO)
        .collect(Collectors.toList());

    categoryList.forEach(dto -> dto.setTotal(
        categoryRepository.countTotalArticlesByCategory(
            categoryDTO.getCategoryId(), languageId
        )
    );
}

And for completeness, a mappable version of setting total:

void aMethod(Long? languageId) {
    List<CategoryTranslation> categoriesTranslation = categoriesRepository
        .findByLanguageId(languageId);
    List<CategoryDTO> categoryList = categoriesTranslation
        .stream()
        .map(categoriesAdapter::category2DTO)
        .map(x -> setTotal(x, languageId))
        .collect(Collectors.toList());
}

CategoryDTO setTotal(CategoryDTO ctd, Long? languageId) {
    ctd.setTotal(
        categoryRepository.countTotalArticlesByCategory(ctd.getCategoryId(), languageId)
    );
    return ctd;
}


问:
Cannot load webUI correctly
I could get the page on localhost:8089 but not the style.css .These are the results from firefox and chrome:

Firefox:

```<code>GET http://localhost:8089/static/style.css?v=1.0   [HTTP/1.1 200 OK 17ms]
The stylesheet http://localhost:8089/static/style.css?v=1.0 was not loaded because its MIME type, “application/x-css”, is not “text/css”.
</code>```

Chrome:

```<code>localhost/:5 Resource interpreted as Stylesheet but transferred with MIME type application/x-css: "http://localhost:8089/static/style.css?v=1.0".
</code>```

How to make the web normal? pls help.

答:
Is it possible you are encountering the same problem mentioned here?

https://community.grafana.com/t/grafana-start-but-stylesheets-not-displayed/3250/11

Specifically check your registry (https://gogs.io/docs/intro/troubleshooting#windows):

Error: Resource interpreted as Stylesheet but transferred with MIME type application/x-css

Causes: wrong value in the Windows registry

Solution: Find .css in HKEY_CLASSES_ROOT in registry and change its Content Type to text/css.

Title: Cannot load webUI correctly

Body:
I could get the page on localhost:8089 but not the style.css .These are the results from firefox and chrome:

Firefox:

GET http://localhost:8089/static/style.css?v=1.0   [HTTP/1.1 200 OK 17ms]
The stylesheet http://localhost:8089/static/style.css?v=1.0 was not loaded because its MIME type, “application/x-css”, is not “text/css”.

Chrome:

localhost/:5 Resource interpreted as Stylesheet but transferred with MIME type application/x-css: "http://localhost:8089/static/style.css?v=1.0".

How to make the web normal? pls help.


问:
Splitting strings in half, python
I have this string my_string = '717460881855742062' how can I split it in half? The string is auto-generated so just splitting by the 1 won't work

答:
Something like this should do the job:

```<code>my_string = '717460881855742062'

length = int(len(my_string) / 2)
first_part = my_string[:length]
second_part = my_string[length:]

print(first_part)
print(second_part)
</code>```

output:

717460881

855742062

You can modify it and make sure you take also handle the situation
where the length%2 is not 0.

Title: Splitting strings in half, python

Body:
Something like this should do the job:

my_string = '717460881855742062'

length = int(len(my_string) / 2)
first_part = my_string[:length]
second_part = my_string[length:]

print(first_part)
print(second_part)

output:

717460881

855742062

You can modify it and make sure you take also handle the situation
where the length%2 is not 0.


问:
Format ldap result into json
I need to convert ldap result into json. i have been trying for hours and I did not find any solution.

search_filter = "CN=My Name"
attrs = ['givenName', 'sn', 'thumbnail_pic', 'phone', 'mail']
result = connect.search_s(base_dn, ldap.SCOPE_SUBTREE, search_filter, attrs)
```

<p>I have this output:</p>

<pre class="lang-py prettyprint-override"><code>('CN=My Name,OU=City,OU=Company,DC=com,DC=lan', {'sn': [b'Name'], 'givenName': [b'My'], 'phone': [b'+111 111 111 111'], 'mail': [b'My.Name@company.com'], 'thumbnail_pic': [b'binary data of picture']})
</code>```

And I want to convert it into this pretty json

```<code>[
            {
                "first_name": "My",
                "last_name": "Name",
                "picture": "binary data of picture",
                "phone_number": "+111 111 111 111",
                "email": "My.Name@company.com",
            }
]
</code>```

I am desperate for help since I think I tried almost everything... Any ideas please?

答:
Try to use simplejson. This library can handle bytes strings very well.

pip3 install simplejson
```

<p>Sample usage:</p>

<pre class="lang-py prettyprint-override"><code>import simplejson

ldap_result = ('CN=My Name,OU=City,OU=Company,DC=com,DC=lan', {'sn': [b'Name'], 'givenName': [b'My'], 'phone': [b'+111 111 111 111'], 'mail': [b'My.Name@company.com'], 'thumbnail_pic': [b'binary data of picture']})

print(simplejson.dumps(ldap_result[0][1]))

</code>```

Title: Format ldap result into json

Body:
I need to convert ldap result into json. i have been trying for hours and I did not find any solution.

search_filter = "CN=My Name"
attrs = ['givenName', 'sn', 'thumbnail_pic', 'phone', 'mail']
result = connect.search_s(base_dn, ldap.SCOPE_SUBTREE, search_filter, attrs)

I have this output:

('CN=My Name,OU=City,OU=Company,DC=com,DC=lan', {'sn': [b'Name'], 'givenName': [b'My'], 'phone': [b'+111 111 111 111'], 'mail': [b'My.Name@company.com'], 'thumbnail_pic': [b'binary data of picture']})

And I want to convert it into this pretty json

[
            {
                "first_name": "My",
                "last_name": "Name",
                "picture": "binary data of picture",
                "phone_number": "+111 111 111 111",
                "email": "My.Name@company.com",
            }
]

I am desperate for help since I think I tried almost everything... Any ideas please?

Body:
Try to use simplejson. This library can handle bytes strings very well.

pip3 install simplejson

Sample usage:

import simplejson

ldap_result = ('CN=My Name,OU=City,OU=Company,DC=com,DC=lan', {'sn': [b'Name'], 'givenName': [b'My'], 'phone': [b'+111 111 111 111'], 'mail': [b'My.Name@company.com'], 'thumbnail_pic': [b'binary data of picture']})

print(simplejson.dumps(ldap_result[0][1]))


问:
How to enable web services on moodle?
I have configured moodle on local host and I am trying to generate the token for authentication.

I have already followed these steps :

==  Configuring Moodle for using the application ==

Administration -> Plugins -> Web Services -> External Services -> Enable mobile web service

Administration -> Plugins -> Web Services -> Protocols -> Enable REST

Administration -> Users -> Permission -> Define roles -> Edit the Authenticated user role -> Allow webservice/rest:use

Administration -> Security  -> Site policies -> Change the server upload limit. It can't be Server limit. There is a bug in Moodle Web Services

URL :- http://localhost/moodle/login/token.php?username=admin&password=Turbo@000&service=local_mobile

```<code>Response :-
{
    "error": "Web service is not available (it doesn't exist or might be disabled)",
    "stacktrace": null,
    "debuginfo": null,
    "reproductionlink": null
}
</code>```

答:
check the short name of the service, you can find it here:  Site administration -> Plugins -> Web services -> External services
Click edit for the target service and make sure that it's enabled and the name you use is correct

Title: How to enable web services on moodle?

Body:
I have configured moodle on local host and I am trying to generate the token for authentication.

I have already followed these steps :

==  Configuring Moodle for using the application ==

Administration -> Plugins -> Web Services -> External Services -> Enable mobile web service

Administration -> Plugins -> Web Services -> Protocols -> Enable REST

Administration -> Users -> Permission -> Define roles -> Edit the Authenticated user role -> Allow webservice/rest:use

Administration -> Security  -> Site policies -> Change the server upload limit. It can't be Server limit. There is a bug in Moodle Web Services

URL :- http://localhost/moodle/login/token.php?username=admin&password=Turbo@000&service=local_mobile

Response :-
{
    "error": "Web service is not available (it doesn't exist or might be disabled)",
    "stacktrace": null,
    "debuginfo": null,
    "reproductionlink": null
}


问:
Google OAuth - Where to Store Client ID
I followed this link to allow my users to authenticate via google:

https://dev.to/jorgecf/integrating-google-authentication-with-your-angular-app-4j2a

However, I have to have my Google Client ID in my UI code:

```<code>return pload.then(async () => {
  await gapi.auth2
    .init({ client_id: 'abc123' })  // Put my client ID here. How should I store this?
    .then(auth => {
      this.gapiSetup = true;
      this.authInstance = auth;
    });
});
</code>```

Is that a security issue? If so, where/how would I store that?

答:
The option I've always used is to deploy a configuration file with your web static content, and include Public Open Id Connect Settings in it.

Here is an example configuration file from a code sample of mine. Of course, there is no way anyone can get tokens based on this information - you need valid credentials in addition.

Often components such as UIs and APIs are pushed down a pipeline:

DEV

QA

STAGING

PRODUCTION

Your continuous delivery process can deal with delivering different settings to each stage of the pipeline. Your code is then clean and never includes any hard coded values.

Title: Google OAuth - Where to Store Client ID

Body:
I followed this link to allow my users to authenticate via google:

https://dev.to/jorgecf/integrating-google-authentication-with-your-angular-app-4j2a

However, I have to have my Google Client ID in my UI code:

return pload.then(async () => {
  await gapi.auth2
    .init({ client_id: 'abc123' })  // Put my client ID here. How should I store this?
    .then(auth => {
      this.gapiSetup = true;
      this.authInstance = auth;
    });
});

Is that a security issue? If so, where/how would I store that?


问:
Recursively compare two directories to ensure they have the same files and subdirectories
From what I observe filecmp.dircmp is recursive, but inadequate for my needs, at least in py2.  I want to compare two directories and all their contained files.  Does this exist, or do I need to build (using os.walk, for example).  I prefer pre-built, where someone else has already done the unit-testing :)

The actual 'comparison' can be sloppy (ignore permissions, for example), if that helps.

I would like something boolean, and report_full_closure is a printed report.  It also only goes down common subdirs.  AFIAC, if they have anything in the left or right dir only those are different dirs.  I build this using os.walk instead.

答:
Since a True or False result is all you want, if you have diff installed:

```<code>def are_dir_trees_equal(dir1, dir2):
    process = Popen(["diff", "-r", dir1, dir2], stdout=PIPE)
    exit_code = process.wait()
    return not exit_code
</code>```

Body:
Since a True or False result is all you want, if you have diff installed:

def are_dir_trees_equal(dir1, dir2):
    process = Popen(["diff", "-r", dir1, dir2], stdout=PIPE)
    exit_code = process.wait()
    return not exit_code


问:
mySQL Nested Query Syntax
I am trying to use a nested query approach to build a query-on-query for my mySQL database and failing to correctly generate output.  I am able to import my table into Microsoft Access and build Query1 and then build Query2 on Query1 to get the correct output I'm looking for so I feel like I'm close, I just can't get the right syntax to get the output I'm looking for using a mySQL query approach.

Query1, here is the SQL statement from Access for Query1.

```<code>SELECT DISTINCT MediaBuys.DistrictID, MediaBuys.SpenderID, MediaBuys.PG, MediaBuys.SupportType, MediaBuys.PriSupportType
FROM MediaBuys
WHERE MediaBuys.PG ="P";
</code>```

Query2, if I have built Query1 in Access as above and I run this SQL statement in Access as a separate query built on the first I can generate the output I'm looking for.

```<code>SELECT Query1.DistrictID, Query1.SpenderID, Query1.PG, Query1.SupportType, Query1.PriSupportType, Count(Query1.SupportType) AS CountOfSupportType
FROM Query1 INNER JOIN Query1 AS Query1_1 ON Query1.PG = Query1_1.PG AND Query1.SpenderID = Query1_1.SpenderID AND Query1.DistrictID = Query1_1.DistrictID
GROUP BY Query1.DistrictID, Query1.SpenderID, Query1.PG, Query1.SupportType, Query1.PriSupportType
HAVING Count(Query1.SupportType) > 1;
</code>```

I'd like to be able to produce the same output from a query in mySQL.  Since I have the SQL statements of these two queries I feel like this should be doable, I've attempted to build a nested query in a number of different ways and each attempt fails, it seems I can't put together the correct syntax.  The most common error I receive is "Error Code: 1146. Table 'Query1' doesn't exist".

Is this doable in mySQL and if so can anyone help me with the correct syntax?

答:
Just like you created the query Query1 in Access, create a view View1 in MySql:

```<code>CREATE VIEW View1 AS
SELECT DISTINCT DistrictID, SpenderID, PG, SupportType, PriSupportType
FROM MediaBuys
WHERE PG ='P';
</code>```

and your query will be:

```<code>SELECT
  View1.DistrictID, View1.SpenderID, View1.PG, View1.SupportType, View1.PriSupportType,
  Count(View1.SupportType) AS CountOfSupportType
FROM View1 INNER JOIN View1 AS View1_1
ON View1.PG = View1_1.PG AND View1.SpenderID = View1_1.SpenderID
AND View1.DistrictID = View1_1.DistrictID
GROUP BY View1.DistrictID, View1.SpenderID, View1.PG, View1.SupportType, View1.PriSupportType
HAVING Count(View1.SupportType) > 1;
</code>```

Title: mySQL Nested Query Syntax

Body:
I am trying to use a nested query approach to build a query-on-query for my mySQL database and failing to correctly generate output.  I am able to import my table into Microsoft Access and build Query1 and then build Query2 on Query1 to get the correct output I'm looking for so I feel like I'm close, I just can't get the right syntax to get the output I'm looking for using a mySQL query approach.

Query1, here is the SQL statement from Access for Query1.

SELECT DISTINCT MediaBuys.DistrictID, MediaBuys.SpenderID, MediaBuys.PG, MediaBuys.SupportType, MediaBuys.PriSupportType
FROM MediaBuys
WHERE MediaBuys.PG ="P";

Query2, if I have built Query1 in Access as above and I run this SQL statement in Access as a separate query built on the first I can generate the output I'm looking for.

SELECT Query1.DistrictID, Query1.SpenderID, Query1.PG, Query1.SupportType, Query1.PriSupportType, Count(Query1.SupportType) AS CountOfSupportType
FROM Query1 INNER JOIN Query1 AS Query1_1 ON Query1.PG = Query1_1.PG AND Query1.SpenderID = Query1_1.SpenderID AND Query1.DistrictID = Query1_1.DistrictID
GROUP BY Query1.DistrictID, Query1.SpenderID, Query1.PG, Query1.SupportType, Query1.PriSupportType
HAVING Count(Query1.SupportType) > 1;

I'd like to be able to produce the same output from a query in mySQL.  Since I have the SQL statements of these two queries I feel like this should be doable, I've attempted to build a nested query in a number of different ways and each attempt fails, it seems I can't put together the correct syntax.  The most common error I receive is "Error Code: 1146. Table 'Query1' doesn't exist".

Is this doable in mySQL and if so can anyone help me with the correct syntax?

Body:
Just like you created the query Query1 in Access, create a view View1 in MySql:

CREATE VIEW View1 AS
SELECT DISTINCT DistrictID, SpenderID, PG, SupportType, PriSupportType
FROM MediaBuys
WHERE PG ='P';

and your query will be:

SELECT
  View1.DistrictID, View1.SpenderID, View1.PG, View1.SupportType, View1.PriSupportType,
  Count(View1.SupportType) AS CountOfSupportType
FROM View1 INNER JOIN View1 AS View1_1
ON View1.PG = View1_1.PG AND View1.SpenderID = View1_1.SpenderID
AND View1.DistrictID = View1_1.DistrictID
GROUP BY View1.DistrictID, View1.SpenderID, View1.PG, View1.SupportType, View1.PriSupportType
HAVING Count(View1.SupportType) > 1;


问:
Reactive extensions delayed initialization
It's fairly established that doing work in ctors for types that are resolved using SimpleInjector is bad practice. Although this often leads to certain late initializations of such types, a particularly interesting case is Reactive Extensions subscriptions.

Take for instance an observable sequence that exhibits Replay(1) semantics (actually BehaviorSubject if we take the StartWith into account), e.g.

```<code>private readonly IObservable<Value> _myObservable;

public MyType(IService service)
{
    _myObservable = service.OtherObservable
        .StartWith(service.Value)
        .Select(x => SomeTransform())
        .Replay(1)
        .RefCount();
}

public IObservable<Value> MyObservable => _myObservable;
</code>```

Assume now, that SomeTransform is computationally expensive. From the point of view of SimpleInjector, the above is bad practice. Ok, so we need some kind of Initialize() method to call after SimpleInjector is finished. But what about our replay semantics and our StartWith()? Our consumers expect a value when they Subscribe (assume now that this is guaranteed to happen after initialization)!

How do we get around these restrictions in a nice way while still satisfying SimpleInjector? Here's a summary of requirements:

Don't do extensive work in the ctor (i.e. SomeTransform) should not run

_myObservable should be readonly

MyObservable should exhibit Replay(1) semantics

We should always have an initial value (hence the StartWith)

We do not want to Subscribe inside MyType and cache the value (we like immutability)

I experimented with creating an additional observable that starts with false and then gets set to true on initialize, and then merging that together with _myObservable, but couldn't quite get it to work. Additionally, it doesn't seem like the best solution. In essence, all I want to do is delay until Initialize() is done. There must be some way to do this that I'm not seeing?

答:
One easy solution that comes to mind is the use of Lazy<T>

This could look like:

```<code>private readonly Lazy<IObservable<Value>> _lazyMyObservable;

public MyType(IService service)
{
    _lazyMyObservable =  new Lazy<IObservable<Value>>(() => this.InitObservable(service));
}

private IObservable<Value> InitObservable(IService service)
{
    return service.OtherObservable
        .StartWith(service.Value)
        .Select(x => SomeTransform())
        .Replay(1)
        .RefCount();
 }

 public IObservable<Value> MyObservable => _lazyMyObservable.Value;
</code>```

This will init the variable _lazyMyObservable without actually calling SomeTransform(). When a consumer asks for MyType.MyObservable the InitObservable code will be called one time and one time only. This postpones the initialization to the point where the code is actually used.

This will keep your constructor nice and clean and has no need to add initialization logic.

Note that the ctor of the Lazy<T> has several overloads that you can use if you may have issues with multithreading.

Body:
It's fairly established that doing work in ctors for types that are resolved using SimpleInjector is bad practice. Although this often leads to certain late initializations of such types, a particularly interesting case is Reactive Extensions subscriptions.

Take for instance an observable sequence that exhibits Replay(1) semantics (actually BehaviorSubject if we take the StartWith into account), e.g.

private readonly IObservable<Value> _myObservable;

public MyType(IService service)
{
    _myObservable = service.OtherObservable
        .StartWith(service.Value)
        .Select(x => SomeTransform())
        .Replay(1)
        .RefCount();
}

public IObservable<Value> MyObservable => _myObservable;

Assume now, that SomeTransform is computationally expensive. From the point of view of SimpleInjector, the above is bad practice. Ok, so we need some kind of Initialize() method to call after SimpleInjector is finished. But what about our replay semantics and our StartWith()? Our consumers expect a value when they Subscribe (assume now that this is guaranteed to happen after initialization)!

How do we get around these restrictions in a nice way while still satisfying SimpleInjector? Here's a summary of requirements:

Don't do extensive work in the ctor (i.e. SomeTransform) should not run

_myObservable should be readonly

MyObservable should exhibit Replay(1) semantics

We should always have an initial value (hence the StartWith)

We do not want to Subscribe inside MyType and cache the value (we like immutability)

I experimented with creating an additional observable that starts with false and then gets set to true on initialize, and then merging that together with _myObservable, but couldn't quite get it to work. Additionally, it doesn't seem like the best solution. In essence, all I want to do is delay until Initialize() is done. There must be some way to do this that I'm not seeing?

Body:
One easy solution that comes to mind is the use of Lazy<T>

This could look like:

private readonly Lazy<IObservable<Value>> _lazyMyObservable;

public MyType(IService service)
{
    _lazyMyObservable =  new Lazy<IObservable<Value>>(() => this.InitObservable(service));
}

private IObservable<Value> InitObservable(IService service)
{
    return service.OtherObservable
        .StartWith(service.Value)
        .Select(x => SomeTransform())
        .Replay(1)
        .RefCount();
 }

 public IObservable<Value> MyObservable => _lazyMyObservable.Value;

This will init the variable _lazyMyObservable without actually calling SomeTransform(). When a consumer asks for MyType.MyObservable the InitObservable code will be called one time and one time only. This postpones the initialization to the point where the code is actually used.

This will keep your constructor nice and clean and has no need to add initialization logic.

Note that the ctor of the Lazy<T> has several overloads that you can use if you may have issues with multithreading.


问:
AWS elastic beanstalk deploy always fails (uploading a zipfile)
I upload a new version of my app as a zipfile and click deploy. Then the status changes to severe.

This is the error trace:

```<code>WARN
Environment health has transitioned from Info to Degraded. Command failed on all instances. Incorrect application version found on all instances. Expected version "Sample" (deployment 2). Application update failed 10 seconds ago and took 4 minutes.

ERROR
During an aborted deployment, some instances may have deployed the new application version. To ensure all instances are running the same version, re-deploy the appropriate application version.

ERROR
Failed to deploy application.

ERROR
Unsuccessful command execution on instance id(s) 'i------'. Aborting the operation.

ERROR
[Instance: i-002326d7ceeba0ea9] Command failed on instance. Return code:
1 Output: nginx: [emerg] no host in upstream ":80" in /etc/nginx/conf.d/elasticbeanstalk-nginx-docker-upstream.conf:
2 nginx: configuration file /etc/nginx/nginx.conf test failed Failed to start nginx, abort deployment.
Hook /opt/elasticbeanstalk/hooks/appdeploy/enact/01flip.sh failed.
For more detail, check /var/log/eb-activity.log using console or EB CLI.

ERROR
Failed to start nginx, abort deployment
</code>```

/var/log/eb-activity.log
here are errors in this log:

```<code>[0mInstalling dependencies from Pipfile.lock (5e00f3)â€¦
  Failed to load paths: /bin/sh: 1: /root/.local/share/virtualenvs/app-lp47FrbD/bin/python: not found
...
[2020-05-29T01:51:24.746Z] INFO  [11395] - [Application update v1.3.3-1@3/AppDeployStage1/AppDeployEnactHook/00run.sh] : Completed activity. Result:
  jq: error (at <stdin>:1): Cannot iterate over null (null)
  a2f568b1c255eb9e0fdc6ceebdd29b9ec64b9ab4481a3e1c5bcb11828b0ac526
[2020-05-29T01:51:24.747Z] INFO  [11395] - [Application update v1.3.3-1@3/AppDeployStage1/AppDeployEnactHook/01flip.sh] : Starting activity...
[2020-05-29T01:51:26.099Z] INFO  [11395] - [Application update v1.3.3-1@3/AppDeployStage1/AppDeployEnactHook/01flip.sh] : Activity execution failed, because: nginx: [emerg] no host in upstream ":80" in /etc/nginx/conf.d/elasticbeanstalk-nginx-docker-upstream.conf:2
  nginx: configuration file /etc/nginx/nginx.conf test failed
  Failed to start nginx, abort deployment (ElasticBeanstalk::ExternalInvocationError)
caused by: nginx: [emerg] no host in upstream ":80" in /etc/nginx/conf.d/elasticbeanstalk-nginx-docker-upstream.conf:2
  nginx: configuration file /etc/nginx/nginx.conf test failed
  Failed to start nginx, abort deployment (Executor::NonZeroExitStatus)
...
[2020-05-29T01:51:26.099Z] INFO  [11395] - [Application update v1.3.3-1@3/AppDeployStage1/AppDeployEnactHook/01flip.sh] : Activity failed.
[2020-05-29T01:51:26.099Z] INFO  [11395] - [Application update v1.3.3-1@3/AppDeployStage1/AppDeployEnactHook] : Activity failed.
[2020-05-29T01:51:26.099Z] INFO  [11395] - [Application update v1.3.3-1@3/AppDeployStage1] : Activity failed.
[2020-05-29T01:51:26.100Z] INFO  [11395] - [Application update v1.3.3-1@3] : Completed activity. Result:
  Application update - Command CMD-AppDeploy failed
</code>```

The inability to deploy has been consistent for this environment, after several attempts, even reverting to an older version.

答:
Afterwards, I resolved this by isolating the code and error messages using a local docker image with the zipfile. Running the code on my machine outside of docker did NOT reveal any problems, because the pip / pipenv part was missing some depdendency.

Steps for local docker testing:

WITHIN a docker container:

```<code>docker system prune
</code>```

Go to the folder with Dockerfile

```<code>docker image build -t <app_name>:<version_number> .
</code>```

TO run locally:
   (docker rm <app_name> first, if you've already got a stopped container with the same name from prior testing)

```<code>docker container run --publish 80:80 --name <app_name> myapp:1.0
</code>```

NOTE:
    this won't let you test AWS functions that require environment variables, such as ~.aws credentials because they're not inside the image.
        (but you could add them with your Dockerfile)

Once the docker container is running, you'll see (I saw) error messages that were not there when testing locally, because they were caused by a missing package dependency and a pipenv error.

Body:
I upload a new version of my app as a zipfile and click deploy. Then the status changes to severe.

This is the error trace:

WARN
Environment health has transitioned from Info to Degraded. Command failed on all instances. Incorrect application version found on all instances. Expected version "Sample" (deployment 2). Application update failed 10 seconds ago and took 4 minutes.

ERROR
During an aborted deployment, some instances may have deployed the new application version. To ensure all instances are running the same version, re-deploy the appropriate application version.

ERROR
Failed to deploy application.

ERROR
Unsuccessful command execution on instance id(s) 'i------'. Aborting the operation.

ERROR
[Instance: i-002326d7ceeba0ea9] Command failed on instance. Return code:
1 Output: nginx: [emerg] no host in upstream ":80" in /etc/nginx/conf.d/elasticbeanstalk-nginx-docker-upstream.conf:
2 nginx: configuration file /etc/nginx/nginx.conf test failed Failed to start nginx, abort deployment.
Hook /opt/elasticbeanstalk/hooks/appdeploy/enact/01flip.sh failed.
For more detail, check /var/log/eb-activity.log using console or EB CLI.

ERROR
Failed to start nginx, abort deployment

/var/log/eb-activity.log
here are errors in this log:

[0mInstalling dependencies from Pipfile.lock (5e00f3)â€¦
  Failed to load paths: /bin/sh: 1: /root/.local/share/virtualenvs/app-lp47FrbD/bin/python: not found
...
[2020-05-29T01:51:24.746Z] INFO  [11395] - [Application update v1.3.3-1@3/AppDeployStage1/AppDeployEnactHook/00run.sh] : Completed activity. Result:
  jq: error (at <stdin>:1): Cannot iterate over null (null)
  a2f568b1c255eb9e0fdc6ceebdd29b9ec64b9ab4481a3e1c5bcb11828b0ac526
[2020-05-29T01:51:24.747Z] INFO  [11395] - [Application update v1.3.3-1@3/AppDeployStage1/AppDeployEnactHook/01flip.sh] : Starting activity...
[2020-05-29T01:51:26.099Z] INFO  [11395] - [Application update v1.3.3-1@3/AppDeployStage1/AppDeployEnactHook/01flip.sh] : Activity execution failed, because: nginx: [emerg] no host in upstream ":80" in /etc/nginx/conf.d/elasticbeanstalk-nginx-docker-upstream.conf:2
  nginx: configuration file /etc/nginx/nginx.conf test failed
  Failed to start nginx, abort deployment (ElasticBeanstalk::ExternalInvocationError)
caused by: nginx: [emerg] no host in upstream ":80" in /etc/nginx/conf.d/elasticbeanstalk-nginx-docker-upstream.conf:2
  nginx: configuration file /etc/nginx/nginx.conf test failed
  Failed to start nginx, abort deployment (Executor::NonZeroExitStatus)
...
[2020-05-29T01:51:26.099Z] INFO  [11395] - [Application update v1.3.3-1@3/AppDeployStage1/AppDeployEnactHook/01flip.sh] : Activity failed.
[2020-05-29T01:51:26.099Z] INFO  [11395] - [Application update v1.3.3-1@3/AppDeployStage1/AppDeployEnactHook] : Activity failed.
[2020-05-29T01:51:26.099Z] INFO  [11395] - [Application update v1.3.3-1@3/AppDeployStage1] : Activity failed.
[2020-05-29T01:51:26.100Z] INFO  [11395] - [Application update v1.3.3-1@3] : Completed activity. Result:
  Application update - Command CMD-AppDeploy failed

The inability to deploy has been consistent for this environment, after several attempts, even reverting to an older version.

Body:
Afterwards, I resolved this by isolating the code and error messages using a local docker image with the zipfile. Running the code on my machine outside of docker did NOT reveal any problems, because the pip / pipenv part was missing some depdendency.

Steps for local docker testing:

WITHIN a docker container:

docker system prune

Go to the folder with Dockerfile

docker image build -t <app_name>:<version_number> .

TO run locally:
   (docker rm <app_name> first, if you've already got a stopped container with the same name from prior testing)

docker container run --publish 80:80 --name <app_name> myapp:1.0

NOTE:
    this won't let you test AWS functions that require environment variables, such as ~.aws credentials because they're not inside the image.
        (but you could add them with your Dockerfile)

Once the docker container is running, you'll see (I saw) error messages that were not there when testing locally, because they were caused by a missing package dependency and a pipenv error.


问:
MessageKit set up MessageLabelDelegate for didSelectURL
I'm trying to open url from messages embedded in an NSAttributedString. I'm using the latest version of MessageKit. I'm using the function didSelectURL, but it doesn't seem to reach that part of the code. I came across this solution, but I wanted to follow up with regards to how to set up MessageLabelDelegate. Just like in the linked solution, I have implemented the delegate methods detectorAttributes and enabledDetectors.

I currently have MessageLabelDelegate set up as an extension to my ViewController, but it never seems to reach those methods.

```<code>extension ChatViewController:MessageLabelDelegate {

func didSelectURL(_url: URL) {
// .. open URL
}

}
</code>```

It seems to be getting overwritten by the method didTapMessage in the MessageCellDelegate extension. I tried going through the example code in the MessageKit repo, but still unclear as to how it's meant to be set up or what I'm doing wrong.

UPDATE: The problem was the way I was declaring the NSAttributedString. I was setting its value as a string instead of a URL.

答:
The MessageCellDelegate implements the the MessageLabelDelegate so you need to make sure that the messagesCollectionView.messageCellDelegate is set to the ChatViewController and that the ChatViewController has an extension for MessageCellDelegate where you can put your didSelectURL</p>

```<code>public protocol MessageCellDelegate: MessageLabelDelegate {
</code>```

Body:
I'm trying to open url from messages embedded in an NSAttributedString. I'm using the latest version of MessageKit. I'm using the function didSelectURL, but it doesn't seem to reach that part of the code. I came across this solution, but I wanted to follow up with regards to how to set up MessageLabelDelegate. Just like in the linked solution, I have implemented the delegate methods detectorAttributes and enabledDetectors.

I currently have MessageLabelDelegate set up as an extension to my ViewController, but it never seems to reach those methods.

extension ChatViewController:MessageLabelDelegate {

func didSelectURL(_url: URL) {
// .. open URL
}

}

It seems to be getting overwritten by the method didTapMessage in the MessageCellDelegate extension. I tried going through the example code in the MessageKit repo, but still unclear as to how it's meant to be set up or what I'm doing wrong.

UPDATE: The problem was the way I was declaring the NSAttributedString. I was setting its value as a string instead of a URL.

Body:
The MessageCellDelegate implements the the MessageLabelDelegate so you need to make sure that the messagesCollectionView.messageCellDelegate is set to the ChatViewController and that the ChatViewController has an extension for MessageCellDelegate where you can put your didSelectURL

public protocol MessageCellDelegate: MessageLabelDelegate {


问:
Regex to match LEGAL UK Number Plate
i have been working on matching a legal uk number plate with the following regex expression , however this only matches new number plates like JS07 ZAS not the old J62 LNX format, i need a expression to match both and i cant work out how to match both type of plates.

var plateregex = "([A-HJ-PR-Y]{2}([0][1-9]|[1-9][0-9])|[A-HJ-PR-Y]{1}([1-9]|[1-2][0-9]|30|31|33|40|44|55|50|60|66|70|77|80|88|90|99|111|121|123|222|321|333|444|555|666|777|888|999|100|200|300|400|500|600|700|800|900))[ ][A-HJ-PR-Z]{3}$";

if (!platetext.match(plateregex)) {
    var answer = window.confirm ("Non LEGAL Plate Detected ...");
}
```
<p>well here is the regex expression i made to match both type of plates <code>^([A-HJ-PR-Y]{2,2}[056][0-9]\s?[A-HJ-PR-Y]{3,3})$|^([A-HJ-NP-Y]{1,3}[0-9]{2,3}?\s[A-Z]{3,3})$|^([A-Z]{1,3}\s?[0-9]{1,4}([A-Z]{1,1})?)$|^([0-9]{4,4}[A-Z]{1,3})$|^([A-Z]{1,2}\s?[0-9]{1,4})$|^([A-Z]{2,3}\s?[0-9]{1,4})$|^([0-9]{1,4}\s?[A-Z]{2,3})$</code> however this dosent match anything ? when it should do can you see any problems here for using with javascript regex ?</p>
<p>(Editing on behalf of OP)  Here are some examples of UK registration plates that meet the OP's requirements.  The pattern is double letter followed by double numeric followed by triple letter.</p>
```ML09WKY
BF59DZR
GF54LFK
GL59FVM
LA55JVL
LB59AHD
GF59WUC
```

答:
A quick Google gave me these

```<code>/\b[a-z]{2}([1-9]|0[2-9]|6[0-9]|1[0-9])[a-z]{3}\b/i      # current series
/\b[A-HJ-NP-Y]\d{1,3}[A-Z]{3}\b/        # previous series
/\b[A-Z]{3}\d{1,3}[A-HJ-NP-Y]\b/        # previous series
/\b(?:[A-Z]{1,2}\d{1,4}|[A-Z]{3}\d{1,3})\b/     # old series - letters first
/\b(?:\d{1,4}[A-Z]{1,2}|\d{1,3}[A-Z]{3})\b/     # old series - digits first
</code>```

Looks like you'll have to test them individually.

Title: Regex to match LEGAL UK Number Plate

Body:
i have been working on matching a legal uk number plate with the following regex expression , however this only matches new number plates like JS07 ZAS not the old J62 LNX format, i need a expression to match both and i cant work out how to match both type of plates.

var plateregex = "([A-HJ-PR-Y]{2}([0][1-9]|[1-9][0-9])|[A-HJ-PR-Y]{1}([1-9]|[1-2][0-9]|30|31|33|40|44|55|50|60|66|70|77|80|88|90|99|111|121|123|222|321|333|444|555|666|777|888|999|100|200|300|400|500|600|700|800|900))[ ][A-HJ-PR-Z]{3}$";

if (!platetext.match(plateregex)) {
    var answer = window.confirm ("Non LEGAL Plate Detected ...");
}

well here is the regex expression i made to match both type of plates ^([A-HJ-PR-Y]{2,2}[056][0-9]\s?[A-HJ-PR-Y]{3,3})$|^([A-HJ-NP-Y]{1,3}[0-9]{2,3}?\s[A-Z]{3,3})$|^([A-Z]{1,3}\s?[0-9]{1,4}([A-Z]{1,1})?)$|^([0-9]{4,4}[A-Z]{1,3})$|^([A-Z]{1,2}\s?[0-9]{1,4})$|^([A-Z]{2,3}\s?[0-9]{1,4})$|^([0-9]{1,4}\s?[A-Z]{2,3})$ however this dosent match anything ? when it should do can you see any problems here for using with javascript regex ?

(Editing on behalf of OP)  Here are some examples of UK registration plates that meet the OP's requirements.  The pattern is double letter followed by double numeric followed by triple letter.

ML09WKY
BF59DZR
GF54LFK
GL59FVM
LA55JVL
LB59AHD
GF59WUC

Body:
A quick Google gave me these

/\b[a-z]{2}([1-9]|0[2-9]|6[0-9]|1[0-9])[a-z]{3}\b/i      # current series
/\b[A-HJ-NP-Y]\d{1,3}[A-Z]{3}\b/        # previous series
/\b[A-Z]{3}\d{1,3}[A-HJ-NP-Y]\b/        # previous series
/\b(?:[A-Z]{1,2}\d{1,4}|[A-Z]{3}\d{1,3})\b/     # old series - letters first
/\b(?:\d{1,4}[A-Z]{1,2}|\d{1,3}[A-Z]{3})\b/     # old series - digits first

Looks like you'll have to test them individually.


问:
Insert results of multiple tables into one json_encode()
Excuse my language mistakes, I speak French.

I did some research on this site and elsewhere, but what I have found didn't solve my problem.

I am doing a site where people can post their stories. I'm working on a page where the author should be able to see his stories and chapters of each of them.

I do a query on two tables to get the titles of stories and chapters. I have a table "stories" in which there is the title and summary of each story (and other stuff like id and date of publication). And another table called "chapters", in which there is the title of each chapter and the id of the story to which they belong.

I would like to retrieve these items later in my html, to have something like this:

Story title 1

Chapter 1

Chapter 2

So I do a json_encode () but JSONLint said that the json I get is invalid. PHP is new to me, I began to learn so I'm probably not writing my code correctly.

Here is my code:

```<code><?php
session_start();
require_once('connexion_db.php');

if($db=connect()){
    $userID = $_SESSION['id'];

    $arr = array();

    $reqRecits = $db->query('SELECT titre, id FROM recits WHERE user_id = '.$userID.'');
    $resRecits = $reqRecits->fetchAll(PDO::FETCH_ASSOC);

    foreach ($resRecits as $r){
        $recitID = $r['id'];
        $recitTitre = $r['titre'];

        $reqChapitres = $db->query('SELECT id, titre_chapitre FROM chapitres WHERE recit_id = '.$r['id'].'');
        $resChapitres = $reqChapitres->fetchAll(PDO::FETCH_ASSOC);

        foreach ($resChapitres as $c){
            $chapTitre = $c['titre_chapitre'];
        }

        $arr = array('titre'=>$recitTitre,'chapitre'=>$chapTitre);
        echo json_encode($arr, JSON_UNESCAPED_UNICODE);
    }

}else{
    echo "bdd non connectée.";
}
?>
</code>```

I tested the method proposed here, but the result is worse.
I don't know what to do :(

Thanks for your help!

答:
```<code>>  For Me this is Worked !

 <?php
    header('content-type: application/json');
    date_default_timezone_set('Asia/Dhaka');
    $DatabaseName = "";
    $HostPass = "";
    $HostUser = "";
    $HostName = "LocalHost";
    $db_connect = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);

    $userid = $_GET['id'];
    $status = $_GET['status'];
    $rows = array();
    $datas = array();

    $result = mysqli_query($db_connect, "SELECT id FROM drivers WHERE phone = '$userid'");
    if ($result)
    {
        $row = mysqli_fetch_assoc($result);
        $id = $row['id'];

        $result = mysqli_query($db_connect, "SELECT `delivery_id` , `date`, `time` FROM `driver_orders` WHERE driver_id='$id' AND `status` ='$status'");
        mysqli_set_charset($db_connect,"utf8");
        while ($row = mysqli_fetch_assoc($result))
        {

            $d_id = $row['delivery_id'];

            $data = mysqli_query($db_connect, "SELECT r_name,r_number,r_zone,r_address,amount FROM deliveries  WHERE id = '$d_id'");
            while ($row2 = mysqli_fetch_assoc($data))
            {
                $datas[] = array(
                    "r_name" => $row2['r_name'],
                    "delivery_id" => $row['delivery_id'],
                    "time"=> $row['time'],
                    "date"=> $row['date'],
                    "r_number" => $row2['r_number'],
                    "r_zone" => $row2['r_zone'],
                    "amount" => $row2['amount'],
                    "r_address" => $row2['r_address']

                );

            }

        }

    }

    echo json_encode($datas);

    ?>
</code>```

Body:
Excuse my language mistakes, I speak French.

I did some research on this site and elsewhere, but what I have found didn't solve my problem.

I am doing a site where people can post their stories. I'm working on a page where the author should be able to see his stories and chapters of each of them.

I do a query on two tables to get the titles of stories and chapters. I have a table "stories" in which there is the title and summary of each story (and other stuff like id and date of publication). And another table called "chapters", in which there is the title of each chapter and the id of the story to which they belong.

I would like to retrieve these items later in my html, to have something like this:

Story title 1

Chapter 1

Chapter 2

So I do a json_encode () but JSONLint said that the json I get is invalid. PHP is new to me, I began to learn so I'm probably not writing my code correctly.

Here is my code:

<?php
session_start();
require_once('connexion_db.php');

if($db=connect()){
    $userID = $_SESSION['id'];

    $arr = array();

    $reqRecits = $db->query('SELECT titre, id FROM recits WHERE user_id = '.$userID.'');
    $resRecits = $reqRecits->fetchAll(PDO::FETCH_ASSOC);

    foreach ($resRecits as $r){
        $recitID = $r['id'];
        $recitTitre = $r['titre'];

        $reqChapitres = $db->query('SELECT id, titre_chapitre FROM chapitres WHERE recit_id = '.$r['id'].'');
        $resChapitres = $reqChapitres->fetchAll(PDO::FETCH_ASSOC);

        foreach ($resChapitres as $c){
            $chapTitre = $c['titre_chapitre'];
        }

        $arr = array('titre'=>$recitTitre,'chapitre'=>$chapTitre);
        echo json_encode($arr, JSON_UNESCAPED_UNICODE);
    }

}else{
    echo "bdd non connectée.";
}
?>

I tested the method proposed here, but the result is worse.
I don't know what to do :(

Thanks for your help!


问:
PDF file in VB.NET (upgrade problem from VB 6)
I have upgraded my project from vb6 to VB.NET. The project is used to generate pdf files..
while upgrading I'm getting following problem.

Code:

'UPGRADE_ISSUE: Constant vbUnicode was
  not upgraded. Click for more:

  'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="vbup2070"'
  'taptisColor = IIf(mvarEncodeASCII85,
  ToASCII85(ImgColor),
  StrConv(System.Text.UnicodeEncoding.Unicode.GetString(ImgColor),
  vbUnicode))   sColor =
  IIf(mvarEncodeASCII85,
  ToASCII85(ImgColor),

  DecodeString(System.Text.Encoding.UTF8.GetString(ImgColor)))
  'sColor = IIf(mvarEncodeASCII85,
  ToASCII85(ImgColor),

  StrConv(System.Text.UnicodeEncoding.Unicode.GetString(ImgColor),
  VbStrConv.None))

The problem is that it displays a black coloured rect where it should display the image as logo.

Please help. What to do to resolve unicode upgrade problem?

Thanks!

答:
This Microsoft forum thread could help solve the issue:

Upgrade VBA StrConv Byte Array vbUnicode ToString

Instead of StrConv, try to use the classes in the .NET namespace System.Text.Encoding.

OwnerDisplayName: renu

LastEditorDisplayName: splattne

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: splattne


问:
How to put an Image in image with Android?
I need some help, because I am developing an application which I need to do that an image(2) is in other image(1), and when I move the image(1), the image(2) move to the same place.

Please, give me some information or anything to search. Thanks

答: You could try using a regular ImageView. An ImageView has both a Background and Image, both of which can be drawables.</p>


问:
How can I change this function in R so that it changes the data frame in x?
The code below is my attempt at a function to change the data table in x.
The data table x has columns named MutationStatus and disease. When I plug x as the data table and y as the string within the disease column manually, the function works, however plugging it as a function does not. </p>

```<code>diseaseMutation <- function(x,y) {
  x$MutationStatus[x$disease != y] = "WT"
  x$disease[x$disease != y] = y
}
</code>```

答:
We need to return the 'x'</p>

```<code>diseaseMutation <- function(x,y) {
  x$MutationStatus[x$disease != y] = "WT"
   x$disease[x$disease != y] = y
   x
 }
</code>```

Body:
The code below is my attempt at a function to change the data table in x.
The data table x has columns named MutationStatus and disease. When I plug x as the data table and y as the string within the disease column manually, the function works, however plugging it as a function does not.

diseaseMutation <- function(x,y) {
  x$MutationStatus[x$disease != y] = "WT"
  x$disease[x$disease != y] = y
}

Body:
We need to return the 'x'

diseaseMutation <- function(x,y) {
  x$MutationStatus[x$disease != y] = "WT"
   x$disease[x$disease != y] = y
   x
 }


问:
How to get the Key of selected Entry of Firebase Database in Logcat?

I am getting all the keys, How can I get the key of only the respective position of the cardview when I click on it? Suppose, if i click on card position 2, only that position key is required

Here is my Code :

```<code> databaseReference = FirebaseDatabase.getInstance().getReference("News");
    final String z = databaseReference.child(String.valueOf(homeModelList.get(position))).getKey();

    Toast.makeText(context, z, Toast.LENGTH_SHORT).show();
    databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            Log.e("Position is ", String.valueOf(z));

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
</code>```

I am unable to get the key of respective positions. I am getting Output in logcat as 0,1,2 which the positions of the adapter.

How can I get that Key. Thanks

答:
You can iterate over the children of the datasnapshot to get the key using a for loop.

```<code>databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

        for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
            Log.e("Position is ", String.valueOf(childSnapshot.getKey()));
        }

    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});
</code>```

Body:
I am getting all the keys, How can I get the key of only the respective position of the cardview when I click on it? Suppose, if i click on card position 2, only that position key is required

Here is my Code :

 databaseReference = FirebaseDatabase.getInstance().getReference("News");
    final String z = databaseReference.child(String.valueOf(homeModelList.get(position))).getKey();

    Toast.makeText(context, z, Toast.LENGTH_SHORT).show();
    databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            Log.e("Position is ", String.valueOf(z));

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

I am unable to get the key of respective positions. I am getting Output in logcat as 0,1,2 which the positions of the adapter.

How can I get that Key. Thanks

Body:
You can iterate over the children of the datasnapshot to get the key using a for loop.

databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

        for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
            Log.e("Position is ", String.valueOf(childSnapshot.getKey()));
        }

    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});


答:
Here might be a way out, gathering your data (i.e., changing them from wide to long), creating a date variable and only then translating the result to xts.

```<code>## This assumes that you already have written the data frame (as in your example)
myxts <- ASI_conv_to_USD_2003_2018 %>%
## gather changes the data from wide to long
tidyr::gather("month","value",-Year) %>%
## dmy creates the date variable
mutate(dat = paste0("01 ",month," ",Year) %>% lubridate::dmy()) %>%
## keep only the date and the value
select(dat, value) %>%
## sort by date (not compulsory)
arrange(dat) %>%
## convert to xts (note that xts::as_xts() is deprecated)
timetk::tk_xts(select=value,date_var=dat)
</code>```

Title: Sort date column and convert csv file to a time -series

Body:
I need your help. I am new to R, I have this csv file shorturl.at/chDK9 with the "All Share Index"  from the Nigerian stock exchange, formatted in a matrix, with the months as rows and the years as columns.

I am trying to do 4 things:

Reshape the data, to four columns for Date, Month, Year, ASI

The period should be a date column in the format 01-2013 for January 2013 and so on.

Arrange the data by the date, oldest to newest

Convert the data to a time-series type for analysis (xts prefarably)

So far I have solved 1 & 2 above.

Please see my code below

rASI <- ASI_conv_to_USD_2003_2018
gathered.rASI <- gather(rASI, Month, ASI, -Year)
gathered.rASI$Date <- format(as.Date(paste0(gathered.rASI$Month, gathered.rASI$Year, "01"), format="%b%Y%d"), "%m-%Y")
ASI <- select(gathered.rASI, Date, Month, Year, ASI)

Created on 2020-06-04 by the reprex package (v0.3.0)

I do not know what I am doing wrong, but the date column still shows as a chr. How do I make the date column function as a proper date?

Any help would be greatly appreciated.

Data:

Year,January,February,March,April,May,June,July,August,September,October,November,December
2003,104.904946,108.036674,106.6532671,106.1211644,110.6369777,114.3109402,109.7382693,120.7042254,129.0513061,141.9747008,140.2999274,147.4647619
2004,168.4931751,184.3675093,171.8948949,194.2243976,209.6846881,218.4302457,204.5201028,179.6591854,171.788925,176.3957704,175.7856172,180.1624481
2005,174.3600786,165.874575,156.2704949,165.9616111,162.3373385,162.9130468,165.5409489,177.6973735,190.975969,200.5254592,189.5253288,187.4381323
2006,184.2754864,187.0039216,184.1151874,183.9374803,195.3248086,207.753217,220.2425152,261.5902624,257.3486166,257.9713924,257.9644269,262.3660079
2007,290.763576,321.9563671,344.0977116,373.70341,397.1224052,408.8450816,422.9554882,404.1068702,405.3995157,413.592025,462.4500768,498.6259673
2008,465.9093801,564.6059512,542.1712123,511.539673,507.3090565,481.7790407,457.4977173,411.7628813,398.2089436,312.9651073,284.4105236,240.5413384
2009,151.4739254,160.8334365,136.7210055,147.8068088,203.1480164,183.6687179,169.4245226,152.975866,150.2860646,146.6946313,142.143901,141.1054878
2010,152.3225241,155.1887111,175.6850474,178.6050908,176.5795117,171.5144595,174.5049291,163.103972,154.3394041,169.2037838,167.046543,166.6141118
2011,179.0501835,173.3762495,163.0327771,164.2939247,168.9634855,165.1146804,158.8889704,141.5247531,132.2063595,139.799399,128.3830306,132.7185019
2012,133.3492814,129.4949163,132.8047714,142.0467784,142.1346216,138.9576042,148.4574482,152.9350934,167.5144256,170.2584385,170.6456267,180.8386037
2013,205.1867431,213.04438,216.0144928,215.3981965,243.4601263,232.9424155,244.1989566,233.469857,235.6526892,242.2584675,250.74636,266.2963273
2014,261.3308857,254.8076651,249.6006828,247.9683695,267.1803131,273.6744186,271.1943568,267.5533724,265.4434783,241.8539225,209.9881459,206.9083582
2015,176.4899701,152.4243544,161.5512468,176.6316031,174.6074809,170.307101,153.589313,151.067888,158.9094935,148.4871247,140.5468193,145.7620865
2016,121.710687,125.041883,128.7848346,127.5440712,140.7794402,104.7709381,89.631776,90.34052373,92.97916325,89.3927422,83.19668309,88.25819376
2017,85.43474979,83.04616393,83.42762792,84.35732766,96.74749098,108.4396857,120.8084876,116.2751597,116.1014906,120.1450704,124.20491,125.1822913
2018,145.2937418,141.8812705,136.0134688,135.2162844,124.7488623,125.4006552,121.2306533,114.014232,107.1321563,106.06426,100.7971596,102.5464927

Body:
Here might be a way out, gathering your data (i.e., changing them from wide to long), creating a date variable and only then translating the result to xts.

## This assumes that you already have written the data frame (as in your example)
myxts <- ASI_conv_to_USD_2003_2018 %>%
## gather changes the data from wide to long
tidyr::gather("month","value",-Year) %>%
## dmy creates the date variable
mutate(dat = paste0("01 ",month," ",Year) %>% lubridate::dmy()) %>%
## keep only the date and the value
select(dat, value) %>%
## sort by date (not compulsory)
arrange(dat) %>%
## convert to xts (note that xts::as_xts() is deprecated)
timetk::tk_xts(select=value,date_var=dat)


问:
Create Dataframe columns from list
Disclaimer: Beginner
Will delete if there's a duplicate question already been posted

I'm looking to create a script that will grab data from multiple webpages and store it as columns in a dataframe.
As you can see from below, I can successfully grab data for one stock, I am wondering does anybody have an idea to modify this so I could use something like

```<code>stocklist = ["AMZN", "GOOG", "TSLA"]
</code>```

Script below:

```<code>from time import sleep
from selenium import webdriver
import pandas as pd

driver = webdriver.Chrome('/chromedriver')

stock_list = ['AMZN']
values = []
metrics = []
def stocks():
    for i in stock_list:
        driver.get(f"http://finviz.com/quote.ashx?t={i}")
        value = driver.find_elements_by_xpath("//td[@class='snapshot-td2']")
        metric = driver.find_elements_by_xpath("//td[@class='snapshot-td2-cp']")
        for i in metric:
            metrics.append(i.text)

        for a in value:
           values.append(a.text)

def frames():
    d = pd.DataFrame({'Metrics': metrics,'AMZN': values})

    print(d)
    d.to_csv("AMZN.csv")
</code>```

Ideally would like to create a column for each new stock and their corresponding values.
Currently outputs like below:

```<code>         Metrics     AMZN
0          Index  S&P 500
1            P/E   116.67
2      EPS (ttm)    20.93
3    Insider Own   11.20%
4   Shs Outstand  498.00M
..           ...      ...
67         SMA20    2.96%
68         SMA50   10.13%
69        SMA200   27.34%
70        Volume  689,073
71        Change    0.93%
</code>```

答:
It's is very simple :

```<code>from selenium import webdriver
from time import sleep
from selenium import webdriver
import pandas as pd

driver = webdriver.Chrome(executable_path=r"/chromedriver")

df = pd.DataFrame()

stock_list = ["AMZN", "GOOG", "TSLA"]

for stock in stock_list:
    values = []
    metrics = []

    driver.get(f"http://finviz.com/quote.ashx?t={stock}")
    driver.implicitly_wait(10)

    page_metrics = driver.find_elements_by_xpath("//td[@class='snapshot-td2-cp']")
    for metric in page_metrics:
        metrics.append(metric.text)

    page_values = driver.find_elements_by_xpath("//td[@class='snapshot-td2']")
    for value in page_values:
        values.append(value.text)

    metric_column = 'Metrics_'+stock
    df[metric_column] = metrics
    df[stock] = values

df.to_csv("finviz.csv")
</code>```

Just go through the code you'll understand. This is output in sheet :

I have left one part for you to figure out and fix  -  I am writing 'Metrics' column for each stock - you can change it to single column if that's your requirement.

Title: Create Dataframe columns from list

Body:
Disclaimer: Beginner
Will delete if there's a duplicate question already been posted

I'm looking to create a script that will grab data from multiple webpages and store it as columns in a dataframe.
As you can see from below, I can successfully grab data for one stock, I am wondering does anybody have an idea to modify this so I could use something like

stocklist = ["AMZN", "GOOG", "TSLA"]

Script below:

from time import sleep
from selenium import webdriver
import pandas as pd

driver = webdriver.Chrome('/chromedriver')

stock_list = ['AMZN']
values = []
metrics = []
def stocks():
    for i in stock_list:
        driver.get(f"http://finviz.com/quote.ashx?t={i}")
        value = driver.find_elements_by_xpath("//td[@class='snapshot-td2']")
        metric = driver.find_elements_by_xpath("//td[@class='snapshot-td2-cp']")
        for i in metric:
            metrics.append(i.text)

        for a in value:
           values.append(a.text)

def frames():
    d = pd.DataFrame({'Metrics': metrics,'AMZN': values})

    print(d)
    d.to_csv("AMZN.csv")

Ideally would like to create a column for each new stock and their corresponding values.
Currently outputs like below:

         Metrics     AMZN
0          Index  S&P 500
1            P/E   116.67
2      EPS (ttm)    20.93
3    Insider Own   11.20%
4   Shs Outstand  498.00M
..           ...      ...
67         SMA20    2.96%
68         SMA50   10.13%
69        SMA200   27.34%
70        Volume  689,073
71        Change    0.93%

Body:
It's is very simple :

from selenium import webdriver
from time import sleep
from selenium import webdriver
import pandas as pd

driver = webdriver.Chrome(executable_path=r"/chromedriver")

df = pd.DataFrame()

stock_list = ["AMZN", "GOOG", "TSLA"]

for stock in stock_list:
    values = []
    metrics = []

    driver.get(f"http://finviz.com/quote.ashx?t={stock}")
    driver.implicitly_wait(10)

    page_metrics = driver.find_elements_by_xpath("//td[@class='snapshot-td2-cp']")
    for metric in page_metrics:
        metrics.append(metric.text)

    page_values = driver.find_elements_by_xpath("//td[@class='snapshot-td2']")
    for value in page_values:
        values.append(value.text)

    metric_column = 'Metrics_'+stock
    df[metric_column] = metrics
    df[stock] = values

df.to_csv("finviz.csv")

Just go through the code you'll understand. This is output in sheet :

I have left one part for you to figure out and fix  -  I am writing 'Metrics' column for each stock - you can change it to single column if that's your requirement.


问:
Python - Best practice for user-friendly way of checking for missing library dependencies?
Let's say my Python 3.6 script requires bar in the library foo, which it imports at the beginning:

```<code>from foo import bar
</code>```

What I'd like to do is for the script to attempt the import, and give feedback to a downstream user if foo is not available on their system and that they should install it.

So far, I've managed to hack together this solution which is probably not very good:

```<code>try:
    from foo import bar
except:
    print("Need `foo` library installed")
    exit(1)
</code>```

I used print() because I hope this can be a direct message to the user, but not sure if that's a good idea in the context of exception handling?

Also, there are at least two more problems here:

The except clause would apply to any error that happens during import including cases where the error is something other than the absence of foo. So this probably isn't a good use of exception handling?

My script imports multiple libraries, and I have to create a chunk like the above for each one!

I briefly considered creating a for loop that goes through a list of library dependencies and import each one. E.g.:

```<code>list_of_libraries: list = ["foo", "lorem", "ipsum"]
for library in list_of_libraries:
    try:
        import library
    except:
        print("Need " + library + " library installed")
        exit(1)
</code>```

However, this also looks bad to me because:

Each loop iteration imports the whole library

It would fail because I don't think import takes a string?

It doesn't really solve problem 1 above.

Am I stupidly missing something here? What's a good way to implement this? Thank you.

EDIT: There are existing answers such as this one which discusses how to list dependencies in requirements.txt and installing them with pip. However, my question is focused on solutions I can implement inside my Python script to catch missing libraries and prompting the user to install them.

答:
Exception Clause

You can catch ModuleNotFoundError (exists as of Python 3.6) or ImportError (for all Python versions) to restrict your except clause to cases of import troubles. ModuleNotFoundError is a subclass of ImportError, so catching ImportError will work in all versions of Python.

Error Output

Errors in standard linux applications would be written to stderr instead of stdout. So instead of using plain print, you would do as follows:

```<code>import sys

try:
    from foo import bar
except ImportError:
    print("Need `foo` library installed", file=sys.stderr)
    exit(1)
</code>```

You can test it by redirecting stdout to /dev/null. You will still see the error message:

```<code>$ python foobar.py >> /dev/null
Need `foo` library installed
</code>```

Better Handling Possible?

As for a better method than writing each import individually or looping over the required libraries, I unfortunately do not know. I have seen the try except ImportError pattern been used for compatibility between modules that were renamed from Python 2 to Python 3. So for individual libraries it seems to be normal, but I have not seen anybody mass check imports.

Body:
Let's say my Python 3.6 script requires bar in the library foo, which it imports at the beginning:

from foo import bar

What I'd like to do is for the script to attempt the import, and give feedback to a downstream user if foo is not available on their system and that they should install it.

So far, I've managed to hack together this solution which is probably not very good:

try:
    from foo import bar
except:
    print("Need `foo` library installed")
    exit(1)

I used print() because I hope this can be a direct message to the user, but not sure if that's a good idea in the context of exception handling?

Also, there are at least two more problems here:

The except clause would apply to any error that happens during import including cases where the error is something other than the absence of foo. So this probably isn't a good use of exception handling?

My script imports multiple libraries, and I have to create a chunk like the above for each one!

I briefly considered creating a for loop that goes through a list of library dependencies and import each one. E.g.:

list_of_libraries: list = ["foo", "lorem", "ipsum"]
for library in list_of_libraries:
    try:
        import library
    except:
        print("Need " + library + " library installed")
        exit(1)

However, this also looks bad to me because:

Each loop iteration imports the whole library

It would fail because I don't think import takes a string?

It doesn't really solve problem 1 above.

Am I stupidly missing something here? What's a good way to implement this? Thank you.

EDIT: There are existing answers such as this one which discusses how to list dependencies in requirements.txt and installing them with pip. However, my question is focused on solutions I can implement inside my Python script to catch missing libraries and prompting the user to install them.

Body:
Exception Clause

You can catch ModuleNotFoundError (exists as of Python 3.6) or ImportError (for all Python versions) to restrict your except clause to cases of import troubles. ModuleNotFoundError is a subclass of ImportError, so catching ImportError will work in all versions of Python.

Error Output

Errors in standard linux applications would be written to stderr instead of stdout. So instead of using plain print, you would do as follows:

import sys

try:
    from foo import bar
except ImportError:
    print("Need `foo` library installed", file=sys.stderr)
    exit(1)

You can test it by redirecting stdout to /dev/null. You will still see the error message:

$ python foobar.py >> /dev/null
Need `foo` library installed

Better Handling Possible?

As for a better method than writing each import individually or looping over the required libraries, I unfortunately do not know. I have seen the try except ImportError pattern been used for compatibility between modules that were renamed from Python 2 to Python 3. So for individual libraries it seems to be normal, but I have not seen anybody mass check imports.


问:
4-bit synchronous double down counter jk flip flop
Recently, I am trying to learn digital design and Verilog HDL. I am currently working on flip flops. I was trying to construct a 4-bit synchronous double countdown (down counter) with jk flip flop.

Ex: 1111 - 1101 - 1011 - 1001 - .. (15 - 13 - 11 - ..) etc.

While I was researching on the net, I always found synchronous down counter like 1111 - 1110 - 1101 etc.

How can I implement 4-bit synchronous double countdown (down counter) with jk flip flop?

答:
First thing that comes to my mind is a FSM. What buggers me is the requirement of using JK flipflops. Verilog can allow designs at the PMOS/NMOS level, but I'm not sure this is what you really wwant to do.

A behavioral description of such counter is very straightforward if a FSM is implemented. This one is a 3-bit double countdown. I think you can easily modify it to siut your 4-bit counter.

```<code>module countdown (
  input wire clk,
  input wire rst,
  output reg [2:0] out
  );

  initial out = 3'd7;

  always @(posedge clk or posedge rst) begin
    if (rst == 1'b1) begin
      out <= 3'd7;
    end
    else begin
      case (out)
        3'd7   : out <= 3'd5;
        3'd5   : out <= 3'd3;
        3'd3   : out <= 3'd1;
        3'd1   : out <= 3'd7;
        default: out <= 3'd7;
      endcase
    end
  end
endmodule
</code>```

Of course, there is another way: using an adder. For 4 bits, it would be like this:

```<code>module countdown4b (
  input wire clk,
  input wire rst,
  output reg [3:0] out
  );

  initial out = 4'b1111;

  always @(posedge clk)
    out <= out + 4'b1110;  // -2

endmodule
</code>```

Body:
First thing that comes to my mind is a FSM. What buggers me is the requirement of using JK flipflops. Verilog can allow designs at the PMOS/NMOS level, but I'm not sure this is what you really wwant to do.

A behavioral description of such counter is very straightforward if a FSM is implemented. This one is a 3-bit double countdown. I think you can easily modify it to siut your 4-bit counter.

module countdown (
  input wire clk,
  input wire rst,
  output reg [2:0] out
  );

  initial out = 3'd7;

  always @(posedge clk or posedge rst) begin
    if (rst == 1'b1) begin
      out <= 3'd7;
    end
    else begin
      case (out)
        3'd7   : out <= 3'd5;
        3'd5   : out <= 3'd3;
        3'd3   : out <= 3'd1;
        3'd1   : out <= 3'd7;
        default: out <= 3'd7;
      endcase
    end
  end
endmodule

Of course, there is another way: using an adder. For 4 bits, it would be like this:

module countdown4b (
  input wire clk,
  input wire rst,
  output reg [3:0] out
  );

  initial out = 4'b1111;

  always @(posedge clk)
    out <= out + 4'b1110;  // -2

endmodule


问:
problem with adding UIActivityIndicator to the view !
I am trying to add a UIActivityIndicator to my custom view (programmatically). I am using the following code. But I dont see anything on the screen. Any idea why ?

Thanks.

```<code>UIActivityIndicatorView *activityIndicator=[[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(75, 395, 200, 200)] autorelease];
[activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
activityIndicator.center=self.view.center;
[self.view addSubview:activityIndicator];
</code>```

答: Another reason is maybe because you're not set the activity indicator position correctly. From what I see, you want to place the activity indicator to the center of it's parent view. But to do that, you must do something like activityIndicator.center = CGPointMake(self.view.frame.origin.x + self.view.bounds.size.width / 2.0, self.view.frame.origin.y + self.view.bounds.size.height / 2.0);</p>

Body:
I am trying to add a UIActivityIndicator to my custom view (programmatically). I am using the following code. But I dont see anything on the screen. Any idea why ?

Thanks.

UIActivityIndicatorView *activityIndicator=[[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(75, 395, 200, 200)] autorelease];
[activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
activityIndicator.center=self.view.center;
[self.view addSubview:activityIndicator];


问:
Flutter/Dart XML adding and inserting nodes
I'm trying to get going with the XML library for Flutter but can't make sense of the readme section on inserting and adding nodes.

The readme says "you need to first create a copy as otherwise an XmlParentError is thrown"... this is the error I am getting, but I don't understand what it means by creating a copy or how I would do that.

My code is very simple at the moment:

```<code>    builder = new XmlBuilder();
    XmlDocument document = buildParagraphXML();
    print(document.toXmlString(pretty: true, indent: '\t')); //this prints the xml correctly
    document.children.add(buildParagraphXML());
    print(document.toXmlString(pretty: true, indent: '\t')); //this throws the XMLParentError

  buildParagraphXML() {
    builder.element('paragraphblock', nest: () {
      builder.attribute('paragraphid', '1');
      builder.attribute('title', 'Paragraph 1');
      builder.text('content of paragraph');
    });
    final paragraphXML = builder.build();
    return paragraphXML;
  }
</code>```

The first print returns the accurate XML as:

```<code><paragraphblock paragraphid="1" title="Paragraph 1">Your content here</paragraphblock>
</code>```

The second one should return:

```<code><paragraphblock paragraphid="1" title="Paragraph 1">Your content here</paragraphblock>
<paragraphblock paragraphid="1" title="Paragraph 1">Your content here</paragraphblock>
</code>```

but throws the XML parent error.  Unhandled Exception: Node already has a parent, copy or remove it first: but I don't understand what 'copy or remove it' means...

I then would like to be able to add subnodes to each paragraph, and so on, deeper into the tree.

答:
The first problem I see is that you reuse the builder multiple times. I agree that the error message is a bit misleading: the error happens because the previous <paragraphblock> it re-added to the new document. You probably intend to move the creation of the builder into your method so that it looks like:

XmlDocument buildParagraphXML() {
  final builder = new XmlBuilder();
  builder.element('paragraphblock', nest: () {
    // etc ...
  });
  return builder.build();
}
```

<p>Then the next problem I see in the line <code>document.children.add(buildParagraphXML());</code> that attempts to add a document to another document. If you start with a builder, then ideally you build the complete document with the builder. If you want to go your way, you have to extract the first element from the second document, copy it, and add it to your first document as such:</p>

<pre class="lang-dart prettyprint-override"><code>document.children.add(buildParagraphXML().firstChild.copy());
</code>```

Note that while the above code works, the resulting document is not valid because it contains multiple root elements.

Body:
I'm trying to get going with the XML library for Flutter but can't make sense of the readme section on inserting and adding nodes.

The readme says "you need to first create a copy as otherwise an XmlParentError is thrown"... this is the error I am getting, but I don't understand what it means by creating a copy or how I would do that.

My code is very simple at the moment:

    builder = new XmlBuilder();
    XmlDocument document = buildParagraphXML();
    print(document.toXmlString(pretty: true, indent: '\t')); //this prints the xml correctly
    document.children.add(buildParagraphXML());
    print(document.toXmlString(pretty: true, indent: '\t')); //this throws the XMLParentError

  buildParagraphXML() {
    builder.element('paragraphblock', nest: () {
      builder.attribute('paragraphid', '1');
      builder.attribute('title', 'Paragraph 1');
      builder.text('content of paragraph');
    });
    final paragraphXML = builder.build();
    return paragraphXML;
  }

The first print returns the accurate XML as:

<paragraphblock paragraphid="1" title="Paragraph 1">Your content here</paragraphblock>

The second one should return:

<paragraphblock paragraphid="1" title="Paragraph 1">Your content here</paragraphblock>
<paragraphblock paragraphid="1" title="Paragraph 1">Your content here</paragraphblock>

but throws the XML parent error.  Unhandled Exception: Node already has a parent, copy or remove it first: but I don't understand what 'copy or remove it' means...

I then would like to be able to add subnodes to each paragraph, and so on, deeper into the tree.

Body:
The first problem I see is that you reuse the builder multiple times. I agree that the error message is a bit misleading: the error happens because the previous <paragraphblock> it re-added to the new document. You probably intend to move the creation of the builder into your method so that it looks like:

XmlDocument buildParagraphXML() {
  final builder = new XmlBuilder();
  builder.element('paragraphblock', nest: () {
    // etc ...
  });
  return builder.build();
}

Then the next problem I see in the line document.children.add(buildParagraphXML()); that attempts to add a document to another document. If you start with a builder, then ideally you build the complete document with the builder. If you want to go your way, you have to extract the first element from the second document, copy it, and add it to your first document as such:

document.children.add(buildParagraphXML().firstChild.copy());

Note that while the above code works, the resulting document is not valid because it contains multiple root elements.


问:
Get scrollbar width
I removed the body scrollbar and then must compensate for its lack with padding. To do this, I try to calculate the width of the scrollbar of the div block that appears after removing the body scrollbar and pass the resulting value as padding. This works in Chrome, but does not work in other browsers. Here is my code:

```<code>element = document.getElementById('div');
var scrollBarWidth = element.offsetWidth - element.clientWidth;
  document.body.style.paddingRight = scrollBarWidth + 'px';
</code>```

I would really appreciate a suitable solution.

答:
It seems to work, but maybe there is a simpler solution that works in all browsers?

// Create the measurement node
var scrollDiv = document.createElement("div");
scrollDiv.className = "scrollbar-measure";
document.body.appendChild(scrollDiv);

// Get the scrollbar width
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
console.info(scrollbarWidth); // Mac:  15

// Delete the DIV
document.body.removeChild(scrollDiv);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.scrollbar-measure {
 width: 100px;
 height: 100px;
 overflow: scroll;
 position: absolute;
 top: -9999px;
}</code>```

```<code>document.body.style.paddingRight = (scrollbarWidth) + 'px';
</code>```

Title: Get scrollbar width

Body:
I removed the body scrollbar and then must compensate for its lack with padding. To do this, I try to calculate the width of the scrollbar of the div block that appears after removing the body scrollbar and pass the resulting value as padding. This works in Chrome, but does not work in other browsers. Here is my code:

element = document.getElementById('div');
var scrollBarWidth = element.offsetWidth - element.clientWidth;
  document.body.style.paddingRight = scrollBarWidth + 'px';

I would really appreciate a suitable solution.

Body:
It seems to work, but maybe there is a simpler solution that works in all browsers?

// Create the measurement node
var scrollDiv = document.createElement("div");
scrollDiv.className = "scrollbar-measure";
document.body.appendChild(scrollDiv);

// Get the scrollbar width
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
console.info(scrollbarWidth); // Mac:  15

// Delete the DIV
document.body.removeChild(scrollDiv);

.scrollbar-measure {
 width: 100px;
 height: 100px;
 overflow: scroll;
 position: absolute;
 top: -9999px;
}

document.body.style.paddingRight = (scrollbarWidth) + 'px';


问:
External Static(.a) Libraries in iPhone projects
Over the last few months I've come across various chatter of external/private libraries not being allowed in iPhone apps.[Just to be clear, this is not something thats going to come, its something I was wrongly under the impression that already exists.]

I was looking at the WunderRadio source: http://www.wunderradio.com/code.html
and I noticed they have 3+ .a files in there project.

libcCommon.a liblibmms.a and libffmpegLib.a are the ones I'm looking at.

Have I been misinformed about the use of this kinda of libraries in iPhone projects? Will Apple accept and approve projects that are using them? If so what is it thats not allowed? Is it just use of Apples own private and undocumented libraries, but you are allowed to include your own?

Many Thanks,
-Code

答:
I think they'd be crazy to do that.

There are so many 3rd party libraries out there that it would pretty much kill the developer crowd they've got now. Imagine if you had to write every library over, from scratch? That's nuts...

Of course, I have no proof one way or another. I just think they'd be insane to try and do that.


问:
How to get json from HTML form and keep type of input
I can get json from HTML form but the problem is that all of value in side json are convert to string type.
I have try both

result = json.dumps(request.form)
result = jsonify(request.form)
but result still be the same.
HTML form
Output Json

Is there any way to get the result like this
{
  "department": "sales",
  "donation": 1538,
  "firstName": "abc",
  "lastName": "ccc"
}

HTML Code

```<code><!doctype html>
<html>
   <body>
<div class="container">
        <form action="/display" method="post" id="employForm"
        <fieldset>
        <label>First Name
          <input type="text" name="firstName" placeholder="Joe" required>
        </label>
        <label>Last Name
          <input type="text" name="lastName" id="lastName" placeholder="Schmoe" required>
        </label>
        <label>Homeless cat donation
          <input type="number" name="donation" id="donation" placeholder=1234 required>
        </label>

        <label>
        Department
          <select name="department" required>
            <option value="sales">Sales</option>
            <option value="marketing">Marketing</option>
            <option value="developer">Developer</option>
            <option value="business">Business Relations</option>
            <option value="sysAdmin">Systems Administration</option>
            <option value="operation">Operation</option>
          </select>
        </label>
            Thanks
        </fieldset>
      <button class="button-primary" type="submit" value="Submit" form="employForm">SUBMIT!</button>
    </form>
    </body>
  </div>
 </html>
</code>```

This is the python flask code

```<code>from flask import Flask, render_template, request, jsonify
import json

app = Flask(__name__)
@app.route('/')
def hello():
     return render_template('layout.html')

@app.route('/display', methods=["GET", "POST"])
def display():
    result = jsonify(request.form)
    return result

if __name__ == "__main__":
      app.run(debug = True)
</code>```

答:
Taking notes from this Answer Here

JSON is untyped. Anything sent in JSON format will be converted to a string; so its not possible to send the donation value as an integer.

Body:
I can get json from HTML form but the problem is that all of value in side json are convert to string type.
I have try both

result = json.dumps(request.form)
result = jsonify(request.form)
but result still be the same.
HTML form
Output Json

Is there any way to get the result like this
{
  "department": "sales",
  "donation": 1538,
  "firstName": "abc",
  "lastName": "ccc"
}

HTML Code

<!doctype html>

        <form action="/display" method="post" id="employForm"
        <fieldset>
        First Name
          <input type="text" name="firstName" placeholder="Joe" required>

        Last Name
          <input type="text" name="lastName" id="lastName" placeholder="Schmoe" required>

        Homeless cat donation
          <input type="number" name="donation" id="donation" placeholder=1234 required>

        Department
          <select name="department" required>
            <option value="sales">Sales</option>
            <option value="marketing">Marketing</option>
            <option value="developer">Developer</option>
            <option value="business">Business Relations</option>
            <option value="sysAdmin">Systems Administration</option>
            <option value="operation">Operation</option>
          </select>

            Thanks
        </fieldset>
      <button class="button-primary" type="submit" value="Submit" form="employForm">SUBMIT!</button>
    </form>

This is the python flask code

from flask import Flask, render_template, request, jsonify
import json

app = Flask(__name__)
@app.route('/')
def hello():
     return render_template('layout.html')

@app.route('/display', methods=["GET", "POST"])
def display():
    result = jsonify(request.form)
    return result

if __name__ == "__main__":
      app.run(debug = True)