问:
Angular - How to share a service provided in component with the component's resolver?
I have a messenger component, with a messages service provided in the component itself (as it needs to be component specific) as such:

```<code>@Component({
  selector: "app-messenger",
  templateUrl: "./messenger.page.html",
  styleUrls: ["./messenger.page.scss"],
  providers: [MessagesService],
})
</code>```

I need to load my messages (done in the messages service) before I transition to the messenger component, and am therefore using a resolver (messagesResolver). The messagesService contains the messages, so the resolver needs access to a same instance of the messagesService as the messengerComponent.

How do I do that?

I am currently getting the error from the resolver:

```<code>NullInjectorError: R3InjectorError(MainPageModule)[MessagesResolver -> MessagesResolver -> MessagesService -> MessagesService -> MessagesService]:
  NullInjectorError: No provider for MessagesService!
</code>```

I understood from other Stack Overflow questions that I could Angular's Injector? However I don't know how I would go about this.

Notes on resolver:

It is provided in root using @Injectable({ providedIn: "root", })

It is used in the routing of the module containing the messenger component as such:

```<code>{
    path: "messenger/:chatID",
    loadChildren: () =>
      import("./chats/messenger/messenger.module").then((m) => m.MessengerPageModule),
    resolve: {
      messages: MessagesResolver,
    },
  },
</code>```

答:
Using a factory will allow you to access services, components, properties, functions, etc. when a specific service is created. This allows you to modify the creation process a little bit once the service is created such as assigning a value to a property.

@Component({
  providers: [{
    provide: MessagesService,
    useFactory: (messageResolver: MessageResolver) => messageResolver.msgService,
    deps: [MessageResolver]
  }]
})
export class MessengerComponent {

}
```

Body:
I have a messenger component, with a messages service provided in the component itself (as it needs to be component specific) as such:

@Component({
  selector: "app-messenger",
  templateUrl: "./messenger.page.html",
  styleUrls: ["./messenger.page.scss"],
  providers: [MessagesService],
})

I need to load my messages (done in the messages service) before I transition to the messenger component, and am therefore using a resolver (messagesResolver). The messagesService contains the messages, so the resolver needs access to a same instance of the messagesService as the messengerComponent.

How do I do that?

I am currently getting the error from the resolver:

NullInjectorError: R3InjectorError(MainPageModule)[MessagesResolver -> MessagesResolver -> MessagesService -> MessagesService -> MessagesService]:
  NullInjectorError: No provider for MessagesService!

I understood from other Stack Overflow questions that I could Angular's Injector? However I don't know how I would go about this.

Notes on resolver:

It is provided in root using @Injectable({ providedIn: "root", })

It is used in the routing of the module containing the messenger component as such:

{
    path: "messenger/:chatID",
    loadChildren: () =>
      import("./chats/messenger/messenger.module").then((m) => m.MessengerPageModule),
    resolve: {
      messages: MessagesResolver,
    },
  },


来源: stackexchange

问:
How can I separate 3 different information in a column?
For example, in the column I have, there is a line written 'Ser25Phe'. And I want to split the column HGVS.Consequence e.g. as 'Ser 25 Phe'...

```<code>HGVS.Consequence
           Met1?
           Met1?
           Met1?
         Ala2Glu
         Ala2Ala
         Asn3Asp
         Asn3Asn
         Gly4Trp
         Gly4Arg
         Ala6Glu
           AsAsp
         Arg9Arg
        Lys10Arg
        Lys10Lys
        LeullLeu
        Phe12Ser
        Phe12Cys
        lle13Leu
        lle13Val
        lle13Phe
        Thr15Pro
</code>```

ContentLicense: CC BY-SA 4.0

Body:
For example, in the column I have, there is a line written 'Ser25Phe'. And I want to split the column HGVS.Consequence e.g. as 'Ser 25 Phe'...

HGVS.Consequence
           Met1?
           Met1?
           Met1?
         Ala2Glu
         Ala2Ala
         Asn3Asp
         Asn3Asn
         Gly4Trp
         Gly4Arg
         Ala6Glu
           AsAsp
         Arg9Arg
        Lys10Arg
        Lys10Lys
        LeullLeu
        Phe12Ser
        Phe12Cys
        lle13Leu
        lle13Val
        lle13Phe
        Thr15Pro

Body:
We may use extract from tidyr to split the column into multiple columns

library(dplyr)
library(tidyr)
df %>%
  extract(x3, into = c('v1', 'v2', 'v3'),
    "^([A-Za-z][a-z]+)(\\d*)(\\D+)", convert = TRUE) %>%
  na_if("?")

-output

          x1         x2    v1 v2   v3
1  -0.545880758 0.27253736   Met  1 <NA>
2   0.536585304 0.21981567   Met  1 <NA>
3   0.419623149 0.04366575   Met  1 <NA>
4  -0.583627199 0.07509480   Ala  2  Glu
5   0.847460017 0.39408293   Ala  2  Ala
6   0.266021979 0.36396781   Asn  3  Asp
7   0.444585270 0.25830122   Asn  3  Asn
8  -0.466495124 0.33670415   Gly  4  Trp
9  -0.848370044 0.46251084   Gly  4  Arg
10  0.002311942 0.85627913   Ala  6  Glu
11 -1.316908124 0.46591567    As NA  Asp
12  0.598269113 0.70118573   Arg  9  Arg
13 -0.762214370 0.54757268   Lys 10  Arg
14 -1.429090303 0.99911177   Lys 10  Lys
15  0.332244449 0.45370882 Leull NA  Leu
16 -0.469060688 0.29248872   Phe 12  Ser
17 -0.334986794 0.17262897   Phe 12  Cys
18  1.536252156 0.14751666   lle 13  Leu
19  0.609994533 0.48654307   lle 13  Val
20  0.516335698 0.24613129   lle 13  Phe
21 -0.074308561 0.27913013   Thr 15  Pro

data

structure(list(x1 = c(-0.545880758366027, 0.536585304107612,
0.419623148618683, -0.583627199210279, 0.847460017311944, 0.266021979364892,
0.444585270360416, -0.466495123565759, -0.848370043948898, 0.00231194241576697,
-1.31690812429962, 0.598269112694685, -0.7622143703459, -1.42909030324076,
0.332244449013422, -0.469060687608488, -0.334986793584065, 1.53625215550584,
0.609994533253692, 0.51633569843567, -0.0743085613231125), x2 = c(0.272537359734997,
0.219815669581294, 0.0436657541431487, 0.0750948027707636, 0.39408292947337,
0.36396780773066, 0.25830122246407, 0.336704148678109, 0.462510835379362,
0.856279134983197, 0.465915669221431, 0.701185731682926, 0.547572682844475,
0.999111766461283, 0.453708823537454, 0.292488717008382, 0.172628972679377,
0.147516664350405, 0.486543073318899, 0.246131290215999, 0.279130134964362
), x3 = c("Met1?", "Met1?", "Met1?", "Ala2Glu", "Ala2Ala", "Asn3Asp",
"Asn3Asn", "Gly4Trp", "Gly4Arg", "Ala6Glu", "AsAsp", "Arg9Arg",
"Lys10Arg", "Lys10Lys", "LeullLeu", "Phe12Ser", "Phe12Cys", "lle13Leu",
"lle13Val", "lle13Phe", "Thr15Pro")), class = "data.frame", row.names = c(NA,
-21L))


问:
Redux, Redux Toolkit how to wait until dispatch is finished
guys

Like in the subject is there a solution to wait until dispatch action is finished and then dispatch another?

Do I need thunk?

```<code>dispatch(someAction());
</code>```

when someAction is finished dispatch anotherAction()

```<code>dispatch(anotherAction());
</code>```

答:
To elaborate on the idea of @phry.
I use redux-toolkit and have this as an example thunk:

```<code>export const EXAMPLE_THUNK = createAsyncThunk(
  "group/event/example_thunk",
  async () => {
    // Just resolves after 2 seconds.
    return await new Promise((resolve) => setTimeout(resolve, 2000));
  }
);
</code>```

To dispatch another action after the first dispatch, you can simply await the first dispatch. In my example I updated the loading state.

Although this example works, I am not 100% sure this is the best design pattern out there. Many examples I have seen is updating the state is some dispatch has been resolved! Personally I think this is a more clear way of writing my code

```<code> const handleChangeStatus = async () => {
    setIsLoading(true);
    await dispatch(EXAMPLE_THUNK())
    // Or dispatch something else.
    setIsLoading(false);
  };
</code>```

Body:
guys

Like in the subject is there a solution to wait until dispatch action is finished and then dispatch another?

Do I need thunk?

dispatch(someAction());

when someAction is finished dispatch anotherAction()

dispatch(anotherAction());

Body:
To elaborate on the idea of @phry.
I use redux-toolkit and have this as an example thunk:

export const EXAMPLE_THUNK = createAsyncThunk(
  "group/event/example_thunk",
  async () => {
    // Just resolves after 2 seconds.
    return await new Promise((resolve) => setTimeout(resolve, 2000));
  }
);

To dispatch another action after the first dispatch, you can simply await the first dispatch. In my example I updated the loading state.

Although this example works, I am not 100% sure this is the best design pattern out there. Many examples I have seen is updating the state is some dispatch has been resolved! Personally I think this is a more clear way of writing my code

 const handleChangeStatus = async () => {
    setIsLoading(true);
    await dispatch(EXAMPLE_THUNK())
    // Or dispatch something else.
    setIsLoading(false);
  };


问:
"get: No settings file exists, new profile?" (new NotFoundError("Could not open the file at /tmp using Selenium GeckoDriver on remote Ubuntu ligthsail
I'm struggling with the Firefox webdriver implementation on a Lightsail instance since few days.

I'm trying to make run this simple code:

```<code>opts = FirefoxOptions()
opts.add_argument('-headless')

driver = webdriver.Firefox(options=opts)

print(f"Driver creation: {time.perf_counter() - ts}")
ts = time.perf_counter()

driver.install_addon(os.path.abspath('metamask-10.2.2-an+fx.xpi'), temporary=True)

print(f"Add on installation: {time.perf_counter() - ts}")
ts = time.perf_counter()

driver.get('https://www.youtube.com')

print(f"Go to Youtube: {time.perf_counter() - ts}")

