问:
How do I retrieve the columns of a 2D integer NumPy array that have a mean greater than a certain number?
I have:

```<code>x = np.array([[1,2],[3,4]])
np.mean(x, axis=0) > 2

output: array([False,  True])

</code>```

the expected output for a column with a mean greater than 2:

```<code>[[2]
 [4]]
</code>```

答:
In your code itself something like this can help

```<code>x = np.array([[1,2],[3,4]])
a=(np.mean(x,axis=1)>2)*1
x = x*a
np.array([a[a!=0] for a in x])
</code>```

Gives your desired output

```<code>array([[2],
       [4]])
</code>```

Body:
I have:

x = np.array([[1,2],[3,4]])
np.mean(x, axis=0) > 2

output: array([False,  True])

the expected output for a column with a mean greater than 2:

[[2]
 [4]]

Body:
In your code itself something like this can help

x = np.array([[1,2],[3,4]])
a=(np.mean(x,axis=1)>2)*1
x = x*a
np.array([a[a!=0] for a in x])

Gives your desired output

array([[2],
       [4]])


来源: stackexchange

问:
Setting up a proper dev environment with CI for react-native, typescript, nodejs
Unfortunately, we have projects with different nodejs versions.   I am not sure if this is like java where I can have multiple jdks installed(multiple nodejs installed) and each project magically uses the correct version via a config file?  Also, most commands in tutorials are not including version numbers when installing tools and libraries like so

npm install -g expo-cli (tool)

npm install @react-navigation/native (library)

Coming from gradle with the gradle wrapper where everyone on the team uses the tools and library versions defined in the build.gradle file, this is odd to me.  In the gradle world, everyone on the team uses the same exact version of gradle(gradle itself ensures if one person upgrades it in the repo, everyone gets the upgrade and stays in sync on the same version).  Then there is plugins/tools and those versions are defined and then libraries and those versions are defined.

How do I guarantee everyone is using the same npm, node, expo, etc. tools?

How do I guarantee everyone is using the same libraries?

How do I guarantee everyone is using the same typescript?

Ideally, we upgrade any of these in the repo + any fixes to the upgrade so on checkout, developers start using the new tool + new *.tsx files so it is seamless much like in the gradle world.  In gradle, I upgrade the

version via a property

versions of plugins/tools

build.gradle files

any source code files

and check that all in as a unit such that any developer that checks out is using all the correct versions together.  I want this in react-native for our ios/android mobile project or as close as I can get.

I have hacked things before as in installing 'ant' into the git repo and this worked wonders(even though it is such an ugly hack) and everyone used the tool in the repo instead of the one on their OS.  Perhaps there is a way to do that?

A bloated repo with binaries was worth it's weight in gold to prevent version compatibility hell as people upgraded libraries over time.  NOT only that we found that tool bugs were easier to track down as we could revert the repo.  NOT only that, we could reproduce builds form 1 year ago as the tooling was reverted where todays npm tools can't build the 1 year ago thing due to all the changes.  The advantages just kept piling up and up and I can't even remember all of them.

Tooling running from the repo either via bootstrap like gradle wrapper or full blown thing is generally the best option until the full blown thing is really bloated but even then locking it to a hash on another tool repo could be better

Any ideas welcome here to put my team on all the same tooling(works great for people joining the company or team from another project as well to not have to install much).

thanks,
Dean

答:
Typescript and libraries should be taken care of by removing any carets and tildes in your package.json and specifying exact versions.

One low overhead possibility for the rest could be shell scripting and a private package repo.  You could host the versions you want to install internally, and get it all through cURLs.

Or you could add some simple scripts in your npm pre-install, for example nvm use 12.2.1 should, through error messages, guide the user to installing nvm and using the proper version.

ContentLicense: CC BY-SA 4.0


问:
Parallel web requests with GPU on Google Collab
I need to obtain properties from a web service for a large list of products (~25,000) and this is a very time sensitive operation (ideally I need this to execute in just a few seconds). I coded this first using a for loop as a proof of concept but it's taking 1.25 hours. I'd like to vectorize this code and execute the http requests in parallel using a GPU on Google Collab. I've removed many of the unnecessary details, but it's important to note that the products and their web service urls are stored in a DataFrame.

Will this be faster to execute on a GPU? Or should I just use multiple threads on a CPU?

What is the best way to implement this? And How can I save the results from parallel processes to the results DataFrame (all_product_properties) without running into concurrency problems?

Each product has multiple properties (key-value pairs) that I'm obtaining from the JSON response, but the product_id is not included in the JSON response so I need to add the product_id to the DataFrame.

```<code>#DataFrame containing string column of urls
urls = pd.DataFrame(["www.url1.com", "www.url2.com", ..., "www.url3.com"], columns=["url"])

#initialize empty dataframe to store properties for all products
all_product_properties = pd.DataFrame(columns=["product_id", "property_name", "property_value"])

for i in range(1, len(urls)):

  curr_url = urls.loc[i, "url"]

  try:
    http_response = requests.request("GET", curr_url)

    if http_response is not None:

      http_response_json = json.loads(http_response.text)

      #extract product properties from JSON response
      product_properties_json = http_response_json['product_properties']
      curr_product_properties_df = pd.json_normalize(product_properties_json)

      #add product id since it's not returned in the JSON
      curr_product_properties_df["product_id"] = i

      #save current product properties to DataFrame containing all product properties
      all_product_properties = pd.concat([all_product_properties, curr_product_properties_df ])

  except Exception as e:
    print(e)
</code>```

答:
GPUs probably will not help here since they are meant for accelerating numerical operations. However, since you are trying to parallelize HTTP requests which are I/O bound, you can use Python multithreading (part of the standard library) to reduce the time required.

In addition, concatenating pandas dataframes in a loop is a very slow operation (see: Why does concatenation of DataFrames get exponentially slower?). You can instead append your output to a list, and run just a single concat after the loop has concluded.

Here's how I would implement your code w/ multithreading:

# Use an empty list for storing loop output
all_product_properties = []

thread_local = threading.local()

def get_session():
    if not hasattr(thread_local, "session"):
        thread_local.session = requests.Session()
    return thread_local.session

def download_site(url):
    session = get_session()

    try:
        with session.get(url) as response:
            if response is not None:
                http_response_json = json.loads(response.text)
                product_properties_json = http_response_json['product_properties']
                curr_product_properties_df = pd.json_normalize(product_properties_json)

                #add product id since it's not returned in the JSON
                curr_product_properties_df["product_id"] = i

                #save current product properties to DataFrame containing all product properties
                return curr_product_properties_df
                print(f"Read {len(response.content)} from {url}")
    except Exception as e:
        print(e)

def download_all_sites(sites):
    with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
        all_product_properties = executor.map(download_site, sites)
    return all_product_properties

if __name__ == "__main__":
    # Store URLs as list, example below
    urls = ["https://www.jython.org", "http://olympus.realpython.org/dice"] * 10
    start_time = time.time()
    all_product_properties = download_all_sites(urls)
    all_product_properties = pd.concat(all_product_properties)

    duration = time.time() - start_time
    print(f"Downloaded {len(urls)} in {duration} seconds")
```

Reference: this RealPython article on multithreading and multiprocessing in Python: https://realpython.com/python-concurrency/

Body:
I need to obtain properties from a web service for a large list of products (~25,000) and this is a very time sensitive operation (ideally I need this to execute in just a few seconds). I coded this first using a for loop as a proof of concept but it's taking 1.25 hours. I'd like to vectorize this code and execute the http requests in parallel using a GPU on Google Collab. I've removed many of the unnecessary details, but it's important to note that the products and their web service urls are stored in a DataFrame.

Will this be faster to execute on a GPU? Or should I just use multiple threads on a CPU?

What is the best way to implement this? And How can I save the results from parallel processes to the results DataFrame (all_product_properties) without running into concurrency problems?

Each product has multiple properties (key-value pairs) that I'm obtaining from the JSON response, but the product_id is not included in the JSON response so I need to add the product_id to the DataFrame.

#DataFrame containing string column of urls
urls = pd.DataFrame(["www.url1.com", "www.url2.com", ..., "www.url3.com"], columns=["url"])

#initialize empty dataframe to store properties for all products
all_product_properties = pd.DataFrame(columns=["product_id", "property_name", "property_value"])

for i in range(1, len(urls)):

  curr_url = urls.loc[i, "url"]

  try:
    http_response = requests.request("GET", curr_url)

    if http_response is not None:

      http_response_json = json.loads(http_response.text)

      #extract product properties from JSON response
      product_properties_json = http_response_json['product_properties']
      curr_product_properties_df = pd.json_normalize(product_properties_json)

      #add product id since it's not returned in the JSON
      curr_product_properties_df["product_id"] = i

      #save current product properties to DataFrame containing all product properties
      all_product_properties = pd.concat([all_product_properties, curr_product_properties_df ])

  except Exception as e:
    print(e)

Body:
GPUs probably will not help here since they are meant for accelerating numerical operations. However, since you are trying to parallelize HTTP requests which are I/O bound, you can use Python multithreading (part of the standard library) to reduce the time required.

In addition, concatenating pandas dataframes in a loop is a very slow operation (see: Why does concatenation of DataFrames get exponentially slower?). You can instead append your output to a list, and run just a single concat after the loop has concluded.

Here's how I would implement your code w/ multithreading:

# Use an empty list for storing loop output
all_product_properties = []

thread_local = threading.local()

def get_session():
    if not hasattr(thread_local, "session"):
        thread_local.session = requests.Session()
    return thread_local.session

def download_site(url):
    session = get_session()

    try:
        with session.get(url) as response:
            if response is not None:
                http_response_json = json.loads(response.text)
                product_properties_json = http_response_json['product_properties']
                curr_product_properties_df = pd.json_normalize(product_properties_json)

                #add product id since it's not returned in the JSON
                curr_product_properties_df["product_id"] = i

                #save current product properties to DataFrame containing all product properties
                return curr_product_properties_df
                print(f"Read {len(response.content)} from {url}")
    except Exception as e:
        print(e)

def download_all_sites(sites):
    with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
        all_product_properties = executor.map(download_site, sites)
    return all_product_properties

if __name__ == "__main__":
    # Store URLs as list, example below
    urls = ["https://www.jython.org", "http://olympus.realpython.org/dice"] * 10
    start_time = time.time()
    all_product_properties = download_all_sites(urls)
    all_product_properties = pd.concat(all_product_properties)

    duration = time.time() - start_time
    print(f"Downloaded {len(urls)} in {duration} seconds")

Reference: this RealPython article on multithreading and multiprocessing in Python: https://realpython.com/python-concurrency/


问:
Matplotlib bar labels with new f-string format style
As of matplotlib 3.4.0, Axes.bar_label method allows for labelling bar charts.

However, the labelling format option works with old style formatting, e.g. fmt='%g'

How can I make it work with new style formatting that would allow me to do things like percentages, thousands separators, etc:  '{:,.2f}', '{:.2%}', ...

The first thing that comes to my mind is somehow taking the initial labels from ax.containers and then reformatting them but it also needs to work for different bar structures, grouped bars with different formats and so on.

答:
How can I make bar_label work with new style formatting like percentages, thousands separators, etc?

As of matplotlib 3.7

The fmt param now directly supports {}-based format strings, e.g.:

```<code># >= 3.7
plt.bar_label(bars, fmt='{:,.2f}')
#                       ^no f here (not an actual f-string)
</code>```

Prior to matplotlib 3.7

The fmt param does not support {}-based format strings, so use the labels param. Format the bar container's datavalues with an f-string and set those as the labels, e.g.:

```<code># < 3.7
plt.bar_label(bars, labels=[f'{x:,.2f}' for x in bars.datavalues])
</code>```

Examples:

Thousands separator labels

```<code>bars = plt.bar(list('ABC'), [12344.56, 23456.78, 34567.89])

