问:
Firebase REST API auth not working with React?
Basically a friend and I have been working on our React project and we're using Redux and Redux Thunk on the backend to handle authentication. However, we seem to have ran into an issue. Our request was working before, but now it issues a Fetch Failed Loading: POST, and doesn't continue past the initial call. However, when checking Firebase, it returns the correctly created user. I know it doesn't go past the fetch because the console.log doesn't work at all.</p>

```<code>export const signup = (email, password) => {

return async dispatch => {
    const response = await fetch('https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[API-KEY]',
    {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            email: email,
            password: password,
            returnSecureToken: true
        })
    }
    );

    console.log(response);
</code>```

答:
If async is used in the fetch. Need to do this

```<code>let response = await fetch(You_URL)
let json = await response.json()
</code>```

After the response object is obtained,
it needs an await to get the body content from the response
The link below has instructions
Address： Here is the description

Body:
Basically a friend and I have been working on our React project and we're using Redux and Redux Thunk on the backend to handle authentication. However, we seem to have ran into an issue. Our request was working before, but now it issues a Fetch Failed Loading: POST, and doesn't continue past the initial call. However, when checking Firebase, it returns the correctly created user. I know it doesn't go past the fetch because the console.log doesn't work at all.

export const signup = (email, password) => {

return async dispatch => {
    const response = await fetch('https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[API-KEY]',
    {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            email: email,
            password: password,
            returnSecureToken: true
        })
    }
    );

    console.log(response);

Body:
If async is used in the fetch. Need to do this

let response = await fetch(You_URL)
let json = await response.json()

After the response object is obtained,
it needs an await to get the body content from the response
The link below has instructions
Address： Here is the description


来源: stackexchange

问:
Using Tkinter Themes in oop python
I'm trying to use ttkthemes but for some reason when I import it i just get errors, It's telling me AttributeError: module 'ttkthemes.themed_tk' has no attribute 'Tk' so I tried changing Tk to ThemedTk but it still didn't work, thanks for any help in advance.
Here's the original code

```<code>from tkinter import *
import tkinter as tk
from tkinter import ttk
from ttkthemes import themed_tk as tk
class SeaofBTCapp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)
        self.frames = {}
        for F in (StartPage,Task):
            frame = F(container, self)

            self.frames[F] = frame

            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(StartPage)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()
        frame.winfo_toplevel().geometry("1024x720")
        frame.configure(bg='#333130')

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

class Task(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

app = SeaofBTCapp()
app.mainloop()

</code>```

答:
That's because you used from ttkthemes import themed_tk as tk.

When the next time you use tk.Tk(), it could be themed_tk.Tk().Apparently, Tk class is in the module tkinter, not themed_tk.(Although you has used import tkinter as tk,it has been covered by from ttkthemes import themed_tk as tk.)

You could use from ttkthemes import themed_tk as [another_name] then do what you want.

ContentLicense: CC BY-SA 4.0

Title: Using Tkinter Themes in oop python

Body:
I'm trying to use ttkthemes but for some reason when I import it i just get errors, It's telling me AttributeError: module 'ttkthemes.themed_tk' has no attribute 'Tk' so I tried changing Tk to ThemedTk but it still didn't work, thanks for any help in advance.
Here's the original code

from tkinter import *
import tkinter as tk
from tkinter import ttk
from ttkthemes import themed_tk as tk
class SeaofBTCapp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)
        self.frames = {}
        for F in (StartPage,Task):
            frame = F(container, self)

            self.frames[F] = frame

            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(StartPage)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()
        frame.winfo_toplevel().geometry("1024x720")
        frame.configure(bg='#333130')

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