driver.close()
</code>```

On my local machine, I got for result:

```<code>Driver creation: 1.2246361820007223
Add on installation: 0.9261693749995175
Go to Youtube: 1.8188569550002285
</code>```

And the geckodriver.log:

```<code>1644664439885   geckodriver INFO    Listening on 127.0.0.1:48035
1644664439888   mozrunner::runner   INFO    Running command: "/usr/bin/firefox" "--marionette" "-headless" "--remote-debugging-port" "55337" "-no-remote" "-profile" "/tmp/rust_mozprofileyCDIKp"
*** You are running in headless mode.
1644664440148   Marionette  INFO    Marionette enabled
[GFX1-]: RenderCompositorSWGL failed mapping default framebuffer, no dt
console.warn: SearchSettings: "get: No settings file exists, new profile?" (new NotFoundError("Could not open the file at /tmp/rust_mozprofileyCDIKp/search.json.mozlz4", (void 0)))
DevTools listening on ws://localhost:55337/devtools/browser/1817941e-57a7-42f0-92dc-cc6c9aabaf0b
1644664441030   Marionette  INFO    Listening on port 43901
1644664441101   RemoteAgent WARN    TLS certificate errors will be ignored for this session
JavaScript warning: moz-extension://4ba69c0a-421f-4439-bc86-32f0a1c5a733/background-6.js, line 46: asm.js type error: expecting argument type declaration for 'e' of the form 'arg = arg|0' or 'arg = +arg' or 'arg = fround(arg)'
JavaScript warning: moz-extension://4ba69c0a-421f-4439-bc86-32f0a1c5a733/ui-3.js, line 7: unreachable code after return statement
JavaScript warning: moz-extension://4ba69c0a-421f-4439-bc86-32f0a1c5a733/ui-3.js, line 7: unreachable code after return statement
JavaScript warning: moz-extension://4ba69c0a-421f-4439-bc86-32f0a1c5a733/ui-3.js, line 7: unreachable code after return statement
JavaScript warning: moz-extension://4ba69c0a-421f-4439-bc86-32f0a1c5a733/ui-5.js, line 1: unreachable code after return statement
JavaScript warning: moz-extension://4ba69c0a-421f-4439-bc86-32f0a1c5a733/ui-5.js, line 1: unreachable code after return statement
JavaScript warning: moz-extension://4ba69c0a-421f-4439-bc86-32f0a1c5a733/ui-5.js, line 1: unreachable code after return statement
1644664442980   Marionette  WARN    Ignoring event 'pageshow' because document has an invalid readyState of 'uninitialized'.
</code>```

I would like to have approximatly the same result on my remote Lightsail instance.
I tried a lot of solution I found on google, but nothing worked, so this is what I did:

Delete instance -> Create a new one (Ubuntu 20.04LTS)

Make server routine:

sudo apt-get update

sudo apt-get upgrade

Install GeckoDriver:

wget https://github.com/mozilla/geckodriver/releases/download/v0.30.0/geckodriver-v0.30.0-linux64.tar.gz

tar -xvzf geckodriver*

chmod +x geckodriver

sudo mv geckodriver /usr/local/bin/

Install Firefox:

sudo apt install firefox

Install python3-pip and the requirements for selenium.

The result after launching a test:

```<code>Driver creation: 6.041947366000045
Add on installation: 11.09006381100005
==> Server block after few minutes
</code>```

and the geckodriver.log:

```<code>1644660948039   geckodriver     INFO    Listening on 127.0.0.1:41557
1644660948538   mozrunner::runner       INFO    Running command: "/usr/bin/firefox" "--marionette" "-headless"
"--disable-dev-shm-usage" "--no-sandbox" "--window-size=1920,1080" "--ignore-certificate-errors" "--allow-runni
ng-insecure-content" "--proxy-server=\'direct://\'" "--proxy-bypass-list=*" "--start-maximized" "--disable-gpu"
 "--disable-setuid-sandbox" "--remote-debugging-port" "58861" "-no-remote" "-profile" "/tmp/rust_mozprofilejTQJ