# >= v3.7
plt.bar_label(bars, fmt='${:,.2f}')
</code>```
```<code># < v3.7
plt.bar_label(bars, labels=[f'${x:,.2f}' for x in bars.datavalues])
</code>```

Percentage labels

```<code>bars = plt.bar(list('ABC'), [0.123456, 0.567890, 0.789012])

# >= 3.7
plt.bar_label(bars, fmt='{:.2%}')  # >= 3.7
</code>```
```<code># < 3.7
plt.bar_label(bars, labels=[f'{x:.2%}' for x in bars.datavalues])
</code>```

Stacked percentage labels

```<code>x = list('ABC')
y = [0.7654, 0.6543, 0.5432]

fig, ax = plt.subplots()
ax.bar(x, y)
ax.bar(x, 1 - np.array(y), bottom=y)

# now 2 bar containers: white labels for blue bars, black labels for orange bars
colors = list('wk')

# >= 3.7
for bars, color in zip(ax.containers, colors):
    ax.bar_label(bars, fmt='{:.1%}', color=color, label_type='center')
</code>```
```<code># < 3.7
for bars, color in zip(ax.containers, colors):
    labels = [f'{x:.1%}' for x in bars.datavalues]
    ax.bar_label(bars, labels=labels, color=color, label_type='center')
</code>```

Body:
How can I make bar_label work with new style formatting like percentages, thousands separators, etc?

As of matplotlib 3.7

The fmt param now directly supports {}-based format strings, e.g.:

# >= 3.7
plt.bar_label(bars, fmt='{:,.2f}')
#                       ^no f here (not an actual f-string)

Prior to matplotlib 3.7

The fmt param does not support {}-based format strings, so use the labels param. Format the bar container's datavalues with an f-string and set those as the labels, e.g.:

# < 3.7
plt.bar_label(bars, labels=[f'{x:,.2f}' for x in bars.datavalues])

Examples:

Thousands separator labels

bars = plt.bar(list('ABC'), [12344.56, 23456.78, 34567.89])

# >= v3.7
plt.bar_label(bars, fmt='${:,.2f}')

# < v3.7
plt.bar_label(bars, labels=[f'${x:,.2f}' for x in bars.datavalues])

Percentage labels

bars = plt.bar(list('ABC'), [0.123456, 0.567890, 0.789012])

# >= 3.7
plt.bar_label(bars, fmt='{:.2%}')  # >= 3.7

# < 3.7
plt.bar_label(bars, labels=[f'{x:.2%}' for x in bars.datavalues])

Stacked percentage labels

x = list('ABC')
y = [0.7654, 0.6543, 0.5432]

fig, ax = plt.subplots()
ax.bar(x, y)
ax.bar(x, 1 - np.array(y), bottom=y)

# now 2 bar containers: white labels for blue bars, black labels for orange bars
colors = list('wk')

# >= 3.7
for bars, color in zip(ax.containers, colors):
    ax.bar_label(bars, fmt='{:.1%}', color=color, label_type='center')

# < 3.7
for bars, color in zip(ax.containers, colors):
    labels = [f'{x:.1%}' for x in bars.datavalues]
    ax.bar_label(bars, labels=labels, color=color, label_type='center')


问:
Setting up the development environment for React Native in Apple M1
How to setup up the development environment for React Native in Apple M1 ARM-based system?</p>

答:
RN Environment Set For Android & iOS :

Install home-brew (https://brew.sh)

/bin/bash -c "$(curl -fsSL

https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

Install node & watchman (from terminal)

brew install node

brew install watchman

Don’t use the wrong JDK for React Native if you’re using an M1 Mac
…or you’ll be going 2x as slow and not know why

*Reference (https://shift.infinite.red/dont-use-the-wrong-jdk-for-react-native-if-you-re-using-an-m1-mac-252533dd47a2)

Install SDKMAN (https://sdkman.io)

curl -s "https://get.sdkman.io" | bash
sdk list java (check the version you want to install)
sdk install java 11.0.14-zulu

*Using of Sdkman (https://towardsdatascience.com/install-and-run-multiple-java-versions-on-linux-using-sdkman-858571bce6cf)

Download and Install Android Studio

Select AS for Mac (https://developer.android.com/studio/preview)

Select the Mac with Apple chip

Android Studio installs the latest Android SDK by default.

Select latest Android SDK Command-line Tools (Preference > Android SDK > SDK Tools > show package details)

Add the following lines to your in your ~/.zshrc :

export ANDROID_HOME=$HOME/Library/Android/sdk

export PATH=$PATH:$ANDROID_HOME/emulator

export PATH=$PATH:$ANDROID_HOME/tools

export PATH=$PATH:$ANDROID_HOME/tools/bin

export PATH=$PATH:$ANDROID_HOME/platform-tools

Note : To add this :

Open terminal & type nano $HOME/.zshrc

Copy that 5 lines and paste it

Control + O and then press return (to save).

Control + x (to exit)

Create project :

npx react-native init AwesomeProject

Run project :
npx react-native run-android - (to run in android)

Reaming Setup for iOS :

Install Xcode from Appstore

ruby -v (ruby is default installed)

Open terminal and type :

sudo xcode-select -switch /Applications/Xcode.app/Contents/   Developer

sudo xcode-select --install

brew install libffi

brew install cocoapods

Now to run iOS application

Simulator : npx react-native run-is

Device :
npm install -g ios-deploy
Run on a connected device, e.g. Max's iPhone:

react-native run-ios --device "Max's iPhone"


问:
FileHandler double logs string in a file
```<code>import logging

logger = logging.getLogger(__name__)
logger.addHandler(logging.FileHandler(filename='logloglog.log'))
logger.critical('A!')

for handler in logger.handlers:
    handler.close()

logger.addHandler(logging.FileHandler(filename='logloglog.log'))
logger.critical('B!')
</code>```

I am trying to understand why the above code logs B! string in logloglog.log file twice. It confuses me, since I log both A! and B! only one time. Can you help me?

答:
logger.addHandler was called twice, so there are two file handlers (pointing at the same filename):

```<code>>>> logger.handlers
[<FileHandler /home/wglenn/git/modules/logloglog.log (NOTSET)>,
 <FileHandler /home/wglenn/git/modules/logloglog.log (NOTSET)>]
</code>```

By the time logger.critical('B!') is called, each handler will write out the event once.

It does not matter that you've closed handlers earlier, logging will just re-open the resource when it needs to emit, if necessary.

Body:
import logging

logger = logging.getLogger(__name__)
logger.addHandler(logging.FileHandler(filename='logloglog.log'))
logger.critical('A!')

for handler in logger.handlers:
    handler.close()

logger.addHandler(logging.FileHandler(filename='logloglog.log'))
logger.critical('B!')

I am trying to understand why the above code logs B! string in logloglog.log file twice. It confuses me, since I log both A! and B! only one time. Can you help me?

Body:
logger.addHandler was called twice, so there are two file handlers (pointing at the same filename):

>>> logger.handlers
[<FileHandler /home/wglenn/git/modules/logloglog.log (NOTSET)>,
 <FileHandler /home/wglenn/git/modules/logloglog.log (NOTSET)>]

By the time logger.critical('B!') is called, each handler will write out the event once.

It does not matter that you've closed handlers earlier, logging will just re-open the resource when it needs to emit, if necessary.


问:
extracting a list within a list in a tuple which happens to be in a pd.series
```<code>x=
[[(some text,[a]), (some text,[b]), (some text,[c]).........]]
   [[(some text,[d]), (some text,[e]), (some text,[f]).........]]
    [[(some text,[g]), (some text,[h]), (some text,[k]).........]]
    [[(some text,[i]), (some text,[x]), (some text,[y]).........]]
    [[(some text,[z]), (some text,[t]), (some text,[w]).........]]
    [[(some text,[t]), (some text,[g]), (some text,[u]).........]]

type(x)

pandas.core.series.Series
</code>```

I want to create a series that only contains the values of the list within the tuple such as those[a] or [u] or [w].

How can I extract? Thank you.

UPDATE: I realized the way I phrase the question was confusing. I changed it now. It represents my problem better. Basically, I need to extract all [a] or [u] or [w]row by row. This is tokenized text data, they are words in sentences. Sorry for the confusion.

Body:
x=
[[(some text,[a]), (some text,[b]), (some text,[c]).........]]
   [[(some text,[d]), (some text,[e]), (some text,[f]).........]]
    [[(some text,[g]), (some text,[h]), (some text,[k]).........]]
    [[(some text,[i]), (some text,[x]), (some text,[y]).........]]
    [[(some text,[z]), (some text,[t]), (some text,[w]).........]]
    [[(some text,[t]), (some text,[g]), (some text,[u]).........]]

type(x)

pandas.core.series.Series

I want to create a series that only contains the values of the list within the tuple such as those[a] or [u] or [w].

How can I extract? Thank you.

UPDATE: I realized the way I phrase the question was confusing. I changed it now. It represents my problem better. Basically, I need to extract all [a] or [u] or [w]row by row. This is tokenized text data, they are words in sentences. Sorry for the confusion.

Body:
Use:

x =[('a',['b']), ('c',['d']),('e',['f'])]
x1 = pd.Series(x)
x1.apply(lambda y: y[1])

The result:

Based on your comment:

temp = pd.Series(["[[('aaaa', ['bbbb']), ('cccc', ['ddddd'])]]", "[[('a',['b']), ('c',['d']), ('e',['f'])]]"])
temp.apply(lambda x: [x[1] for x in eval(x)[0]])

And, the result:


问:
SEAndroid: Does dump state get prop violate never allow rule
When building AOSP S(12), I encounter a strange problem, but maybe only in sometimes / some machine. The error.log is as follows

```<code>neverallow check failed at out/target/product/msmnile_au/obj/ETC/plat_sepolicy.cil_intermediates/plat_sepolicy.cil:22861 from system/sepolicy/private/property.te:46
  (neverallow domain base_typeattr_745 (file (ioctl read write create setattr lock relabelfrom append unlink link rename open watch watch_mount watch_sb watch_with_perm watch_reads)))
    <root>
    allow at out/target/product/msmnile_au/obj/ETC/plat_sepolicy.cil_intermediates/plat_sepolicy.cil:8901
      (allow dumpstate property_type (file (read getattr map open)))
    <root>
    allow at out/target/product/msmnile_au/obj/ETC/plat_sepolicy.cil_intermediates/plat_sepolicy.cil:11533
      (allow init property_type (file (read write create getattr setattr relabelto append map unlink rename open)))
    <root>
    allow at out/target/product/msmnile_au/obj/ETC/plat_pub_versioned.cil_intermediates/plat_pub_versioned.cil:6370
      (allow dumpstate_31_0 property_type (file (read getattr map open)))
    <root>
    allow at out/target/product/msmnile_au/obj/ETC/plat_pub_versioned.cil_intermediates/plat_pub_versioned.cil:8170
      (allow init_31_0 property_type (file (read write create getattr setattr relabelto append map unlink rename open)))