class Task(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

app = SeaofBTCapp()
app.mainloop()


问:
JavaScript invoke transactions in MarkLogic
I have xml document:

```<code><product-inventory>
  <product>
    <name>shoe</name>
    <price>100</price>
    <date>2020-05-31</date>
  </product>
  <product>
   <name>dress</name>
    <price>100</price>
    <date>2020-06-01</date>
  </product>
  <product>
   <name>dress</name>
    <price>200</price>
    <date>2020-06-02</date>
  </product>
</product-inventory>
</code>```

I wrote a program to update the 2nd price element, audit such update, finally retrieve the updated document.
The program contains three functions. I still see the old document when the program reaches the final retrieval step.  If I open another window, I do see the updated document.

```<code><product-inventory>
  <product>
    <name>shoe</name>
    <price>100</price>
    <date>2020-05-31</date>
  </product>
  <product>
   <name>dress</name>
    <price>700</price>
    <date>2020-06-01</date>
    <audit>
      <modifiedBy>admin</modifiedBy>
      <modifiedDate>2020-06-02T16:12:14.9664853-04:00</modifiedDate>
    </audit>
  </product>
  <product>
   <name>dress</name>
    <price>200</price>
    <date>2020-06-02</date>
  </product>
</product-inventory>
</code>```

The gist of the functions:

```<code>function  updateDoc() {
**************
   xdmp.nodeReplace(
**************
};

function auditHistory() {
*********************
   xdmp.nodeInsertAfter(
*********************
};

function retrieveDoc() {
  return fn.collection('product')
};

xdmp.invokeFunction(function(){
  declareUpdate();
  updateDoc();
  auditHistory();
}),
retrieveDoc();
</code>```

Can someone explain why I still see the old document when the program reaches retrieveDoc()?

答:
I believe you need to wrap retrieveDoc() into another xdmp.invokeFunction to see the updated document.

xdmp.invokeFunction(() => {
  return retrieveDoc()
})
```

Body:
I have xml document:

<product-inventory>
  <product>
    <name>shoe</name>
    <price>100</price>
    <date>2020-05-31</date>
  </product>
  <product>
   <name>dress</name>
    <price>100</price>
    <date>2020-06-01</date>
  </product>
  <product>
   <name>dress</name>
    <price>200</price>
    <date>2020-06-02</date>
  </product>
</product-inventory>

I wrote a program to update the 2nd price element, audit such update, finally retrieve the updated document.
The program contains three functions. I still see the old document when the program reaches the final retrieval step.  If I open another window, I do see the updated document.

<product-inventory>
  <product>
    <name>shoe</name>
    <price>100</price>
    <date>2020-05-31</date>
  </product>
  <product>
   <name>dress</name>
    <price>700</price>
    <date>2020-06-01</date>
    <audit>
      <modifiedBy>admin</modifiedBy>
      <modifiedDate>2020-06-02T16:12:14.9664853-04:00</modifiedDate>
    </audit>
  </product>
  <product>
   <name>dress</name>
    <price>200</price>
    <date>2020-06-02</date>
  </product>
</product-inventory>

The gist of the functions:

function  updateDoc() {
**************
   xdmp.nodeReplace(
**************
};

function auditHistory() {
*********************
   xdmp.nodeInsertAfter(
*********************
};

function retrieveDoc() {
  return fn.collection('product')
};

xdmp.invokeFunction(function(){
  declareUpdate();
  updateDoc();
  auditHistory();
}),
retrieveDoc();

Can someone explain why I still see the old document when the program reaches retrieveDoc()?


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

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

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

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

Many Thanks,
-Code

答:
.a files are called static libraries.  When you build your code, they essentially get compiled in at build time.  These are definitely allowed by Apple.  In fact, XCode provides a template for a "Cocoa Touch Static Library" when creating a new project.

.dylib files on the other hand are dynamic libraries and are not allowed by Apple.  They are separate code files that can be shared by multiple applications as their code gets brought in to your app at run time.

Saurik (the guy who created Cydia) solved this issue by creating Mobile Substrate for jailbroken iPhones.  It allows devs to create dynamic libraries in order to alter the functionality of existing Apple classes.

Hope this clears the issue up.

ContentLicense: CC BY-SA 3.0


问:
Py2App Placing PIL Dylibs in Zip file
I have an python application that uses the Python Imaging Library (PIL) and is packaged using Py2app. Numpy dylibs are found in the app contents directory:

```<code>demo.app/Contents/Resources/lib/python3.8/numpy/.dylibs/libgcc_s.1.dylib

</code>```

where they can be searched for and signed but PIP dylibs are inside a python3.8.zip file

```<code>demo.app/Contents/Resources/lib/python3.zip -> ./PIL/.dylibs/libfreetype.6.dylib
</code>```

where one would have to unzip, sign, and rezip them. Why does this happen and how do I prevent it so that I don't have to treat it different?

答:
py2app implements special handling of certain packages via a mechanism called "recipes".  It comes with built-in recipes for certain packages including numpy, which is why numpy is excluded from the .zip file.  (Here's the built-in numpy recipe.)

In addition to the built-in recipes, you can define your own recipes for py2app to use.  Just define a class that has a check method, and monkey-patch it as an attribute onto py2app.recipes:

# In setup.py

class PIL_recipe:
    def check(self, cmd, mf):
        m = mf.findNode("PIL")
        if m is None or m.filename is None:
            return None

        # Exclude from site-packages.zip
        return {"packages": ["PIL"]}

py2app.recipes.PIL = PIL_recipe()

...

setup(...)
```

<p>If you need to do this with several libraries, you can generalize this trick so that it doesn't hard-code the name of the package:</p>

```class ExcludeFromZip_Recipe(object):
    def __init__(self, module):
        self.module = module

    def check(self, cmd, mf):
        m = mf.findNode(self.module)
        if m is None:
            return None

        # Don't put the module in the site-packages.zip file
        return {"packages": [self.module]}

for module in ['PIL', 'skimage', 'sklearn', 'jsonschema']:
    setattr( py2app.recipes, module, ExcludeFromZip_Recipe(module) )
```

Disclaimer: This is how I've solved this problem in the past.  But I'm not sure why your zip file is named python3.zip instead of site-packages.zip.

Title: Py2App Placing PIL Dylibs in Zip file

Body:
I have an python application that uses the Python Imaging Library (PIL) and is packaged using Py2app. Numpy dylibs are found in the app contents directory:

demo.app/Contents/Resources/lib/python3.8/numpy/.dylibs/libgcc_s.1.dylib

where they can be searched for and signed but PIP dylibs are inside a python3.8.zip file

demo.app/Contents/Resources/lib/python3.zip -> ./PIL/.dylibs/libfreetype.6.dylib

where one would have to unzip, sign, and rezip them. Why does this happen and how do I prevent it so that I don't have to treat it different?

Body:
py2app implements special handling of certain packages via a mechanism called "recipes".  It comes with built-in recipes for certain packages including numpy, which is why numpy is excluded from the .zip file.  (Here's the built-in numpy recipe.)

In addition to the built-in recipes, you can define your own recipes for py2app to use.  Just define a class that has a check method, and monkey-patch it as an attribute onto py2app.recipes:

# In setup.py

class PIL_recipe:
    def check(self, cmd, mf):
        m = mf.findNode("PIL")
        if m is None or m.filename is None:
            return None

        # Exclude from site-packages.zip
        return {"packages": ["PIL"]}

py2app.recipes.PIL = PIL_recipe()

...

setup(...)

If you need to do this with several libraries, you can generalize this trick so that it doesn't hard-code the name of the package:

class ExcludeFromZip_Recipe(object):
    def __init__(self, module):
        self.module = module

    def check(self, cmd, mf):
        m = mf.findNode(self.module)
        if m is None:
            return None

        # Don't put the module in the site-packages.zip file
        return {"packages": [self.module]}

for module in ['PIL', 'skimage', 'sklearn', 'jsonschema']:
    setattr( py2app.recipes, module, ExcludeFromZip_Recipe(module) )

Disclaimer: This is how I've solved this problem in the past.  But I'm not sure why your zip file is named python3.zip instead of site-packages.zip.


问:
Selenium browser instance can be accessible from a different process?
What I am currently trying to do is the following. There are a number of changing values (js driven) in a website that I am monitoring and saving to a database using Selenium. The values are read through infinite loops, from elements found with selenium's find_element.

This works as intended with one process. However, when I try to multiprocess this (to monitor multiple values at the same time), there seems to be no way to do it without opening one separate browser for each process (unfeasible, since we are talking about close to 60 different elements).

The browser I open before multiprocessing seems to not be available from within the various processes. Even if I find the elements before the multiprocessing step, I cannot pass them to the process since the webelements can't be pickled.

Am I doing something wrong, is selenium not the tool for the job, or is there another way?

The code below doesn't actually work, it's just meant to show the structure of what I currently have as a "working version". What I need to get away from is opening the browser from within the function and have all my processes relying on a single browser.

```<code>import time
import datetime
import os
from selenium import webdriver
from multiprocessing import Pool

def sampling(value_ID):
    dir = os.path.dirname(__file__)

    driver = webdriver.Firefox(dir)
    driver.get("https:\\website.org")

    monitored_value = driver.find_element_by_xpath('value_ID')

    while(1):
            print(monitored_value.text)
            time.sleep(0.1)

value_array = [1,2,3,4,5,6]

if __name__ == '__main__':
    with Pool(6) as p:
        p.map(getSampleRT, value_array)
</code>```

答:
You can checkout selenium abstract listeners if you want to capture the changes in elements. By implementing a listener you can get rid of infinite loops. Here is an example that i think it can work for you.

class EventListeners(AbstractEventListener):
    def before_change_value_of(self, element, driver):
        # check if this is the element you are looking for
        # do your stuff
        print("element changed!")

driver_with_listeners = EventFiringWebDriver(driver, EventListeners()
# wait as much as you like while your listeners are working
driver_with_listeners.implicitly_wait(20000)
```

Also you can checkout this post for more complete implementation.

Body:
What I am currently trying to do is the following. There are a number of changing values (js driven) in a website that I am monitoring and saving to a database using Selenium. The values are read through infinite loops, from elements found with selenium's find_element.

This works as intended with one process. However, when I try to multiprocess this (to monitor multiple values at the same time), there seems to be no way to do it without opening one separate browser for each process (unfeasible, since we are talking about close to 60 different elements).

The browser I open before multiprocessing seems to not be available from within the various processes. Even if I find the elements before the multiprocessing step, I cannot pass them to the process since the webelements can't be pickled.

Am I doing something wrong, is selenium not the tool for the job, or is there another way?

The code below doesn't actually work, it's just meant to show the structure of what I currently have as a "working version". What I need to get away from is opening the browser from within the function and have all my processes relying on a single browser.

import time
import datetime
import os
from selenium import webdriver
from multiprocessing import Pool

def sampling(value_ID):
    dir = os.path.dirname(__file__)

    driver = webdriver.Firefox(dir)
    driver.get("https:\\website.org")

    monitored_value = driver.find_element_by_xpath('value_ID')

    while(1):
            print(monitored_value.text)
            time.sleep(0.1)

value_array = [1,2,3,4,5,6]

if __name__ == '__main__':
    with Pool(6) as p:
        p.map(getSampleRT, value_array)

Body:
You can checkout selenium abstract listeners if you want to capture the changes in elements. By implementing a listener you can get rid of infinite loops. Here is an example that i think it can work for you.

class EventListeners(AbstractEventListener):
    def before_change_value_of(self, element, driver):
        # check if this is the element you are looking for
        # do your stuff
        print("element changed!")

driver_with_listeners = EventFiringWebDriver(driver, EventListeners()
# wait as much as you like while your listeners are working
driver_with_listeners.implicitly_wait(20000)

Also you can checkout this post for more complete implementation.


答:
You overwrote your tk wich represents the tkinter module with ttkthemes.themed_tk.

tk.Tk being the window of tkinter module you can't access it anymore

Title: Using Tkinter Themes in oop python


问:
Flutter non-removable notifications
I wonder if there's a way to make a fixed notificatior or a non-removable notification using Flutter. I already seen "flutter_local_notifications" but I can't find a way to make something like this: notification example

Thanks in advance!

答: As ALL notifications are removable in iOS (please correct me if I am wrong) its unlikely that you will find a flutter plugin that has this functionality. So your best bet is to implement this yourself using platform channels and use Notification.FLAG_NO_CLEAR; to make the notifications un-removable.

Title: Flutter non-removable notifications


问:
How to remove backend address pool configuration from load balancer
I have used Az-powershell task in azure devops pipeline and tried below cmdlet.Its showing error " Set_AzLoadBalancer: Resource/Subscription/MySUbscription ID>/resourceGroups/MyresourceGroup/providers/Microsift.Net/LoadBalancer/MyLoadBalancer/LoadBalancingRules/MyLoadBalancingrule was not found.Please make sure that the referenced resource exists, and that both resources are in same region ."
 Please suggest</p>

```<code>Get-AzLoadBalancer -Name "MyLoadBalancer" -ResourceGroupName "MyResourceGroup" | Remove-AzLoadBalancerBackendAddressPoolConfig -Name "BackendAddressPool02" | Set-AzLoadBalancer
</code>```

答:
I suppose you did not show the complete error message, seems I can reproduce your issue.

The error was caused by your Backend pool referenced by the Load balancing rule, so to fix the issue, you need to use the command below to remove the rule first.

```<code>$loadbalancer = Get-AzLoadBalancer -Name <LoadBalancer-name> -ResourceGroupName <group-name>
Remove-AzLoadBalancerRuleConfig -LoadBalancer $loadbalancer -Name <rule-name> | Set-AzLoadBalancer
</code>```

Then run the command to remove the Backend pool, it works.

```<code>Get-AzLoadBalancer -Name "<LoadBalancer-name>" -ResourceGroupName "<group-name>" | Remove-AzLoadBalancerBackendAddressPoolConfig -Name "joyback1" | Set-AzLoadBalancer
</code>```

Body:
I have used Az-powershell task in azure devops pipeline and tried below cmdlet.Its showing error " Set_AzLoadBalancer: Resource/Subscription/MySUbscription ID>/resourceGroups/MyresourceGroup/providers/Microsift.Net/LoadBalancer/MyLoadBalancer/LoadBalancingRules/MyLoadBalancingrule was not found.Please make sure that the referenced resource exists, and that both resources are in same region ."
 Please suggest

Get-AzLoadBalancer -Name "MyLoadBalancer" -ResourceGroupName "MyResourceGroup" | Remove-AzLoadBalancerBackendAddressPoolConfig -Name "BackendAddressPool02" | Set-AzLoadBalancer

Body:
I suppose you did not show the complete error message, seems I can reproduce your issue.

The error was caused by your Backend pool referenced by the Load balancing rule, so to fix the issue, you need to use the command below to remove the rule first.

$loadbalancer = Get-AzLoadBalancer -Name <LoadBalancer-name> -ResourceGroupName <group-name>
Remove-AzLoadBalancerRuleConfig -LoadBalancer $loadbalancer -Name <rule-name> | Set-AzLoadBalancer

Then run the command to remove the Backend pool, it works.

Get-AzLoadBalancer -Name "<LoadBalancer-name>" -ResourceGroupName "<group-name>" | Remove-AzLoadBalancerBackendAddressPoolConfig -Name "joyback1" | Set-AzLoadBalancer


问:
puppeteer : how check if browser is still open and working
im trying to open multiple tabs in a single browser instance  , after they're done i close the tabs and then re-opening those tabs every x seconds ... but i want to keep the browser itself open so i dont have to login in each tab on every loop

so the browser remains open , tabs open and close

here is my simplified code  , pleas ignore syntax erros

```<code>var  global_browser = false ;
async function init_puppeteer( settings ) {

    if(global_browser === false )
        global_browser = await puppeteer.launch({headless: false  , args:['--no-sandbox']});

    for(var i = 0  ; i < settings.length ; i++ )
    {
        var setting = settings[i];
        open_tab($setting);
    }
}

 async function open_tab( setting ){
    const page    = await global_browser.newPage();
    // do stuff
    page.close();
}

setInterval(function (){
    init_puppeteer(settings)
}, 50000 );
</code>```

here is the problem , sometimes browser crashes or it get closed for whatever reason but the global_browser remains an object /instance of puppeteer  ... of curse it wont work when i try open a tab with that instance  , and i get something like

```<code>(node:5720) UnhandledPromiseRejectionWarning: Error: WebSocket is not open: readyState 3 (CLOSED)
</code>```

here is my question , how can i check and make sure i have a working/open instance of puppeteer in global_browser ? so i can create a new instance and replace it if the previous one is closed

答:
If you just close all tabs (or browser window) but browser process is still there (but no any window).

disconnected event will not be triggered.

Then you can check whether all tabs are closed by:

        if ((await browser.pages()).length === 0) {
          // no tabs opening, do stuff
        }
```

Body:
im trying to open multiple tabs in a single browser instance  , after they're done i close the tabs and then re-opening those tabs every x seconds ... but i want to keep the browser itself open so i dont have to login in each tab on every loop

so the browser remains open , tabs open and close

here is my simplified code  , pleas ignore syntax erros

var  global_browser = false ;
async function init_puppeteer( settings ) {

    if(global_browser === false )
        global_browser = await puppeteer.launch({headless: false  , args:['--no-sandbox']});

    for(var i = 0  ; i < settings.length ; i++ )
    {
        var setting = settings[i];
        open_tab($setting);
    }
}

 async function open_tab( setting ){
    const page    = await global_browser.newPage();
    // do stuff
    page.close();
}

setInterval(function (){
    init_puppeteer(settings)
}, 50000 );

here is the problem , sometimes browser crashes or it get closed for whatever reason but the global_browser remains an object /instance of puppeteer  ... of curse it wont work when i try open a tab with that instance  , and i get something like

(node:5720) UnhandledPromiseRejectionWarning: Error: WebSocket is not open: readyState 3 (CLOSED)

here is my question , how can i check and make sure i have a working/open instance of puppeteer in global_browser ? so i can create a new instance and replace it if the previous one is closed


问:
How to print content of multiple urls onto one single txt.file?
Good afternoon, I am new to stack overflow so I apologize in advance if my question is not in the right format.

I have a list of URLs such as these (but many more),

```<code>master_urls =
['https://www.sec.gov/Archives/edgar/daily-index/2020/QTR1/master.20190102.idx',
'https://www.sec.gov/Archives/edgar/daily-index/2020/QTR1/master.20190103.idx]
</code>```

and I want to write the content onto one single txt.file.
Using one of these URLs works perfectly fine. I do the steps below to achieve it:

```<code>file_url = r"https://www.sec.gov/Archives/edgar/daily-index/2019/QTR2/master.20190401.idx"

content = requests.get(file_url).content

with open('master_20190401.txt', 'wb') as f:
    f.write(content)
</code>```

The txt.file looks like this (this is just a small sample of the text file, but it's all the same as shown below just with different company names ...etc):

```<code>CIK|Company Name|Form Type|Date Filed|File Name
--------------------------------------------------------------------------------
1000045|NICHOLAS FINANCIAL INC|8-K|20190401|edgar/data/1000045/0001193125-19-093800.txt
1000209|MEDALLION FINANCIAL CORP|SC 13D/A|20190401|edgar/data/1000209/0001193125-19-094732.txt
1000228|HENRY SCHEIN INC|4|20190401|edgar/data/1000228/0001209191-19-021970.txt
1000275|ROYAL BANK OF CANADA|424B2|20190401|edgar/data/1000275/0001140361-19-006199.txt
</code>```

I tried the following code to get the content of all URLs onto one text file

```<code>for file in master_urls:
    content = requests.get(file).content
    with open('complete_list.txt', 'w') as f:
        f.write(content)
</code>```

but it does not work.

Can anyone help me get the content of each URL in my list of URLs onto one single text file?

Thank you in advance.

答:
Since you are opening your file inside the loop for every URL, the file is getting overwrriten.

try this :

```<code>with open('complete_list.txt', 'wb') as f:
  for url in master_urls:
     content = requests.get(url).content
     f.write(content)
</code>```

Body:
Good afternoon, I am new to stack overflow so I apologize in advance if my question is not in the right format.

I have a list of URLs such as these (but many more),

master_urls =
['https://www.sec.gov/Archives/edgar/daily-index/2020/QTR1/master.20190102.idx',
'https://www.sec.gov/Archives/edgar/daily-index/2020/QTR1/master.20190103.idx]

and I want to write the content onto one single txt.file.
Using one of these URLs works perfectly fine. I do the steps below to achieve it:

file_url = r"https://www.sec.gov/Archives/edgar/daily-index/2019/QTR2/master.20190401.idx"

content = requests.get(file_url).content

with open('master_20190401.txt', 'wb') as f:
    f.write(content)

The txt.file looks like this (this is just a small sample of the text file, but it's all the same as shown below just with different company names ...etc):

CIK|Company Name|Form Type|Date Filed|File Name
--------------------------------------------------------------------------------
1000045|NICHOLAS FINANCIAL INC|8-K|20190401|edgar/data/1000045/0001193125-19-093800.txt
1000209|MEDALLION FINANCIAL CORP|SC 13D/A|20190401|edgar/data/1000209/0001193125-19-094732.txt
1000228|HENRY SCHEIN INC|4|20190401|edgar/data/1000228/0001209191-19-021970.txt
1000275|ROYAL BANK OF CANADA|424B2|20190401|edgar/data/1000275/0001140361-19-006199.txt

I tried the following code to get the content of all URLs onto one text file

for file in master_urls:
    content = requests.get(file).content
    with open('complete_list.txt', 'w') as f:
        f.write(content)

but it does not work.

Can anyone help me get the content of each URL in my list of URLs onto one single text file?

Thank you in advance.

Body:
Since you are opening your file inside the loop for every URL, the file is getting overwrriten.

try this :

with open('complete_list.txt', 'wb') as f:
  for url in master_urls:
     content = requests.get(url).content
     f.write(content)


问:
Travis build failed due to git submodule repository not found
I have an Android project with a main app (a git repo) and several modules (git repos cloned as submodule). Today it starts building fail due to submodule repository not found when it tried to build the newly PR code. Travis log looks like below

The main app clones fine, just submodules which failed to clone. I tried to rebuild commits that succeeded last week, but they start building fail too.

答:
After hours of searching and trial, I found it's caused by a recent change of Travis

The solution that works for me is go to each submodule's Travis' settings page and turn on "Allow files from this repository to be used in builds on other repositories".

After turning on all submodules, the building pass like it used to be.


问:
The different output when I input for direct and text file in c
Following is my code:

```<code>#include <stdio.h>
#include <string.h>

int main(){
    int a;
    scanf(" %d",&a);
    setbuf(stdin, 0);
    char *ch[a][10];

    int i = 0;
    for(i = 0; i < a; i++){
        fgets(&ch[i], 10, stdin);
        printf("output: %s\n",ch[i]);
    }

    return 0;
}
</code>```

When I input :
2
G
GPA

Output is :
output: G
output: GPA

But I input same data from the text file, It output is:
output:
output: G

Like this:
enter image description here

Why is this so?

答:
The problem is the setbuf(stdin, 0); line, don't use this to clear stdin.

Instead add a function like this to the code and call it after scanf to clear any characters left in stdin:

```<code>void clear_stdin(void){
    int c;
    while ((c=getchar()) != '\n' && c != EOF);
}
</code>```

Also this:

```<code>    char *ch[a][10];
</code>```

Creates a matrix of pointers of dimension a x 10 that point to char values. And it is not what you want, since you didn't make them point anywhere your compiler should be warning you that there is a problem.

You should use a normal matrix of char instead:

```<code>    char ch[a][10];
</code>```

And there is no need to use & here:

```<code>    fgets(&ch[i], 10, stdin);
</code>```

Since in this case ch[i] is a memory address already. So it should be:

```<code>    fgets(ch[i], 10, stdin);
</code>```

Body:
Following is my code:

#include <stdio.h>
#include <string.h>

int main(){
    int a;
    scanf(" %d",&a);
    setbuf(stdin, 0);
    char *ch[a][10];

    int i = 0;
    for(i = 0; i < a; i++){
        fgets(&ch[i], 10, stdin);
        printf("output: %s\n",ch[i]);
    }

    return 0;
}

When I input :
2
G
GPA

Output is :
output: G
output: GPA

But I input same data from the text file, It output is:
output:
output: G

Like this:
enter image description here

Why is this so?

Body:
The problem is the setbuf(stdin, 0); line, don't use this to clear stdin.

Instead add a function like this to the code and call it after scanf to clear any characters left in stdin:

void clear_stdin(void){
    int c;
    while ((c=getchar()) != '\n' && c != EOF);
}

Also this:

    char *ch[a][10];

Creates a matrix of pointers of dimension a x 10 that point to char values. And it is not what you want, since you didn't make them point anywhere your compiler should be warning you that there is a problem.

You should use a normal matrix of char instead:

    char ch[a][10];

And there is no need to use & here:

    fgets(&ch[i], 10, stdin);

Since in this case ch[i] is a memory address already. So it should be:

    fgets(ch[i], 10, stdin);


问:
Simple java lib for text templating?
I need to template some email texts. Nothing fancy, just replace something like @name@ with real value. No pictures, no fancy formatting etc.

What java lib could you recommend? The simplier the better.

答: Have you tried Apache Velocity?</p>

Title: Simple java lib for text templating?

Body: Have you tried Apache Velocity?


问:
Changing class dynamically with *ngIf in child component
first, I apologize if this has been answered in some way before, I did find two close answers here:

Question similar     | Solution Close

There are three components inside of an Angular Material Sidenav component . The containing component (red in the screenshot) has buttons that look like tabs, which when clicked load one of the three components.

```<code><button (click)="onTabClick(1)"><i class="fas fa-layer-plus"></i>
<button (click)="onTabClick(2)"><i class="fas fa-map-marker-edit"></i></button>
<button (click)="onTabClick(3)"><i class="fas fa-plus-square"></i></button>
</code>```

The buttons swap out components with *ngIf

```<code> <app-map-features *ngIf="tabIndex === 1" [id]="'test'" ></app-map-features>
 <app-map-edit-live-data *ngIf="tabIndex === 2" [id]="'test2'" ></app-map-edit-live-data>
 <app-map-zoom *ngIf="tabIndex === 3" [className]="'other'"></app-map-zoom>
</code>```

TS:

```<code>export class containingComponent implements OnInit {
  tabIndex = 1 ;
  onTabClick(index) {
    this.tabIndex = index;
  }
</code>```

On click, a background color is applied to the the Font-Awesome icon. This works as expected.

```<code>.fas:hover {
  background-color: $primary-color;
}
</code>```

The goal is that when a certain component is showing, the .fas background color to be different in order to indicate when a certain component's content is showing.

I won't go into all of the things that I have tried because none of them have worked! What are some ways to just get the class to update when taxIndex has a certain value as true? It seems like the components aren't aware of each other.

答:
Not a proper answer, but you're missing an ending tag on your first button unless it's a typo</p>

```<code><button (click)="onTabClick(1)"><i class="fas fa-layer-plus"></i> {here}
</code>```

Body:
first, I apologize if this has been answered in some way before, I did find two close answers here:

Question similar     | Solution Close

There are three components inside of an Angular Material Sidenav component . The containing component (red in the screenshot) has buttons that look like tabs, which when clicked load one of the three components.

<button (click)="onTabClick(1)">
<button (click)="onTabClick(2)"></button>
<button (click)="onTabClick(3)"></button>

The buttons swap out components with *ngIf

 <app-map-features *ngIf="tabIndex === 1" [id]="'test'" ></app-map-features>
 <app-map-edit-live-data *ngIf="tabIndex === 2" [id]="'test2'" ></app-map-edit-live-data>
 <app-map-zoom *ngIf="tabIndex === 3" [className]="'other'"></app-map-zoom>

TS:

export class containingComponent implements OnInit {
  tabIndex = 1 ;
  onTabClick(index) {
    this.tabIndex = index;
  }

On click, a background color is applied to the the Font-Awesome icon. This works as expected.

.fas:hover {
  background-color: $primary-color;
}

The goal is that when a certain component is showing, the .fas background color to be different in order to indicate when a certain component's content is showing.

I won't go into all of the things that I have tried because none of them have worked! What are some ways to just get the class to update when taxIndex has a certain value as true? It seems like the components aren't aware of each other.

Body:
Not a proper answer, but you're missing an ending tag on your first button unless it's a typo

<button (click)="onTabClick(1)"><i class="fas fa-layer-plus"></i> {here}


问:
Using icons in Bootstrap 4.5
I'm trying to figure out how to use the icons in Bootstrap 4.5 via CSS. Are there any code examples you can point me to? Ideally I'd like to know what CSS declarations are needed to be able to use them like Font Awesome e.g.
.

The documentation at bootstrap https://icons.getbootstrap.com/#usage is not sufficient for me to figure out how to use them in a similar fashion. In other words, I'd like to be able to use jquery to set a class on an object to add an icon dynamically but I don't understand the CSS I need to do this.

答:
i cant find in the doc that bootstrap icon is fontawesome icon
after you install it you use it as a svg like this one

```<code><svg class="bi bi-app" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
  <path fill-rule="evenodd" d="M11 2H5a3 3 0 0 0-3 3v6a3 3 0 0 0 3 3h6a3 3 0 0 0 3-3V5a3 3 0 0 0-3-3zM5 1a4 4 0 0 0-4 4v6a4 4 0 0 0 4 4h6a4 4 0 0 0 4-4V5a4 4 0 0 0-4-4H5z"/>
</svg>
</code>```

or you can use it this way after you download the svg to you project

```<code><img src="/assets/img/bootstrap.svg" alt="" width="32" height="32" title="Bootstrap">
</code>```

or on your css

```<code>.bi::before {
  display: inline-block;
  content: "";
  background-image: url("data:image/svg+xml,<svg viewBox='0 0 16 16' fill='%23333' xmlns='http://www.w3.org/2000/svg'><path fill-rule='evenodd' d='M8 9.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3z' clip-rule='evenodd'/></svg>");
  background-repeat: no-repeat;
  background-size: 1rem 1rem;
}
</code>```

Title: Using icons in Bootstrap 4.5

Body:
i cant find in the doc that bootstrap icon is fontawesome icon
after you install it you use it as a svg like this one

<svg class="bi bi-app" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
  <path fill-rule="evenodd" d="M11 2H5a3 3 0 0 0-3 3v6a3 3 0 0 0 3 3h6a3 3 0 0 0 3-3V5a3 3 0 0 0-3-3zM5 1a4 4 0 0 0-4 4v6a4 4 0 0 0 4 4h6a4 4 0 0 0 4-4V5a4 4 0 0 0-4-4H5z"/>
</svg>

or you can use it this way after you download the svg to you project

<img src="/assets/img/bootstrap.svg" alt="" width="32" height="32" title="Bootstrap">

or on your css

.bi::before {
  display: inline-block;
  content: "";
  background-image: url("data:image/svg+xml,<svg viewBox='0 0 16 16' fill='%23333' xmlns='http://www.w3.org/2000/svg'><path fill-rule='evenodd' d='M8 9.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3z' clip-rule='evenodd'/></svg>");
  background-repeat: no-repeat;
  background-size: 1rem 1rem;
}


问:
how to add a variable inside of a label in Tkinter?
In a normal print statement, I am able to put in a variable inside the statement like :

```<code>x=1
print("x is equal to" x)
</code>```

But how would I be able to write the same thing in tkinter?

```<code>x=2
label1 = Label(text="x is equal to " x)
</code>```

that's what my line of code looks like right now. any help will be appreciated, thanks

答:
First, typecast your variable to a string using str(), then concatenate it to the title string as follows:

```<code>marks = 505
label = Label(root, text="I got "+str(marks)+" marks.")
</code>```

I hope that it may help you......

Body:
In a normal print statement, I am able to put in a variable inside the statement like :

x=1
print("x is equal to" x)

But how would I be able to write the same thing in tkinter?

x=2
label1 = Label(text="x is equal to " x)

that's what my line of code looks like right now. any help will be appreciated, thanks

Body:
First, typecast your variable to a string using str(), then concatenate it to the title string as follows:

marks = 505
label = Label(root, text="I got "+str(marks)+" marks.")

I hope that it may help you......


问:
What is the difference between AWS and AWS_PROXY in CloudFormation::APIGateway?
What is the difference between AWS and AWS_PROXY in a CloudFormation template with a AWS::ApiGateway::Method - Integration:Type, with a Lambda backend? I was constantly getting 502 errors just now and realized that I needed to respond with a very specifically formatted JSON response. When I created API Gateways from the console I never bumped into this issue. It does work now but I want to know the underlying differences so I can learn.

Here's the part from the CF Template:

VisitorCounterAPIGatewayRootMethod:
    Type: AWS::ApiGateway::Method
    Properties:
      AuthorizationType: NONE
      HttpMethod: GET
      Integration:
        IntegrationHttpMethod: POST
        Type: AWS_PROXY #THIS is my question. AWS or AWS_PROXY?
        Uri: !Sub
          - arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${lambdaArn}/invocations
          - lambdaArn: !GetAtt VisitorCountLambda.Arn
      ResourceId: !GetAtt VisitorCounterAPIGateway.RootResourceId
      RestApiId: !Ref VisitorCounterAPIGateway
```

<p>And here's the response code from my Lambda function (Python3.7):</p>

<pre class="lang-py prettyprint-override"><code>apiResponse = {
    "isBase64Encoded": False,
    "statusCode": 200,
    "body": json.dumps({
        "visitorCount": int(float(response["Attributes"]["amount"]))
    })
}
</code>```

Thank you.

答:
AWS and AWS_PROXY are two types of integration in API Gateway.

AWS_PROXY is only used with lambda and it is the simplest way of working with lambda with API Gateway. It means:

For HTTP proxy integration, API Gateway passes the entire request and response between the frontend and an HTTP backend. For Lambda proxy integration, API Gateway sends the entire request as input to a backend Lambda function. API Gateway then transforms the Lambda function output to a frontend HTTP response.

AWS can be used with any AWS service, including lambda. It is more complex to setup and usually it is used when you want to integrate API gateway with, e.g., SQS or Kinesis or other AWS services:

This type of integration lets an API expose AWS service actions. In AWS integration, you must configure both the integration request and integration response and set up necessary data mappings from the method request to the integration request, and from the integration response to the method response.

So to answer your question:

Type: AWS_PROXY #THIS is my question. AWS or AWS_PROXY?

If you can, use AWS_PROXY. This is the most streamlined and easiest to work and setup form of integration with lambda. It only works with lambda anyway. Since entire response and reply are just pass-through the API gateway, you must ensure that your lambda returns correct headers and status code to the caller.

Use AWS with other services, such as SQS. You can still use lambda, but it requires more setup. But the benefit is that you have more control over what's get passed into your lambda, and how the response is passed to the caller. Usually you would use AWS with lambda if you have existing lambda and you can't change it. This way in AWS integration you can shape and mold the inputs and outputs from the caller to lambda and back, without changing the lambda.

Short example on AWS and AWS_PROXY integrations in CloudFormation, showing that when you use AWS integration, you can define extra parameters (myParam) that can be passed to your lambda:

AWS_PROXY

```<code>MyApiResourceMethod:
  Type: AWS::ApiGateway::Method
  Properties:
    AuthorizationType: None
    HttpMethod: GET
    Integration:
      IntegrationHttpMethod: POST
      Type: AWS_PROXY
      Uri: !Sub >-
        arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${LambdaArn1}/invocations
    MethodResponses:
      - ResponseModels: {"application/json": "Empty"}
        StatusCode: 200
ResourceId: !Ref MyResource
RestApiId: !Ref MyRestApi
</code>```

AWS

```<code>MyApiResourceMethod:
  Type: AWS::ApiGateway::Method
  Properties:
    AuthorizationType: None
    #AuthorizerId: String
    HttpMethod: GET
    Integration:
      IntegrationHttpMethod: POST
        - ResponseTemplates:
            application/json: ""
          StatusCode: 200
      PassthroughBehavior: WHEN_NO_TEMPLATES
      RequestTemplates:
        application/json: |
              {
                 "myParam": "$input.params('myParam')"
              }
      Type: AWS
      Uri: !Sub >-
        arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${LambdaArn2}/invocations
    MethodResponses:
      - ResponseModels: {"application/json": "Empty"}
        StatusCode: 200
    ResourceId: !Ref MyResource
    RestApiId: !Ref MyRestApi
</code>```

Body:
What is the difference between AWS and AWS_PROXY in a CloudFormation template with a AWS::ApiGateway::Method - Integration:Type, with a Lambda backend? I was constantly getting 502 errors just now and realized that I needed to respond with a very specifically formatted JSON response. When I created API Gateways from the console I never bumped into this issue. It does work now but I want to know the underlying differences so I can learn.

Here's the part from the CF Template:

VisitorCounterAPIGatewayRootMethod:
    Type: AWS::ApiGateway::Method
    Properties:
      AuthorizationType: NONE
      HttpMethod: GET
      Integration:
        IntegrationHttpMethod: POST
        Type: AWS_PROXY #THIS is my question. AWS or AWS_PROXY?
        Uri: !Sub
          - arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${lambdaArn}/invocations
          - lambdaArn: !GetAtt VisitorCountLambda.Arn
      ResourceId: !GetAtt VisitorCounterAPIGateway.RootResourceId
      RestApiId: !Ref VisitorCounterAPIGateway

And here's the response code from my Lambda function (Python3.7):

apiResponse = {
    "isBase64Encoded": False,
    "statusCode": 200,
    "body": json.dumps({
        "visitorCount": int(float(response["Attributes"]["amount"]))
    })
}

Thank you.

Body:
AWS and AWS_PROXY are two types of integration in API Gateway.

AWS_PROXY is only used with lambda and it is the simplest way of working with lambda with API Gateway. It means:

For HTTP proxy integration, API Gateway passes the entire request and response between the frontend and an HTTP backend. For Lambda proxy integration, API Gateway sends the entire request as input to a backend Lambda function. API Gateway then transforms the Lambda function output to a frontend HTTP response.

AWS can be used with any AWS service, including lambda. It is more complex to setup and usually it is used when you want to integrate API gateway with, e.g., SQS or Kinesis or other AWS services:

This type of integration lets an API expose AWS service actions. In AWS integration, you must configure both the integration request and integration response and set up necessary data mappings from the method request to the integration request, and from the integration response to the method response.

So to answer your question:

Type: AWS_PROXY #THIS is my question. AWS or AWS_PROXY?

If you can, use AWS_PROXY. This is the most streamlined and easiest to work and setup form of integration with lambda. It only works with lambda anyway. Since entire response and reply are just pass-through the API gateway, you must ensure that your lambda returns correct headers and status code to the caller.

Use AWS with other services, such as SQS. You can still use lambda, but it requires more setup. But the benefit is that you have more control over what's get passed into your lambda, and how the response is passed to the caller. Usually you would use AWS with lambda if you have existing lambda and you can't change it. This way in AWS integration you can shape and mold the inputs and outputs from the caller to lambda and back, without changing the lambda.

Short example on AWS and AWS_PROXY integrations in CloudFormation, showing that when you use AWS integration, you can define extra parameters (myParam) that can be passed to your lambda:

AWS_PROXY

MyApiResourceMethod:
  Type: AWS::ApiGateway::Method
  Properties:
    AuthorizationType: None
    HttpMethod: GET
    Integration:
      IntegrationHttpMethod: POST
      Type: AWS_PROXY
      Uri: !Sub >-
        arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${LambdaArn1}/invocations
    MethodResponses:
      - ResponseModels: {"application/json": "Empty"}
        StatusCode: 200
ResourceId: !Ref MyResource
RestApiId: !Ref MyRestApi

AWS

MyApiResourceMethod:
  Type: AWS::ApiGateway::Method
  Properties:
    AuthorizationType: None
    #AuthorizerId: String
    HttpMethod: GET
    Integration:
      IntegrationHttpMethod: POST
        - ResponseTemplates:
            application/json: ""
          StatusCode: 200
      PassthroughBehavior: WHEN_NO_TEMPLATES
      RequestTemplates:
        application/json: |
              {
                 "myParam": "$input.params('myParam')"
              }
      Type: AWS
      Uri: !Sub >-
        arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${LambdaArn2}/invocations
    MethodResponses:
      - ResponseModels: {"application/json": "Empty"}
        StatusCode: 200
    ResourceId: !Ref MyResource
    RestApiId: !Ref MyRestApi


问:
SQL update : deduplication of email address by adding + ID before @
I'm trying to update a clients table in mySQL containing duplicate email addresses and a unique custom_ID. I would like to change duplicate email addresses by adding a '+' and customer_ID before the @ sign, but only for the email addresses that are not unique.</p>

```<code>UPDATE clients SET email = REPLACE(email,'@', CONCAT('+',custom_ID,'@'))

INPUT
+-----------+-------------------------+
| custom_ID | email                   |
+-----------+-------------------------+
|  1001     | john.smith@live.com     |
|  1002     |    evyandy@email.net    |
|  1007     |    evyandy@email.net    |
|  1012     |        ann@live.com     |
|  1020     |       rick@yahoo.com    |
|  1021     |        ann@live.com     |
|  1023     |    evyandy@email.net    |
|  1024     |       emma@gmail.com    |
+-----------+-------------------------+

 OUTPUT
+-----------+----------------------------+
| custom_ID | email                      |
+-----------+----------------------------+
|  1001     |   john.smith@live.com      |
|  1002     |      evyandy@email.net     |
|  1007     | evyandy+1007@email.net     |
|  1012     |          ann@live.com      |
|  1020     |         rick@yahoo.com     |
|  1021     |     ann+1021@live.com      |
|  1023     | evyandy+1023@email.net     |
|  1024     |         emma@gmail.com     |
+-----------+----------------------------+
</code>```

答:
You can use update with window functions and a join:

```<code>update clients c join
       (select c.*, row_number() over (partition by email order by custom_id) as seqnum
        from clients cc
       ) cc
       on c.custom_id = cc.custom_id
    set email = concat(substring_index(email, '@', 1), '+', custom_id, '@', substring_index(email, '@', -1))
    where cc.seqnum > 1;
</code>```

Body:
I'm trying to update a clients table in mySQL containing duplicate email addresses and a unique custom_ID. I would like to change duplicate email addresses by adding a '+' and customer_ID before the @ sign, but only for the email addresses that are not unique.

UPDATE clients SET email = REPLACE(email,'@', CONCAT('+',custom_ID,'@'))

INPUT
+-----------+-------------------------+
| custom_ID | email                   |
+-----------+-------------------------+
|  1001     | john.smith@live.com     |
|  1002     |    evyandy@email.net    |
|  1007     |    evyandy@email.net    |
|  1012     |        ann@live.com     |
|  1020     |       rick@yahoo.com    |
|  1021     |        ann@live.com     |
|  1023     |    evyandy@email.net    |
|  1024     |       emma@gmail.com    |
+-----------+-------------------------+

 OUTPUT
+-----------+----------------------------+
| custom_ID | email                      |
+-----------+----------------------------+
|  1001     |   john.smith@live.com      |
|  1002     |      evyandy@email.net     |
|  1007     | evyandy+1007@email.net     |
|  1012     |          ann@live.com      |
|  1020     |         rick@yahoo.com     |
|  1021     |     ann+1021@live.com      |
|  1023     | evyandy+1023@email.net     |
|  1024     |         emma@gmail.com     |
+-----------+----------------------------+

Body:
You can use update with window functions and a join:

update clients c join
       (select c.*, row_number() over (partition by email order by custom_id) as seqnum
        from clients cc
       ) cc
       on c.custom_id = cc.custom_id
    set email = concat(substring_index(email, '@', 1), '+', custom_id, '@', substring_index(email, '@', -1))
    where cc.seqnum > 1;


答:
I can't see all your code but if I understand correctly, you want to be able to change the background color based on what component is selected.
Since this is tied to the tab index, you can use [ngClass] on the background component and dynamically switch classes based on the tab index as follows:

HTML:

```<code><!-- This is the component with the red outline in your screenshot, since I can't see your code... -->

<red-outline-component
  [ngClass] = "{'map-features-bg': tabIndex === 1, 'map-edit-bg': tabIndex === 2, 'map-zoom-bg': tabIndex === 3}">
    ...
</red-outline-component>
</code>```

CSS: (You don't need to provide the color in each class, but I do it so that I can change the color to suit the background-color for more contrast and readability).

```<code>.map-features-bg {
  background-color: some-color;
  color: some-color;
}

.map-edit-bg {
  background-color: some-color;
  color: some-color;
}

.map-zoom-bg {
  background-color: some-color;
  color: some-color;
}
</code>```

[ngClass] allows us to apply classes dynamically based on the value of variables in our HTML and Component Class. You can read more about it here.

Hope this helps

Title: Changing class dynamically with *ngIf in child component

Body:
I can't see all your code but if I understand correctly, you want to be able to change the background color based on what component is selected.
Since this is tied to the tab index, you can use [ngClass] on the background component and dynamically switch classes based on the tab index as follows:

HTML:

<!-- This is the component with the red outline in your screenshot, since I can't see your code... -->

<red-outline-component
  [ngClass] = "{'map-features-bg': tabIndex === 1, 'map-edit-bg': tabIndex === 2, 'map-zoom-bg': tabIndex === 3}">
    ...
</red-outline-component>

CSS: (You don't need to provide the color in each class, but I do it so that I can change the color to suit the background-color for more contrast and readability).

.map-features-bg {
  background-color: some-color;
  color: some-color;
}

.map-edit-bg {
  background-color: some-color;
  color: some-color;
}

.map-zoom-bg {
  background-color: some-color;
  color: some-color;
}

[ngClass] allows us to apply classes dynamically based on the value of variables in our HTML and Component Class. You can read more about it here.

Hope this helps


问:
Android Studio “cannot resolve symbol R” but project compiles and runs
Android Studio displays in all java files in red : “cannot resolve symbol R” but the project compiles and runs.

I have tried every solution here:
Android Studio "cannot resolve symbol" but project compiles and works, but with no luck.

I tried to :

invalidate caches and restart android studio

delete .gradle and .idea folders

clean and rebuild the project

install a new version of android studio

mess up with gradle file then undo changes and sync project

One thing that I want to try, but I don't know how to achieve, is to reopen the project from scratch as I was opening it for the first time, but I don't know how to do this.

I also tried answers from here:
Android Studio says "cannot resolve symbol" but project compiles,
but again with no luck.

Android studio version = 3.2.1

dependency versions in gradle project file:

```<code>classpath 'com.android.tools.build:gradle:3.4.0-alpha01'
classpath 'com.google.gms:google-services:4.0.0'
</code>```

答:
It says cannot resolve symbol, but it can run.

In my case, I just reload the needed *.jar files to the libs folder.

File >> invalidate caches/restart

Rebuild Project

Sync

Run

Works for me!

It looks like the library did not load my "imports" properly the first time.

That's why the import methods cannot be seen in my main_activity.xml.

Body:
Android Studio displays in all java files in red : “cannot resolve symbol R” but the project compiles and runs.

I have tried every solution here:
Android Studio "cannot resolve symbol" but project compiles and works, but with no luck.

I tried to :

invalidate caches and restart android studio

delete .gradle and .idea folders

clean and rebuild the project

install a new version of android studio

mess up with gradle file then undo changes and sync project

One thing that I want to try, but I don't know how to achieve, is to reopen the project from scratch as I was opening it for the first time, but I don't know how to do this.

I also tried answers from here:
Android Studio says "cannot resolve symbol" but project compiles,
but again with no luck.

Android studio version = 3.2.1

dependency versions in gradle project file:

classpath 'com.android.tools.build:gradle:3.4.0-alpha01'
classpath 'com.google.gms:google-services:4.0.0'


问:
Online version of Android Studio 4
My nephew wants to learn android development, he only has a chromebook that his school gave which restricts him to install anything. So checking if there's a browser based online version of Android Studio (4 preferably) where he can write code, execute wihtout installing locally. thanks in advance</p>

答:
Ideal for him would be to:

buy his own machine

connect to existing machines at his home or relatives using teamviewer (or any other remote access software)

buy a VPS and setup android studio on it, then connect using remote access software as in step 2 to use it. (google provides 1 year free vps for up to 300$ at cloud.google.com or he can also use azure by microsoft student discount)

I hope it helps.

Title: Online version of Android Studio 4


问:
Compare two images if they have almost identical RGB color distribution
I have two colored images img1 and img2 as defined below

```<code> img1 = cv2.imread("source1")
 img2 = cv2.imread("source2")
</code>```

Now I want to know if the distribution of the RGB value of two images is almost identical.  As a human, I can see from the RGB histogram distribution of the two images that they are almost identical or not. But is there a way that I can do this via OpenCV, that it can tell that two images are almost identical with it comes to its RGB distribution?

```<code>color = ('b','g','r')
for i,col in enumerate(color):
   histr = cv.calcHist([img1],[i],None,[256],[0,256])
   plt.subplot(1,2,1)
   plt.plot(histr,color = col)
   plt.xlim([0,256])
   plt.title("Img 1")

   histr = cv.calcHist([img2],[i],None,[256],[0,256])
   plt.subplot(1,2,2)
   plt.plot(histr,color = col)
   plt.xlim([0,256])
   plt.title("Img 2")
plt.show()
</code>```

答:
You can use cv2.compareHist() in Python/OpenCV. It takes two histograms that can be 1D, 2D or 3D histograms and returns a metric score of similarity.

See https://docs.opencv.org/3.4/d6/dc7/group__imgproc__hist.html#gaf4190090efa5c47cb367cf97a9a519bd and https://docs.opencv.org/3.4/d8/dc8/tutorial_histogram_comparison.html and https://www.pyimagesearch.com/2014/07/14/3-ways-compare-histograms-using-opencv-python/, for example

Body:
I have two colored images img1 and img2 as defined below

 img1 = cv2.imread("source1")
 img2 = cv2.imread("source2")

Now I want to know if the distribution of the RGB value of two images is almost identical.  As a human, I can see from the RGB histogram distribution of the two images that they are almost identical or not. But is there a way that I can do this via OpenCV, that it can tell that two images are almost identical with it comes to its RGB distribution?

color = ('b','g','r')
for i,col in enumerate(color):
   histr = cv.calcHist([img1],[i],None,[256],[0,256])
   plt.subplot(1,2,1)
   plt.plot(histr,color = col)
   plt.xlim([0,256])
   plt.title("Img 1")

   histr = cv.calcHist([img2],[i],None,[256],[0,256])
   plt.subplot(1,2,2)
   plt.plot(histr,color = col)
   plt.xlim([0,256])
   plt.title("Img 2")
plt.show()


问:
Embed Tableau in Markdown (Hugo Academic)
I am trying to embed some Tableau dashboards into my new blog, which is built in Hugo Academic via RStudio Blogdown. I include the code, and, although my site renders fine (no errors), the dashboard never shows up - just whatever text I included before/after it.

Here is the complete embed code (a mix of HTML and Javascript):

```<code><div class='tableauPlaceholder' id='viz1581355801663' style='position: relative'><noscript><a href='#'>
<img alt=' ' src='https://public.tableau.com/static/images/St/StudentEnrollmentDashboardPortfolio/Dashboard1/1_rss.png' style='border: none' /></a>
</noscript>
<object class='tableauViz'  style='display:none;'><param name='host_url' value='https%3A%2F%2Fpublic.tableau.com%2F' />
<param name='embed_code_version' value='3' />
<param name='site_root' value='' />
<param name='name' value='StudentEnrollmentDashboardPortfolio/Dashboard1' />
<param name='tabs' value='no' /><param name='toolbar' value='yes' />
<param name='static_image' value='https://public.tableau.com/static/images/St/StudentEnrollmentDashboardPortfolio/Dashboard1/1.png' />
<param name='animate_transition' value='yes' />
<param name='display_static_image' value='yes' /><param name='display_spinner' value='yes' /><param name='display_overlay' value='yes' />
<param name='display_count' value='yes' /></object></div>
<script type='text/javascript'>
                    var divElement = document.getElementById('viz1581355801663');
var vizElement = divElement.getElementsByTagName('object')[0];
 if ( divElement.offsetWidth > 800 ) { vizElement.style.width='1000px';vizElement.style.height='827px';} else if ( divElement.offsetWidth > 500 ) { vizElement.style.width='1000px';vizElement.style.height='827px';}
else { vizElement.style.width='100%';vizElement.style.height='727px';}
var scriptElement = document.createElement('script');
scriptElement.src = 'https://public.tableau.com/javascripts/api/viz_v1.js';                    vizElement.parentNode.insertBefore(scriptElement, vizElement);                <
/script>
</code>```

答:
In the config.toml file, go to the "Configure the Markdown Renderer" section. Turn unsafe to true. It should solve your issue. I struggled with the same issue for hours.</p>

```<code># Configure the Markdown renderer.
[markup]
  defaultMarkdownHandler = "goldmark"
  [markup.goldmark]
    [markup.goldmark.renderer]
      unsafe = true  # Enable user to embed HTML snippets in Markdown content.
</code>```

Body:
I am trying to embed some Tableau dashboards into my new blog, which is built in Hugo Academic via RStudio Blogdown. I include the code, and, although my site renders fine (no errors), the dashboard never shows up - just whatever text I included before/after it.

Here is the complete embed code (a mix of HTML and Javascript):

<object class='tableauViz'  style='display:none;'><param name='host_url' value='https%3A%2F%2Fpublic.tableau.com%2F' />
<param name='embed_code_version' value='3' />
<param name='site_root' value='' />
<param name='name' value='StudentEnrollmentDashboardPortfolio/Dashboard1' />
<param name='tabs' value='no' /><param name='toolbar' value='yes' />
<param name='static_image' value='https://public.tableau.com/static/images/St/StudentEnrollmentDashboardPortfolio/Dashboard1/1.png' />
<param name='animate_transition' value='yes' />
<param name='display_static_image' value='yes' /><param name='display_spinner' value='yes' /><param name='display_overlay' value='yes' />
<param name='display_count' value='yes' /></object>

Body:
In the config.toml file, go to the "Configure the Markdown Renderer" section. Turn unsafe to true. It should solve your issue. I struggled with the same issue for hours.

# Configure the Markdown renderer.
[markup]
  defaultMarkdownHandler = "goldmark"
  [markup.goldmark]
    [markup.goldmark.renderer]
      unsafe = true  # Enable user to embed HTML snippets in Markdown content.


问:
business layer with multiple objects with all properties filled from DB or one object with only a subset filled
I am building a middle size system and I am facing a problem that probably some of you have faced before. In my business layer I return business objects with a subset of properties that are important for that business method, I am worried because I can end up with to much objects with meaningless names or only one where only a subset of properties are filled in a given method. Let me put an example.

Case 1

For example, a user belongs to a city, which in turns belongs to a state and a country, User, City, State and Country are tables on my database with a lot of fields, but I want a list of users with a list of Orders, so I create a business object called for example UserWithOthers with only the important properties (UserId, UserName, CityName, StateName, CountryName, List<Order>) and my DAL retrieves only that fields from Database.

Case 2

I want to return now a user with the amount of orders, I end with the following fields in my business object (UserId, UserName, CityName, StateName, CountryName, OrdersCount) and the class could be called for example UserWithOrderCount

I have thought in some options:

Make that two business classes and fill them separately in each DAL method (this objects are simple but consider that method can have a complex select query that needs to be encapsulated for reuse so repository pattern doesn't fit well here, at least I think that).

Create only one object User with all the properties (UserId, UserName, CityName, StateName, CountryName, OrdersCount, List<Order>) and fill  only a subset in each DAL method, but that implies Semantic Coupling when you use a method, because you must know which subset of fields are filled from database, and semantic coupling is the worst of all coupling.

Option 1 doesn't handle well if I need later in another view, both, List<Order> and OrdersCount properties.

Consider now that if you use ASP.NET MVC good practices tells that you need a ViewModel to pass to the view, I thought to return ViewModels from my Businnes Layer, but I don't think is a good idea, it feels like I am violating something, and also is not possible because my business layer is in another assembly and not the web application.

I don't want to write the same Linq query over and over again, but if use NHibernate or EFCodeFirst is "like" option one, and I will need to create tons of small business objects.

How do you handle this situation? I think this is a high level design decision.

答:
First of all, I definitely agree with you about some things not do:

Don't partially-populate business objects, as you then put responsibility for knowing which properties are populated onto the business layer's clients, which is very bad practice.

Don't return ViewModels from your business layer; your business layer is supposed to represent the business concepts of your application's domain, and a ViewModel is a data object which contains the data necessary to display a particular view of one part of that domain - the two are very different things and the business layer should be completely unaware that its business objects are used in any kind of GUI.

I would go with your first suggestion - create one separate business object to represent  each business concept. I would then use an ORM (like EF or NHibernate) to populate those objects for me, with dedicated Repositories for each group of objects. I'd then use an application layer which calls the repositories to return whatever objects are required. to this end your Repository can include methods which return joined Users and Orders for times when you know you need to have those two types used together. This allows you to return a User with all their Orders in one query, while retaining separate, meaningful entities to represent Users and Orders.


问:
How to fix gyp ERR! inside a npm build
I recently built a mean stack app and containerized it. However, I have trouble build it on my raspberry pi and I don't understand the error.

When I build my app over my debian machine, everything build perfectly. Even if I get this line during the build process:

```<code>node-pre-gyp WARN Using needle for node-pre-gyp https download
</code>```

Unfortunately, I cannot build  the same container on my raspberry. This warning get really worse and exit with error code 1:

```<code>node-pre-gyp WARN Using needle for node-pre-gyp https download
node-pre-gyp WARN Tried to download(404): https://github.com/kelektiv/node.bcryp                                                                                t.js/releases/download/v4.0.1/bcrypt_lib-v4.0.1-napi-v3-linux-arm-musl.tar.gz
node-pre-gyp WARN Pre-built binaries not found for bcrypt@4.0.1 and node@13.1.0                                                                                (node-v79 ABI, musl) (falling back to source compile with node-gyp)
gyp ERR! find Python
gyp ERR! find Python Python is not set from command line or npm configuration
gyp ERR! find Python Python is not set from environment variable PYTHON
gyp ERR! find Python checking if "python" can be used
gyp ERR! find Python - "python" is not in PATH or produced an error
gyp ERR! find Python checking if "python2" can be used
gyp ERR! find Python - "python2" is not in PATH or produced an error
gyp ERR! find Python checking if "python3" can be used
gyp ERR! find Python - "python3" is not in PATH or produced an error
gyp ERR! find Python
gyp ERR! find Python **********************************************************
gyp ERR! find Python You need to install the latest version of Python.
gyp ERR! find Python Node-gyp should be able to find and use Python. If not,
gyp ERR! find Python you can try one of the following options:
gyp ERR! find Python - Use the switch --python="/path/to/pythonexecutable"
gyp ERR! find Python   (accepted by both node-gyp and npm)
gyp ERR! find Python - Set the environment variable PYTHON
gyp ERR! find Python - Set the npm configuration variable python:
gyp ERR! find Python   npm config set python "/path/to/pythonexecutable"
gyp ERR! find Python For more information consult the documentation at:
gyp ERR! find Python https://github.com/nodejs/node-gyp#installation
gyp ERR! find Python **********************************************************
gyp ERR! find Python
gyp ERR! configure error
gyp ERR! stack Error: Could not find any Python installation to use
gyp ERR! stack     at PythonFinder.fail (/usr/local/lib/node_modules/npm/node_mo                                                                                dules/node-gyp/lib/find-python.js:307:47)
gyp ERR! stack     at PythonFinder.runChecks (/usr/local/lib/node_modules/npm/no                                                                                de_modules/node-gyp/lib/find-python.js:136:21)
gyp ERR! stack     at PythonFinder.<anonymous> (/usr/local/lib/node_modules/npm/                                                                                node_modules/node-gyp/lib/find-python.js:179:16)
gyp ERR! stack     at PythonFinder.execFileCallback (/usr/local/lib/node_modules                                                                                /npm/node_modules/node-gyp/lib/find-python.js:271:16)
gyp ERR! stack     at exithandler (child_process.js:302:5)
gyp ERR! stack     at ChildProcess.errorhandler (child_process.js:314:5)
gyp ERR! stack     at ChildProcess.emit (events.js:210:5)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_proces                                                                                s.js:270:12)
gyp ERR! stack     at onErrorNT (internal/child_process.js:456:16)
gyp ERR! stack     at processTicksAndRejections (internal/process/task_queues.js                                                                                :80:21)
gyp ERR! System Linux 4.19.97-v7l+
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_mod                                                                                ules/node-gyp/bin/node-gyp.js" "configure" "--fallback-to-build" "--module=/app/                                                                                node_modules/bcrypt/lib/binding/napi-v3/bcrypt_lib.node" "--module_name=bcrypt_l                                                                                ib" "--module_path=/app/node_modules/bcrypt/lib/binding/napi-v3" "--napi_version                                                                                =5" "--node_abi_napi=napi" "--napi_build_version=3" "--node_napi_label=napi-v3"
gyp ERR! cwd /app/node_modules/bcrypt
gyp ERR! node -v v13.1.0
gyp ERR! node-gyp -v v5.0.5
gyp ERR! not ok
node-pre-gyp ERR! build error
node-pre-gyp ERR! stack Error: Failed to execute '/usr/local/bin/node /usr/local                                                                                /lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js configure --fallback                                                                                -to-build --module=/app/node_modules/bcrypt/lib/binding/napi-v3/bcrypt_lib.node                                                                                --module_name=bcrypt_lib --module_path=/app/node_modules/bcrypt/lib/binding/napi                                                                                -v3 --napi_version=5 --node_abi_napi=napi --napi_build_version=3 --node_napi_lab                                                                                el=napi-v3' (1)
node-pre-gyp ERR! stack     at ChildProcess.<anonymous> (/app/node_modules/node-                                                                                pre-gyp/lib/util/compile.js:83:29)
node-pre-gyp ERR! stack     at ChildProcess.emit (events.js:210:5)
node-pre-gyp ERR! stack     at maybeClose (internal/child_process.js:1028:16)
node-pre-gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/chi                                                                                ld_process.js:283:5)
node-pre-gyp ERR! System Linux 4.19.97-v7l+
node-pre-gyp ERR! command "/usr/local/bin/node" "/app/node_modules/.bin/node-pre                                                                                -gyp" "install" "--fallback-to-build"
node-pre-gyp ERR! cwd /app/node_modules/bcrypt
node-pre-gyp ERR! node -v v13.1.0
node-pre-gyp ERR! node-pre-gyp -v v0.14.0
node-pre-gyp ERR! not ok
Failed to execute '/usr/local/bin/node /usr/local/lib/node_modules/npm/node_modu                                                                                les/node-gyp/bin/node-gyp.js configure --fallback-to-build --module=/app/node_mo                                                                                dules/bcrypt/lib/binding/napi-v3/bcrypt_lib.node --module_name=bcrypt_lib --modu                                                                                le_path=/app/node_modules/bcrypt/lib/binding/napi-v3 --napi_version=5 --node_abi                                                                                _napi=napi --napi_build_version=3 --node_napi_label=napi-v3' (1)
npm WARN clockmachine-api@1.0.0 No repository field.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! bcrypt@4.0.1 install: `node-pre-gyp install --fallback-to-build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the bcrypt@4.0.1 install script.
npm ERR! This is probably not a problem with npm. There is likely additional log                                                                                ging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2020-05-26T14_29_34_636Z-debug.log
ERROR: Service 'backend' failed to build: The command '/bin/sh -c npm install' returned a non-zero code: 1
</code>```

I don't understand this error code, because I have python, python2 and python3. Furthermore, if I type npm install node-pre-gyp it's working but not inside the container. I tried to clean npm cache and use with different nodejs version. the initial one, the 12.16.3 and the 14.x one.

Can you explain to me why this errors occurs ? What dependency should I fullfill and how to get the log inside the container?

答:
If you don't really need Node 13, maybe you can try using Node 8 (either using NVM or choosing the right Node Docker image).

This will skip building bcrypt.

(The reason you're even building bcrypt is because NPM "Pre-built binaries not found for bcrypt@4.0.1 and node@13.1.0")

Title: How to fix gyp ERR! inside a npm build

Body:
I recently built a mean stack app and containerized it. However, I have trouble build it on my raspberry pi and I don't understand the error.

When I build my app over my debian machine, everything build perfectly. Even if I get this line during the build process:

node-pre-gyp WARN Using needle for node-pre-gyp https download

Unfortunately, I cannot build  the same container on my raspberry. This warning get really worse and exit with error code 1:

node-pre-gyp WARN Using needle for node-pre-gyp https download
node-pre-gyp WARN Tried to download(404): https://github.com/kelektiv/node.bcryp                                                                                t.js/releases/download/v4.0.1/bcrypt_lib-v4.0.1-napi-v3-linux-arm-musl.tar.gz
node-pre-gyp WARN Pre-built binaries not found for bcrypt@4.0.1 and node@13.1.0                                                                                (node-v79 ABI, musl) (falling back to source compile with node-gyp)
gyp ERR! find Python
gyp ERR! find Python Python is not set from command line or npm configuration
gyp ERR! find Python Python is not set from environment variable PYTHON
gyp ERR! find Python checking if "python" can be used
gyp ERR! find Python - "python" is not in PATH or produced an error
gyp ERR! find Python checking if "python2" can be used
gyp ERR! find Python - "python2" is not in PATH or produced an error
gyp ERR! find Python checking if "python3" can be used
gyp ERR! find Python - "python3" is not in PATH or produced an error
gyp ERR! find Python
gyp ERR! find Python **********************************************************
gyp ERR! find Python You need to install the latest version of Python.
gyp ERR! find Python Node-gyp should be able to find and use Python. If not,
gyp ERR! find Python you can try one of the following options:
gyp ERR! find Python - Use the switch --python="/path/to/pythonexecutable"
gyp ERR! find Python   (accepted by both node-gyp and npm)
gyp ERR! find Python - Set the environment variable PYTHON
gyp ERR! find Python - Set the npm configuration variable python:
gyp ERR! find Python   npm config set python "/path/to/pythonexecutable"
gyp ERR! find Python For more information consult the documentation at:
gyp ERR! find Python https://github.com/nodejs/node-gyp#installation
gyp ERR! find Python **********************************************************
gyp ERR! find Python
gyp ERR! configure error
gyp ERR! stack Error: Could not find any Python installation to use
gyp ERR! stack     at PythonFinder.fail (/usr/local/lib/node_modules/npm/node_mo                                                                                dules/node-gyp/lib/find-python.js:307:47)
gyp ERR! stack     at PythonFinder.runChecks (/usr/local/lib/node_modules/npm/no                                                                                de_modules/node-gyp/lib/find-python.js:136:21)
gyp ERR! stack     at PythonFinder.<anonymous> (/usr/local/lib/node_modules/npm/                                                                                node_modules/node-gyp/lib/find-python.js:179:16)
gyp ERR! stack     at PythonFinder.execFileCallback (/usr/local/lib/node_modules                                                                                /npm/node_modules/node-gyp/lib/find-python.js:271:16)
gyp ERR! stack     at exithandler (child_process.js:302:5)
gyp ERR! stack     at ChildProcess.errorhandler (child_process.js:314:5)
gyp ERR! stack     at ChildProcess.emit (events.js:210:5)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_proces                                                                                s.js:270:12)
gyp ERR! stack     at onErrorNT (internal/child_process.js:456:16)
gyp ERR! stack     at processTicksAndRejections (internal/process/task_queues.js                                                                                :80:21)
gyp ERR! System Linux 4.19.97-v7l+
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_mod                                                                                ules/node-gyp/bin/node-gyp.js" "configure" "--fallback-to-build" "--module=/app/                                                                                node_modules/bcrypt/lib/binding/napi-v3/bcrypt_lib.node" "--module_name=bcrypt_l                                                                                ib" "--module_path=/app/node_modules/bcrypt/lib/binding/napi-v3" "--napi_version                                                                                =5" "--node_abi_napi=napi" "--napi_build_version=3" "--node_napi_label=napi-v3"
gyp ERR! cwd /app/node_modules/bcrypt
gyp ERR! node -v v13.1.0
gyp ERR! node-gyp -v v5.0.5
gyp ERR! not ok
node-pre-gyp ERR! build error
node-pre-gyp ERR! stack Error: Failed to execute '/usr/local/bin/node /usr/local                                                                                /lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js configure --fallback                                                                                -to-build --module=/app/node_modules/bcrypt/lib/binding/napi-v3/bcrypt_lib.node                                                                                --module_name=bcrypt_lib --module_path=/app/node_modules/bcrypt/lib/binding/napi                                                                                -v3 --napi_version=5 --node_abi_napi=napi --napi_build_version=3 --node_napi_lab                                                                                el=napi-v3' (1)
node-pre-gyp ERR! stack     at ChildProcess.<anonymous> (/app/node_modules/node-                                                                                pre-gyp/lib/util/compile.js:83:29)
node-pre-gyp ERR! stack     at ChildProcess.emit (events.js:210:5)
node-pre-gyp ERR! stack     at maybeClose (internal/child_process.js:1028:16)
node-pre-gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/chi                                                                                ld_process.js:283:5)
node-pre-gyp ERR! System Linux 4.19.97-v7l+
node-pre-gyp ERR! command "/usr/local/bin/node" "/app/node_modules/.bin/node-pre                                                                                -gyp" "install" "--fallback-to-build"
node-pre-gyp ERR! cwd /app/node_modules/bcrypt
node-pre-gyp ERR! node -v v13.1.0
node-pre-gyp ERR! node-pre-gyp -v v0.14.0
node-pre-gyp ERR! not ok
Failed to execute '/usr/local/bin/node /usr/local/lib/node_modules/npm/node_modu                                                                                les/node-gyp/bin/node-gyp.js configure --fallback-to-build --module=/app/node_mo                                                                                dules/bcrypt/lib/binding/napi-v3/bcrypt_lib.node --module_name=bcrypt_lib --modu                                                                                le_path=/app/node_modules/bcrypt/lib/binding/napi-v3 --napi_version=5 --node_abi                                                                                _napi=napi --napi_build_version=3 --node_napi_label=napi-v3' (1)
npm WARN clockmachine-api@1.0.0 No repository field.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! bcrypt@4.0.1 install: `node-pre-gyp install --fallback-to-build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the bcrypt@4.0.1 install script.
npm ERR! This is probably not a problem with npm. There is likely additional log                                                                                ging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2020-05-26T14_29_34_636Z-debug.log
ERROR: Service 'backend' failed to build: The command '/bin/sh -c npm install' returned a non-zero code: 1

I don't understand this error code, because I have python, python2 and python3. Furthermore, if I type npm install node-pre-gyp it's working but not inside the container. I tried to clean npm cache and use with different nodejs version. the initial one, the 12.16.3 and the 14.x one.

Can you explain to me why this errors occurs ? What dependency should I fullfill and how to get the log inside the container?


问:
replace names of all directiories and files in PS
I want to replace all space characters into "_" in names of all subfolders and files.
Unfortunately when I type:

```<code>Get-ChildItem -recurse -name | ForEach-Object { Rename-Item $_ $_.replace(" ","_") }
</code>```

Error message:

Rename-Item : Source and destination path must be different. At line:1
  char:60
  + Get-ChildItem -recurse -name | ForEach-Object { Rename-Item <<<<  $_ $.replace(" ","") }
      + CategoryInfo          : WriteError: (PATH_HERE) [Rename-Item], IOException
      + FullyQualifiedErrorId : RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommand

How I should improve this short code?

答:
Adding a filter worked for me:</p>

```<code>Get-ChildItem C:\path-to-directory -Recurse -Filter *foo* | Rename-Item -NewName { $_.name -replace 'foo', 'bar'} -verbose
</code>```

Body:
I want to replace all space characters into "_" in names of all subfolders and files.
Unfortunately when I type:

Get-ChildItem -recurse -name | ForEach-Object { Rename-Item $_ $_.replace(" ","_") }

Error message:

Rename-Item : Source and destination path must be different. At line:1
  char:60
  + Get-ChildItem -recurse -name | ForEach-Object { Rename-Item <<<<  $_ $.replace(" ","") }
      + CategoryInfo          : WriteError: (PATH_HERE) [Rename-Item], IOException
      + FullyQualifiedErrorId : RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommand

How I should improve this short code?

Body:
Adding a filter worked for me:

Get-ChildItem C:\path-to-directory -Recurse -Filter *foo* | Rename-Item -NewName { $_.name -replace 'foo', 'bar'} -verbose


问:
if cardNumberArray[0] == 4: IndexError: list index out of range
Just started learning python and I'm trying to print different things based on the user's input, however, when I run the code I get this error:

```<code>    if cardNumberArray[0] == 4:
    IndexError: list index out of range
</code>```

I don't understand why when a number of 14-16 integers is inputted, the program says that cardNumberArray[0] is out of range, and why my program won't even print the different values given the below code.

```<code>cardNumber = input("what is the number?\n")
cardNumberArray = []

for i in cardNumberArray:
  cardNumberArray.append(int(i))
  print(f"Ith value: {cardNumberArray[i]}")

if cardNumberArray[0] == 4:
    print("VISA")
elif cardNumberArray[0] == 5:
  if cardNumberArray[1] == 1 or cardNumberArray[1] == 2 or cardNumberArray[1] == 3 or cardNumberArray[1] == 4 or cardNumberArray[1] == 4 or cardNumberArray[1] == 5:
    print("MASTERCARD")
elif cardNumberArray[0] == 3:
  if cardNumberArray[1] == 4 or cardNumberArray[1] == 7:
    print("AMEX")
else:
  print("INVALID")
</code>```

答:
The reason index 0 is out of range is because you haven't added any value to the list yet, and there are some more errors, like you need to convert the string into an integer, and instead of subscripting the value in the list, you need to subscript the index:</p>

```<code>cardNumber = input("what is the number?\n")
cardNumberArray = [int(cardNumber)]

for i in range(len(cardNumberArray)):
  print(f"Ith value: {cardNumberArray[i]}")
</code>```

Body:
Just started learning python and I'm trying to print different things based on the user's input, however, when I run the code I get this error:

    if cardNumberArray[0] == 4:
    IndexError: list index out of range

I don't understand why when a number of 14-16 integers is inputted, the program says that cardNumberArray[0] is out of range, and why my program won't even print the different values given the below code.

cardNumber = input("what is the number?\n")
cardNumberArray = []

for i in cardNumberArray:
  cardNumberArray.append(int(i))
  print(f"Ith value: {cardNumberArray[i]}")

if cardNumberArray[0] == 4:
    print("VISA")
elif cardNumberArray[0] == 5:
  if cardNumberArray[1] == 1 or cardNumberArray[1] == 2 or cardNumberArray[1] == 3 or cardNumberArray[1] == 4 or cardNumberArray[1] == 4 or cardNumberArray[1] == 5:
    print("MASTERCARD")
elif cardNumberArray[0] == 3:
  if cardNumberArray[1] == 4 or cardNumberArray[1] == 7:
    print("AMEX")
else:
  print("INVALID")

Body:
The reason index 0 is out of range is because you haven't added any value to the list yet, and there are some more errors, like you need to convert the string into an integer, and instead of subscripting the value in the list, you need to subscript the index:

cardNumber = input("what is the number?\n")
cardNumberArray = [int(cardNumber)]

for i in range(len(cardNumberArray)):
  print(f"Ith value: {cardNumberArray[i]}")


问:
How do I conditionally render from three different options in React Native?
I want to conditionally render in React Native, but there are three different options: loading screen, the user has no messages, or display all the users messages. I have a variable called conversations which is fetched from my database, but before the fetch completes it is null, so I want to display a loading indicator. After the fetch is complete, I want to display a message if the user has no current chats, or display a table containing all the users chats if the user does have existing chats. My thought was something like this:

return (
  <View>
    {conversations ? conversations.length === 0 ? (
      <Text>You have no messages.</Text>
    ) : (
      <ConversationTable conversations={conversations} />
    ) : (
      <ActivityIndicator />
    )}
  </View>
)
```

Is there a better way to do this?

答:
In my opinion, if branch inside the JSX could bring some messy, and pretty confuse to trace code complicate view.

So my suggestion is put your if branch outside of the return called, something like this:

```<code>render() {
   ...
   let view = null;
   if (conversation == null) {
           view = <ActivityIndicator />
   } else {
       if (conversation.length == 0)
           view = <Text>You have no messages.</Text>
       else
           view = <ConversationTable conversations={conversations} />
   }

   ...
   return (
       <View>
           {view}
       </View>
   )
}
</code>```

Body:
I want to conditionally render in React Native, but there are three different options: loading screen, the user has no messages, or display all the users messages. I have a variable called conversations which is fetched from my database, but before the fetch completes it is null, so I want to display a loading indicator. After the fetch is complete, I want to display a message if the user has no current chats, or display a table containing all the users chats if the user does have existing chats. My thought was something like this:

return (
  <View>
    {conversations ? conversations.length === 0 ? (
      <Text>You have no messages.</Text>
    ) : (
      <ConversationTable conversations={conversations} />
    ) : (
      <ActivityIndicator />
    )}
  </View>
)

Is there a better way to do this?

Body:
In my opinion, if branch inside the JSX could bring some messy, and pretty confuse to trace code complicate view.

So my suggestion is put your if branch outside of the return called, something like this:

render() {
   ...
   let view = null;
   if (conversation == null) {
           view = <ActivityIndicator />
   } else {
       if (conversation.length == 0)
           view = <Text>You have no messages.</Text>
       else
           view = <ConversationTable conversations={conversations} />
   }

   ...
   return (
       <View>
           {view}
       </View>
   )
}