s8"
*** You are running in headless mode.
[GFX1-]: glxtest: libGL.so.1 missing
[GFX1-]: glxtest: libEGL missing
1644660949544   Marionette      INFO    Marionette enabled
[GFX1-]: RenderCompositorSWGL failed mapping default framebuffer, no dt
console.warn: SearchSettings: "get: No settings file exists, new profile?" (new NotFoundError("Could not open t
he file at /tmp/rust_mozprofilejTQJs8/search.json.mozlz4", (void 0)))
DevTools listening on ws://localhost:58861/devtools/browser/73d9a07f-26e3-45aa-b118-79158a25d2dd
1644660953547   Marionette      INFO    Listening on port 46187
1644660953617   RemoteAgent     WARN    TLS certificate errors will be ignored for this session
</code>```

The difference I found from the local geckodriver.log, is about libGL and libEgl, so I install:

apt install libgl1-mesa-glx

apt install libegl-dev

After testing:

```<code>Driver creation: 5.604287772000134
Add on installation: 52.37673208100023
==> Block after few minutes
</code>```

The geckodriver.log:

```<code>1644671693878   geckodriver     INFO    Listening on 127.0.0.1:38405
1644671694374   mozrunner::runner       INFO    Running command: "/usr/bin/firefox" "--marionette" "-headless"
"--remote-debugging-port" "35887" "-no-remote" "-profile" "/tmp/rust_mozprofileNhzPGd"
*** You are running in headless mode.
[GFX1-]: glxtest: Unable to open a connection to the X server
[GFX1-]: glxtest: libEGL missing
1644671695500   Marionette      INFO    Marionette enabled
[GFX1-]: RenderCompositorSWGL failed mapping default framebuffer, no dt
console.warn: SearchSettings: "get: No settings file exists, new profile?" (new NotFoundError("Could not open t
he file at /tmp/rust_mozprofileNhzPGd/search.json.mozlz4", (void 0)))
DevTools listening on ws://localhost:35887/devtools/browser/b99cd6dd-92a1-4c98-aec0-8c2dfb6c29b1
1644671699397   Marionette      INFO    Listening on port 39313
1644671699537   RemoteAgent     WARN    TLS certificate errors will be ignored for this session
JavaScript warning: moz-extension://2c7aa371-d63f-4896-8c5f-dab9902639ff/background-6.js, line 46: asm.js type
error: expecting argument type declaration for 'e' of the form 'arg = arg|0' or 'arg = +arg' or 'arg = fround(a
rg)'
</code>```

I really don't know how to make it work on my Lightsail instance.
I don't know what I can add to help someone to find a solution, maybe the versionning on my remote:

firefox -v: Mozilla Firefox 96.0

I tried a lot of other solutions found on the web, but as I don't understand what's the problem, everything else does nothing more.
Thanks advance.

答:
This error message...

```<code>1644671694374   mozrunner::runner       INFO    Running command: "/usr/bin/firefox" "--marionette" "-headless" "--remote-debugging-port" "35887" "-no-remote" "-profile" "/tmp/rust_mozprofileNhzPGd"
*** You are running in headless mode.
[GFX1-]: glxtest: Unable to open a connection to the X server
[GFX1-]: glxtest: libEGL missing
1644671695500   Marionette      INFO    Marionette enabled
[GFX1-]: RenderCompositorSWGL failed mapping default framebuffer, no dt
console.warn: SearchSettings: "get: No settings file exists, new profile?" (new NotFoundError("Could not open the file at /tmp/rust_mozprofileNhzPGd/search.json.mozlz4", (void 0)))
</code>```

...implies that the GeckoDriver instance was unable to initiate/spawn a new Browsing Context.

The most probable reason is there is/are dangling/zombie rust_mozprofile instances clinging within the /tmp directory. As a result, though /tmp/rust_mozprofileNhzPGd was created by GeckoDriver but /tmp/rust_mozprofileNhzPGd/search.json.mozlz4 can't be accessed.

Solution

You need to invoke driver.quit() within tearDown(){} method to close & destroy the WebDriver and Web Client instances gracefully at the end of each execution. Incase the dangling/zombie GeckoDriver process still continues to occupy your system memory you need to forcefully kill them.

References

You can find a relevant detailed discussions in:

console.warn: SearchSettings: "get: No settings file exists, new profile?" (new Error("", "(unknown module)")) using Selenium and Java

Error: Can't find profile directory. console.warn: SearchSettings: "get: No settings file exists, new profile?" using GeckoDriver Firefox and Selenium

Additionally, you may need to update the firefox version to the latest release of v97.0.

Body:
I'm struggling with the Firefox webdriver implementation on a Lightsail instance since few days.

I'm trying to make run this simple code:

opts = FirefoxOptions()
opts.add_argument('-headless')

driver = webdriver.Firefox(options=opts)

print(f"Driver creation: {time.perf_counter() - ts}")
ts = time.perf_counter()

driver.install_addon(os.path.abspath('metamask-10.2.2-an+fx.xpi'), temporary=True)

print(f"Add on installation: {time.perf_counter() - ts}")
ts = time.perf_counter()

driver.get('https://www.youtube.com')

print(f"Go to Youtube: {time.perf_counter() - ts}")

driver.close()

On my local machine, I got for result:

Driver creation: 1.2246361820007223
Add on installation: 0.9261693749995175
Go to Youtube: 1.8188569550002285

And the geckodriver.log:

1644664439885   geckodriver INFO    Listening on 127.0.0.1:48035
1644664439888   mozrunner::runner   INFO    Running command: "/usr/bin/firefox" "--marionette" "-headless" "--remote-debugging-port" "55337" "-no-remote" "-profile" "/tmp/rust_mozprofileyCDIKp"
*** You are running in headless mode.
1644664440148   Marionette  INFO    Marionette enabled
[GFX1-]: RenderCompositorSWGL failed mapping default framebuffer, no dt
console.warn: SearchSettings: "get: No settings file exists, new profile?" (new NotFoundError("Could not open the file at /tmp/rust_mozprofileyCDIKp/search.json.mozlz4", (void 0)))
DevTools listening on ws://localhost:55337/devtools/browser/1817941e-57a7-42f0-92dc-cc6c9aabaf0b
1644664441030   Marionette  INFO    Listening on port 43901
1644664441101   RemoteAgent WARN    TLS certificate errors will be ignored for this session
JavaScript warning: moz-extension://4ba69c0a-421f-4439-bc86-32f0a1c5a733/background-6.js, line 46: asm.js type error: expecting argument type declaration for 'e' of the form 'arg = arg|0' or 'arg = +arg' or 'arg = fround(arg)'
JavaScript warning: moz-extension://4ba69c0a-421f-4439-bc86-32f0a1c5a733/ui-3.js, line 7: unreachable code after return statement
JavaScript warning: moz-extension://4ba69c0a-421f-4439-bc86-32f0a1c5a733/ui-3.js, line 7: unreachable code after return statement
JavaScript warning: moz-extension://4ba69c0a-421f-4439-bc86-32f0a1c5a733/ui-3.js, line 7: unreachable code after return statement
JavaScript warning: moz-extension://4ba69c0a-421f-4439-bc86-32f0a1c5a733/ui-5.js, line 1: unreachable code after return statement
JavaScript warning: moz-extension://4ba69c0a-421f-4439-bc86-32f0a1c5a733/ui-5.js, line 1: unreachable code after return statement
JavaScript warning: moz-extension://4ba69c0a-421f-4439-bc86-32f0a1c5a733/ui-5.js, line 1: unreachable code after return statement
1644664442980   Marionette  WARN    Ignoring event 'pageshow' because document has an invalid readyState of 'uninitialized'.

I would like to have approximatly the same result on my remote Lightsail instance.
I tried a lot of solution I found on google, but nothing worked, so this is what I did:

Delete instance -> Create a new one (Ubuntu 20.04LTS)

Make server routine:

sudo apt-get update

sudo apt-get upgrade

Install GeckoDriver:

wget https://github.com/mozilla/geckodriver/releases/download/v0.30.0/geckodriver-v0.30.0-linux64.tar.gz

tar -xvzf geckodriver*

chmod +x geckodriver

sudo mv geckodriver /usr/local/bin/

Install Firefox:

sudo apt install firefox

Install python3-pip and the requirements for selenium.

The result after launching a test:

Driver creation: 6.041947366000045
Add on installation: 11.09006381100005
==> Server block after few minutes

and the geckodriver.log:

1644660948039   geckodriver     INFO    Listening on 127.0.0.1:41557
1644660948538   mozrunner::runner       INFO    Running command: "/usr/bin/firefox" "--marionette" "-headless"
"--disable-dev-shm-usage" "--no-sandbox" "--window-size=1920,1080" "--ignore-certificate-errors" "--allow-runni
ng-insecure-content" "--proxy-server=\'direct://\'" "--proxy-bypass-list=*" "--start-maximized" "--disable-gpu"
 "--disable-setuid-sandbox" "--remote-debugging-port" "58861" "-no-remote" "-profile" "/tmp/rust_mozprofilejTQJ
s8"
*** You are running in headless mode.
[GFX1-]: glxtest: libGL.so.1 missing
[GFX1-]: glxtest: libEGL missing
1644660949544   Marionette      INFO    Marionette enabled
[GFX1-]: RenderCompositorSWGL failed mapping default framebuffer, no dt
console.warn: SearchSettings: "get: No settings file exists, new profile?" (new NotFoundError("Could not open t
he file at /tmp/rust_mozprofilejTQJs8/search.json.mozlz4", (void 0)))
DevTools listening on ws://localhost:58861/devtools/browser/73d9a07f-26e3-45aa-b118-79158a25d2dd
1644660953547   Marionette      INFO    Listening on port 46187
1644660953617   RemoteAgent     WARN    TLS certificate errors will be ignored for this session

The difference I found from the local geckodriver.log, is about libGL and libEgl, so I install:

apt install libgl1-mesa-glx

apt install libegl-dev

After testing:

Driver creation: 5.604287772000134
Add on installation: 52.37673208100023
==> Block after few minutes

The geckodriver.log:

1644671693878   geckodriver     INFO    Listening on 127.0.0.1:38405
1644671694374   mozrunner::runner       INFO    Running command: "/usr/bin/firefox" "--marionette" "-headless"
"--remote-debugging-port" "35887" "-no-remote" "-profile" "/tmp/rust_mozprofileNhzPGd"
*** You are running in headless mode.
[GFX1-]: glxtest: Unable to open a connection to the X server
[GFX1-]: glxtest: libEGL missing
1644671695500   Marionette      INFO    Marionette enabled
[GFX1-]: RenderCompositorSWGL failed mapping default framebuffer, no dt
console.warn: SearchSettings: "get: No settings file exists, new profile?" (new NotFoundError("Could not open t
he file at /tmp/rust_mozprofileNhzPGd/search.json.mozlz4", (void 0)))
DevTools listening on ws://localhost:35887/devtools/browser/b99cd6dd-92a1-4c98-aec0-8c2dfb6c29b1
1644671699397   Marionette      INFO    Listening on port 39313
1644671699537   RemoteAgent     WARN    TLS certificate errors will be ignored for this session
JavaScript warning: moz-extension://2c7aa371-d63f-4896-8c5f-dab9902639ff/background-6.js, line 46: asm.js type
error: expecting argument type declaration for 'e' of the form 'arg = arg|0' or 'arg = +arg' or 'arg = fround(a
rg)'

I really don't know how to make it work on my Lightsail instance.
I don't know what I can add to help someone to find a solution, maybe the versionning on my remote:

firefox -v: Mozilla Firefox 96.0

I tried a lot of other solutions found on the web, but as I don't understand what's the problem, everything else does nothing more.
Thanks advance.

Body:
This error message...

1644671694374   mozrunner::runner       INFO    Running command: "/usr/bin/firefox" "--marionette" "-headless" "--remote-debugging-port" "35887" "-no-remote" "-profile" "/tmp/rust_mozprofileNhzPGd"
*** You are running in headless mode.
[GFX1-]: glxtest: Unable to open a connection to the X server
[GFX1-]: glxtest: libEGL missing
1644671695500   Marionette      INFO    Marionette enabled
[GFX1-]: RenderCompositorSWGL failed mapping default framebuffer, no dt
console.warn: SearchSettings: "get: No settings file exists, new profile?" (new NotFoundError("Could not open the file at /tmp/rust_mozprofileNhzPGd/search.json.mozlz4", (void 0)))

...implies that the GeckoDriver instance was unable to initiate/spawn a new Browsing Context.

The most probable reason is there is/are dangling/zombie rust_mozprofile instances clinging within the /tmp directory. As a result, though /tmp/rust_mozprofileNhzPGd was created by GeckoDriver but /tmp/rust_mozprofileNhzPGd/search.json.mozlz4 can't be accessed.

Solution

You need to invoke driver.quit() within tearDown(){} method to close & destroy the WebDriver and Web Client instances gracefully at the end of each execution. Incase the dangling/zombie GeckoDriver process still continues to occupy your system memory you need to forcefully kill them.

References

You can find a relevant detailed discussions in:

console.warn: SearchSettings: "get: No settings file exists, new profile?" (new Error("", "(unknown module)")) using Selenium and Java

Error: Can't find profile directory. console.warn: SearchSettings: "get: No settings file exists, new profile?" using GeckoDriver Firefox and Selenium

Additionally, you may need to update the firefox version to the latest release of v97.0.


问:
Doing multiple sorts across more than one line of code?
I have an array that stores the order that I want to sort a list by.

```<code>SortOrderArray: "Color", "Volume", "Weight"
</code>```

So I want to order my list by Color, Volume, then Weight

```<code>MyList.OrderBy(a=>a.Color).ThenBy(a=>a.Volume).ThenBy(a=>a.Weight).ToList();
</code>```

So that's pretty good.  Now, I want to be able to write a function that does this sorting based on the sortOrder array I send in:

```<code>public List<row> GetSortedList(List<row> list, string[] sortOrder){
    ???
}
</code>```

I can't figure out how to do this without writing a linq query for every combination of sortOrders (27 different queries just seems like the worst way to accomplish this, and has a fairly high possibility of me making a tiny mistake).  I would like to be able to just write 3 linq queries that reorders the list according to each of the 3 sorting methods, something like this:

```<code>switch(sortOrder[0]){
    Sort by the first sort method
}
switch(sortOrder[1]){
    Sort by the second sort method
}
switch(sortOrder[2]){
    Sort by the third sort method
}
</code>```

But if I try doing the above code, it just resorts it each time, instead of doing sub-sorts after the one above it.  Hope that is clear, any help would be appreciated.

答: If you have a limited number of possible fields to sort by, a switch might be the best solution. If you're looking for something that scales, you'll have to generate a lambda expression on the fly, and use reflection to call the appropriately-typed .OrderBy and .ThenBy methods.

ContentLicense: CC BY-SA 3.0

Body:
I have an array that stores the order that I want to sort a list by.

SortOrderArray: "Color", "Volume", "Weight"

So I want to order my list by Color, Volume, then Weight

MyList.OrderBy(a=>a.Color).ThenBy(a=>a.Volume).ThenBy(a=>a.Weight).ToList();

So that's pretty good.  Now, I want to be able to write a function that does this sorting based on the sortOrder array I send in:

public List<row> GetSortedList(List<row> list, string[] sortOrder){
    ???
}

I can't figure out how to do this without writing a linq query for every combination of sortOrders (27 different queries just seems like the worst way to accomplish this, and has a fairly high possibility of me making a tiny mistake).  I would like to be able to just write 3 linq queries that reorders the list according to each of the 3 sorting methods, something like this:

switch(sortOrder[0]){
    Sort by the first sort method
}
switch(sortOrder[1]){
    Sort by the second sort method
}
switch(sortOrder[2]){
    Sort by the third sort method
}

But if I try doing the above code, it just resorts it each time, instead of doing sub-sorts after the one above it.  Hope that is clear, any help would be appreciated.


问:
How do you change the title of a pdf using django?
So I have this app that allows you to upload pdfs then you can view them in the browser and it works fine but the only problem is that my title is a regex for some reason :

Screenshot

urls.py

```<code>urlpatterns = [
               path("show_file/r'^(?P<file_id>\d+)",v.show_file, name="show_file" ),
]
</code>```

views.py

```<code>def show_file(response,file_id):
    doc = Document.objects.get(id=file_id)
    pdf = open(f"media/{doc.file}", 'rb')
    return FileResponse(pdf, content_type='application/pdf')
</code>```

models.py

class Document(models.Model):
    title = models.CharField(max_length=65, null=False, blank=False)
    subject = models.CharField(max_length=20)
    grade = models.IntegerField()
    file = models.FileField(upload_to="documents/")
    date_uploaded = models.DateField(null=False)
```
<p><code>forms.py</code></p>
<pre class="lang-py prettyprint-override"><code>class DocumentsForm(forms.ModelForm):
    subject = forms.ChoiceField(choices=subject_choices)
    grade = forms.ChoiceField(choices=grade_choices)
    class Meta:
        model = Document
        fields = ("title","subject","grade","file","date_uploaded")
</code>```

答:
Your browser is showing the last segment of the URL in the absence of any other title. Just change your URL to

```<code>path("show_file/<file_id>", v.show_file, name="show_file"),
</code>```

What you have now seems to be a half-baked porting of a regexp-based re_path to the <>-based paths.

Body:
So I have this app that allows you to upload pdfs then you can view them in the browser and it works fine but the only problem is that my title is a regex for some reason :

Screenshot

urls.py

urlpatterns = [
               path("show_file/r'^(?P<file_id>\d+)",v.show_file, name="show_file" ),
]

views.py

def show_file(response,file_id):
    doc = Document.objects.get(id=file_id)
    pdf = open(f"media/{doc.file}", 'rb')
    return FileResponse(pdf, content_type='application/pdf')

models.py

class Document(models.Model):
    title = models.CharField(max_length=65, null=False, blank=False)
    subject = models.CharField(max_length=20)
    grade = models.IntegerField()
    file = models.FileField(upload_to="documents/")
    date_uploaded = models.DateField(null=False)

forms.py

class DocumentsForm(forms.ModelForm):
    subject = forms.ChoiceField(choices=subject_choices)
    grade = forms.ChoiceField(choices=grade_choices)
    class Meta:
        model = Document
        fields = ("title","subject","grade","file","date_uploaded")

Body:
Your browser is showing the last segment of the URL in the absence of any other title. Just change your URL to

path("show_file/<file_id>", v.show_file, name="show_file"),

What you have now seems to be a half-baked porting of a regexp-based re_path to the <>-based paths.


问:
AttributeError: 'str' object has no attribute 'values' (compare dataframes)
I am a beginner at Python, and I have some issues with a code I wrote.

I have 2 dataframes: one with general informations about books (dfMediaGe), and the other with the names of books which were shown on TV (dfTV).

My goal is to compare them, and to fill the column 'At least 1 TV emission' in dfMediaGe with a 1 if the book appears in the dfTV dataframe.

My difficulty is that the dataframes do not have the same number of lines/columns.

Here is a sample of dfMediaGe :

```<code>    Titre   original_title  AUTEUR  DATE    EDITEUR THEMESIMPLE THEME   GENRE   rating  rating_average  ... current_count   done_count  list_count  recommend_count review_count    TRADUITDE   LANGUEECRITURE  NOTE    At least 1 TV emission  id
0   La souris des dents NaN Roger, Marie-Sabine|Desbons, Marie  01/01/2021  Lito    TIPJJ001 Eveil  J000100 Jeunesse - Eveil et Fiction / Histoire...   GJEU003 Jeunesse / Mini albums|GJEU013 Jeuness...   NaN NaN ... 0.0 0.0 0.0 0.0 0.0 NaN fre NaN 0   46220676.0

1   La petite mare du grand crocodile   NaN Buteau, Gaëlle|Hudrisier, Cécile    01/01/2021  Lito    TIPJJ001 Eveil  J000100 Jeunesse - Eveil et Fiction / Histoire...   GJEU003 Jeunesse / Mini albums|GJEU013 Jeuness...   NaN NaN 0.0 0.0 0.0 0.0 0.0 0.0 NaN fre NaN 46220678.0
</code>```

and here is a sample of dfTV :

```<code>    Titre   AUTEUR  DATE    EDITEUR GENRE   THEMESIMPLE TRADUITDE   NOTE    THEME   LANGUEECRITURE  FORMATNUMERIQUE PUBLIC  MATIERE LEXIQUE DESCRIPTION
0   Les strates Bagieu, Pénélope    11/12/2021  Gallimard   NaN TIPBD001 Albums NaN NaN T090200 Bandes dessinées / Bandes dessinées fre NaN NaN NaN NaN 1 vol. ; illustrations en noir et blanc ; 24 x...
</code>```

And here is the code I wrote, which is not working at all.

```<code>  for Titre, r in dfMediaGe.iterrows():
    for Titre, r in dfTV.iterrows():
        p = 0
        if r['Titre'].values == (dfTV['Titre']).values.any():
            p = 1
            r['Au moins 1 passage TV'].append(p)
</code>```

I do get this error :

```<code>AttributeError: 'str' object has no attribute 'values'
</code>```

Thank you very much for your help !!

答:
I don't think your two data frames not having the same amount of columns is a problem.

You can achieve what you are looking for using this:

```<code>data_dfMediaGe = [
    ['Les strates Bagieu'],
    ['La petite mare du grand crocodile'],
    ['La souris des dents NaN Roger'],
    ['Movie XYZ']
]
dfMediaGe = pd.DataFrame(data=data_dfMediaGe, columns=['Titre'])
dfMediaGe['Au moins 1 passage TV'] = 0

data_dfTV = [
    ['La petite mare du grand crocodile'],
    ['Movie XYZ']
]
dfTV = pd.DataFrame(data=data_dfTV, columns=['Titre'])

for i, row in dfMediaGe.iterrows():
    if row['Titre'] in list(dfTV['Titre']):
        dfMediaGe.at[i, 'Au moins 1 passage TV'] = 1

print(dfMediaGe)

                               Titre  Au moins 1 passage TV
0                 Les strates Bagieu                      0
1  La petite mare du grand crocodile                      1
2      La souris des dents NaN Roger                      0
3                          Movie XYZ                      1
</code>```

All you have to do is iterate through rows in dfMediaGe and check if the value in the Titrecolumn is present in dfTV in the Titre column.

Body:
I am a beginner at Python, and I have some issues with a code I wrote.

I have 2 dataframes: one with general informations about books (dfMediaGe), and the other with the names of books which were shown on TV (dfTV).

My goal is to compare them, and to fill the column 'At least 1 TV emission' in dfMediaGe with a 1 if the book appears in the dfTV dataframe.

My difficulty is that the dataframes do not have the same number of lines/columns.

Here is a sample of dfMediaGe :

    Titre   original_title  AUTEUR  DATE    EDITEUR THEMESIMPLE THEME   GENRE   rating  rating_average  ... current_count   done_count  list_count  recommend_count review_count    TRADUITDE   LANGUEECRITURE  NOTE    At least 1 TV emission  id
0   La souris des dents NaN Roger, Marie-Sabine|Desbons, Marie  01/01/2021  Lito    TIPJJ001 Eveil  J000100 Jeunesse - Eveil et Fiction / Histoire...   GJEU003 Jeunesse / Mini albums|GJEU013 Jeuness...   NaN NaN ... 0.0 0.0 0.0 0.0 0.0 NaN fre NaN 0   46220676.0

1   La petite mare du grand crocodile   NaN Buteau, Gaëlle|Hudrisier, Cécile    01/01/2021  Lito    TIPJJ001 Eveil  J000100 Jeunesse - Eveil et Fiction / Histoire...   GJEU003 Jeunesse / Mini albums|GJEU013 Jeuness...   NaN NaN 0.0 0.0 0.0 0.0 0.0 0.0 NaN fre NaN 46220678.0

and here is a sample of dfTV :

    Titre   AUTEUR  DATE    EDITEUR GENRE   THEMESIMPLE TRADUITDE   NOTE    THEME   LANGUEECRITURE  FORMATNUMERIQUE PUBLIC  MATIERE LEXIQUE DESCRIPTION
0   Les strates Bagieu, Pénélope    11/12/2021  Gallimard   NaN TIPBD001 Albums NaN NaN T090200 Bandes dessinées / Bandes dessinées fre NaN NaN NaN NaN 1 vol. ; illustrations en noir et blanc ; 24 x...

And here is the code I wrote, which is not working at all.

  for Titre, r in dfMediaGe.iterrows():
    for Titre, r in dfTV.iterrows():
        p = 0
        if r['Titre'].values == (dfTV['Titre']).values.any():
            p = 1
            r['Au moins 1 passage TV'].append(p)

I do get this error :

AttributeError: 'str' object has no attribute 'values'

Thank you very much for your help !!

Body:
I don't think your two data frames not having the same amount of columns is a problem.

You can achieve what you are looking for using this:

data_dfMediaGe = [
    ['Les strates Bagieu'],
    ['La petite mare du grand crocodile'],
    ['La souris des dents NaN Roger'],
    ['Movie XYZ']
]
dfMediaGe = pd.DataFrame(data=data_dfMediaGe, columns=['Titre'])
dfMediaGe['Au moins 1 passage TV'] = 0

data_dfTV = [
    ['La petite mare du grand crocodile'],
    ['Movie XYZ']
]
dfTV = pd.DataFrame(data=data_dfTV, columns=['Titre'])

for i, row in dfMediaGe.iterrows():
    if row['Titre'] in list(dfTV['Titre']):
        dfMediaGe.at[i, 'Au moins 1 passage TV'] = 1

print(dfMediaGe)

                               Titre  Au moins 1 passage TV
0                 Les strates Bagieu                      0
1  La petite mare du grand crocodile                      1
2      La souris des dents NaN Roger                      0
3                          Movie XYZ                      1

All you have to do is iterate through rows in dfMediaGe and check if the value in the Titrecolumn is present in dfTV in the Titre column.


问:
How to set default selected value in ModelChoiceField while working with ModelForm?
I am creating a simple form through ModelForm,i have made 4 tables which consists of  one main table, and 3 sub tables which is the foreign keys of main tables,everything is working perfect.

```<code>But I want that there must be selected value in form which will show in the frontend by default.
</code>```

by default it is showing -------- in select tag of html but i want that it will show some label like in my case: it will be better if it  shows Select Job Description by default rather than ------

so how can i implement that?

My forms.py

```<code>from django import forms
from django.utils.translation import gettext_lazy as _
from numpy import empty
from .models import SignUpModel

class SignUpForm(forms.ModelForm):
    first_name = forms.CharField(widget=forms.TextInput(
        attrs={'placeholder': 'First Name'}), required=True, error_messages={'required': 'First Name is required'})
    last_name = forms.CharField(widget=forms.TextInput(
        attrs={'placeholder': 'Last Name'}), required=True, error_messages={'required': 'Last Name is required'})
    email = forms.EmailField(widget=forms.EmailInput(
        attrs={'placeholder': 'Email Address'}), required=True, error_messages={'required': 'Email Address is required'})

    class Meta:
        model = SignUpModel
        fields = ['first_name', 'last_name', 'email', 'password',
                  'company_name', 'job', 'mobile_no', 'country', 'state']
        widgets = {
            'password': forms.PasswordInput(attrs={'placeholder': 'Password'}),
            'company_name': forms.TextInput(attrs={'placeholder': 'Company Name'}),
            'mobile_no': forms.NumberInput(attrs={'placeholder': 'Mobile Number'}),
        }
        error_messages = {
            'password': {
                'required': _('password is required')
            },
            'mobile_no': {
                'required': _('Mobile Number is required')
            },
            'company_name': {
                'required': _('Company Name is required')
            },
            'job': {
                'required': _('Job description must be selected')
            },
            'state': {
                'required': _('State Name is required')
            }
        }
</code>```

Models.py

```<code>    from django.db import models
    from django.contrib.auth.models import User

    class JobType(models.Model):
        job_name = models.CharField(max_length=50)

        def __str__(self):
            return self.job_name
    class Country(models.Model):
        country_name = models.CharField(max_length=50)
        def __str__(self):
            return self.country_name

    class IndianStates(models.Model):
        state_name = models.CharField(max_length=30)
        def __str__(self):
            return self.state_name

    class SignUpModel(User):
        company_name = models.CharField(max_length=80)
        job = models.ForeignKey(JobType, on_delete=models.CASCADE)
        mobile_no = models.PositiveIntegerField()
        country = models.ForeignKey(Country, on_delete=models.CASCADE, blank=True)
        state = models.ForeignKey(IndianStates, on_delete=models.CASCADE)
</code>```

my template file

```<code><body>

    {% if form %}
    <form method="POST" novalidate>
        {% csrf_token %}
        {% if form.non_field_errors %}
        {% for error in form.non_field_errors  %}
        <div>
            {{error}}

        </div>
        {% endfor %}
        {% endif %}
        {% for field in form %}
        <div>
            {{field}}
            {% for error in field.errors  %}
            <div class="red">
                {{error}}

            </div>
            {% endfor %}
        </div>
        {% endfor %}

        <input type="submit" value="Register">

    </form>
    {% endif %}

</body>
</code>```

Views.py

```<code>from django.shortcuts import render
from django.views.generic.base import TemplateView
from . forms import SignUpForm
from django.views.generic.edit import CreateView

class HomeTemplateView(CreateView):
    template_name = 'home/index.html'
    form_class = SignUpForm
    success_url = '/thanks/'

class CreatedThanksTemplate(TemplateView):
    template_name = 'home/thanks.html'
</code>```

答:
You can set the empty_label=… parameter [Django-doc] of the ModelChoiceField. Since then we need to define the rest of the parameters as well, it might be better to set it in the constructor of the ModelForm, so:

```<code>class SignUpForm(forms.ModelForm):
    # …

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['job']<strong>.empty_label = 'Select Job Description'</strong>

    class Meta:
        model = SignUpModel
        # …</code>```

Note: Models doesn't require model to be the suffix, so you may change it to SignUp from <s>SignUpModel</s>.

Body:
I am creating a simple form through ModelForm,i have made 4 tables which consists of  one main table, and 3 sub tables which is the foreign keys of main tables,everything is working perfect.

But I want that there must be selected value in form which will show in the frontend by default.

by default it is showing -------- in select tag of html but i want that it will show some label like in my case: it will be better if it  shows Select Job Description by default rather than ------

so how can i implement that?

My forms.py

from django import forms
from django.utils.translation import gettext_lazy as _
from numpy import empty
from .models import SignUpModel

class SignUpForm(forms.ModelForm):
    first_name = forms.CharField(widget=forms.TextInput(
        attrs={'placeholder': 'First Name'}), required=True, error_messages={'required': 'First Name is required'})
    last_name = forms.CharField(widget=forms.TextInput(
        attrs={'placeholder': 'Last Name'}), required=True, error_messages={'required': 'Last Name is required'})
    email = forms.EmailField(widget=forms.EmailInput(
        attrs={'placeholder': 'Email Address'}), required=True, error_messages={'required': 'Email Address is required'})

    class Meta:
        model = SignUpModel
        fields = ['first_name', 'last_name', 'email', 'password',
                  'company_name', 'job', 'mobile_no', 'country', 'state']
        widgets = {
            'password': forms.PasswordInput(attrs={'placeholder': 'Password'}),
            'company_name': forms.TextInput(attrs={'placeholder': 'Company Name'}),
            'mobile_no': forms.NumberInput(attrs={'placeholder': 'Mobile Number'}),
        }
        error_messages = {
            'password': {
                'required': _('password is required')
            },
            'mobile_no': {
                'required': _('Mobile Number is required')
            },
            'company_name': {
                'required': _('Company Name is required')
            },
            'job': {
                'required': _('Job description must be selected')
            },
            'state': {
                'required': _('State Name is required')
            }
        }

Models.py

    from django.db import models
    from django.contrib.auth.models import User

    class JobType(models.Model):
        job_name = models.CharField(max_length=50)

        def __str__(self):
            return self.job_name
    class Country(models.Model):
        country_name = models.CharField(max_length=50)
        def __str__(self):
            return self.country_name

    class IndianStates(models.Model):
        state_name = models.CharField(max_length=30)
        def __str__(self):
            return self.state_name

    class SignUpModel(User):
        company_name = models.CharField(max_length=80)
        job = models.ForeignKey(JobType, on_delete=models.CASCADE)
        mobile_no = models.PositiveIntegerField()
        country = models.ForeignKey(Country, on_delete=models.CASCADE, blank=True)
        state = models.ForeignKey(IndianStates, on_delete=models.CASCADE)

my template file

    {% if form %}
    <form method="POST" novalidate>
        {% csrf_token %}
        {% if form.non_field_errors %}
        {% for error in form.non_field_errors  %}

            {{error}}

        {% endfor %}
        {% endif %}
        {% for field in form %}

            {{field}}
            {% for error in field.errors  %}

                {{error}}

            {% endfor %}

        {% endfor %}

        <input type="submit" value="Register">

    </form>
    {% endif %}

Views.py

from django.shortcuts import render
from django.views.generic.base import TemplateView
from . forms import SignUpForm
from django.views.generic.edit import CreateView

class HomeTemplateView(CreateView):
    template_name = 'home/index.html'
    form_class = SignUpForm
    success_url = '/thanks/'

class CreatedThanksTemplate(TemplateView):
    template_name = 'home/thanks.html'

Body:
You can set the empty_label=… parameter [Django-doc] of the ModelChoiceField. Since then we need to define the rest of the parameters as well, it might be better to set it in the constructor of the ModelForm, so:

class SignUpForm(forms.ModelForm):
    # …

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['job'].empty_label = 'Select Job Description'

    class Meta:
        model = SignUpModel
        # …

Note: Models doesn't require model to be the suffix, so you may change it to SignUp from <s>SignUpModel</s>.


问:
Error in solidity code: Return argument type bytes1 is not implicitly convertible to expected type
I have setter and getter:

```<code>    function setFunc(bytes calldata _value) public {
        getBytes = _value;
    }

function getFunc() public view returns(bytes calldata) {
        return getBytes;
    }
</code>```

When I run my code, the compiler shows that

```<code>TypeError: Return argument type bytes1 is not implicitly convertible to expected type (type of first return variable) bytes calldata.
  --> contracts/GetterSetter.sol:38:16:
   |
38 |         return getBytes[];
   |                ^^^^^^^^^^
</code>```

Before that I had another error:

```<code>TypeError: Data location must be "memory" or "calldata" for return parameter in function, but none was given.
  --> contracts/GetterSetter.sol:37:51:
   |
37 |     function requestedBytes() public view returns(bytes) {
   |                                                   ^^^^^
</code>```

Could you help to resolve it and what input example should I provide into setter for correct functions working?

I will be really appreciate for your help!

答:
The getter function return type needs to have the memory data location.

It's because the EVM loads the value from storage to memory, and then returns it from memory.

```<code>pragma solidity ^0.8;

contract MyContract {
    bytes getBytes;

    function setFunc(bytes calldata _value) public {
        getBytes = _value;
    }

    function getFunc() public view returns(bytes memory) {
        return getBytes;
    }
}
</code>```

The return type could have the calldata location only if it's returning the actual and unchanged calldata from the input param:

```<code>pragma solidity ^0.8;

contract MyContract {
    function getFunc(bytes calldata _value) public pure returns(bytes calldata) {
        return _value;
    }
}
</code>```

Body:
I have setter and getter:

    function setFunc(bytes calldata _value) public {
        getBytes = _value;
    }

function getFunc() public view returns(bytes calldata) {
        return getBytes;
    }

When I run my code, the compiler shows that

TypeError: Return argument type bytes1 is not implicitly convertible to expected type (type of first return variable) bytes calldata.
  --> contracts/GetterSetter.sol:38:16:
   |
38 |         return getBytes[];
   |                ^^^^^^^^^^

Before that I had another error:

TypeError: Data location must be "memory" or "calldata" for return parameter in function, but none was given.
  --> contracts/GetterSetter.sol:37:51:
   |
37 |     function requestedBytes() public view returns(bytes) {
   |                                                   ^^^^^

Could you help to resolve it and what input example should I provide into setter for correct functions working?

I will be really appreciate for your help!

Body:
The getter function return type needs to have the memory data location.

It's because the EVM loads the value from storage to memory, and then returns it from memory.

pragma solidity ^0.8;

contract MyContract {
    bytes getBytes;

    function setFunc(bytes calldata _value) public {
        getBytes = _value;
    }

    function getFunc() public view returns(bytes memory) {
        return getBytes;
    }
}

The return type could have the calldata location only if it's returning the actual and unchanged calldata from the input param:

pragma solidity ^0.8;

contract MyContract {
    function getFunc(bytes calldata _value) public pure returns(bytes calldata) {
        return _value;
    }
}


问:
Which Version Control System would you use for a 1000+ developer organization? Why?
There are many SCM systems out there. Some open, some closed, some free, some quite expensive. Which one (please choose only one) would you use for a 3000+ developer organization with several sites (some behind a very slow link)? Explain why you chose the one you chose. (Give some reasons, not just "because".)

答:
For such a huge installation, there are at least the following major requirements: Data safety, maturity, robustness, Scalability, price (a per seat licence vs. open source always makes a huge difference regardless of the price per seat), ease of administration

I would think that subversion would be just fine.

There is support available (from collabnet, clearvision, wandisco and others). You could ask them if subversion would be able to handle your task.

subversion has a very mature database backend - FSFS. It is absolutely rock solid and since 1.5 it can handle really many revisions without performance degradation. The revisions are written in a file system. So the reliability of your subversion repository depends on the quality of your file system, os and storage system.

This is why I would recommend Solaris 10 with ZFS as the file system. ZFS has really great file system features for production systems. But above all it provides data integrity checksumming. So with this amount of source code in the subversion repository you won't have to worry about repository corruption because of a silent hard drive bit error or controller or cable bit error. By now ZFS is mature enough that it can be safely used as a UFS or whatever replacement.

I don't know about the hardware requirements. Maybe Collabnet could give you advice.

But a really good start (which could be used as NFS storage or backup storage if it turns out to be too slow - you will definitely be able to make good use of it anyway) would be a 2nd generation thumper, i.e Sun Fire X4540 Server: You can have (all within a nice 4U Rack Server for 80.000$ (list price - this will be likely negotiable)): 48 TB Disk space!, 8 AMD Opteron CPU cores,  64 GB RAM,  Solaris 10 preinstalled, 3 year Platinum software and hardware support from sun. So the mere hardware and support price for this server would be 25$ per seat of your 3000 Developers.

To assure really great data safety, you could partition the 48 hard drives as follows: 3 drives for the operating system (3-way Raid-1 mirror), 3 hot spares (not used, on stand-by in the case of a failure of the other drives), a zfs pool of 14 3-way Raid 1 mirrors (14*3=42 drives) for the subversion repository. If you would like to fill the 14 TB ZFS Raid space only by 80% then this would be approximately 10 Tebibyte of real usable disk space for the repository, i.e. an average of 3 GB per developer.

With this configuration: Subversion 1.6 on a Sun x4540 thumper with 10 TiB 3-way Raid-1 ZFS redundant and checksummed disk space this should be a really serious start.

If the compute power isn't enough for 3000+ developers than you could buy a beefier server which could use the disk space of the thumper. If the disk performance is too slow you could hook up a huge array of fast scsi drives to the compute server and use the thumper as a backup solution.

Certainly, it would make sense to get consulting services from collabnet regarding the planning and deployment of this subversion server and to get platinum support for the hardware and solaris operating system from sun.

Edit (answer to comment #1): For distributed teams there is the possibility of a master-slave configuration: WebDAV-Proxy. Each local team has a slave server, which replicates the repository. The developers get all checkouts from this slave. The checkins are forwarded transparently from the slave to the master. In this way, the master is always current. The vast majority of traffic is checkouts: Every developer gets every checkin any developer commits. So the checkout traffic should be 99.97%  of the traffic with 3000 developers. If you have a local team with 50 developers, the checkout traffic would be reduced by 98%. The checkins shouldn't be a problem: how fast can anybody type new code? Obviously, for a small team you won't buy a thumper. You just need a box with enough hard drive space (i.e. if you intend to hold the hole repository 10TB). It can be a raid5 configuration as data loss isn't the end of the company. You won't need Solaris either. You could put linux on it if the local people would be more comfortable with it. Again: ask a consultant like collabnet if this is really a sound concept. With this many seats it shouldn't be a problem to pay for a one time consultation. They can set up the whole thing. Sun delivers the box with solaris pre-installed. You have sun support. So you won't need a solaris guru on site, as the configuration shouldn't change for the next years. This configuration means that

the slow line from the team to the headquarter won't be clogged with redundant checkout data and

the members of the local team can get their checkouts quickly

it would dramatically reduce the load at the thumper - this means with that configuration you shouldn't have to worry at all whether the thumper is capable of handling the load

it reduces the bandwidth costs

Edit (after the release of the M3000): A much more extreme hardware configuration targeted even more towards insane data integrity would be the combination of a M3000 server and a J4500 array:

the J4500 Storage Array is practically a thumper, but without the CPU-power and external storage interfaces which enables it to be connected to a server.

The M3000 Server is a Sparc64 server at a midrange price with high end RAS features. Most data paths and even cpu registers are checksummed, etc. The RAM is not only ECC protected but has the equivalent of the IBM Chipkill feature: It's raid on memory: not only single bit errors are detected and corrected, but entire memory chips may fail completely while no data is lost - similar to failing hard drives in raid arrays.

As the ZFS file system does CPU-based error checksumming on the data before it comes from, or after it goes to the CPU, the quality of the storage controller and cabling of the J4500 is not important. What matters are the bit error prevention and detection capabilities of the M3000 CPU, Memory, memory controller, etc.

Unfortuntely, the high quality memory sticks sun is using to improve the quality even more are that much expensive that the combination of the four core (eight threads) 4GB Ram M3000 + 48 TB J4500 would be roughly equivalent to the thumper, but if you would like to increase the server memory from 4GB to 8, 16 or 32 GB for in-memory caching purposes, the price goes up steeply. But maybe a 4GB configuration would even be enough if the master-slave configuration for distributed teams is used.

This hardware combination would be worth a thought if the source code and data integrity of this 3000 developer repository is valued extremely highly by the management. Then it would also make sense to add two or more thumpers as a rotating backup solution (not neccessary to protect against hardware failure, but to protect against administrator mistakes or for off-site backups in case of physical desasters).

As this would be a Sparc and not a x86 solution, there are certified Collabnet Subversion binaries for this platform available freely.

One of the advantages of subversion is also the excellent documentation: There is an excellent book from O'Reilly (Version Control with Subversion) also available for free as a PDF or HTML version.

To sum it up: With the combination Subversion 1.6 + Solaris 10 + 3-way-raid-1 redundant and checksummed ZFS + thumper + master-slave server replication for local teams + sun support + collabnet/clearvision/orcaware/Karl Vogel consultation + excellent and free subversion manual for all developers you should have a solution which provides

Extremely High Data Safety (very important for so much source code - you do not want to corrupt your repository, bit errors do happen, hard drives do fail!) You have one master data repository which holds all your versions/revisions really reliably: The main feature of source control systems.

Maturity - Subversion has been used by many, many companies and open source projects.

Scalability - With the master-slave replication you should not have a load problem on the master server: The load of the checkins are negligible. The checkouts are handled by the slaves.

No High Latency for local teams behind slow connections (because of the replication)

A low price: subversion is free (no per seat fee), excellent free documentation, over a three year period only 8$ per seat per year hardware and support costs for the master server, cheap linux boxes for slaves, one-time consultancy from collabnet et. al., low bandwidth costs because of master-slave-replication.

Ease of administration: Essentially no administration of the master server: The subversion consultant can deploy everything. Sun staff will swap faulty hard drives, etc. Slaves can be linux boxes or whatever administration skills are available at the local sites. Excellent subversion documentation.

OwnerDisplayName: Vasco Duarte

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: blowdart


问:
How can I have PHP avoid lazy evaluation?
I have an interesting question about the way PHP evaluates boolean expressions.   When you have, for example,

```<code>$expression = $expression1 and $expression2;
</code>```

or

```<code>if ($expression1 and $expression2)
</code>```

PHP first checks if $expression1 evaluates to true. If this is not the case, then $expression2 is simply skipped to avoid unnecessary calculations.  In a script I am writing, I have:

```<code>if ($validator->valid("title") and $validator->valid("text"))
</code>```

I need to have the second statement ($validator->valid("text")) evaluated even if the first one evaluates to false.  I would like to ask you whether there is some easy way to force PHP to always evaluate both statements. Thank you!

答:
This might not be the best implementation, but you could always do:</p>

```<code>$a=$validator->valid("title");
$b=$validator->valid("text");
if($a && $b) {...}
</code>```

LastEditorDisplayName: Eddie

Body:
I have an interesting question about the way PHP evaluates boolean expressions.   When you have, for example,

$expression = $expression1 and $expression2;

or

if ($expression1 and $expression2)

PHP first checks if $expression1 evaluates to true. If this is not the case, then $expression2 is simply skipped to avoid unnecessary calculations.  In a script I am writing, I have:

if ($validator->valid("title") and $validator->valid("text"))

I need to have the second statement ($validator->valid("text")) evaluated even if the first one evaluates to false.  I would like to ask you whether there is some easy way to force PHP to always evaluate both statements. Thank you!

Body:
This might not be the best implementation, but you could always do:

$a=$validator->valid("title");
$b=$validator->valid("text");
if($a && $b) {...}

OwnerDisplayName: dmondark


问:
How to select points from matrix with given probability?
I have a numpy.ndarray points representing a set of coordinate points:

```<code>[[0 0]
 [0 1]
 [0 2]
 [1 0]
 [1 1]
 [1 2]
 [2 0]
 [2 1]
 [2 2]]
</code>```

I want to get a subset of this points some_points where each point is independently taken with probability prob. How can I do this using only numpy?

P.S. For instance, if prob=0.5 some_points will contain about a half of original points.

答:
```<code>n = points.size
some_points = points[np.random.rand(n * n) < p]
</code>```

Body:
I have a numpy.ndarray points representing a set of coordinate points:

[[0 0]
 [0 1]
 [0 2]
 [1 0]
 [1 1]
 [1 2]
 [2 0]
 [2 1]
 [2 2]]

I want to get a subset of this points some_points where each point is independently taken with probability prob. How can I do this using only numpy?

P.S. For instance, if prob=0.5 some_points will contain about a half of original points.


问:
Overrideing hardcoded element style inside an iframe
I have no access to the html for this form, all theming has to be done via css that is loaded into the iframe which displays the form. Yes, this code is annoying and bad practice, but it is what it is.

```<code><input
    class="give-input required"
    type="text"
    name="give_first"
    autocomplete="given-name"
    placeholder="First Name"
    id="give-first"
    value=""
    required=""
    aria-required="true"
    style="padding-left: 33px!important;" tabindex="1">
</code>```

Versions of the below, beginning with #give-first and adding greater specificity, do not work

```<code>#give-first-name-wrap input#give-first.give-input.required[style]
{
    padding-left:0;
}
</code>```

I don't have a hook to load jQuery into the iframe, very annoyingly!

All suggestions gratefully received.

答:
style attributes have higher specificity than any selector.

They can only be overridden if they aren't !important and you use an !important rule.

In this case, the rule is !important so you can't override it.

You could replace it with JS. You don't need jQuery.

Body:
I have no access to the html for this form, all theming has to be done via css that is loaded into the iframe which displays the form. Yes, this code is annoying and bad practice, but it is what it is.

<input
    class="give-input required"
    type="text"
    name="give_first"
    autocomplete="given-name"
    placeholder="First Name"
    id="give-first"
    value=""
    required=""
    aria-required="true"
    style="padding-left: 33px!important;" tabindex="1">

Versions of the below, beginning with #give-first and adding greater specificity, do not work

#give-first-name-wrap input#give-first.give-input.required[style]
{
    padding-left:0;
}

I don't have a hook to load jQuery into the iframe, very annoyingly!

All suggestions gratefully received.


问:
linear algebra (partial) solving in python
I have a dictionary with a tuple as key and a result as value.
I'm looking for a way to "solve" as many keys as possible, even if it's not possible to "solve" all of then.

```<code>input : {(A, C):1,(A, B, C): 1}
output : {(A, C):1, (A, B, C): 1, B:0}
</code>```

in other word :

```<code>modified input :
    1*A + 0*B + 1*C = 1
    1*A + 1*B + 1*C = 1
output :
A = ?
B = 0
C = ?
</code>```

I can only use numpy and scipy.

I tried this, but it must be square matrix :

```<code>import numpy as np
a = np.array([[1, 0, 1], [1, 1, 1]])
b = np.array([1, 1])
from scipy import linalg
x = linalg.solve(a, b)
print(x)
</code>```

Do you have ideas where I should look at ?

this code does the trick, but it's not very 'clean'

```<code>import numpy as np
A=np.array([[1, 0, 1], [1, 1, 1]])
B=np.array([1,1])
s = solutionNonSquare = np.linalg.lstsq(A, B)[0]
for i,val in enumerate(s):
    if val < 0.0001:
        print('x[',i,'] = 0')
    else:
        print('x[',i,'] = ?')

print(s)
</code>```

Thanks a lot for your smartness

答:
Matrix a is Non square Matrix, so it does not have full Rank. However, we can compute pseudo inverse, using np.linalg.pinv and then we can compute x = np.matmul(a_psudo_inv, b)

```<code>import numpy as np
a = np.array([[1, 0, 1], [1, 1, 1]])
b = np.array([1, 1])
from numpy import linalg

a_psudo_inv = np.linalg.pinv(a)
print(a_psudo_inv)

print(a_psudo_inv.shape)
x = np.matmul(a_psudo_inv, b)
print(x)
</code>```

Solution >> [5.00000000e-01 5.55111512e-16 5.00000000e-01]

Body:
I have a dictionary with a tuple as key and a result as value.
I'm looking for a way to "solve" as many keys as possible, even if it's not possible to "solve" all of then.

input : {(A, C):1,(A, B, C): 1}
output : {(A, C):1, (A, B, C): 1, B:0}

in other word :

modified input :
    1*A + 0*B + 1*C = 1
    1*A + 1*B + 1*C = 1
output :
A = ?
B = 0
C = ?

I can only use numpy and scipy.

I tried this, but it must be square matrix :

import numpy as np
a = np.array([[1, 0, 1], [1, 1, 1]])
b = np.array([1, 1])
from scipy import linalg
x = linalg.solve(a, b)
print(x)

Do you have ideas where I should look at ?

this code does the trick, but it's not very 'clean'

import numpy as np
A=np.array([[1, 0, 1], [1, 1, 1]])
B=np.array([1,1])
s = solutionNonSquare = np.linalg.lstsq(A, B)[0]
for i,val in enumerate(s):
    if val < 0.0001:
        print('x[',i,'] = 0')
    else:
        print('x[',i,'] = ?')

print(s)

Thanks a lot for your smartness

Body:
Matrix a is Non square Matrix, so it does not have full Rank. However, we can compute pseudo inverse, using np.linalg.pinv and then we can compute x = np.matmul(a_psudo_inv, b)

import numpy as np
a = np.array([[1, 0, 1], [1, 1, 1]])
b = np.array([1, 1])
from numpy import linalg

a_psudo_inv = np.linalg.pinv(a)
print(a_psudo_inv)

print(a_psudo_inv.shape)
x = np.matmul(a_psudo_inv, b)
print(x)

Solution >> [5.00000000e-01 5.55111512e-16 5.00000000e-01]


问:
Saving a html file to public_html
I have a small Flask application that runs fine locally, however when I go to run the application on my server, it runs but I am not able to get the output to save to a public_html folder.

This is the area I believe I am having the issue, when I run the application remotely:

```<code>df.to_html('/home/mydomain/public_html/data/candles.html', index = False)
</code>```

If I run the application locally, this location works fine:

```<code>df.to_html('candles.html', index = False)
</code>```

I have ensured that the remote folder 'data' has full access - 0777.

What am I doing wrong?

答:
If you don't have an exception occurring, then very likely the file was saved, but not where you think it should have. If you did not provide a full path, the destination will be relative to the application directory. The solution is to be explicit and provide a full path, unless you are using some Flask functions that already have a default setting.

You should never grant 0777 permissions on public_html, that is a potential vulnerability. For example, someone could upload a shell to that directory if they can leverage a security flaw on your website.

There is not enough context, but the user running the process (Apache, Nginx or whatever) should not have write permissions here. If you must grant write permissions, create a dedicated directory (preferably outside the webroot unless they have to be exposed to the user), then add some directives to stipulate that files present in the directory cannot be executed. So that even if a webshell is uploaded it cannot run.

Title: Saving a html file to public_html

Body:
I have a small Flask application that runs fine locally, however when I go to run the application on my server, it runs but I am not able to get the output to save to a public_html folder.

This is the area I believe I am having the issue, when I run the application remotely:

df.to_html('/home/mydomain/public_html/data/candles.html', index = False)

If I run the application locally, this location works fine:

df.to_html('candles.html', index = False)

I have ensured that the remote folder 'data' has full access - 0777.

What am I doing wrong?


问:
ar.js location based not placing at coordinates
So ar.js has a location based feature where you can place objects at certain coordinates. However no matter which coordinates I set it to the 3d object is placed on me, and sticks to me. My GPS may not be extremely accurate but its accurate enough within like a 500 foot radius. So it shouldn't show up when I set the coordinates to 0,0. I have tried it in both firefox and chrome. I also downloaded the libraries and stored them locally to get around the CORS issues, however nothing has seemed to fix it.

Code:

```<code><html>
<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>GeoAR.js demo</title>
    <script src='https://aframe.io/releases/0.9.2/aframe.min.js'></script>
    <script src="./aframe-ar.min.js"></script>
    <script src="./aframe-extras.loaders.min.js"></script>
</head>

<body style='margin: 0; overflow: hidden;'>
    <a-scene
        vr-mode-ui="enabled: false"
        embedded
        arjs='sourceType: webcam; sourceWidth:1280; sourceHeight:960; displayWidth: 1280; displayHeight: 960; debugUIEnabled: false;'>
        <a-entity gltf-model="./Assets/magnemite/scene.gltf" rotation="0 180 0" scale="0.15 0.15 0.15" gps-entity-place="longitude: 0; latitude: 0;" animation-mixer/>
        <a-camera gps-camera rotation-reader></a-camera>
    </a-scene>
</body>
</code>```

答: I've had a similar issue and discovered that I needed to enable location services for my browser app (Safari on IOS). That said, I'm still having problems with items following me around a bit so I'm not sure if that's the complete answer (I'm still looking).</p>

Body:
So ar.js has a location based feature where you can place objects at certain coordinates. However no matter which coordinates I set it to the 3d object is placed on me, and sticks to me. My GPS may not be extremely accurate but its accurate enough within like a 500 foot radius. So it shouldn't show up when I set the coordinates to 0,0. I have tried it in both firefox and chrome. I also downloaded the libraries and stored them locally to get around the CORS issues, however nothing has seemed to fix it.

Code:

    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>GeoAR.js demo</title>


问:
The "_cake_model_" cache configuration does not exist after CakePHP upgrade 3.3.16 > 3.6.7
I am getting the error:

The "_cake_model_" cache configuration does not exist.

after upgrading from CakePHP v3.3.16 to 3.6.7.

However the cache configuration does exist, this from config/app.php:

```<code>'Cache' => [
    '_cake_model_' => [
        'className' => 'Cake\Cache\Engine\FileEngine',
        'prefix' => 'myapp_cake_model_',
        'path' => CACHE . 'models/',
        'serialize' => true,
        'duration' => '+2 minutes',
        'url' => env('CACHE_CAKEMODEL_URL', null),
    ],
],
</code>```

Anyone have an idea why this is happening?

答:
In my case it was NULL in the "className" position. The change below corrected the error.

```<code>  'className' => 'File'
</code>```

Maybe then there is a problem with correct reading of the className field.

Body:
I am getting the error:

The "_cake_model_" cache configuration does not exist.

after upgrading from CakePHP v3.3.16 to 3.6.7.

However the cache configuration does exist, this from config/app.php:

'Cache' => [
    '_cake_model_' => [
        'className' => 'Cake\Cache\Engine\FileEngine',
        'prefix' => 'myapp_cake_model_',
        'path' => CACHE . 'models/',
        'serialize' => true,
        'duration' => '+2 minutes',
        'url' => env('CACHE_CAKEMODEL_URL', null),
    ],
],

Anyone have an idea why this is happening?

Body:
In my case it was NULL in the "className" position. The change below corrected the error.

  'className' => 'File'

Maybe then there is a problem with correct reading of the className field.


问:
onDrawerClosed and onDrawerOpened not being called
I am playing with the DrawerListener , and unfortunately the official documentation is not quite detailed, not to say there aren't any examples  given.

All I want to test is showing a Toast message when the Drawer closes, but its just not happening, its not being called at all, any ideas  ? Below the code

```<code>public class MainActivity extends ActionBarActivity implements DrawerLayout.DrawerListener {

  DrawerLayout.DrawerListener mele;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final DrawerLayout olia=(DrawerLayout)findViewById(R.id.container);

    ListView meka=(ListView)findViewById(R.id.left_drawer);

    String [] karo={"meka","deka","beka"};

    ArrayAdapter<String> mera=new ArrayAdapter<String>     ( this,android.R.layout.simple_list_item_1,karo);

    meka.setAdapter(mera);

     olia.setDrawerListener(mele);

    meka.setOnItemClickListener(new OnItemClickListener () {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub

              olia.closeDrawers();
        }

    });

}

@Override
public void onDrawerClosed(View arg0) {
    // TODO Auto-generated method stub

    Toast.makeText(MainActivity.this, "OK Opened", Toast.LENGTH_LONG).show();
    Log.d("meke", "CLOSED  DRAWER" );
}
</code>```

答:
Note that setDrawerListener(DrawerLayout.DrawerListener) is deprecated.

Use addDrawerListener(DrawerLayout.DrawerListener) instead.

Body:
I am playing with the DrawerListener , and unfortunately the official documentation is not quite detailed, not to say there aren't any examples  given.

All I want to test is showing a Toast message when the Drawer closes, but its just not happening, its not being called at all, any ideas  ? Below the code

public class MainActivity extends ActionBarActivity implements DrawerLayout.DrawerListener {

  DrawerLayout.DrawerListener mele;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final DrawerLayout olia=(DrawerLayout)findViewById(R.id.container);

    ListView meka=(ListView)findViewById(R.id.left_drawer);

    String [] karo={"meka","deka","beka"};

    ArrayAdapter<String> mera=new ArrayAdapter<String>     ( this,android.R.layout.simple_list_item_1,karo);

    meka.setAdapter(mera);

     olia.setDrawerListener(mele);

    meka.setOnItemClickListener(new OnItemClickListener () {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub

              olia.closeDrawers();
        }

    });

}

@Override
public void onDrawerClosed(View arg0) {
    // TODO Auto-generated method stub

    Toast.makeText(MainActivity.this, "OK Opened", Toast.LENGTH_LONG).show();
    Log.d("meke", "CLOSED  DRAWER" );
}


问:
Dictionary key name from combination of string and variable value
Basically, I am trying to append values from a list as key-value pairs to a new dictionary. I want the key names in a specific format and order.

```<code>#!/usr/bin/env python3
ipv4_list = ["192.168.1.2", "192.168.1.3", "192.168.1.4"]
ipv4_dic = {}
ipv4_len = len(ipv4_list)
i = 1

for val in range(len(ipv4_list)):
    ipv4_dic[i] = ipv4_list[val]
    i+=1

print(ipv4_dic)
</code>```

Current output:

```<code>{1: '192.168.1.2', 2: '192.168.1.3', 3: '192.168.1.4'}
</code>```

The above is good but I want to change key names to something like IP1, IP2, etc.

How do I make that in the line ipv4_dic[i] = ipv4_list[key]

I tried something like ipv4_dic["IP"+i] but does not work.

```<code>    ipv4_dic["IP"+i] = ipv4_list[val]
TypeError: can only concatenate str (not "int") to str
</code>```

The expected dictionary output as follows:

```<code>{IP1: '192.168.1.2', IP2: '192.168.1.3', IP3: '192.168.1.4'}
</code>```

Body:
Basically, I am trying to append values from a list as key-value pairs to a new dictionary. I want the key names in a specific format and order.

#!/usr/bin/env python3
ipv4_list = ["192.168.1.2", "192.168.1.3", "192.168.1.4"]
ipv4_dic = {}
ipv4_len = len(ipv4_list)
i = 1

for val in range(len(ipv4_list)):
    ipv4_dic[i] = ipv4_list[val]
    i+=1

print(ipv4_dic)

Current output:

{1: '192.168.1.2', 2: '192.168.1.3', 3: '192.168.1.4'}

The above is good but I want to change key names to something like IP1, IP2, etc.

How do I make that in the line ipv4_dic[i] = ipv4_list[key]

I tried something like ipv4_dic["IP"+i] but does not work.

    ipv4_dic["IP"+i] = ipv4_list[val]
TypeError: can only concatenate str (not "int") to str

The expected dictionary output as follows:

{IP1: '192.168.1.2', IP2: '192.168.1.3', IP3: '192.168.1.4'}

Body:
Use a dictionary comprehension with enumerate starting a 1:

ipv4_list = ["192.168.1.2", "192.168.1.3", "192.168.1.4"]
ipv4_dic  = {f'IP{n}':ip for n,ip in enumerate(ipv4_list,1)}

print(ipv4_dic)
{'IP1': '192.168.1.2', 'IP2': '192.168.1.3', 'IP3': '192.168.1.4'}


问:
Groupby within groups
I have data like this:

```<code>df = pd.DataFrame({
    'a': ['milk', 'eggs', 'eggs', 'butter', 'butter',
          'milk', 'eggs', 'eggs', 'butter', 'butter'],
    'b': ['billy', 'bob', 'frank', 'frank', 'sue',
          'frank', 'sue', 'sue', 'sue', 'sue'],
    'c': ['1/30', '1/30', '1/31', '1/31', '1/31',
          '3/31', '3/31', '3/31', '5/31', '5/31'],
}, index=list('ABCDEFGHIJ'))
</code>```

I want the inverse of the counts for each distinct value of c in b. Billy and Bob each have one distinct value in c, so their counts are both equal to one. Frank has two dates, so his is 0.5, etc.

Desired output:

```<code>A    1.000000
B    1.000000
C    0.500000
D    0.500000
E    0.333333
F    0.500000
G    0.333333
H    0.333333
I    0.333333
J    0.333333
dtype: float64
</code>```

I think I need to manipulate groupby(some group).count() and/or groupby(some group).transform('count'), but I'm not sure how to manipulate them and what else I need (if anything) - or if there's a better way.

I tried variations on

```<code>df.groupby(['b', 'c'], as_index=False)['c'].transform('count').reset_index()
</code>```

(based on aggregating within a groupby), to no avail.

I could probably figure out an "ugly" way but I'd very much like to know how to do this in 1-2 lines (if possible).

Thanks!

答:
I'm sure there's a better way, I'm really unfamiliar with anything beyond the basics of Pandas, but this seems to do what you want:

df.merge(pd.DataFrame(1 / df.groupby("b")["c"].nunique()).reset_index(), on="b").set_index(df.index)
```
<p>Output:</p>
<pre class="lang-py prettyprint-override"><code>        a      b   c_x       c_y
A    milk  billy  1/30  1.000000
B    eggs    bob  1/30  1.000000
C    eggs  frank  1/31  0.500000
D  butter  frank  1/31  0.500000
E    milk  frank  3/31  0.500000
F  butter    sue  1/31  0.333333
G    eggs    sue  3/31  0.333333
H    eggs    sue  3/31  0.333333
I  butter    sue  5/31  0.333333
J  butter    sue  5/31  0.333333
</code>```

Title: Groupby within groups

Body:
I have data like this:

df = pd.DataFrame({
    'a': ['milk', 'eggs', 'eggs', 'butter', 'butter',
          'milk', 'eggs', 'eggs', 'butter', 'butter'],
    'b': ['billy', 'bob', 'frank', 'frank', 'sue',
          'frank', 'sue', 'sue', 'sue', 'sue'],
    'c': ['1/30', '1/30', '1/31', '1/31', '1/31',
          '3/31', '3/31', '3/31', '5/31', '5/31'],
}, index=list('ABCDEFGHIJ'))

I want the inverse of the counts for each distinct value of c in b. Billy and Bob each have one distinct value in c, so their counts are both equal to one. Frank has two dates, so his is 0.5, etc.

Desired output:

A    1.000000
B    1.000000
C    0.500000
D    0.500000
E    0.333333
F    0.500000
G    0.333333
H    0.333333
I    0.333333
J    0.333333
dtype: float64

I think I need to manipulate groupby(some group).count() and/or groupby(some group).transform('count'), but I'm not sure how to manipulate them and what else I need (if anything) - or if there's a better way.

I tried variations on

df.groupby(['b', 'c'], as_index=False)['c'].transform('count').reset_index()

(based on aggregating within a groupby), to no avail.

I could probably figure out an "ugly" way but I'd very much like to know how to do this in 1-2 lines (if possible).

Thanks!

Body:
I'm sure there's a better way, I'm really unfamiliar with anything beyond the basics of Pandas, but this seems to do what you want:

df.merge(pd.DataFrame(1 / df.groupby("b")["c"].nunique()).reset_index(), on="b").set_index(df.index)

Output:

        a      b   c_x       c_y
A    milk  billy  1/30  1.000000
B    eggs    bob  1/30  1.000000
C    eggs  frank  1/31  0.500000
D  butter  frank  1/31  0.500000
E    milk  frank  3/31  0.500000
F  butter    sue  1/31  0.333333
G    eggs    sue  3/31  0.333333
H    eggs    sue  3/31  0.333333
I  butter    sue  5/31  0.333333
J  butter    sue  5/31  0.333333


问:
jQuery - remove user input text from textarea
Okay I have a list of devices where i can select which to edit.
I have 3 states for the edit. When no devices are selected, when 1 device is selected or when x devices are selected.

The problem i have is when a user type some text in the textarea (commentField) and cancels the edit to edit another device, the text there was typed in the textarea won't disapere. It stays so when i get the new dialog for the new edit, the commentfield has the text from the old commentField (as if it wasn't cleared)

I have tried the following codes to remove the text (both when then cancel button is pressed and when i start a new dialog), but nothing works:

```<code>$("#commentField").text(" ");
$("#commentField").value = ' ';
</code>```

Is there anyone who knows how to remove user-typed text from a textarea using jQuery??

Thanks in advance.

-Thor

答:
You can remove text from the textarea like this:

```<code>$("#commentField").html("");
</code>```

EDIT: this does not work, but I'd be really interested as to why. I always thought that the text between the textarea tags was innerHTML and html() is supposed to replace just that. Wouldn't it make sense to have textarea like input?  or is it just because textareas contain long amounts of text that would look tacky between quotation marks?.

Using regular javascript with innerHTML it works for me in FF6.
demo here

Body:
Okay I have a list of devices where i can select which to edit.
I have 3 states for the edit. When no devices are selected, when 1 device is selected or when x devices are selected.

The problem i have is when a user type some text in the textarea (commentField) and cancels the edit to edit another device, the text there was typed in the textarea won't disapere. It stays so when i get the new dialog for the new edit, the commentfield has the text from the old commentField (as if it wasn't cleared)

I have tried the following codes to remove the text (both when then cancel button is pressed and when i start a new dialog), but nothing works:

$("#commentField").text(" ");
$("#commentField").value = ' ';

Is there anyone who knows how to remove user-typed text from a textarea using jQuery??

Thanks in advance.

-Thor

Body:
You can remove text from the textarea like this:

$("#commentField").html("");

EDIT: this does not work, but I'd be really interested as to why. I always thought that the text between the textarea tags was innerHTML and html() is supposed to replace just that. Wouldn't it make sense to have textarea like input?  or is it just because textareas contain long amounts of text that would look tacky between quotation marks?.

Using regular javascript with innerHTML it works for me in FF6.
demo here


问:
Remove previous rows from dataframe based on condition
I have two dataframe say df1 (primary dataframe) and df2. I want to drop all previous rows from df1 based on a condition from df2. My dataframe are like below:

df2

```<code>           tradingsymbol      Time
0                   AAAA  12:54:40
1                   BBBB  12:53:33
2                   CCCC  12:51:50
</code>```

df1.head(20)

```<code>            tradingsymbol      Time  last_price
0                    AAAA  09:20:10       84.40
1                    AAAA  09:20:10       85.95
2                    AAAA  12:55:60       84.70 <-Valid Row
3                    AAAA  13:22:10       86.35 <-Valid Row
4                    AAAA  14:55:40       87.10 <-Valid Row

5                    BBBB  09:20:13       88.95
6                    BBBB  09:20:13       88.80
7                    BBBB  09:20:14       88.30
8                    BBBB  14:23:11       87.30 <-Valid Row

9                    CCCC  09:20:15       90.15
10                   CCCC  09:20:16       90.10
11                   CCCC  09:20:17       91.05
12                   CCCC  09:20:18       90.95
</code>```

I want to remove all rows from df1 previous to time in Time column of df2 for each tradingsymbol. I want my result as below:

```<code>            tradingsymbol      Time  last_price
2                    AAAA  12:55:60       84.70
3                    AAAA  13:22:10       86.35
4                    AAAA  14:55:40       87.10
8                    BBBB  14:23:11       87.30
</code>```

答:
You can use pd.concat and sort values to put remove flags.

Code

import io
import numpy as np
import pandas as pd

# Sample creation
s1 = '''tradingsymbol,Time,last_price
AAAA,09:20:10,84.40
AAAA,09:20:10,85.95
AAAA,12:55:60,84.70
AAAA,13:22:10,86.35
AAAA,14:55:40,87.10
BBBB,09:20:13,88.95
BBBB,09:20:13,88.80
BBBB,09:20:14,88.30
BBBB,14:23:11,87.30
CCCC,09:20:15,90.15
CCCC,09:20:16,90.10
CCCC,09:20:17,91.05
CCCC,09:20:18,90.95'''

s2 = '''tradingsymbol,Time
AAAA,12:54:40
BBBB,12:53:33
CCCC,12:51:50'''

df1 = pd.read_csv(io.StringIO(s1), dtype={'last_pirce': np.float64})
df1.Time = pd.to_datetime(df1.Time, format='%H:%M:%S').dt.time

df2 = pd.read_csv(io.StringIO(s2))
df2.Time = pd.to_datetime(df2.Time, format='%H:%M:%S').dt.time

# Operations to remove specific rows
df = pd.concat([df1, df2], axis=0).sort_values(['tradingsymbol', 'Time'], ascending=[True, False])
df['flag'] = df.last_price.isnull()
df.flag = df.groupby('tradingsymbol').flag.cumsum()
df = df[df.flag==0].sort_values(['tradingsymbol', 'Time']).drop('flag', axis=1)
```

Output

tradingsymbol
Time
last_price

2
AAAA
12:56:00
84.7

3
AAAA
13:22:10
86.35

4
AAAA
14:55:40
87.1

8
BBBB
14:23:11
87.3

Body:
I have two dataframe say df1 (primary dataframe) and df2. I want to drop all previous rows from df1 based on a condition from df2. My dataframe are like below:

df2

           tradingsymbol      Time
0                   AAAA  12:54:40
1                   BBBB  12:53:33
2                   CCCC  12:51:50

df1.head(20)

            tradingsymbol      Time  last_price
0                    AAAA  09:20:10       84.40
1                    AAAA  09:20:10       85.95
2                    AAAA  12:55:60       84.70 <-Valid Row
3                    AAAA  13:22:10       86.35 <-Valid Row
4                    AAAA  14:55:40       87.10 <-Valid Row

5                    BBBB  09:20:13       88.95
6                    BBBB  09:20:13       88.80
7                    BBBB  09:20:14       88.30
8                    BBBB  14:23:11       87.30 <-Valid Row

9                    CCCC  09:20:15       90.15
10                   CCCC  09:20:16       90.10
11                   CCCC  09:20:17       91.05
12                   CCCC  09:20:18       90.95

I want to remove all rows from df1 previous to time in Time column of df2 for each tradingsymbol. I want my result as below:

            tradingsymbol      Time  last_price
2                    AAAA  12:55:60       84.70
3                    AAAA  13:22:10       86.35
4                    AAAA  14:55:40       87.10
8                    BBBB  14:23:11       87.30

Body:
You can use pd.concat and sort values to put remove flags.

Code

import io
import numpy as np
import pandas as pd

# Sample creation
s1 = '''tradingsymbol,Time,last_price
AAAA,09:20:10,84.40
AAAA,09:20:10,85.95
AAAA,12:55:60,84.70
AAAA,13:22:10,86.35
AAAA,14:55:40,87.10
BBBB,09:20:13,88.95
BBBB,09:20:13,88.80
BBBB,09:20:14,88.30
BBBB,14:23:11,87.30
CCCC,09:20:15,90.15
CCCC,09:20:16,90.10
CCCC,09:20:17,91.05
CCCC,09:20:18,90.95'''

s2 = '''tradingsymbol,Time
AAAA,12:54:40
BBBB,12:53:33
CCCC,12:51:50'''

df1 = pd.read_csv(io.StringIO(s1), dtype={'last_pirce': np.float64})
df1.Time = pd.to_datetime(df1.Time, format='%H:%M:%S').dt.time

df2 = pd.read_csv(io.StringIO(s2))
df2.Time = pd.to_datetime(df2.Time, format='%H:%M:%S').dt.time

# Operations to remove specific rows
df = pd.concat([df1, df2], axis=0).sort_values(['tradingsymbol', 'Time'], ascending=[True, False])
df['flag'] = df.last_price.isnull()
df.flag = df.groupby('tradingsymbol').flag.cumsum()
df = df[df.flag==0].sort_values(['tradingsymbol', 'Time']).drop('flag', axis=1)

Output

tradingsymbol
Time
last_price

2
AAAA
12:56:00
84.7

3
AAAA
13:22:10
86.35

4
AAAA
14:55:40
87.1

8
BBBB
14:23:11
87.3


问:
How to develop Python Library in DataBricks without packaging and installing after every single change?
For simplicity, say I have 2 Python scripts. 1 is main, 1 is lib. My question is how can I test my lib in main without needing to build the lib and installing it every single time?

Single file can be done easily as answered here ( https://stackoverflow.com/a/67280018/18105234 ). What about I have nested library?

The idea is to perform development in DataBricks like in a Jupyter Lab.

答:
There are two approaches:

Use %run (doc) to include the "library" notebook into "main" notebook. You need to re-execute that %run cell.  Full example of this approach could be found in this file.

Use new functionality of Databricks Repos called arbitrary files - in this case, your library code should be in the Python file, together with corresponding __init__.py (right now you can't use notebooks), and then you include it as a "normal" Python package using import command.  To automatically reload changes from package you need to use special magic commands, as it's shown in another example:

```<code>%load_ext autoreload
%autoreload 2
</code>```

The 2nd approach has more advantages, as it allows to take the code, and, for example, build a library from it, or apply more code checks, that aren't possible with notebooks out of box.

P.S. My repository shows full example of how to use Databricks Repos and perform testing of the code in notebooks from CI/CD pipeline

Body:
There are two approaches:

Use %run (doc) to include the "library" notebook into "main" notebook. You need to re-execute that %run cell.  Full example of this approach could be found in this file.

Use new functionality of Databricks Repos called arbitrary files - in this case, your library code should be in the Python file, together with corresponding __init__.py (right now you can't use notebooks), and then you include it as a "normal" Python package using import command.  To automatically reload changes from package you need to use special magic commands, as it's shown in another example:

%load_ext autoreload
%autoreload 2

The 2nd approach has more advantages, as it allows to take the code, and, for example, build a library from it, or apply more code checks, that aren't possible with notebooks out of box.

P.S. My repository shows full example of how to use Databricks Repos and perform testing of the code in notebooks from CI/CD pipeline


问:
JqueryUI autocomplete in Rails3
```<code>$(document).ready ->
  $('#auto').autocomplete( source: "main/search" )
</code>```

the code beyond set up the autocomplete env,'#auto' is an input filed.

In my main controller I got the search action

```<code>def search
  @user = User.find_by_name 'castiel'
  respond_to do |format|
    format.json { render :json => @user.to_json(:only => :name) }
  end
end
</code>```

everything seems working perfectly fine.When I type in a char,let's say a "c",so the ajax request was sent and received the json data.

In firebug, it shows the ajax request successfully get the json data below

```<code>{"name":"castiel"}
</code>```

so far so good,but the json data's type is not the kind that autocomplete demanded.It demands that json data is like below.

```<code>{"id":"castiel", "label":"castiel", "value":"castiel"}
</code>```

So here is problem,how to modify the josn data to the kind that I wanted.

答:
In the success function, you need to return something like</p>

```<code>.autocomplete({
    source: function(request, response){
        $.ajax({
            url: "main/search",
            dataType: "json",
            data: {
                style: "full",
                maxRows: 12,
                term: request.term
            },success: function( data ) {
                    response( $.map( data, function( user ) {
                        return {
                            label: user.name,
                            value: user.id
                        }
                    }));
</code>```

Title: JqueryUI autocomplete in Rails3

Body:
$(document).ready ->
  $('#auto').autocomplete( source: "main/search" )

the code beyond set up the autocomplete env,'#auto' is an input filed.

In my main controller I got the search action

def search
  @user = User.find_by_name 'castiel'
  respond_to do |format|
    format.json { render :json => @user.to_json(:only => :name) }
  end
end

everything seems working perfectly fine.When I type in a char,let's say a "c",so the ajax request was sent and received the json data.

In firebug, it shows the ajax request successfully get the json data below

{"name":"castiel"}

so far so good,but the json data's type is not the kind that autocomplete demanded.It demands that json data is like below.

{"id":"castiel", "label":"castiel", "value":"castiel"}

So here is problem,how to modify the josn data to the kind that I wanted.

Body:
In the success function, you need to return something like

.autocomplete({
    source: function(request, response){
        $.ajax({
            url: "main/search",
            dataType: "json",
            data: {
                style: "full",
                maxRows: 12,
                term: request.term
            },success: function( data ) {
                    response( $.map( data, function( user ) {
                        return {
                            label: user.name,
                            value: user.id
                        }
                    }));