Failed to generate binary
Failed to build policydb
</code>```

Then I check the rules. system/sepolicy/private/property.te:46 says:

```<code>enforce_sysprop_owner(`
  neverallow domain {
    property_type
    -system_property_type
    -product_property_type
    -vendor_property_type
  }:file no_rw_file_perms;
')
</code>```

and system/sepolicy/public/dumpstate.te:278 says:

```<code># Read any system properties
get_prop(dumpstate, property_type)
</code>```

My question is, does this violate the never allow rule and cause this error?
If yes, why sometimes this error does not pop up.
If not, what is the reason for my error?

Thanks in advance.

答:
I have added below code under device/xiaomi/juice/BroadConfig.mk

```<code># Sepolicy
SELINUX_IGNORE_NEVERALLOWS := true
</code>```

However this is not supported in user builds. Only supported in userdebug and eng builds.

Body:
When building AOSP S(12), I encounter a strange problem, but maybe only in sometimes / some machine. The error.log is as follows

neverallow check failed at out/target/product/msmnile_au/obj/ETC/plat_sepolicy.cil_intermediates/plat_sepolicy.cil:22861 from system/sepolicy/private/property.te:46
  (neverallow domain base_typeattr_745 (file (ioctl read write create setattr lock relabelfrom append unlink link rename open watch watch_mount watch_sb watch_with_perm watch_reads)))
    <root>
    allow at out/target/product/msmnile_au/obj/ETC/plat_sepolicy.cil_intermediates/plat_sepolicy.cil:8901
      (allow dumpstate property_type (file (read getattr map open)))
    <root>
    allow at out/target/product/msmnile_au/obj/ETC/plat_sepolicy.cil_intermediates/plat_sepolicy.cil:11533
      (allow init property_type (file (read write create getattr setattr relabelto append map unlink rename open)))
    <root>
    allow at out/target/product/msmnile_au/obj/ETC/plat_pub_versioned.cil_intermediates/plat_pub_versioned.cil:6370
      (allow dumpstate_31_0 property_type (file (read getattr map open)))
    <root>
    allow at out/target/product/msmnile_au/obj/ETC/plat_pub_versioned.cil_intermediates/plat_pub_versioned.cil:8170
      (allow init_31_0 property_type (file (read write create getattr setattr relabelto append map unlink rename open)))

Failed to generate binary
Failed to build policydb

Then I check the rules. system/sepolicy/private/property.te:46 says:

enforce_sysprop_owner(`
  neverallow domain {
    property_type
    -system_property_type
    -product_property_type
    -vendor_property_type
  }:file no_rw_file_perms;
')

and system/sepolicy/public/dumpstate.te:278 says:

# Read any system properties
get_prop(dumpstate, property_type)

My question is, does this violate the never allow rule and cause this error?
If yes, why sometimes this error does not pop up.
If not, what is the reason for my error?

Thanks in advance.

Body:
I have added below code under device/xiaomi/juice/BroadConfig.mk

# Sepolicy
SELINUX_IGNORE_NEVERALLOWS := true

However this is not supported in user builds. Only supported in userdebug and eng builds.


问:
Switch Logo color in Dark Mode issue
I have a black color logo for my portfolio and i would like to switch it white when Dark Mode : https://www.paulinerouger.com/

I have tried:

Using CSS Variables

```<code><img class="nav_logo" src="assets/img/PR_logo.png" alt="original logo" />

body {
  --nav_logo: url(PR_logo.png) no-repeat;

}

body[data-theme="dark"] {
  --nav_logo: url(PR_logo_white.png) no-repeat;
}

.nav_logo {
    background: var(--nav_logo);
  }

</code>```

Using SVG

```<code>
 <img class="nav_logo" src="assets/img/PR_logo.svg" id="svg" alt="PR Logo">

.nav_logo {
    fill: currentColor;
}
</code>```

Unfortunately none of the above has worked.
Any suggestion?

答:
change stroke="#000" in your svg to stroke="currentColor"</p>
```<code>body.dark-theme .nav__logo{
    color: #FFFFFF;
}
</code>```

Title: Switch Logo color in Dark Mode issue

Body:
I have a black color logo for my portfolio and i would like to switch it white when Dark Mode : https://www.paulinerouger.com/

I have tried:

Using CSS Variables

body {
  --nav_logo: url(PR_logo.png) no-repeat;

}

body[data-theme="dark"] {
  --nav_logo: url(PR_logo_white.png) no-repeat;
}

.nav_logo {
    background: var(--nav_logo);
  }

Using SVG

.nav_logo {
    fill: currentColor;
}

Unfortunately none of the above has worked.
Any suggestion?

Body:
change stroke="#000" in your svg to stroke="currentColor"

body.dark-theme .nav__logo{
    color: #FFFFFF;
}


问:
Cannot add image and save to pdf file using PDFKit
I have a class to edit pdf by inserting an image into the pdf and save a new pdf with the inserted image.

Below code is the way I use to achieve the scenario, by creating a custom PDFAnnotation. I specify type as .widget instead of .stamp to avoid having black line drawing across diagonal.

final private class PDFImageAnnotation: PDFAnnotation {

    var image: UIImage?

    convenience init(_ image: UIImage?, bounds: CGRect, properties: [AnyHashable: Any]?) {
        self.init(bounds: bounds, forType: PDFAnnotationSubtype.widget, withProperties: properties)
        self.image = image
    }

    override func draw(with box: PDFDisplayBox, in context: CGContext) {
        super.draw(with: box, in: context)

        // Drawing the image within the annotation's bounds.
        guard let cgImage = image?.cgImage else { return }
        context.draw(cgImage, in: bounds)
    }
}
```
<p>Below is how I display pdf and select image to save in pdf</p>
<pre class="lang-swift prettyprint-override"><code>private func setupPDF() {
    guard let url = url else { return }
    pdfView.document = PDFDocument(url: url)
    pdfView.autoScales = true
}

private func addImageAndSave(_ image: UIImage) {
    guard let page = pdfView.currentPage else { return }

    let pageBounds = page.bounds(for: .cropBox)
    let imageBounds = CGRect(x: pageBounds.midX, y: pageBounds.midY, width: image.size.width, height: image.size.height)
    let imageStamp = PDFImageAnnotation(image, bounds: imageBounds, properties: nil)
    imageStamp.shouldDisplay = true
    imageStamp.shouldPrint = true
    page.addAnnotation(imageStamp)

    // Save PDF with image
    let fileName = url.lastPathComponent
    let saveUrl = FileManager.default.temporaryDirectory.appendingPathComponent(fileName, isDirectory: false)
    pdfView.document?.write(to: saveUrl)
}
</code>```

However the result pdf file is below

The preview on right column does display the picture but when open the pdf in Preview app or any browser the picture is not there.

How can I make the picture appear in the final pdf file?

Thanks.

答:
I have to also draw that image on PDFPage to make them appear in the saved pdf file

final private class ImagePDFPage: PDFPage {

    /// A flag indicates whether to draw image on a page
    ///
    /// - Note: Set this to `true` before write pdf to file otherwise the image will not be appeared in pdf file
    var saveImageToPDF: Bool = false

    private var imageAnnotation: EkoPDFImageAnnotation? = nil

    func addImageAnnotation(_ annotation: EkoPDFImageAnnotation) {
        imageAnnotation = annotation
        addAnnotation(annotation)
    }

    func removeImageAnnotation() {
        guard let imageAnnotation = imageAnnotation else { return }
        self.imageAnnotation = nil
        removeAnnotation(imageAnnotation)
    }

    override func draw(with box: PDFDisplayBox, to context: CGContext) {
        super.draw(with: box, to: context)

        guard saveImageToPDF,
              let annotation = imageAnnotation,
              let cgImage = annotation.image?.cgImage else { return }
        context.draw(cgImage, in: annotation.bounds)
    }
}
```
<p>and update <code>PDFDocument.delegate</code> to tell to use <code>ImagePDFPage</code> as a class for pdf page</p>
<pre class="lang-swift prettyprint-override"><code>extension PDFEditorViewController: PDFDocumentDelegate {
    func classForPage() -> AnyClass {
        return ImagePDFPage.self
    }
}
</code>```

The result

Body:
I have a class to edit pdf by inserting an image into the pdf and save a new pdf with the inserted image.

Below code is the way I use to achieve the scenario, by creating a custom PDFAnnotation. I specify type as .widget instead of .stamp to avoid having black line drawing across diagonal.

final private class PDFImageAnnotation: PDFAnnotation {

    var image: UIImage?

    convenience init(_ image: UIImage?, bounds: CGRect, properties: [AnyHashable: Any]?) {
        self.init(bounds: bounds, forType: PDFAnnotationSubtype.widget, withProperties: properties)
        self.image = image
    }

    override func draw(with box: PDFDisplayBox, in context: CGContext) {
        super.draw(with: box, in: context)

        // Drawing the image within the annotation's bounds.
        guard let cgImage = image?.cgImage else { return }
        context.draw(cgImage, in: bounds)
    }
}

Below is how I display pdf and select image to save in pdf

private func setupPDF() {
    guard let url = url else { return }
    pdfView.document = PDFDocument(url: url)
    pdfView.autoScales = true
}

private func addImageAndSave(_ image: UIImage) {
    guard let page = pdfView.currentPage else { return }

    let pageBounds = page.bounds(for: .cropBox)
    let imageBounds = CGRect(x: pageBounds.midX, y: pageBounds.midY, width: image.size.width, height: image.size.height)
    let imageStamp = PDFImageAnnotation(image, bounds: imageBounds, properties: nil)
    imageStamp.shouldDisplay = true
    imageStamp.shouldPrint = true
    page.addAnnotation(imageStamp)

    // Save PDF with image
    let fileName = url.lastPathComponent
    let saveUrl = FileManager.default.temporaryDirectory.appendingPathComponent(fileName, isDirectory: false)
    pdfView.document?.write(to: saveUrl)
}

However the result pdf file is below

The preview on right column does display the picture but when open the pdf in Preview app or any browser the picture is not there.

How can I make the picture appear in the final pdf file?

Thanks.

Body:
I have to also draw that image on PDFPage to make them appear in the saved pdf file

final private class ImagePDFPage: PDFPage {

    /// A flag indicates whether to draw image on a page
    ///
    /// - Note: Set this to `true` before write pdf to file otherwise the image will not be appeared in pdf file
    var saveImageToPDF: Bool = false

    private var imageAnnotation: EkoPDFImageAnnotation? = nil

    func addImageAnnotation(_ annotation: EkoPDFImageAnnotation) {
        imageAnnotation = annotation
        addAnnotation(annotation)
    }

    func removeImageAnnotation() {
        guard let imageAnnotation = imageAnnotation else { return }
        self.imageAnnotation = nil
        removeAnnotation(imageAnnotation)
    }

    override func draw(with box: PDFDisplayBox, to context: CGContext) {
        super.draw(with: box, to: context)

        guard saveImageToPDF,
              let annotation = imageAnnotation,
              let cgImage = annotation.image?.cgImage else { return }
        context.draw(cgImage, in: annotation.bounds)
    }
}

and update PDFDocument.delegate to tell to use ImagePDFPage as a class for pdf page

extension PDFEditorViewController: PDFDocumentDelegate {
    func classForPage() -> AnyClass {
        return ImagePDFPage.self
    }
}

The result


问:
Read/write file in Documents directory problem
I am trying to write a very basic text string to my documents directory and work from there to later save other files etc.

I am currently stuck with it not writing anything into my Documents directory

(In my viewDidLoad)

```<code>NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)
NSString *documentsDirectory = [pathArray objectAtIndex:0];

NSString *textPath = [documentsDirectory stringByAppendingPathComponent:@"file1.txt"];
NSString *text = @"My cool text message";

[[NSFileManager defaultManager] createFileAtPath:textPath contents:nil attributes:nil];
[text writeToFile:textPath atomically:NO encoding:NSUTF8StringEncoding error:NULL];
NSLog(@"Text file data: %@",[[NSFileManager defaultManager] contentsAtPath:textPath]);
</code>```

This is what gets printed out:

2011-06-27 19:04:43.485 MyApp[5731:707] Text file data: (null)

If I try this, it also prints out null:

```<code>NSLog(@"My Documents: %@", [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:NULL]);
</code>```

What have I missed or am I doing wrong while writing to this file?
Might it be something I need to change in my plist or some frameworks/imports needed?

Thanks

[EDIT]
I passed a NSError object through the writeToFile and got this error:

Error: Error Domain=NSCocoaErrorDomain Code=512 "The operation couldn’t be completed. (Cocoa error 512.)" UserInfo=0x12aa00 {NSFilePath=/var/mobile/Applications/887F4691-3B75-448F-9384-31EBF4E3B63E/Documents/file1.txt, NSUnderlyingError=0x14f6b0 "The operation couldn’t be completed. Not a directory"}

[EDIT 2]
This works fine on the simulator but not on my phone :/

答: Put an NSLog statement after every line where you are setting a variable's value, so that you can inspect those values. This should help you quickly pinpoint where things start to go wrong.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to write a very basic text string to my documents directory and work from there to later save other files etc.

I am currently stuck with it not writing anything into my Documents directory

(In my viewDidLoad)

NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)
NSString *documentsDirectory = [pathArray objectAtIndex:0];

NSString *textPath = [documentsDirectory stringByAppendingPathComponent:@"file1.txt"];
NSString *text = @"My cool text message";

[[NSFileManager defaultManager] createFileAtPath:textPath contents:nil attributes:nil];
[text writeToFile:textPath atomically:NO encoding:NSUTF8StringEncoding error:NULL];
NSLog(@"Text file data: %@",[[NSFileManager defaultManager] contentsAtPath:textPath]);

This is what gets printed out:

2011-06-27 19:04:43.485 MyApp[5731:707] Text file data: (null)

If I try this, it also prints out null:

NSLog(@"My Documents: %@", [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:NULL]);

What have I missed or am I doing wrong while writing to this file?
Might it be something I need to change in my plist or some frameworks/imports needed?

Thanks

[EDIT]
I passed a NSError object through the writeToFile and got this error:

Error: Error Domain=NSCocoaErrorDomain Code=512 "The operation couldn’t be completed. (Cocoa error 512.)" UserInfo=0x12aa00 {NSFilePath=/var/mobile/Applications/887F4691-3B75-448F-9384-31EBF4E3B63E/Documents/file1.txt, NSUnderlyingError=0x14f6b0 "The operation couldn’t be completed. Not a directory"}

[EDIT 2]
This works fine on the simulator but not on my phone :/


问:
How can I check if treeUri is empty?
I want to check if a treeUri has any files in it or if its empty, so I can delete the Folder. Ive tried listFiles but comes up with Landrodix.etc. and not the actual list. Thanks.

On Folder select

```<code>Intent intent = new
Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, 42);
</code>```

Activity Result

```<code>DocumentFile dfile =
DocumentFile.fromTreeUri(this, uri);
DocumentFile[] de = dfile.listFiles();
st = de.toString();
</code>```

答:
I figured it out

```<code>Uri uri = Uri.parse(muri);
DocumentFile directory =
DocumentFile.fromTreeUri(this, uri);
DocumentFile[] files =
directory.listFiles();
double w3 =
Double.parseDouble(Integer.toString
(files3.length));
</code>```

feel free to use this code no credits required
it just .length

Title: How can I check if treeUri is empty?

Body:
I want to check if a treeUri has any files in it or if its empty, so I can delete the Folder. Ive tried listFiles but comes up with Landrodix.etc. and not the actual list. Thanks.

On Folder select

Intent intent = new
Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, 42);

Activity Result

DocumentFile dfile =
DocumentFile.fromTreeUri(this, uri);
DocumentFile[] de = dfile.listFiles();
st = de.toString();

Body:
I figured it out

Uri uri = Uri.parse(muri);
DocumentFile directory =
DocumentFile.fromTreeUri(this, uri);
DocumentFile[] files =
directory.listFiles();
double w3 =
Double.parseDouble(Integer.toString
(files3.length));

feel free to use this code no credits required
it just .length


问:
How to add button in scroll View using script in unity
I am new to unity and am using unity 2020.3.26f1 . I am receiving an array of names from server. I want to make buttons dynamically using those names inside scroll view using c# script and assign on Click() that simply prints the name of button when its clicked. I just don't know how to create button dynamically. Following is the script I have attached to scroll View;</p>
```<code>public string allNames;

void Start()
{
    StartCoroutine(getNames());
}

IEnumerator getNames()
{
    UnityWebRequest www = UnityWebRequest.Get("http://localhost:8080/names");
    yield return www.SendWebRequest();

    if (www.result != UnityWebRequest.Result.Success)
    {
        Debug.Log(www.error);
    }
    else
    {
        allNames = www.downloadHandler.text;
        allNames = allNames.Replace("[", "");
        allNames = allNames.Replace("]", "");
        allNames = allNames.Replace("\"","");

        string[] separatedNames = allNames.Split(',');
        for (int i = 0; i < separatedNames.Length; i++)
        {
            Debug.Log(separatedNames[i]);
            //make buttons here and attach them to scroll View
        }
    }
}
</code>```

答:
Make a nice button and save it as prefab.

Instantiate it or Pool it.

Add onClick events.

GameObject buttonPrefab;

```<code> void MyAwesomeCreator()
 {
     GameObject go = Instantiate(buttonPrefab);
     var button = GetComponent<UnityEngine.UI.Button>();
     button.onClick.AddListener(() => FooOnClick());
 }
 void FooOnClick()
 {
     Debug.Log("Ta-Da!");
 }
</code>```

Copied from Unity Forum

Body:
I am new to unity and am using unity 2020.3.26f1 . I am receiving an array of names from server. I want to make buttons dynamically using those names inside scroll view using c# script and assign on Click() that simply prints the name of button when its clicked. I just don't know how to create button dynamically. Following is the script I have attached to scroll View;

public string allNames;

void Start()
{
    StartCoroutine(getNames());
}

IEnumerator getNames()
{
    UnityWebRequest www = UnityWebRequest.Get("http://localhost:8080/names");
    yield return www.SendWebRequest();

    if (www.result != UnityWebRequest.Result.Success)
    {
        Debug.Log(www.error);
    }
    else
    {
        allNames = www.downloadHandler.text;
        allNames = allNames.Replace("[", "");
        allNames = allNames.Replace("]", "");
        allNames = allNames.Replace("\"","");

        string[] separatedNames = allNames.Split(',');
        for (int i = 0; i < separatedNames.Length; i++)
        {
            Debug.Log(separatedNames[i]);
            //make buttons here and attach them to scroll View
        }
    }
}

Body:
Make a nice button and save it as prefab.

Instantiate it or Pool it.

Add onClick events.

GameObject buttonPrefab;

 void MyAwesomeCreator()
 {
     GameObject go = Instantiate(buttonPrefab);
     var button = GetComponent<UnityEngine.UI.Button>();
     button.onClick.AddListener(() => FooOnClick());
 }
 void FooOnClick()
 {
     Debug.Log("Ta-Da!");
 }

Copied from Unity Forum


问:
Expo AppLoading hiding SplashScreen immediately on app load in TestFlight
I have an Expo Managed React Native application. I have some async functions that are called before the main app screen renders. It works perfectly fine on dev mode, production dev mode and Expo Go, but on Test Flight the app immediately hides the Splash Screen.

The long and short of it is that I have a state hook that changes when the AppLoading async method completes. During that async period I update my Context API to include the fetched data from an SQLite database. Here is my code:

```<code>import React, { useContext, useEffect, useState } from 'react';
import AppLoading from 'expo-app-loading';
import {
  StyleSheet,
  FlatList,
  View,
  Text,
} from 'react-native';
import { Icon } from 'react-native-elements';
import Card from '../components/Card';
import Colors from '../constants/Colors';
import DatabaseService from '../services/database.service';

import { AppContext } from '../contexts/appContext';

export default () => {
  /**
   * Vars
   */
  const databaseService = DatabaseService.getService();

  /**
   * State
   */
  const [appInitialized, setAppInitialized] = useState(false);
  const [appInitializedFail, setAppInitializedFail] = useState(false);

  /**
   * Contexts
   */
  const { cardsArray, dispatchEvent } = useContext(AppContext);

  /**
   * On mount initialize the database and query for all cards
   */
  useEffect(() => {
    initialize()
      .then(didInitialize => {
        if (didInitialize) {
          setAppInitialized(true);
        } else {
          setAppInitialized(true);
          setAppInitializedFail(true);
        }
      })
      .catch(err => {
        setAppInitialized(true);
        setAppInitializedFail(true);

        console.error(err);
      });
  }, []);

  /**
   * Prepare the app by loading async data
   *
   * @returns {Promise}
   */
  const initialize = async () => {
    const _initialTime = new Date();

    return databaseService.init()
      .then(async database => {
        return getAllCards(database)
          .then(async createdData => {
            const [createdArray, createdMap] = createdData;

            await dispatchEvent('UPDATE_CARDS_MAP', createdMap);
            await dispatchEvent('UPDATE_CARDS_ARRAY', createdArray);

            console.debug(
              `\nFetched all ${createdArray.length} results in ${(new Date() - _initialTime) / 1000}s.`
            );

            return true;
          })
          .catch(err => {
            console.error(err);

            return false;
          });
      })
      .catch(err => {
        console.error(err);

        return false;
      });
  };

  /**
   * Query the database for all cards
   *
   * @param {Class} database Service to utilize our database queries on
   * @returns {Promise}
   */
  const getAllCards = (database) => {
    return new Promise((resolve, reject) => {
      database.db.transaction(
        (tx) => {
          tx.executeSql(
            `SELECT cards.* FROM cards ORDER BY RANDOM()`,
            [],
            (_, res) => {
              const cards = createCardsArray(res.rows._array);

              resolve(cards);
            },
            (_, err) => {
              console.error(err);

              reject(err);
            }
          );
        },
        (err) => {
          console.error(err);

          reject(err);
        }
      );
    });
  };

  /**
   * Create cards array based on a set of cards passed through
   *
   * @param {Object} cards Raw cards array before we manipulate the data
   * @returns {Array}
   */
  const createCardsArray = (cards) => {
    const createdMap = {};
    const createdArray = cards.map(card => {
      const { uuid, otherFaceIds, scryfallId, layout, side } = card;
      const url = `https://api.scryfall.com/cards/${scryfallId}?format=image&version=`;

      let isTransform = undefined;
      let isFlip = undefined;
      let isMeld = undefined;
      let isSplit = undefined;
      let isDual = undefined;
      let imageUrl = `${url}normal`;
      let cropUrl = `${url}art_crop`;
      let thumbUrl = `${url}small`;

      if (otherFaceIds) {
        isDual = true;

        // Cards with two faces
        if (layout.includes('transform') || layout.includes('modal_dfc')) {
          isTransform = true;

          if (side === 'b') {
            imageUrl = imageUrl + `&face=back`;
            cropUrl = cropUrl + `&face=back`;
          }
          // Cards with two sets of data but one side of a card
        } else if (layout.includes('flip')) {
          isFlip = true;
        } else if (layout.includes('meld')) {
          isMeld = true;
        } else if (layout.includes('split')) {
          isSplit = true;
        }
      }

      const newCard = {
        ...card,
        imageUrl,
        cropUrl,
        thumbUrl,
        isDual,
        isTransform,
        isSplit,
        isFlip,
        isMeld,
      };

      createdMap[uuid] = newCard;

      return newCard;
    });

    return [createdArray, createdMap];
  };

  /**
   * Render the loading view
   *
   * @returns {JSX}
   */
  if (!appInitialized) {
    return (
      <AppLoading />
    );
  }

  /**
   * Render the error view
   *
   * @returns {JSX}
   */
  if (appInitializedFail) {
    return (
      <View style={styles.screenView}>
        <Icon color={Colors.redColor} size={40} name="warning-outline" type="ionicon" />
        <Text style={styles.errorText}>The database failed to load!</Text>
        <Text style={[styles.errorText, styles.errorTextSmall]}>You can try restarting the application, restarting your device or reinstalling the application to resolve this issue.</Text>
      </View>
    );
  }

  /**
   * Render the successful view
   *
   * @returns {JSX}
   */
  return (
    <View style={styles.screenView}>
      <FlatList
        data={cardsArray}
        renderItem={({ item: card }) => <Card
          card={card}
          hideFavoriteButton={false}
        />}
        keyExtractor={item => item.id}
      />
    </View>
  );
};

/**
 * Styles
 */
const styles = StyleSheet.create({
  screenView: {
    ...StyleSheet.absoluteFill,
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: Colors.darkColor,
    paddingLeft: 20,
    paddingRight: 20,
  },
  errorText: {
    textAlign: 'center',
    color: Colors.redColor,
    fontSize: 20,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  errorTextSmall: {
    fontSize: 16,
    color: Colors.lightColor,
  }
});
</code>```

Can anyone decipher whats going on here to cause TestFlight to not respect the AppLoading component?

答:
Turns out the issue was that my promise setup was not returning correctly, the proper way to return the promises to not hide the AppLoading component was to change my code to this using Expo Splash Screen and changing my promises like so:</p>
```<code>import React, { useContext, useEffect, useState } from 'react';
import * as SplashScreen from 'expo-splash-screen';
import {
  StyleSheet,
  FlatList,
  View,
  Text,
} from 'react-native';
import { Icon } from 'react-native-elements';
import * as Analytics from 'expo-firebase-analytics';
import Card from '../components/Card';
import Colors from '../constants/Colors';
import DatabaseService from '../services/database.service';

import { AppContext } from '../contexts/appContext';

SplashScreen.preventAutoHideAsync();

export default () => {
  /**
   * Vars
   */
  const databaseService = DatabaseService.getService();

  /**
   * State
   */
  const [appInitializedFail, setAppInitializedFail] = useState(false);
  const [errorHasBeenSet, setErrorHasBeenSet] = useState(false);
  const [errorCode, setErrorCode] = useState(null);

  /**
   * Contexts
   */
  const { cardsArray, dispatchEvent } = useContext(AppContext);

  /**
   * On mount initialize the database and query for all cards
   */
  useEffect(() => {
    initialize()
      .then(didInitialize => {
        if (!!didInitialize) {
          SplashScreen.hideAsync();
        } else {
          setErrorViewState('Error: App initialized with no data.');
        }
      })
      .catch(err => {
        setErrorViewState('Error: Failed to initialize application.');

        console.error(err);
      });
  }, []);

  /**
   * Prepare the app by loading async data
   *
   * @returns {Promise}
   */
  const initialize = async () => {
    const _initialTime = new Date();

    return databaseService.init(setErrorViewState)
      .then(async database => {
        return await getAllCards(database)
          .then(results => {
            if(results){
              const [createdArray, createdMap] = results;

              dispatchEvent('UPDATE_CARDS_MAP', createdMap);
              dispatchEvent('UPDATE_CARDS_ARRAY', createdArray);

              console.debug(
                `\nFetched all ${createdArray.length} results in ${(new Date() - _initialTime) / 1000}s.`
              );

              return true;
            } else {
              setErrorViewState('Error: No database data.');

              return false;
            }
          })
          .catch(err => {
            setErrorViewState('Error: Failed to get database data.');

            return err;
          });
      })
      .catch(err => {
        setErrorViewState('Error: Failed to initialize the database.');

        return err;
      });
  };

  /**
   * Query the database for all cards
   *
   * @param {Class} database Service to utilize our database queries on
   * @returns {Promise}
   */
  const getAllCards = (database) => {
    return new Promise(async (resolve, reject) => {
      return await database.db.transaction(
        (tx) => {
          tx.executeSql(
            `SELECT cards.* FROM cards ORDER BY RANDOM()`,
            [],
            (_, res) => {
              const cards = createCardsArray(res.rows._array);

              resolve(cards);
            },
            (_, err) => {
              setErrorViewState('Error: Failed to execute query.');

              reject(err);
            }
          );
        },
        (err) => {
          setErrorViewState('Error: Failed to execute transaction.');

          reject(err);
        }
      );
    });
  };

  /**
   * Create cards array based on a set of cards passed through
   *
   * @param {Object} cards Raw cards array before we manipulate the data
   * @returns {Array}
   */
  const createCardsArray = (cards) => {
    const createdMap = {};
    const createdArray = cards
      .map(card => {
        const { uuid, otherFaceIds, scryfallId, layout, side } = card;
        const url = `https://api.scryfall.com/cards/${scryfallId}?format=image&version=`;

        let isTransform = undefined;
        let isFlip = undefined;
        let isMeld = undefined;
        let isSplit = undefined;
        let isDual = undefined;
        let imageUrl = `${url}normal`;
        let cropUrl = `${url}art_crop`;
        let thumbUrl = `${url}small`;

        if (otherFaceIds) {
          isDual = true;

          // Cards with two faces
          if (layout.includes('transform') || layout.includes('modal_dfc')) {
            isTransform = true;

            if (side === 'b') {
              imageUrl = imageUrl + `&face=back`;
              cropUrl = cropUrl + `&face=back`;
            }
            // Cards with two sets of data but one side of a card
          } else if (layout.includes('flip')) {
            isFlip = true;
          } else if (layout.includes('meld')) {
            isMeld = true;
          } else if (layout.includes('split')) {
            isSplit = true;
          }
        }

        const newCard = {
          ...card,
          imageUrl,
          cropUrl,
          thumbUrl,
          isDual,
          isTransform,
          isSplit,
          isFlip,
          isMeld,
        };

        createdMap[uuid] = newCard;

        return newCard;
      })
      // Filter out other sides so we can see the main face first and swap them later
      .filter(card => card.side === 'a' || !card.side);

    return [createdArray, createdMap];
  };

  /**
   * Set state to show our error message
   */
  const setErrorViewState = (errorCode = null) => {
    // Ensure we establish the first caught error
    if(!errorHasBeenSet){
      setErrorHasBeenSet(true);
      setAppInitializedFail(true);
      setErrorCode(errorCode);

      SplashScreen.hideAsync();

      Analytics.logEvent('app_failed_initialization', {
        contentType: 'text',
        itemId: errorCode || 'Error: Unknown',
        method: 'app load'
      });
    }
  }

  /**
   * Render the error view
   *
   * @returns {JSX}
   */
  if (appInitializedFail) {
    return (
      <View style={styles.screenView}>
        <Icon color={Colors.redColor} size={40} name="warning-outline" type="ionicon" />
        <Text style={styles.errorText}>There was a problem</Text>
        {errorCode && <Text style={[styles.errorText, styles.errorCode]}>{errorCode}</Text>}
        <Text style={[styles.errorText, styles.errorTextSmall]}>You can try restarting the application, restarting your device and reinstalling the application to resolve this issue.</Text>
        <Text style={[styles.errorText, styles.errorTextSmall]}>If that does not work, please take a screenshot and report this to the developer.</Text>
      </View>
    );
  }

  /**
   * Render the successful view
   *
   * @returns {JSX}
   */
  return (
    <View style={styles.screenView}>
      <FlatList
        data={cardsArray}
        keyExtractor={item => item.id}
        showsVerticalScrollIndicator={false}
        renderItem={({ item: card }) => <Card
          card={card}
          hideFavoriteButton={false}
        />}
      />
    </View>
  );
};

/**
 * Styles
 */
const styles = StyleSheet.create({
  screenView: {
    ...StyleSheet.absoluteFill,
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: Colors.darkColor,
  },
  errorText: {
    textAlign: 'center',
    color: Colors.redColor,
    fontSize: 20,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  errorCode: {
    fontSize: 18,
  },
  errorTextSmall: {
    fontSize: 16,
    color: Colors.lightColor,
  }
});
</code>```

Body:
I have an Expo Managed React Native application. I have some async functions that are called before the main app screen renders. It works perfectly fine on dev mode, production dev mode and Expo Go, but on Test Flight the app immediately hides the Splash Screen.

The long and short of it is that I have a state hook that changes when the AppLoading async method completes. During that async period I update my Context API to include the fetched data from an SQLite database. Here is my code:

import React, { useContext, useEffect, useState } from 'react';
import AppLoading from 'expo-app-loading';
import {
  StyleSheet,
  FlatList,
  View,
  Text,
} from 'react-native';
import { Icon } from 'react-native-elements';
import Card from '../components/Card';
import Colors from '../constants/Colors';
import DatabaseService from '../services/database.service';

import { AppContext } from '../contexts/appContext';

export default () => {
  /**
   * Vars
   */
  const databaseService = DatabaseService.getService();

  /**
   * State
   */
  const [appInitialized, setAppInitialized] = useState(false);
  const [appInitializedFail, setAppInitializedFail] = useState(false);

  /**
   * Contexts
   */
  const { cardsArray, dispatchEvent } = useContext(AppContext);

  /**
   * On mount initialize the database and query for all cards
   */
  useEffect(() => {
    initialize()
      .then(didInitialize => {
        if (didInitialize) {
          setAppInitialized(true);
        } else {
          setAppInitialized(true);
          setAppInitializedFail(true);
        }
      })
      .catch(err => {
        setAppInitialized(true);
        setAppInitializedFail(true);

        console.error(err);
      });
  }, []);

  /**
   * Prepare the app by loading async data
   *
   * @returns {Promise}
   */
  const initialize = async () => {
    const _initialTime = new Date();

    return databaseService.init()
      .then(async database => {
        return getAllCards(database)
          .then(async createdData => {
            const [createdArray, createdMap] = createdData;

            await dispatchEvent('UPDATE_CARDS_MAP', createdMap);
            await dispatchEvent('UPDATE_CARDS_ARRAY', createdArray);

            console.debug(
              `\nFetched all ${createdArray.length} results in ${(new Date() - _initialTime) / 1000}s.`
            );

            return true;
          })
          .catch(err => {
            console.error(err);

            return false;
          });
      })
      .catch(err => {
        console.error(err);

        return false;
      });
  };

  /**
   * Query the database for all cards
   *
   * @param {Class} database Service to utilize our database queries on
   * @returns {Promise}
   */
  const getAllCards = (database) => {
    return new Promise((resolve, reject) => {
      database.db.transaction(
        (tx) => {
          tx.executeSql(
            `SELECT cards.* FROM cards ORDER BY RANDOM()`,
            [],
            (_, res) => {
              const cards = createCardsArray(res.rows._array);

              resolve(cards);
            },
            (_, err) => {
              console.error(err);

              reject(err);
            }
          );
        },
        (err) => {
          console.error(err);

          reject(err);
        }
      );
    });
  };

  /**
   * Create cards array based on a set of cards passed through
   *
   * @param {Object} cards Raw cards array before we manipulate the data
   * @returns {Array}
   */
  const createCardsArray = (cards) => {
    const createdMap = {};
    const createdArray = cards.map(card => {
      const { uuid, otherFaceIds, scryfallId, layout, side } = card;
      const url = `https://api.scryfall.com/cards/${scryfallId}?format=image&version=`;

      let isTransform = undefined;
      let isFlip = undefined;
      let isMeld = undefined;
      let isSplit = undefined;
      let isDual = undefined;
      let imageUrl = `${url}normal`;
      let cropUrl = `${url}art_crop`;
      let thumbUrl = `${url}small`;

      if (otherFaceIds) {
        isDual = true;

        // Cards with two faces
        if (layout.includes('transform') || layout.includes('modal_dfc')) {
          isTransform = true;

          if (side === 'b') {
            imageUrl = imageUrl + `&face=back`;
            cropUrl = cropUrl + `&face=back`;
          }
          // Cards with two sets of data but one side of a card
        } else if (layout.includes('flip')) {
          isFlip = true;
        } else if (layout.includes('meld')) {
          isMeld = true;
        } else if (layout.includes('split')) {
          isSplit = true;
        }
      }

      const newCard = {
        ...card,
        imageUrl,
        cropUrl,
        thumbUrl,
        isDual,
        isTransform,
        isSplit,
        isFlip,
        isMeld,
      };

      createdMap[uuid] = newCard;

      return newCard;
    });

    return [createdArray, createdMap];
  };

  /**
   * Render the loading view
   *
   * @returns {JSX}
   */
  if (!appInitialized) {
    return (
      <AppLoading />
    );
  }

  /**
   * Render the error view
   *
   * @returns {JSX}
   */
  if (appInitializedFail) {
    return (
      <View style={styles.screenView}>
        <Icon color={Colors.redColor} size={40} name="warning-outline" type="ionicon" />
        <Text style={styles.errorText}>The database failed to load!</Text>
        <Text style={[styles.errorText, styles.errorTextSmall]}>You can try restarting the application, restarting your device or reinstalling the application to resolve this issue.</Text>
      </View>
    );
  }

  /**
   * Render the successful view
   *
   * @returns {JSX}
   */
  return (
    <View style={styles.screenView}>
      <FlatList
        data={cardsArray}
        renderItem={({ item: card }) => <Card
          card={card}
          hideFavoriteButton={false}
        />}
        keyExtractor={item => item.id}
      />
    </View>
  );
};

/**
 * Styles
 */
const styles = StyleSheet.create({
  screenView: {
    ...StyleSheet.absoluteFill,
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: Colors.darkColor,
    paddingLeft: 20,
    paddingRight: 20,
  },
  errorText: {
    textAlign: 'center',
    color: Colors.redColor,
    fontSize: 20,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  errorTextSmall: {
    fontSize: 16,
    color: Colors.lightColor,
  }
});

Can anyone decipher whats going on here to cause TestFlight to not respect the AppLoading component?

Body:
Turns out the issue was that my promise setup was not returning correctly, the proper way to return the promises to not hide the AppLoading component was to change my code to this using Expo Splash Screen and changing my promises like so:

import React, { useContext, useEffect, useState } from 'react';
import * as SplashScreen from 'expo-splash-screen';
import {
  StyleSheet,
  FlatList,
  View,
  Text,
} from 'react-native';
import { Icon } from 'react-native-elements';
import * as Analytics from 'expo-firebase-analytics';
import Card from '../components/Card';
import Colors from '../constants/Colors';
import DatabaseService from '../services/database.service';

import { AppContext } from '../contexts/appContext';

SplashScreen.preventAutoHideAsync();

export default () => {
  /**
   * Vars
   */
  const databaseService = DatabaseService.getService();

  /**
   * State
   */
  const [appInitializedFail, setAppInitializedFail] = useState(false);
  const [errorHasBeenSet, setErrorHasBeenSet] = useState(false);
  const [errorCode, setErrorCode] = useState(null);

  /**
   * Contexts
   */
  const { cardsArray, dispatchEvent } = useContext(AppContext);

  /**
   * On mount initialize the database and query for all cards
   */
  useEffect(() => {
    initialize()
      .then(didInitialize => {
        if (!!didInitialize) {
          SplashScreen.hideAsync();
        } else {
          setErrorViewState('Error: App initialized with no data.');
        }
      })
      .catch(err => {
        setErrorViewState('Error: Failed to initialize application.');

        console.error(err);
      });
  }, []);

  /**
   * Prepare the app by loading async data
   *
   * @returns {Promise}
   */
  const initialize = async () => {
    const _initialTime = new Date();

    return databaseService.init(setErrorViewState)
      .then(async database => {
        return await getAllCards(database)
          .then(results => {
            if(results){
              const [createdArray, createdMap] = results;

              dispatchEvent('UPDATE_CARDS_MAP', createdMap);
              dispatchEvent('UPDATE_CARDS_ARRAY', createdArray);

              console.debug(
                `\nFetched all ${createdArray.length} results in ${(new Date() - _initialTime) / 1000}s.`
              );

              return true;
            } else {
              setErrorViewState('Error: No database data.');

              return false;
            }
          })
          .catch(err => {
            setErrorViewState('Error: Failed to get database data.');

            return err;
          });
      })
      .catch(err => {
        setErrorViewState('Error: Failed to initialize the database.');

        return err;
      });
  };

  /**
   * Query the database for all cards
   *
   * @param {Class} database Service to utilize our database queries on
   * @returns {Promise}
   */
  const getAllCards = (database) => {
    return new Promise(async (resolve, reject) => {
      return await database.db.transaction(
        (tx) => {
          tx.executeSql(
            `SELECT cards.* FROM cards ORDER BY RANDOM()`,
            [],
            (_, res) => {
              const cards = createCardsArray(res.rows._array);

              resolve(cards);
            },
            (_, err) => {
              setErrorViewState('Error: Failed to execute query.');

              reject(err);
            }
          );
        },
        (err) => {
          setErrorViewState('Error: Failed to execute transaction.');

          reject(err);
        }
      );
    });
  };

  /**
   * Create cards array based on a set of cards passed through
   *
   * @param {Object} cards Raw cards array before we manipulate the data
   * @returns {Array}
   */
  const createCardsArray = (cards) => {
    const createdMap = {};
    const createdArray = cards
      .map(card => {
        const { uuid, otherFaceIds, scryfallId, layout, side } = card;
        const url = `https://api.scryfall.com/cards/${scryfallId}?format=image&version=`;

        let isTransform = undefined;
        let isFlip = undefined;
        let isMeld = undefined;
        let isSplit = undefined;
        let isDual = undefined;
        let imageUrl = `${url}normal`;
        let cropUrl = `${url}art_crop`;
        let thumbUrl = `${url}small`;

        if (otherFaceIds) {
          isDual = true;

          // Cards with two faces
          if (layout.includes('transform') || layout.includes('modal_dfc')) {
            isTransform = true;

            if (side === 'b') {
              imageUrl = imageUrl + `&face=back`;
              cropUrl = cropUrl + `&face=back`;
            }
            // Cards with two sets of data but one side of a card
          } else if (layout.includes('flip')) {
            isFlip = true;
          } else if (layout.includes('meld')) {
            isMeld = true;
          } else if (layout.includes('split')) {
            isSplit = true;
          }
        }

        const newCard = {
          ...card,
          imageUrl,
          cropUrl,
          thumbUrl,
          isDual,
          isTransform,
          isSplit,
          isFlip,
          isMeld,
        };

        createdMap[uuid] = newCard;

        return newCard;
      })
      // Filter out other sides so we can see the main face first and swap them later
      .filter(card => card.side === 'a' || !card.side);

    return [createdArray, createdMap];
  };

  /**
   * Set state to show our error message
   */
  const setErrorViewState = (errorCode = null) => {
    // Ensure we establish the first caught error
    if(!errorHasBeenSet){
      setErrorHasBeenSet(true);
      setAppInitializedFail(true);
      setErrorCode(errorCode);

      SplashScreen.hideAsync();

      Analytics.logEvent('app_failed_initialization', {
        contentType: 'text',
        itemId: errorCode || 'Error: Unknown',
        method: 'app load'
      });
    }
  }

  /**
   * Render the error view
   *
   * @returns {JSX}
   */
  if (appInitializedFail) {
    return (
      <View style={styles.screenView}>
        <Icon color={Colors.redColor} size={40} name="warning-outline" type="ionicon" />
        <Text style={styles.errorText}>There was a problem</Text>
        {errorCode && <Text style={[styles.errorText, styles.errorCode]}>{errorCode}</Text>}
        <Text style={[styles.errorText, styles.errorTextSmall]}>You can try restarting the application, restarting your device and reinstalling the application to resolve this issue.</Text>
        <Text style={[styles.errorText, styles.errorTextSmall]}>If that does not work, please take a screenshot and report this to the developer.</Text>
      </View>
    );
  }

  /**
   * Render the successful view
   *
   * @returns {JSX}
   */
  return (
    <View style={styles.screenView}>
      <FlatList
        data={cardsArray}
        keyExtractor={item => item.id}
        showsVerticalScrollIndicator={false}
        renderItem={({ item: card }) => <Card
          card={card}
          hideFavoriteButton={false}
        />}
      />
    </View>
  );
};

/**
 * Styles
 */
const styles = StyleSheet.create({
  screenView: {
    ...StyleSheet.absoluteFill,
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: Colors.darkColor,
  },
  errorText: {
    textAlign: 'center',
    color: Colors.redColor,
    fontSize: 20,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  errorCode: {
    fontSize: 18,
  },
  errorTextSmall: {
    fontSize: 16,
    color: Colors.lightColor,
  }
});


问:
asp.net WebSocket keep alive after Action is done
In an asp.net core (5.0) web application, is it possible to keep the socket alive without having a infinite while loop? (while (webSocket.State == WebSocketState.Open) If the loop is the only way to do that, isn't that very inefficient?

This is essentially what I would like to achieve

public class SocketController : Controller
{

  [HttpGet]
  [Route("Connect")]
  public async Task ConnectAsync()
  {
    if (HttpContext.WebSockets.IsWebSocketRequest)
    {
      var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();
      SocketManager.registerSocket(User, webSocket);
      var outputBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes("pong"));
      await webSocket.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
    }
    else
    {
      HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
    }
  }

}
```
<p>This seems to work but, it doesn't seem right</p>
<pre class="lang-cs prettyprint-override"><code>public class SocketController : Controller
{

  [HttpGet]
  [Route("Connect")]
  public async Task ConnectAsync()
  {
    if (HttpContext.WebSockets.IsWebSocketRequest)
    {
      var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();
      // stuff
      while (webSocket.State == WebSocketState.Open) ;
    }
    else
    {
      HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
    }
  }

}
</code>```

Minimal example to check socket closing:

var socket = new WebSocket("wss://localhost:44331/Socket/Connect");
socket.onclose = function (err) {
    console.log("CLOSED");
    console.error(err);
};
```
<p>If I remove the loop, the connection closes on the JS side, the moment the action finishes executing, output:</p>
```CLOSED
{
    isTrusted: true,
    bubbles: false,
    cancelBubble: false,
    cancelable: false,
    code: 1006,
    composed: false,
    currentTarget: [WebSocket Object],
    defaultPrevented: false,
    eventPhase: 0,
    path: [],
    reason: "",
    returnValue: true,
    srcElement: [WebSocket Object],
    target: [WebSocket Object],
    timeStamp: 958.5999999998603,
    type: "close",
    wasClean: false
}
```

答:
WebSocket use ping/pong heartbeat to keepalive.

A Ping frame may serve either as a keepalive or as a means to verify
that the remote endpoint is still responsive.

But when the client gets a Ping, a Pong must be sent back to the server

Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in
response, unless it already received a Close frame. It SHOULD respond
with Pong frame as soon as is practical.

You can use KeepAliveInterval to set How frequently to send "ping" frames to the client to ensure proxies keep the connection open. The default is two minutes.

```<code>var webSocketOptions = new WebSocketOptions()
{
    KeepAliveInterval = TimeSpan.FromSeconds(120),
};

app.UseWebSockets(webSocketOptions);
</code>```

In your code, while (webSocket.State == WebSocketState.Open) just check the state of websocket and it will not keep the websocket alive.

The server is not automatically informed when the client disconnects due to loss of connectivity. The server receives a disconnect message only if the client sends it, which can't be done if the internet connection is lost. If you want to take some action when that happens, set a timeout after nothing is received from the client within a certain time window.

Body:
In an asp.net core (5.0) web application, is it possible to keep the socket alive without having a infinite while loop? (while (webSocket.State == WebSocketState.Open) If the loop is the only way to do that, isn't that very inefficient?

This is essentially what I would like to achieve

public class SocketController : Controller
{

  [HttpGet]
  [Route("Connect")]
  public async Task ConnectAsync()
  {
    if (HttpContext.WebSockets.IsWebSocketRequest)
    {
      var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();
      SocketManager.registerSocket(User, webSocket);
      var outputBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes("pong"));
      await webSocket.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
    }
    else
    {
      HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
    }
  }

}

This seems to work but, it doesn't seem right

public class SocketController : Controller
{

  [HttpGet]
  [Route("Connect")]
  public async Task ConnectAsync()
  {
    if (HttpContext.WebSockets.IsWebSocketRequest)
    {
      var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();
      // stuff
      while (webSocket.State == WebSocketState.Open) ;
    }
    else
    {
      HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
    }
  }

}

Minimal example to check socket closing:

var socket = new WebSocket("wss://localhost:44331/Socket/Connect");
socket.onclose = function (err) {
    console.log("CLOSED");
    console.error(err);
};

If I remove the loop, the connection closes on the JS side, the moment the action finishes executing, output:

CLOSED
{
    isTrusted: true,
    bubbles: false,
    cancelBubble: false,
    cancelable: false,
    code: 1006,
    composed: false,
    currentTarget: [WebSocket Object],
    defaultPrevented: false,
    eventPhase: 0,
    path: [],
    reason: "",
    returnValue: true,
    srcElement: [WebSocket Object],
    target: [WebSocket Object],
    timeStamp: 958.5999999998603,
    type: "close",
    wasClean: false
}

Body:
WebSocket use ping/pong heartbeat to keepalive.

A Ping frame may serve either as a keepalive or as a means to verify
that the remote endpoint is still responsive.

But when the client gets a Ping, a Pong must be sent back to the server

Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in
response, unless it already received a Close frame. It SHOULD respond
with Pong frame as soon as is practical.

You can use KeepAliveInterval to set How frequently to send "ping" frames to the client to ensure proxies keep the connection open. The default is two minutes.

var webSocketOptions = new WebSocketOptions()
{
    KeepAliveInterval = TimeSpan.FromSeconds(120),
};

app.UseWebSockets(webSocketOptions);

In your code, while (webSocket.State == WebSocketState.Open) just check the state of websocket and it will not keep the websocket alive.

The server is not automatically informed when the client disconnects due to loss of connectivity. The server receives a disconnect message only if the client sends it, which can't be done if the internet connection is lost. If you want to take some action when that happens, set a timeout after nothing is received from the client within a certain time window.


问:
Modify ggsurvplot (font.size) and type of confidence intervals
I am trying to modify and better understand the way the function ggsurvplot() works (package: survminer):

First of all some code:

```<code>
suppressPackageStartupMessages(library(survival))
suppressPackageStartupMessages(library(survminer))
suppressPackageStartupMessages(library(tidyverse))

set.seed(2020)

exp <- sample_n(lung, size = 10, replace = F) %>%
  select(time, status)

exp <- sample_n(lung, size = 10, replace = F) %>%
  select(time, status)

exp$survival <- Surv(exp$time, exp$status == 2)

exp_fit <- survfit(survival ~ 1, data = exp, conf.type = "log-log")

ggsurvplot(exp_fit,
           data = exp,
           palette = "black",
           censor.shape = "I",
           censor.size = 5.5,
           xlab = "days",
           ylab = "survival probability",
           conf.int = T,
           surv.scale = "percent",
           legend.title = "censored data",
           legend.lab = "",
           legend ="bottom")

</code>```

The dataframe used is called lung. The data is contained in the package survival.

Basically I have two questions:

The plot prints confidence intervals as it should, BUT what type of them? Are they the same I specified within the survfit() function I used to create the object exp_fit and if not what needs to be the changed so that the same type of confidence intervals are used?

The font size of the legend is quite small. How can I make it bigger?
I tried to work with theme(), but unfortunately it did not work.

I will appreciate your answers. Thanks in advance.

答:
RE question 1

I was wondering the same thing and found this online:

"The function ggsurvplot inherits the chosen confidence interval from the survfit object."
https://www2.karlin.mff.cuni.cz/~vavraj/cda/exercise_04.html

Body:
I am trying to modify and better understand the way the function ggsurvplot() works (package: survminer):

First of all some code:

suppressPackageStartupMessages(library(survival))
suppressPackageStartupMessages(library(survminer))
suppressPackageStartupMessages(library(tidyverse))

set.seed(2020)

exp <- sample_n(lung, size = 10, replace = F) %>%
  select(time, status)

exp <- sample_n(lung, size = 10, replace = F) %>%
  select(time, status)

exp$survival <- Surv(exp$time, exp$status == 2)

exp_fit <- survfit(survival ~ 1, data = exp, conf.type = "log-log")

ggsurvplot(exp_fit,
           data = exp,
           palette = "black",
           censor.shape = "I",
           censor.size = 5.5,
           xlab = "days",
           ylab = "survival probability",
           conf.int = T,
           surv.scale = "percent",
           legend.title = "censored data",
           legend.lab = "",
           legend ="bottom")

The dataframe used is called lung. The data is contained in the package survival.

Basically I have two questions:

The plot prints confidence intervals as it should, BUT what type of them? Are they the same I specified within the survfit() function I used to create the object exp_fit and if not what needs to be the changed so that the same type of confidence intervals are used?

The font size of the legend is quite small. How can I make it bigger?
I tried to work with theme(), but unfortunately it did not work.

I will appreciate your answers. Thanks in advance.


问:
jQuery Animate Question
I have a very basic function which I am using jQuery to slide some content either out (from left to right) or back in (from right to left). The code below works, however, what I am trying to do now is include the "+" at the end of my "overDiv", and make it so that it will always show.

To paint a more lucid picture, right now if you paste that code into your editor and include google's jQuery, you will see that clicking the "+" eliminates the "overDiv" block completely. However, what I want to do is place the "+" at the end of the "overDiv" block so that when the text 'disappears' off of the page, the + will always remain. Hopefully that makes some sense?

Thanks in advance.

```<code><body>

<script language="javascript" type="text/javascript">
$(function() {
    // when we click on the a-href id 'togglen', we move the overDiv to the left.
$('#togglen').click(function() {
    // simple animation
    $('#overDiv').animate({
      left: parseInt($('#overDiv').css('left'),10) == 0 ? -$('#overDiv').outerWidth() : 0
    });
  }); //
});

</script>
<div><a href="#" id="togglen">+</a></div>
<div style="background-color:#CCC; width:180px;  position:absolute; left:0; overflow:hidden; float:left;" id="overDiv">Lorem ipsum.</div>
</code>```

答: http://jsfiddle.net/KmmbK/ I pasted your code into a jsfiddle. Looks like the '+' does always remain. Do you want the '+' inside the disappearing div? If so simply subtract the width of the '+' from the distance the div animates off screen.</p>

Title: jQuery Animate Question

Body:
I have a very basic function which I am using jQuery to slide some content either out (from left to right) or back in (from right to left). The code below works, however, what I am trying to do now is include the "+" at the end of my "overDiv", and make it so that it will always show.

To paint a more lucid picture, right now if you paste that code into your editor and include google's jQuery, you will see that clicking the "+" eliminates the "overDiv" block completely. However, what I want to do is place the "+" at the end of the "overDiv" block so that when the text 'disappears' off of the page, the + will always remain. Hopefully that makes some sense?

Thanks in advance.

+

Lorem ipsum.


问:
Gatsby.js: I set up a css rule for body for a template but it works throughout the entire app
I set up a background image with css (background-image) in the body tag of the template so that only shows in the pages generated with it, however that's affecting all 'body's in the entire gatsby.js website.</p>

答:
This is normal behavior. It's not a Gatsby issue. It's how React's templating/code-splitting works.

You are defining a CSS rule in your isolated CSS but it's bundled when the project is compiled (because of webpack) and because of the specificity, it affects all body tag. In the end, your template will be also injected into the output HTML so all the imports in it will also merge in the final output.

The easiest and most straightforward solution I think is to define a
 (or another tag) just as a direct child of the body for each template/page you want to customize and give a specific class name to apply the CSS only to that template/page. Increasing the specificity is the easiest way to apply.

Soon, in the new Chromium version (99) we will be able to define layered components in order to enhance the specificity and improve that kind of behaviors you've described.

Body:
This is normal behavior. It's not a Gatsby issue. It's how React's templating/code-splitting works.

You are defining a CSS rule in your isolated CSS but it's bundled when the project is compiled (because of webpack) and because of the specificity, it affects all body tag. In the end, your template will be also injected into the output HTML so all the imports in it will also merge in the final output.

The easiest and most straightforward solution I think is to define a <section> (or another tag) just as a direct child of the body for each template/page you want to customize and give a specific class name to apply the CSS only to that template/page. Increasing the specificity is the easiest way to apply.

Soon, in the new Chromium version (99) we will be able to define layered components in order to enhance the specificity and improve that kind of behaviors you've described.


问:
CSS Container margin bottom issue
Hi for mobile version I need margin bottom (white space from bottom of the screen) to the container, it was not working. I have tried position absolute still it was not working. I don't know what mistake exactly I did in here.

```<code> ****Desktop version CSS****
       #container {
       width: 70%;
       margin: 0 auto;
       display: flex;
       height: 100vh;
       align-items: center;
</code>```

}

```<code>****mobile version CSS****
 `     #container {
       display: block;
       text-align: center;
       margin-bottom:25px;
}
</code>```

答:
```<code>****mobile version CSS****
 `     #container {
       display: block;
       text-align: center;
       margin-bottom:25px !important;
}
</code>```

Title: CSS Container margin bottom issue

Body:
Hi for mobile version I need margin bottom (white space from bottom of the screen) to the container, it was not working. I have tried position absolute still it was not working. I don't know what mistake exactly I did in here.

 ****Desktop version CSS****
       #container {
       width: 70%;
       margin: 0 auto;
       display: flex;
       height: 100vh;
       align-items: center;

}

****mobile version CSS****
 `     #container {
       display: block;
       text-align: center;
       margin-bottom:25px;
}


问:
Aggregate nested field with condition
I've multiple documents in following format:

Document #1:

```<code>{
   "stats":{
      "cars":[
         {
            "isEnabled": false,
            "name":"BMW"
         },
         {
            "isEnabled": true,
            "name":"Mercedes"
         }
      ]
   }
}
</code>```

Document #2:

```<code>{
   "stats":{
      "cars":[
         {
            "isEnabled": true,  <--- changed to TRUE
            "name":"BMW"
         },
         {
            "isEnabled": false, <--- changed to FALSE
            "name":"Mercedes"
         }
      ]
   }
}
</code>```

And I'm trying to achieve result which will give me overview of cars which has isEnabled set on true in ALL documents.

The aggregation result should look like this (simplified):

```<code>{
   "buckets": [
      {
          "key": "BMW",
          "doc_count": 1   <---- Only 1, because 1 document has set true in "isEnabled"
      },
      {
          "key": "Mercedes",
          "doc_count": 1   <---- Only 1, because 1 document has set true in "isEnabled"
      },
   ]
}
</code>```

What I've tried

I've tried multiple aggregations, but I'm not able to get the results based on the isEnabled condition, example what I've tried:

```<code>{
    "size": 0,
    "aggs": {
        "carResult": {
            "terms": {
                "field": "stats.cars.name.keyword"
            },
            "aggs": {
                "carsResult": {
                    "terms": {
                        "field": "stats.cars.isEnabled"
                    }
                }
            }
        }
    }
}
</code>```

答:
If you make stats.cars nested you can use following query to aggregate enabled cars.

```<code>{
  "size": 0,
  "aggs": {
    "carResult": {
      "nested": {
        "path": "stats.cars"
      },
      "inner": {
        "asd": {
          "filter": {
            "term": {
              "stats.cars.isEnabled": true
            }
          },
          "inner": {
            "asd": {
              "terms": {
                "field": "stats.cars.name.keyword",
                "size": 10
              }
            }
          }
        }
      }
    }
  }
}
</code>```

This is how you make a field mapping nested from the documentation:
https://www.elastic.co/guide/en/elasticsearch/reference/current/nested.html

Title: Aggregate nested field with condition

Body:
I've multiple documents in following format:

Document #1:

{
   "stats":{
      "cars":[
         {
            "isEnabled": false,
            "name":"BMW"
         },
         {
            "isEnabled": true,
            "name":"Mercedes"
         }
      ]
   }
}

Document #2:

{
   "stats":{
      "cars":[
         {
            "isEnabled": true,  <--- changed to TRUE
            "name":"BMW"
         },
         {
            "isEnabled": false, <--- changed to FALSE
            "name":"Mercedes"
         }
      ]
   }
}

And I'm trying to achieve result which will give me overview of cars which has isEnabled set on true in ALL documents.

The aggregation result should look like this (simplified):

{
   "buckets": [
      {
          "key": "BMW",
          "doc_count": 1   <---- Only 1, because 1 document has set true in "isEnabled"
      },
      {
          "key": "Mercedes",
          "doc_count": 1   <---- Only 1, because 1 document has set true in "isEnabled"
      },
   ]
}

What I've tried

I've tried multiple aggregations, but I'm not able to get the results based on the isEnabled condition, example what I've tried:

{
    "size": 0,
    "aggs": {
        "carResult": {
            "terms": {
                "field": "stats.cars.name.keyword"
            },
            "aggs": {
                "carsResult": {
                    "terms": {
                        "field": "stats.cars.isEnabled"
                    }
                }
            }
        }
    }
}

Body:
If you make stats.cars nested you can use following query to aggregate enabled cars.

{
  "size": 0,
  "aggs": {
    "carResult": {
      "nested": {
        "path": "stats.cars"
      },
      "inner": {
        "asd": {
          "filter": {
            "term": {
              "stats.cars.isEnabled": true
            }
          },
          "inner": {
            "asd": {
              "terms": {
                "field": "stats.cars.name.keyword",
                "size": 10
              }
            }
          }
        }
      }
    }
  }
}

This is how you make a field mapping nested from the documentation:
https://www.elastic.co/guide/en/elasticsearch/reference/current/nested.html


问:
Pytorch update hyper-parameter using current loss, RuntimeError: Trying to backward through the graph a second time
I am defining my own loss function, and my own loss function has a hyper-parameter Lambda. For example, if the prediction is y, then I define the loss function as Loss = Lambda * y. I want to update my Lambda at some iteration using the current round's Loss. For example, at some specific iteration, I want my Lambda to be updated as Lambda = Lambda + Loss, then it returns the error of

```<code>RuntimeError: Trying to backward through the graph a second time (or directly access saved tensors after they have already been freed). Saved intermediate values of the graph are freed when you call .backward() or autograd.grad(). Specify retain_graph=True if you need to backward through the graph a second time or if you need to access saved tensors after calling backward.
</code>```

Specifically, my naive code is as follows:

```<code>import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim

batch_size, input, output = 10, 3, 3
model = nn.Linear(input, output)
optimizer = optim.Adam(model.parameters(), lr=1e-3)
lam = torch.from_numpy(np.array([0.1, 0.1, 0.1]))
lam.requires_grad = False

for i in range(10):
    x = torch.rand(batch_size, input)
    output = model(x)
    loss = torch.sum(lam*output)
    if i == 5:
        lam = lam + torch.clone(loss)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    print(loss)
</code>```

I had the feeling that the error was caused by using Loss to update my Lambda. So I used the code torch.clone(loss), hoping not to influence loss, it didn't help. Does anyone know how to fix the problem? Some explanation about why this error occurs would be great!

答:
Firstly take a look this link.
There's explanation why the error occurs in your code.

To reduce memory usage, during the .backward() call, all the intermediary results are deleted when they are not needed anymore. Hence if you try to call .backward() again, the intermediary results don’t exist and the backward pass cannot be performed (and you get the error you see).

So if you want to fix the problem, you can easily solve it by adding a parameter:

```<code>loss.backward(retain_graph=True)
</code>```

or

```<code>lam = lam + torch.Tensor([loss.item()])
</code>```

Hopefully it helps! ;)

Body:
I am defining my own loss function, and my own loss function has a hyper-parameter Lambda. For example, if the prediction is y, then I define the loss function as Loss = Lambda * y. I want to update my Lambda at some iteration using the current round's Loss. For example, at some specific iteration, I want my Lambda to be updated as Lambda = Lambda + Loss, then it returns the error of

RuntimeError: Trying to backward through the graph a second time (or directly access saved tensors after they have already been freed). Saved intermediate values of the graph are freed when you call .backward() or autograd.grad(). Specify retain_graph=True if you need to backward through the graph a second time or if you need to access saved tensors after calling backward.

Specifically, my naive code is as follows:

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim

batch_size, input, output = 10, 3, 3
model = nn.Linear(input, output)
optimizer = optim.Adam(model.parameters(), lr=1e-3)
lam = torch.from_numpy(np.array([0.1, 0.1, 0.1]))
lam.requires_grad = False

for i in range(10):
    x = torch.rand(batch_size, input)
    output = model(x)
    loss = torch.sum(lam*output)
    if i == 5:
        lam = lam + torch.clone(loss)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    print(loss)

I had the feeling that the error was caused by using Loss to update my Lambda. So I used the code torch.clone(loss), hoping not to influence loss, it didn't help. Does anyone know how to fix the problem? Some explanation about why this error occurs would be great!

Body:
Firstly take a look this link.
There's explanation why the error occurs in your code.

To reduce memory usage, during the .backward() call, all the intermediary results are deleted when they are not needed anymore. Hence if you try to call .backward() again, the intermediary results don’t exist and the backward pass cannot be performed (and you get the error you see).

So if you want to fix the problem, you can easily solve it by adding a parameter:

loss.backward(retain_graph=True)

or

lam = lam + torch.Tensor([loss.item()])

Hopefully it helps! ;)