问:
React Dayjs Date Picker Component not working: Browser console error: Uncaught TypeError: number 0 is not iterable
I copied the Dayjs date picker component from the MUI website (https://mui.com/x/react-date-pickers/date-picker/). However, this const seems to not work. It makes my whole page go blank.My console doesn't give me an error but I just reviewed the browser console and it gave me this error: Uncaught TypeError: number 0 is not iterable. This error is in the line where the const is defined.

```<code>const [value, setValue] = React.useState<Dayjs | null>(dayjs('2022-04-07'));
</code>```

I have imported everything necessary and when I change the const, the webpage works and the date picker shows up, you just can't pick a date.

Any ideas what I'm doing wrong?

Here is the entire function:

```<code>export function StartDatePicker() {
  const [value, setValue] = React.useState<Dayjs | null>(dayjs('2022-04-07'));

  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>

        <DatePicker
          label="Date"
          openTo="year"
          views={['year', 'month', 'day']}
          value={value}
          onChange={(newValue) => {
            setValue(newValue);
          }}
          renderInput={(params) => <TextField {...params} />}
        />
    </LocalizationProvider>
  );
}
</code>```

I tried creating a function that would add a Dayjs Date Picker to my webpage. I expected for the day picker to appear once I add the function. Instead, when I added it, the whole page went blank and the browser consoler gave me an error message: Uncaught TypeError: number 0 is not iterable

Body:
I copied the Dayjs date picker component from the MUI website (https://mui.com/x/react-date-pickers/date-picker/). However, this const seems to not work. It makes my whole page go blank.My console doesn't give me an error but I just reviewed the browser console and it gave me this error: Uncaught TypeError: number 0 is not iterable. This error is in the line where the const is defined.

const [value, setValue] = React.useState<Dayjs | null>(dayjs('2022-04-07'));

I have imported everything necessary and when I change the const, the webpage works and the date picker shows up, you just can't pick a date.

Any ideas what I'm doing wrong?

Here is the entire function:

export function StartDatePicker() {
  const [value, setValue] = React.useState<Dayjs | null>(dayjs('2022-04-07'));

  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>

        <DatePicker
          label="Date"
          openTo="year"
          views={['year', 'month', 'day']}
          value={value}
          onChange={(newValue) => {
            setValue(newValue);
          }}
          renderInput={(params) => <TextField {...params} />}
        />
    </LocalizationProvider>
  );
}

I tried creating a function that would add a Dayjs Date Picker to my webpage. I expected for the day picker to appear once I add the function. Instead, when I added it, the whole page went blank and the browser consoler gave me an error message: Uncaught TypeError: number 0 is not iterable


来源: stackexchange

问:
socket.io process reference value
How do I get the last value of the link from socket.io?

Example:

```<code>http://localhost:3000/dashboard/admin3
</code>```

I need /admin3  and a full referer arrives to me.

How can I only get the last value? I want to process it on client side.

Currently I just emit the last value. Is this the best solution?

ContentLicense: CC BY-SA 4.0

Title: socket.io process reference value

Body:
How do I get the last value of the link from socket.io?

Example:

http://localhost:3000/dashboard/admin3

I need /admin3  and a full referer arrives to me.

How can I only get the last value? I want to process it on client side.

Currently I just emit the last value. Is this the best solution?


问:
TemporalDate is missing 1 day even though the first day of the month is selected Flutter Aws
I am using flutter for developing a new application. I will not talk about backend much because the only backend problem is for my field i use temporalDate this model is created by amplify.
In frontend I have a creation form and when i update the value I am copying a Objective model.

This is my update function:

```<code>bool _isSaving = false;

Future<void> update(Objective model) async {
  if (!formKey.currentState!.validate()) {
    AppUtils.showSnackBar(
      context,
      text: 'Please check the form',
      type: SnackBarType.error,
    );

    return;
  }

  if (_isSaving) {
    AppUtils.showSnackBar(
      context,
      text: 'Save in progress, please wait',
      type: SnackBarType.error,
    );

    return;
  }

  final Objective model = model.copyWith(
    title: goalProvider.title,
    startDate: TemporalDate(modelProvider.startDate),
    periodInMonths: modelProvider.periodInMonths,
    salaryGross: modelProvider.salary,
    depositionGross: modelProvider.monthlyDepositionAmount,
  );
  print("Original model first: ${modelProvider.startDate}");
  debugPrint(model.toString());

  _isSaving = true;
  try {
    await ref
        .read(draftEditControllerProvider.notifier)
        .update(model);
    AppUtils.showSnackBar(context, text: 'Saved');
    context.go('/goals');
  } catch (error) {
    AppUtils.showSnackBar(
      context,
      text: 'Error while saving: $error',
      type: SnackBarType.error,
    );
  } finally {
    _isSaving = false;
  }
}
</code>```

‘‘‘

As you see I put two print
First is  print("Original model first: ${modelProvider.startDate}");
and this is showing me what user enter(so correct date and always first day of the month)

Original goal first: 2024-01-01 00:00:00.000

debugPrint(model.toString()); objectiveStartDate=2023-12-31 But here is a problem somehow value is changing with TemporalDate

```<code>Objective {(...other values)objectiveStartDate=2023-12-31(..other values)}
</code>```

Objective model is

```<code>  TemporalDate get startDate {
    try {
      return _startDate!;
    } catch(e) {
      throw new AmplifyCodeGenModelException(
          AmplifyExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage,
          recoverySuggestion:
            AmplifyExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion,
          underlyingException: e.toString()
          );
    }
  }
</code>```

As you see TemporalDate changing my input as one day before.

Could you please help me?

Body:
I am using flutter for developing a new application. I will not talk about backend much because the only backend problem is for my field i use temporalDate this model is created by amplify.
In frontend I have a creation form and when i update the value I am copying a Objective model.

This is my update function:

bool _isSaving = false;

Future<void> update(Objective model) async {
  if (!formKey.currentState!.validate()) {
    AppUtils.showSnackBar(
      context,
      text: 'Please check the form',
      type: SnackBarType.error,
    );

    return;
  }

  if (_isSaving) {
    AppUtils.showSnackBar(
      context,
      text: 'Save in progress, please wait',
      type: SnackBarType.error,
    );

    return;
  }

  final Objective model = model.copyWith(
    title: goalProvider.title,
    startDate: TemporalDate(modelProvider.startDate),
    periodInMonths: modelProvider.periodInMonths,
    salaryGross: modelProvider.salary,
    depositionGross: modelProvider.monthlyDepositionAmount,
  );
  print("Original model first: ${modelProvider.startDate}");
  debugPrint(model.toString());

  _isSaving = true;
  try {
    await ref
        .read(draftEditControllerProvider.notifier)
        .update(model);
    AppUtils.showSnackBar(context, text: 'Saved');
    context.go('/goals');
  } catch (error) {
    AppUtils.showSnackBar(
      context,
      text: 'Error while saving: $error',
      type: SnackBarType.error,
    );
  } finally {
    _isSaving = false;
  }
}

‘‘‘

As you see I put two print
First is  print("Original model first: ${modelProvider.startDate}");
and this is showing me what user enter(so correct date and always first day of the month)

Original goal first: 2024-01-01 00:00:00.000

debugPrint(model.toString()); objectiveStartDate=2023-12-31 But here is a problem somehow value is changing with TemporalDate

Objective {(...other values)objectiveStartDate=2023-12-31(..other values)}

Objective model is

  TemporalDate get startDate {
    try {
      return _startDate!;
    } catch(e) {
      throw new AmplifyCodeGenModelException(
          AmplifyExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage,
          recoverySuggestion:
            AmplifyExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion,
          underlyingException: e.toString()
          );
    }
  }

As you see TemporalDate changing my input as one day before.

Could you please help me?


问:
Using aws cli list-services command in shell script results in unexpected behavior
This is the code I have

# filename: script.sh
cluster="some_cluster_name"

aws_cli_response=$(aws ecs list-services --cluster $cluster_name --output text)
echo $aws_cli_response
echo "${aws_cli_response}"
```
<p>The resulting output of <code>sh script.sh</code> is</p>
```SERVICEARNS <arn1> SERVICEARNS <arn2> SERVICEARNS <arn3> ...
SERVICEARNS <arn1>
SERVICEARNS <arn2>
SERVICEARNS <arn3>
...
```
<p>I didn't expect <code>"${aws_cli_response}"</code> to somehow make the one line string into a well structured line by line result. I thought it would require some sort of looping logic to create this line by line result. But I was surprised by getting this result.</p>
<p>So to investigate how this result could have happened I've created a simple script that looks like this:</p>
<pre class="lang-bash prettyprint-override"><code>text="SERVICEARNS text1 SERVICEARNS text2"

echo $text
echo "${text}"
</code>```

But to my surprise I got this result that I would previously have anticipated had I not seen the first script's outcome:

SERVICEARNS text1 SERVICEARNS text2
SERVICEARNS text1 SERVICEARNS text2
```

Could anyone explain why the first that simply echos a string variable which is just a bunch of single line text result in this clean looking string result?

Thanks in advance. Happy coding everyone.

Body:
This is the code I have

# filename: script.sh
cluster="some_cluster_name"

aws_cli_response=$(aws ecs list-services --cluster $cluster_name --output text)
echo $aws_cli_response
echo "${aws_cli_response}"

The resulting output of sh script.sh is

SERVICEARNS <arn1> SERVICEARNS <arn2> SERVICEARNS <arn3> ...
SERVICEARNS <arn1>
SERVICEARNS <arn2>
SERVICEARNS <arn3>
...

I didn't expect "${aws_cli_response}" to somehow make the one line string into a well structured line by line result. I thought it would require some sort of looping logic to create this line by line result. But I was surprised by getting this result.

So to investigate how this result could have happened I've created a simple script that looks like this:

text="SERVICEARNS text1 SERVICEARNS text2"

echo $text
echo "${text}"

But to my surprise I got this result that I would previously have anticipated had I not seen the first script's outcome:

SERVICEARNS text1 SERVICEARNS text2
SERVICEARNS text1 SERVICEARNS text2

Could anyone explain why the first that simply echos a string variable which is just a bunch of single line text result in this clean looking string result?

Thanks in advance. Happy coding everyone.


问:
Illegal url for new iframe when pushed from a windows machine
I am using the google sign in button for my firebase project which works as intended when it is pushed from a mac.

However when pushed from a windows machine I received the following error when I hit the google sign in button:

```<code>2.b95cb065.chunk.js:2 Uncaught Error: Illegal url for new iframe - https://***.firebaseapp.com%0D/__/auth/iframe?apiKey=***%0D&appName=%5BDEFAULT%5D-firebaseui-temp&v=8.2.5&fw=FirebaseUI-web&usegapi=1&jsh=m%3B%2F_%2Fscs%2Fabc-static%2F_%2Fjs%2Fk%3Dgapi.lb.en.ydLROSGdlBE.O%2Fd%3D1%2Frs%3DAHpOoo_OUY4V-VcsLuRVnUuYVO758FydkA%2Fm%3D__features__#id=I0_1671205169815&_gfid=I0_1671205169815&parent=https%3A%2F%2F***.firebaseapp.com&pfname=&rpctoken=40576440
    at _.Vk (cb=gapi.loaded_0?le=scs:148:96)
    at yl (cb=gapi.loaded_0?le=scs:158:18)
    at _.zl (cb=gapi.loaded_0?le=scs:159:26)
    at _.Gl (cb=gapi.loaded_0?le=scs:165:147)
    at _.Wm.openChild (cb=gapi.loaded_0?le=scs:268:378)
    at _.Wm.open (cb=gapi.loaded_0?le=scs:273:12)
    at 2.b95cb065.chunk.js:2:921890
    at new Et (2.b95cb065.chunk.js:2:849923)
    at 2.b95cb065.chunk.js:2:921836
    at Dt.i.a.i.g (2.b95cb065.chunk.js:2:851228)
</code>```

This is how I initalize firebase:

```<code>const firebaseConfig = {

  apiKey: process.env.REACT_APP_FIREBASE_APIKEY,
  authDomain: process.env.REACT_APP_FIREBASE_AUTHDOMAIN,
  projectId: process.env.REACT_APP_FIREBASE_PROJECTID,
  storageBucket: process.env.REACT_APP_FIREBASE_STORAGEBUCKET,
  messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGINGSENDERID,
  appId: process.env.REACT_APP_FIREBASE_APPID,
};

if (process.env.NODE_ENV === "development") {
  console.log(firebaseConfig);
}

export const app = firebase.initializeApp(firebaseConfig);

(async () => {
  await firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION);
})();

export default firebase;
</code>```

And this is how the environmental variables are defined:

```<code>REACT_APP_FIREBASE_APIKEY=***
REACT_APP_FIREBASE_AUTHDOMAIN=***.firebaseapp.com
REACT_APP_FIREBASE_DATABASEURL=
REACT_APP_FIREBASE_PROJECTID=***
REACT_APP_FIREBASE_STORAGEBUCKET=***.appspot.com
REACT_APP_FIREBASE_MESSAGINGSENDERID=***
REACT_APP_FIREBASE_APPID=***
REACT_APP_ENV=development
</code>```

The url is not in quotes and there are no commas in it and it also does not start with https://

Body:
I am using the google sign in button for my firebase project which works as intended when it is pushed from a mac.

However when pushed from a windows machine I received the following error when I hit the google sign in button:

2.b95cb065.chunk.js:2 Uncaught Error: Illegal url for new iframe - https://***.firebaseapp.com%0D/__/auth/iframe?apiKey=***%0D&appName=%5BDEFAULT%5D-firebaseui-temp&v=8.2.5&fw=FirebaseUI-web&usegapi=1&jsh=m%3B%2F_%2Fscs%2Fabc-static%2F_%2Fjs%2Fk%3Dgapi.lb.en.ydLROSGdlBE.O%2Fd%3D1%2Frs%3DAHpOoo_OUY4V-VcsLuRVnUuYVO758FydkA%2Fm%3D__features__#id=I0_1671205169815&_gfid=I0_1671205169815&parent=https%3A%2F%2F***.firebaseapp.com&pfname=&rpctoken=40576440
    at _.Vk (cb=gapi.loaded_0?le=scs:148:96)
    at yl (cb=gapi.loaded_0?le=scs:158:18)
    at _.zl (cb=gapi.loaded_0?le=scs:159:26)
    at _.Gl (cb=gapi.loaded_0?le=scs:165:147)
    at _.Wm.openChild (cb=gapi.loaded_0?le=scs:268:378)
    at _.Wm.open (cb=gapi.loaded_0?le=scs:273:12)
    at 2.b95cb065.chunk.js:2:921890
    at new Et (2.b95cb065.chunk.js:2:849923)
    at 2.b95cb065.chunk.js:2:921836
    at Dt.i.a.i.g (2.b95cb065.chunk.js:2:851228)

This is how I initalize firebase:

const firebaseConfig = {

  apiKey: process.env.REACT_APP_FIREBASE_APIKEY,
  authDomain: process.env.REACT_APP_FIREBASE_AUTHDOMAIN,
  projectId: process.env.REACT_APP_FIREBASE_PROJECTID,
  storageBucket: process.env.REACT_APP_FIREBASE_STORAGEBUCKET,
  messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGINGSENDERID,
  appId: process.env.REACT_APP_FIREBASE_APPID,
};

if (process.env.NODE_ENV === "development") {
  console.log(firebaseConfig);
}

export const app = firebase.initializeApp(firebaseConfig);

(async () => {
  await firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION);
})();

export default firebase;

And this is how the environmental variables are defined:

REACT_APP_FIREBASE_APIKEY=***
REACT_APP_FIREBASE_AUTHDOMAIN=***.firebaseapp.com
REACT_APP_FIREBASE_DATABASEURL=
REACT_APP_FIREBASE_PROJECTID=***
REACT_APP_FIREBASE_STORAGEBUCKET=***.appspot.com
REACT_APP_FIREBASE_MESSAGINGSENDERID=***
REACT_APP_FIREBASE_APPID=***
REACT_APP_ENV=development

The url is not in quotes and there are no commas in it and it also does not start with https://


问:
Should Kotlin's suspend function be allowed for valid CDI Producers / Beans
According to Jakarta's CDI 2.0 (and 4.0 as well) spec:
https://jakarta.ee/specifications/cdi/2.0/cdi-spec-2.0.html#producer_method

If a producer method return type contains a wildcard type parameter or
is an array type whose component type contains a wildcard type
parameter, the container automatically detects the problem and treats
it as a definition error.

CDI spec is not precise enough. I'm not certain if it refers to a class definition or generated bytecode (for JVM languages). That may impact Kotlin's suspend functions.

Kotlin's compiler transforms suspend function into continuation passing style (CPS). It analyzes the context in which coroutine is going to be executed and do a transformation into a state machine with local variables representing a coroutine's state.
It adds Continuation and wildcard result (Any?) because Kotlin does not support union types.

Then depending on various factor the same Continuation object (related to function invocation) can be passed from one suspended function to another if they are bounded within the same state machine.

My understanding is that Continuation is instantiated when the suspend function is called for the first time at runtime. Whenever we call the same function from different contexts we create different Continuation instances.

I was exploring different frameworks and created several projects in Kotlin/Arrow and Spring, Quarkus, Micronaut where I define my hexagonal ports as type aliases:

```<code>typealias AssignKeyboard = suspend (String) -> Either<KeyboardError, Unit>
typealias AssignMouse = suspend (String) -> Either<MouseError, Unit>
</code>```

Those are producers / beans definitions:

```<code>@ApplicationScoped // or @Bean // or @Singleton
// @Named(BeanName.ASSIGN_KEYBOARD)
fun assignLocalKeyboardBean(shellAdapter: ShellAdapter): AssignKeyboard = // code

@ApplicationScoped // or @Bean // or @Singleton
// @Named(BeanName.ASSIGN_MOUSE)
fun assignLocalMouseBean(shellAdapter: ShellAdapter): AssignMouse = // code
</code>```

And an injection point:

```<code>class KeyboardController(
// @Inject
// @Named(BeanName.ASSIGN_KEYBOARD)
   private val assignKeyboard: AssignKeyboard,
) {
// code
}
</code>```

Spring supports suspend functions for producers and I didn't have to specify a qualifier to inject it.
Quarkus was able to create producers from suspend function (recently they blocked it) and inject it with help of Qualifier.

This is an example how Quarkus represents:

```<code>kotlin.jvm.functions.Function2<String, ? super kotlin.coroutines.Continuation<? super arrow.core.Either<? extends rg.KeyboardError, ? extends kotlin.Unit>>, ?>
</code>```

Micronout detects a wildcard without @Named qualifier.

The question how CDI should look like for suspend functions? Can we apply to them? Should smart analyzer be introduced? Continuation depends on an injection context, so maybe they should be skipped in analysis together with result.

More details can be found here:
https://kotlinlang.org/spec/asynchronous-programming-with-coroutines.html#asynchronous-programming-with-coroutines

Update

A full source code can be found here:

https://github.com/gonciarz/cdi-quarkus

https://github.com/gonciarz/cdi-spring

https://github.com/gonciarz/cdi-micronaut

Body:
According to Jakarta's CDI 2.0 (and 4.0 as well) spec:
https://jakarta.ee/specifications/cdi/2.0/cdi-spec-2.0.html#producer_method

If a producer method return type contains a wildcard type parameter or
is an array type whose component type contains a wildcard type
parameter, the container automatically detects the problem and treats
it as a definition error.

CDI spec is not precise enough. I'm not certain if it refers to a class definition or generated bytecode (for JVM languages). That may impact Kotlin's suspend functions.

Kotlin's compiler transforms suspend function into continuation passing style (CPS). It analyzes the context in which coroutine is going to be executed and do a transformation into a state machine with local variables representing a coroutine's state.
It adds Continuation and wildcard result (Any?) because Kotlin does not support union types.

Then depending on various factor the same Continuation object (related to function invocation) can be passed from one suspended function to another if they are bounded within the same state machine.

My understanding is that Continuation is instantiated when the suspend function is called for the first time at runtime. Whenever we call the same function from different contexts we create different Continuation instances.

I was exploring different frameworks and created several projects in Kotlin/Arrow and Spring, Quarkus, Micronaut where I define my hexagonal ports as type aliases:

typealias AssignKeyboard = suspend (String) -> Either<KeyboardError, Unit>
typealias AssignMouse = suspend (String) -> Either<MouseError, Unit>

Those are producers / beans definitions:

@ApplicationScoped // or @Bean // or @Singleton
// @Named(BeanName.ASSIGN_KEYBOARD)
fun assignLocalKeyboardBean(shellAdapter: ShellAdapter): AssignKeyboard = // code

@ApplicationScoped // or @Bean // or @Singleton
// @Named(BeanName.ASSIGN_MOUSE)
fun assignLocalMouseBean(shellAdapter: ShellAdapter): AssignMouse = // code

And an injection point:

class KeyboardController(
// @Inject
// @Named(BeanName.ASSIGN_KEYBOARD)
   private val assignKeyboard: AssignKeyboard,
) {
// code
}

Spring supports suspend functions for producers and I didn't have to specify a qualifier to inject it.
Quarkus was able to create producers from suspend function (recently they blocked it) and inject it with help of Qualifier.

This is an example how Quarkus represents:

kotlin.jvm.functions.Function2<String, ? super kotlin.coroutines.Continuation<? super arrow.core.Either<? extends rg.KeyboardError, ? extends kotlin.Unit>>, ?>

Micronout detects a wildcard without @Named qualifier.

The question how CDI should look like for suspend functions? Can we apply to them? Should smart analyzer be introduced? Continuation depends on an injection context, so maybe they should be skipped in analysis together with result.

More details can be found here:
https://kotlinlang.org/spec/asynchronous-programming-with-coroutines.html#asynchronous-programming-with-coroutines

Update

A full source code can be found here:

https://github.com/gonciarz/cdi-quarkus

https://github.com/gonciarz/cdi-spring

https://github.com/gonciarz/cdi-micronaut


问:
Count the number of hours if within a certain range in Excel, but count only if a certain criteria is met
#1I am trying to use Excel to determine coverage during certain hours that our stores are open (approx. 200 stores).

I have counted the number of hours that fall into a certain range using this: =IF(F29<$M$8,0,IF(D29>$N$8,0,IF(D29<$M$8,IF(F29>$N$8,$N$8-$M$8,F29-M$8),IF(F29>$N$8,$N$8-D29,F29-D29))))*24

...however, now I would like to take the result from that sheet and have it populate another sheet if the store number matches, i.e. if A12 = 10/31/2022 and M12 = 005, plug the number from K12 on picture #1 into the appropriate spot in my other spreadsheet.

Ideally, I'd also like to break it out hour by hour, to have it return a 1 if the range includes 6a - 6:59a, then a 1 if it includes 7a - 7:59a, etc. But for now, my spreadsheet totals the number of hours in the range.

Any ideas on the best way to do this? I'm sure there's more than one way. I've worked with nesting formulas but I'm having a devil of a time getting this to return properly.

TIA!

I've tried a couple different COUNTIFS formulas, but they were unable to calculate

Also tried this: =IF(AND('0-ST Punch Audit TEST.xlsx'!$A$12:$A$992=C9,'0-ST Punch Audit TEST.xlsx'!$M$12:$M$992=16),'0-ST Punch Audit TEST.xlsx'!K12,0)


问:
Stanford Stanza NLP to networkx: superimpose NER entities onto graph of words
Here is a sample program which will take a text (example is in italian but Stanza supports many languages) and builds and displays a graph of the words (only certain Parts of Speech) and their syntactic relationships:

```<code>"""
Sample program to analyze a phrase with Stanfords STANZA and
build a networkx graph selecting certain token types
"""
import stanza
import networkx as nx
import matplotlib.pyplot as plt

IN_TXT = "All'ippica disse nel 1999 Ignazio Larussa. Poi a Taranto svenne!"
LANG = "it"
ALLOWED_POS = ["NOUN", "PROPN", "VERB"]
NXDOPTS = {
    "node_color": "orange",
    "edge_color": "powderblue",
    "node_size": 400,
    "width": 2,
}

# download appropriate language model
stanza.download(LANG, verbose=False)
nlp = stanza.Pipeline(
    LANG,
    processors="tokenize, pos, lemma, mwt, ner, depparse",
    verbose=False,
    use_gpu=False,
)
# generate a STANZA document from the given text via the pipeline
doc = nlp(IN_TXT)

for sentence in doc.sentences:
    # initialize G as MultiDiGraph for every sentence
    G = nx.DiGraph()
    # fill the graph with the relevant data
    G.add_node(0, id=0, text="ROOT", lemma="ROOT", upos="ROOT")  # fictitious ROOT node
    for word in [w for w in sentence.words if w.pos in ALLOWED_POS]:
        wordict = word.to_dict()
        G.add_node(wordict["id"], **wordict)
        G.add_edge(wordict["id"], wordict["head"], label=wordict["deprel"])
    # compute graph drawing parameters
    pos = nx.spring_layout(G)
    nodelabels = nx.get_node_attributes(G, "text")
    edgelabels = nx.get_edge_attributes(G, "label")
    # and now display the graphs
    nx.draw(G, pos, with_labels=True, labels=nodelabels, **NXDOPTS)
    nx.draw_networkx_edge_labels(G, pos, edge_labels=edgelabels)
    plt.margins(0.2)
    plt.suptitle(sentence.text)
    plt.show()
    # clear the graph to repeat for another sentence
    G.clear()
</code>```

and here is the resulting graph:

The NLP pipeline also performs a NER on the same text and here are the two recognized name entities (a person and a place:

```<code>[{
  "text": "Ignazio Larussa",
  "type": "PER",
  "start_char": 26,
  "end_char": 41
}, {
  "text": "Taranto",
  "type": "LOC",
  "start_char": 49,
  "end_char": 56
}]
</code>```

I would like to be able to map these two on the graph above.

In Taranto's case where the NER span equals the word span, I guess I just need to map the NER span onto the right word start and end chars.

In "Ignazio Larussa"'s case things are more tricky, since the NER span encompasses TWO words. So in this case I want to show only ONE node with the NER span "Ignazio Larussa" connected via the nsubj edge to the "disse" verb.

How would you handle networkx G graph to achieve this? Thanks a lot

Body:
Here is a sample program which will take a text (example is in italian but Stanza supports many languages) and builds and displays a graph of the words (only certain Parts of Speech) and their syntactic relationships:

"""
Sample program to analyze a phrase with Stanfords STANZA and
build a networkx graph selecting certain token types
"""
import stanza
import networkx as nx
import matplotlib.pyplot as plt

IN_TXT = "All'ippica disse nel 1999 Ignazio Larussa. Poi a Taranto svenne!"
LANG = "it"
ALLOWED_POS = ["NOUN", "PROPN", "VERB"]
NXDOPTS = {
    "node_color": "orange",
    "edge_color": "powderblue",
    "node_size": 400,
    "width": 2,
}

# download appropriate language model
stanza.download(LANG, verbose=False)
nlp = stanza.Pipeline(
    LANG,
    processors="tokenize, pos, lemma, mwt, ner, depparse",
    verbose=False,
    use_gpu=False,
)
# generate a STANZA document from the given text via the pipeline
doc = nlp(IN_TXT)

for sentence in doc.sentences:
    # initialize G as MultiDiGraph for every sentence
    G = nx.DiGraph()
    # fill the graph with the relevant data
    G.add_node(0, id=0, text="ROOT", lemma="ROOT", upos="ROOT")  # fictitious ROOT node
    for word in [w for w in sentence.words if w.pos in ALLOWED_POS]:
        wordict = word.to_dict()
        G.add_node(wordict["id"], **wordict)
        G.add_edge(wordict["id"], wordict["head"], label=wordict["deprel"])
    # compute graph drawing parameters
    pos = nx.spring_layout(G)
    nodelabels = nx.get_node_attributes(G, "text")
    edgelabels = nx.get_edge_attributes(G, "label")
    # and now display the graphs
    nx.draw(G, pos, with_labels=True, labels=nodelabels, **NXDOPTS)
    nx.draw_networkx_edge_labels(G, pos, edge_labels=edgelabels)
    plt.margins(0.2)
    plt.suptitle(sentence.text)
    plt.show()
    # clear the graph to repeat for another sentence
    G.clear()

and here is the resulting graph:

The NLP pipeline also performs a NER on the same text and here are the two recognized name entities (a person and a place:

[{
  "text": "Ignazio Larussa",
  "type": "PER",
  "start_char": 26,
  "end_char": 41
}, {
  "text": "Taranto",
  "type": "LOC",
  "start_char": 49,
  "end_char": 56
}]

I would like to be able to map these two on the graph above.

In Taranto's case where the NER span equals the word span, I guess I just need to map the NER span onto the right word start and end chars.

In "Ignazio Larussa"'s case things are more tricky, since the NER span encompasses TWO words. So in this case I want to show only ONE node with the NER span "Ignazio Larussa" connected via the nsubj edge to the "disse" verb.

How would you handle networkx G graph to achieve this? Thanks a lot


问:
ZSH shell script loops MANY times?
So I want to convert these blogposts to PDF using wkhtmltopdf

On MacOS in automator I set up a WorkFlow: GET SPECIFIED TEXT > EXTRACT URLS FROM TEXT > RUN SHELL SCRIPT (shell: /bin/zsh, pass input: as arguments)

```<code>#!/bin/zsh
# url example: "https://www.somewordpressblog.com/2022/12/16/some-post-title/"

i=1
for url in "$@"
do
    title1=${url[(ws:/:)6]}                 # split with delimiter / sixth part
    title2=${(U)title1//-/ }                # replace all hypens with spaces and capitalize
    title3="$i. - "                         # prefix add numbers
    title4=".pdf"                           # suffix add .PDF extension
    title5="${title3}${title2}${title4}"    # join everything

    /usr/local/bin/wkhtmltopdf --disable-javascript --print-media-type $url $title5
    ((i+=1))
done
</code>```

The files got downloaded, but for a test with only 2 URL's there was like 2 minutes waiting and the RESULTS from the Schell Script showed me 84 items!!
I am counting 14 DONES from the wkhtmltopdf output.

What is wrong with this loop? Do I need to implement something to wait for the loop to continue or something? And How?

Any code suggestions welcome as well, first day with ZSH..

Title: ZSH shell script loops MANY times?

Body:
So I want to convert these blogposts to PDF using wkhtmltopdf

On MacOS in automator I set up a WorkFlow: GET SPECIFIED TEXT > EXTRACT URLS FROM TEXT > RUN SHELL SCRIPT (shell: /bin/zsh, pass input: as arguments)

#!/bin/zsh
# url example: "https://www.somewordpressblog.com/2022/12/16/some-post-title/"

i=1
for url in "$@"
do
    title1=${url[(ws:/:)6]}                 # split with delimiter / sixth part
    title2=${(U)title1//-/ }                # replace all hypens with spaces and capitalize
    title3="$i. - "                         # prefix add numbers
    title4=".pdf"                           # suffix add .PDF extension
    title5="${title3}${title2}${title4}"    # join everything

    /usr/local/bin/wkhtmltopdf --disable-javascript --print-media-type $url $title5
    ((i+=1))
done

The files got downloaded, but for a test with only 2 URL's there was like 2 minutes waiting and the RESULTS from the Schell Script showed me 84 items!!
I am counting 14 DONES from the wkhtmltopdf output.

What is wrong with this loop? Do I need to implement something to wait for the loop to continue or something? And How?

Any code suggestions welcome as well, first day with ZSH..


问:
Pygame Chroma Key
There's a lot of files in directory that has background that I need to chroma key, and as said theres a lot of the files
 so it would be hard to do it using hand

is there any way I can add Chroma Key To Pygame?

Title: Pygame Chroma Key


问:
Regex: find character in block of text between quotes which may appear zero or more times
Im trying to create a regex which can help parse a URL path within a CEF syslog message. My parser has trouble with un-escaped "=" within values and a more robust regex would fix it.

```<code>Shortened Sample:

<14>1 2022-12-16T12:07:15+00:00 HOSTNAME CEF:0|Palo Alto Networks|PAN-OS|9.4.1|Suspicious HTTP Evasion Found|THREAT|1|rt=Dec 16 2022 12:07:15 GMT deviceExternalId=000000000 request="browser.events.data.msn.com/OneCollector/1.0?cors=true&content" cs2Label=URL Category cs2=internet-portals

</code>```

The "request" key typically contains the path and it can contain 0 or more "=".

I haven't seen any examples yet, but I think a fair assumption would be that any number of other fields could contain a similar string and the regex should be able to handle it.

GOAL: Identify all "=" inside any value wrapped in quotes

My regex-foo isn't great, I can capture up to 1 "=", but trying to expand any more either breaks captures, or it captures more than required.

```<code>Pattern: \".*(=).*\"
Captures only one instance inside one value, not great if there are more than 1 "=" or more keys which contain quoted strings with "=" inside.

MATCHES (find ** for match):
<14>1 2022-12-16T12:07:15+00:00 HOSTNAME CEF:0|Palo Alto Networks|PAN-OS|9.4.1|Suspicious HTTP Evasion Found|THREAT|1|rt=Dec 16 2022 12:07:15 GMT deviceExternalId=000000000 request="browser.events.data.msn.com/OneCollector/1.0?cors**=**true&content" cs2Label=URL Category cs2=internet-portals

FAILS (find ** for match, note there are 2 "="):
<14>1 2022-12-16T12:07:15+00:00 HOSTNAME CEF:0|Palo Alto Networks|PAN-OS|9.4.1|Suspicious HTTP Evasion Found|THREAT|1|rt=Dec 16 2022 12:07:15 GMT deviceExternalId=000000000 request="browser.events.data.msn.com/OneCollector/1.0?cors=true&content**=**" cs2Label=URL Category cs2=internet-portals

EXPECTED (find ** for match):
<14>1 2022-12-16T12:07:15+00:00 HOSTNAME CEF:0|Palo Alto Networks|PAN-OS|9.4.1|Suspicious HTTP Evasion Found|THREAT|1|rt=Dec 16 2022 12:07:15 GMT deviceExternalId=000000000 request="browser.events.data.msn.com/OneCollector/1.0?cors**=**true&content**=**" cs2Label=URL Category cs2=internet-portals
</code>```

Body:
Im trying to create a regex which can help parse a URL path within a CEF syslog message. My parser has trouble with un-escaped "=" within values and a more robust regex would fix it.

Shortened Sample:

<14>1 2022-12-16T12:07:15+00:00 HOSTNAME CEF:0|Palo Alto Networks|PAN-OS|9.4.1|Suspicious HTTP Evasion Found|THREAT|1|rt=Dec 16 2022 12:07:15 GMT deviceExternalId=000000000 request="browser.events.data.msn.com/OneCollector/1.0?cors=true&content" cs2Label=URL Category cs2=internet-portals

The "request" key typically contains the path and it can contain 0 or more "=".

I haven't seen any examples yet, but I think a fair assumption would be that any number of other fields could contain a similar string and the regex should be able to handle it.

GOAL: Identify all "=" inside any value wrapped in quotes

My regex-foo isn't great, I can capture up to 1 "=", but trying to expand any more either breaks captures, or it captures more than required.

Pattern: \".*(=).*\"
Captures only one instance inside one value, not great if there are more than 1 "=" or more keys which contain quoted strings with "=" inside.

MATCHES (find ** for match):
<14>1 2022-12-16T12:07:15+00:00 HOSTNAME CEF:0|Palo Alto Networks|PAN-OS|9.4.1|Suspicious HTTP Evasion Found|THREAT|1|rt=Dec 16 2022 12:07:15 GMT deviceExternalId=000000000 request="browser.events.data.msn.com/OneCollector/1.0?cors**=**true&content" cs2Label=URL Category cs2=internet-portals

FAILS (find ** for match, note there are 2 "="):
<14>1 2022-12-16T12:07:15+00:00 HOSTNAME CEF:0|Palo Alto Networks|PAN-OS|9.4.1|Suspicious HTTP Evasion Found|THREAT|1|rt=Dec 16 2022 12:07:15 GMT deviceExternalId=000000000 request="browser.events.data.msn.com/OneCollector/1.0?cors=true&content**=**" cs2Label=URL Category cs2=internet-portals

EXPECTED (find ** for match):
<14>1 2022-12-16T12:07:15+00:00 HOSTNAME CEF:0|Palo Alto Networks|PAN-OS|9.4.1|Suspicious HTTP Evasion Found|THREAT|1|rt=Dec 16 2022 12:07:15 GMT deviceExternalId=000000000 request="browser.events.data.msn.com/OneCollector/1.0?cors**=**true&content**=**" cs2Label=URL Category cs2=internet-portals


问:
Getting the position of the mouse or gesture during a Drag and Drop in .Net MAUI
Is it possible to get the position of the mouse or the finger during a Drag and Drop, using .Net MAUI?

Using the GestureRecognizers, I can use the DropGestureRecognizer to receive the DragOver event or the Drop event inside a view/control.  But I cannot find any way to get the position of the mouse or the finger during those events!

PointerGestureRecognizer are not fired during a Drag and Drop process.

I need this information to allow a Drop only in a small region of my GraphicsView.

I would expect the DragEventArgs to have a GetPosition method!


问:
Merge 2 SELECT statements into one
I am fairly new to SQL and I have wrote 2 different select statements to query my database and I was wondering how I would go about merging them into one SELECT query as they look fairly identical and I'm sure it can be done i'm just scratching my head at the moment and haven't been able to come up with the solution

These are my 2 select statements:

```<code>select part.Id, part.Name, part.Quantity,
        part.Cost AS "Individual Part Cost",
        Quantity * Cost AS"Total Part Cost"
from part, repair
where repair.Id = part.RepairId
and monthname(repair.Date) = "December";
</code>```
```<code>select SUM(Cost) AS "Total Month Cost", avg(Cost) AS "Average Month Cost"
from part, repair
where repair.Id = part.RepairId
and monthname(repair.Date) = "September"
</code>```

Title: Merge 2 SELECT statements into one

Body:
I am fairly new to SQL and I have wrote 2 different select statements to query my database and I was wondering how I would go about merging them into one SELECT query as they look fairly identical and I'm sure it can be done i'm just scratching my head at the moment and haven't been able to come up with the solution

These are my 2 select statements:

select part.Id, part.Name, part.Quantity,
        part.Cost AS "Individual Part Cost",
        Quantity * Cost AS"Total Part Cost"
from part, repair
where repair.Id = part.RepairId
and monthname(repair.Date) = "December";

select SUM(Cost) AS "Total Month Cost", avg(Cost) AS "Average Month Cost"
from part, repair
where repair.Id = part.RepairId
and monthname(repair.Date) = "September"


问:
How to run Cypress Parallelization on the Bitbucket?
How to run Cypress Parallelization on the Bitbucket ?
I have such bitbucket-pipelines.yml

```<code>e2e: &e2e
  name: E2E tests
  caches:
    - node
    - cypress
  script:
    - npm install
    - npm run start:ci
  artifacts:
    # store any generates images and videos as artifacts
    - cypress/videos/**/*.mp4
    - cypress/screenshots/**/*.png

pipelines:
  default:
    - step:
        name: 'E2E tests'
        caches:
          - npm
          - cypress
          - node
        script:
          - npm install
        artifacts:
          - build/**
    - parallel:
      # run N steps in parallel
      - step:
          <<: *e2e
      - step:
          <<: *e2e
      - step:
          <<: *e2e

</code>```

package.json file:

```<code>{
  "name": "profile",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "cypress open",
    "start:ci": "cypress run --record --parallel --ci-build-id $BITBUCKET_BUILD_NUMBER --key $CYPRESS_RECORD_KEY --record"
  },
</code>```

cypress.config.js

```<code>module.exports = defineConfig({
  viewportWidth: 1920,
  viewportHeight: 1080,
  defaultCommandTimeout: 6000,
  hideXHRInCommandLog: true,
  retries: 1,
  e2e: {
    // We've imported your old cypress plugins here.
    // You may want to clean this up later by importing these.
    setupNodeEvents(on, config) {
      return require('./cypress/plugins/index.js')(on, config)
    },
    baseUrl: 'https://frontend.test.novoconnect.org/',
  },
})
</code>```

Screenshot from Bitbucket pipeline:
enter image description here
It runs only one job without Parallelization  tests, as you can see on the screenshot

To fix bitbucket file

Body:
How to run Cypress Parallelization on the Bitbucket ?
I have such bitbucket-pipelines.yml

e2e: &e2e
  name: E2E tests
  caches:
    - node
    - cypress
  script:
    - npm install
    - npm run start:ci
  artifacts:
    # store any generates images and videos as artifacts
    - cypress/videos/**/*.mp4
    - cypress/screenshots/**/*.png

pipelines:
  default:
    - step:
        name: 'E2E tests'
        caches:
          - npm
          - cypress
          - node
        script:
          - npm install
        artifacts:
          - build/**
    - parallel:
      # run N steps in parallel
      - step:
          <<: *e2e
      - step:
          <<: *e2e
      - step:
          <<: *e2e

package.json file:

{
  "name": "profile",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "cypress open",
    "start:ci": "cypress run --record --parallel --ci-build-id $BITBUCKET_BUILD_NUMBER --key $CYPRESS_RECORD_KEY --record"
  },

cypress.config.js

module.exports = defineConfig({
  viewportWidth: 1920,
  viewportHeight: 1080,
  defaultCommandTimeout: 6000,
  hideXHRInCommandLog: true,
  retries: 1,
  e2e: {
    // We've imported your old cypress plugins here.
    // You may want to clean this up later by importing these.
    setupNodeEvents(on, config) {
      return require('./cypress/plugins/index.js')(on, config)
    },
    baseUrl: 'https://frontend.test.novoconnect.org/',
  },
})

Screenshot from Bitbucket pipeline:
enter image description here
It runs only one job without Parallelization  tests, as you can see on the screenshot

To fix bitbucket file


问:
Play a voice message while ringing Twilio Incoming Calls Using TwiMl
<?xml version="1.0" encoding="UTF-8"?> <Response> <Say>Hello Test!</Say> <Connect action="https://handler.twilio.com/twiml/EH435a2e43f695b8a362222222222222">      <Conversation serviceInstanceSid="IS22222222c2" inboundTimeout="50" record="record-from-answer"/> </Connect> </Response>
I added the above TwiMl with record and voicemail feature.
I need to modify this to match my following requirement.
When a call comes to Twilio number I need to play voice.Not like above "Hello Test!"
It should play during call ringing. The caller should listen to my customer voice until the worker or agent answers before the inboundTimeout.
This is related to incoming calls. Not related with

``

```<code><?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Say>Hello Test!</Say>
    <Connect action="https://handler.twilio.com/twiml/EH435a2e43f695b8a362222222222222">
        <Conversation serviceInstanceSid="IS22222222c2" inboundTimeout="50" record="record-from-answer"/>
    </Connect>
</Response>
</code>```

``

Body:
<?xml version="1.0" encoding="UTF-8"?> <Response> <Say>Hello Test!</Say> <Connect action="https://handler.twilio.com/twiml/EH435a2e43f695b8a362222222222222">      <Conversation serviceInstanceSid="IS22222222c2" inboundTimeout="50" record="record-from-answer"/> </Connect> </Response>
I added the above TwiMl with record and voicemail feature.
I need to modify this to match my following requirement.
When a call comes to Twilio number I need to play voice.Not like above "Hello Test!"
It should play during call ringing. The caller should listen to my customer voice until the worker or agent answers before the inboundTimeout.
This is related to incoming calls. Not related with

``

<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Say>Hello Test!</Say>
    <Connect action="https://handler.twilio.com/twiml/EH435a2e43f695b8a362222222222222">
        <Conversation serviceInstanceSid="IS22222222c2" inboundTimeout="50" record="record-from-answer"/>
    </Connect>
</Response>

``


问:
react-table : How can i put an updated element in the last page?
I use react-table v7.7.

I do that when I update a cell in my table

```<code>const list = [...data]

var newList = []
list[index][colonne] = value
var listWithoutRemovedElement = list.filter(x => x.id != id )
var removed = list.filter(x => x.id == id )
newList = listWithoutRemovedElement.concat(removed)

setData(newList)
</code>```

When I go to the last page my updated row is not at the end of the table.
I guess it is a pagination issue cause when I do that in a table with just one page I see the updated row.

How can i put an updated row in the last page ?

Body:
I use react-table v7.7.

I do that when I update a cell in my table

const list = [...data]

var newList = []
list[index][colonne] = value
var listWithoutRemovedElement = list.filter(x => x.id != id )
var removed = list.filter(x => x.id == id )
newList = listWithoutRemovedElement.concat(removed)

setData(newList)

When I go to the last page my updated row is not at the end of the table.
I guess it is a pagination issue cause when I do that in a table with just one page I see the updated row.

How can i put an updated row in the last page ?


问:
Slice to Map of pointers duplicates values
This is a beginner question about why I get such a result when trying to obtain a Map from a Slice in go lang. I have this code:

```<code>func (p *ProductsStruct) ToMap() map[int32]*Product {
    result := map[int32]*Product{}

    for _, prod := range p.Products {
        result[prod.ProductId] = &prod
    }

    return result
}
</code>```

ProductsStruct has just a slice of Product and Product struct is as follows

```<code>type ProductsMedusa struct {
    Products []ProductMedusa
}

type Product struct {
    ProductId    int32
    ProductTitle string
    PriceUSD     float32
}
</code>```

I cannot understand why calling the function ToMap() produces a result with all the keys but pointers to same object: the last. Also, I am aware of the fact that if I don't use map values as pointers, it works fine.

Thanks

Body:
This is a beginner question about why I get such a result when trying to obtain a Map from a Slice in go lang. I have this code:

func (p *ProductsStruct) ToMap() map[int32]*Product {
    result := map[int32]*Product{}

    for _, prod := range p.Products {
        result[prod.ProductId] = &prod
    }

    return result
}

ProductsStruct has just a slice of Product and Product struct is as follows

type ProductsMedusa struct {
    Products []ProductMedusa
}

type Product struct {
    ProductId    int32
    ProductTitle string
    PriceUSD     float32
}

I cannot understand why calling the function ToMap() produces a result with all the keys but pointers to same object: the last. Also, I am aware of the fact that if I don't use map values as pointers, it works fine.

Thanks


问:
Puppeteer is not terminating after browser.close() is called
So I got a basic puppeteer script working that does some basic stuff: Which looks like this -

```<code>import puppeteer from "puppeteer-extra";
import RecaptchaPlugin from "puppeteer-extra-plugin-recaptcha";
import { executablePath } from "puppeteer";
import { anonymizeProxy } from "proxy-chain";

async function main() {
  console.log("Starting ...");
  const proxy =
    "http://XXXXXXXXXXXXXXXXXXXXXX";
  const newProxyUrl = await anonymizeProxy(proxy);

  puppeteer.use(
    RecaptchaPlugin({
      provider: {
        id: "2captcha",
        token: "XXXXXXXXXXXXXXXXXX",
      },
    })
  );

  // Puppeteer usage as normal (headless is "false" just for this demo)
  const browser = await puppeteer.launch({
    headless: true,
    executablePath: executablePath(),
    args: [
      "--single-process",
      "--no-zygote",
      "--no-sandbox",
      `--proxy-server=${newProxyUrl}`,
    ],
  });

  try {
    const page = await browser.newPage();
    await page.setDefaultNavigationTimeout(180000);

    await page.goto("http://www.example.com");
    // do more things etc etc

    console.log("Closing the page");
    await page.close();
    console.log("Closed the page");
    await browser.close();
    console.log("Closed the browser");
    await browser.process()?.kill();
    console.log("Force closed the browser");
  } catch (error) {
    console.log(error);
  } finally {
    await browser.close();
  }
}

main();

</code>```

Now I would assume that if I started this as a node file then I would assume the node app to exit out after the console logs - "Force closed the browser" but that does not happen - it keeps running indefinitely in the terminal. Any idea how to fix this? I have already tried all the solutions in this stackoverflow and nothing seems to be helping - Puppeteer doesn't close browser

Body:
So I got a basic puppeteer script working that does some basic stuff: Which looks like this -

import puppeteer from "puppeteer-extra";
import RecaptchaPlugin from "puppeteer-extra-plugin-recaptcha";
import { executablePath } from "puppeteer";
import { anonymizeProxy } from "proxy-chain";

async function main() {
  console.log("Starting ...");
  const proxy =
    "http://XXXXXXXXXXXXXXXXXXXXXX";
  const newProxyUrl = await anonymizeProxy(proxy);

  puppeteer.use(
    RecaptchaPlugin({
      provider: {
        id: "2captcha",
        token: "XXXXXXXXXXXXXXXXXX",
      },
    })
  );

  // Puppeteer usage as normal (headless is "false" just for this demo)
  const browser = await puppeteer.launch({
    headless: true,
    executablePath: executablePath(),
    args: [
      "--single-process",
      "--no-zygote",
      "--no-sandbox",
      `--proxy-server=${newProxyUrl}`,
    ],
  });

  try {
    const page = await browser.newPage();
    await page.setDefaultNavigationTimeout(180000);

    await page.goto("http://www.example.com");
    // do more things etc etc

    console.log("Closing the page");
    await page.close();
    console.log("Closed the page");
    await browser.close();
    console.log("Closed the browser");
    await browser.process()?.kill();
    console.log("Force closed the browser");
  } catch (error) {
    console.log(error);
  } finally {
    await browser.close();
  }
}

main();

Now I would assume that if I started this as a node file then I would assume the node app to exit out after the console logs - "Force closed the browser" but that does not happen - it keeps running indefinitely in the terminal. Any idea how to fix this? I have already tried all the solutions in this stackoverflow and nothing seems to be helping - Puppeteer doesn't close browser


问:
How combine Logon Server and Logon Domain into same field on BGInfo
I am trying to combine the Logon Server and Logon Domain fields on BGInfo so they are on the same line and have a dote to separate them, so Logon Server.Logon Domain. The script I have retrieves the Logon Domain and combines the computer name but I can't find anything to retrieve the Logon Server.

```<code> Set objNetwork = CreateObject("WScript.Network")
 strLogonServer = objNetwork.UserDomain
 strLogonDomain = objNetwork.ComputerName

 Set objShell = CreateObject("WScript.Shell")
 objShell.Popup strLogonServer & "." & strLogonDomain
</code>```

Ive tried changing the Logon Domain string to obj.network.UserServer but that doesn't change it.

I also know that CMD produces the logon server via Echo %logonserver% but not sure how to implement that into the string

EDIT:

Created a solution,

Function ReadFromRegistry(strRegistryKey, strDefault)
Dim WSHShell, value

```<code>On Error Resume Next
Set WSHShell = CreateObject("WScript.Shell")
value = WSHShell.RegRead( strRegistryKey )

If err.number <> 0 Then
    readFromRegistry = strDefault
Else
    readFromRegistry = value
End If

Set WSHShell = Nothing
</code>```

End Function

dim objShell
dim strLoginServer
dim strLoginUser

Set objShell = CreateObject("WScript.Shell")

strLogonServer = ReadFromRegistry("HKEY_CURRENT_USER\Volatile Environment\LOGONSERVER", "error")
strLoginUser = ReadFromRegistry("HKEY_CURRENT_USER\Volatile Environment\USERDOMAIN", "error")

strLogonServer = replace(strLogonServer, "", "")

Echo strLogonServer & "." & strLoginUser

Outputs the LogonServer and LogonDomain from registry as an echo with a dot in the middle.

Body:
I am trying to combine the Logon Server and Logon Domain fields on BGInfo so they are on the same line and have a dote to separate them, so Logon Server.Logon Domain. The script I have retrieves the Logon Domain and combines the computer name but I can't find anything to retrieve the Logon Server.

 Set objNetwork = CreateObject("WScript.Network")
 strLogonServer = objNetwork.UserDomain
 strLogonDomain = objNetwork.ComputerName

 Set objShell = CreateObject("WScript.Shell")
 objShell.Popup strLogonServer & "." & strLogonDomain

Ive tried changing the Logon Domain string to obj.network.UserServer but that doesn't change it.

I also know that CMD produces the logon server via Echo %logonserver% but not sure how to implement that into the string

EDIT:

Created a solution,

Function ReadFromRegistry(strRegistryKey, strDefault)
Dim WSHShell, value

On Error Resume Next
Set WSHShell = CreateObject("WScript.Shell")
value = WSHShell.RegRead( strRegistryKey )

If err.number <> 0 Then
    readFromRegistry = strDefault
Else
    readFromRegistry = value
End If

Set WSHShell = Nothing

End Function

dim objShell
dim strLoginServer
dim strLoginUser

Set objShell = CreateObject("WScript.Shell")

strLogonServer = ReadFromRegistry("HKEY_CURRENT_USER\Volatile Environment\LOGONSERVER", "error")
strLoginUser = ReadFromRegistry("HKEY_CURRENT_USER\Volatile Environment\USERDOMAIN", "error")

strLogonServer = replace(strLogonServer, "", "")

Echo strLogonServer & "." & strLoginUser

Outputs the LogonServer and LogonDomain from registry as an echo with a dot in the middle.


问:
Not receiving the information from FIRESTORE , how to wait for the information to arrive? jetpack compose navigation
I am building an app with nested navigation and a screen that fetch profile of celebrities from firestore I have a problem fetching the data before the screen is already loaded and shown. the await() function doesn't make the program wait for the data.

Every time I go to the celeb screen, I want to fetch the fetch the user collection to get the categories of celebs i am intrested in. fetch the userVote collection so that i wont show a Celeb that is already been voted,
then fetch the Celebs collection and filter out the celebs that i dont want to show.

all happen in

retrieveUserVotes()
retrieveCelebs()

i have mad a simple yet complicated example because i need to show the complexity of the code.

also if you think that the way i wrote the code is bad can you explain to me how could i have been write it better?

i am using the navigation explained by phillip lancker youtube
https://www.youtube.com/watch?v=4gUeyNkGE3g&list=PLQkwcJG4YTCSpJ2NLhDTHhi6XBNfk9WiC&index=18&ab_channel=PhilippLackner

github source code
https://github.com/dolev146/stackoverflowexample

i have also made a demo database

MainActivity.kt

```<code>
data class Celeb(
    var Company: String,
    var FirstName: String,
    var LastName: String,
    val BirthDate: Long,
    var ImgUrl: String,
    val CelebInfo: String,
    val Category: String,
    var RightVotes: Long = 0,
    var LeftVotes: Long = 0
)

val userVotesCollectionRef = Firebase.firestore.collection("userVotes")
val userCollectionRef = Firebase.firestore.collection("users")
val celebCollectionRef = Firebase.firestore.collection("celebs")
val celebListFilterNames = mutableListOf<String>()
var celebListParam = mutableListOf<Celeb>()

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            Navigation()

        }
    }
}

fun retrieveUserVotes()= CoroutineScope(Dispatchers.IO).launch {
    try {
        val auth = FirebaseAuth.getInstance()
        var userEmail = auth.currentUser?.email.toString()
        userEmail = "v@v.com" // for testing purposes only it is user that already exists in the database
        userVotesCollectionRef.whereEqualTo("userEmail" , userEmail).get().addOnSuccessListener {
                documents ->
            for (document in documents) {
                val celebName = document.getString("celebFullName")
                celebListFilterNames.add(celebName.toString())
            }
        }
        println(celebListFilterNames)
    }
    catch (e: Exception) {
        withContext(Dispatchers.Main) {
            Log.d("Error", "Error: ${e.message}")
        }
    }
}

fun retrieveCelebs() = CoroutineScope(Dispatchers.IO).launch {
    val auth = FirebaseAuth.getInstance()
    val user = auth.currentUser?.email.toString()
    val userPref = mutableListOf<String>()
    try {
        val docRef = userCollectionRef.document(user)
        val doc = docRef.get().await()
        for (document in doc.data?.entries!!) {
            if (document.key == "userPref") {
                userPref.addAll(document.value as List<String>)
            }
        }
        println(userPref)
    } catch (e: Exception) {
        Log.e("retrieveCelebs", "Error: ${e.message}")
    }

        try {
            val querySnapshot = celebCollectionRef.get().await()
            for (document in querySnapshot.documents) {
                val celebDocument = document
                val celebCompany = celebDocument.data?.get("company").toString()
                val celebFirstName = celebDocument.data?.get("firstName").toString()
                val celebLastName = celebDocument.data?.get("lastName").toString()
                val fullName = "$celebFirstName $celebLastName"
                if(celebListFilterNames.contains(fullName)){
                    continue
                }
                val celebBirthDate = celebDocument.data?.get("birthDate").toString().toLong()
                val celebImgUrl = celebDocument.data?.get("imgUrl").toString()
                val celebInfo = celebDocument.data?.get("celebInfo").toString()
                val celebCategory = celebDocument.data?.get("category").toString()
                if (!userPref.contains(celebCategory)) {
                    continue
                }
                val celebRightVotes = celebDocument.data?.get("rightVotes").toString().toLong()
                val celebLeftVotes = celebDocument.data?.get("leftVotes").toString().toLong()
                val celebObject = Celeb(
                    Company = celebCompany,
                    FirstName = celebFirstName,
                    LastName = celebLastName,
                    BirthDate = celebBirthDate,
                    ImgUrl = celebImgUrl,
                    CelebInfo = celebInfo,
                    Category = celebCategory,
                    RightVotes = celebRightVotes,
                    LeftVotes = celebLeftVotes
                )
                celebListParam.add(celebObject)
            }
            celebListParam.shuffle()

        } catch (e: Exception) {
            Log.d("error celeb", e.toString())
        }

}
</code>```

Navigation.kt

```<code>package com.example.stackoverflowexample

import androidx.compose.runtime.*
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController

@Composable
fun Navigation() {
    val navController = rememberNavController()
    NavHost(navController = navController, startDestination = Screen.SwipeScreen.route) {

        composable(route = Screen.SwipeScreen.route) {
                celebListFilterNames.clear()
                retrieveUserVotes()
                celebListParam.clear()
                retrieveCelebs()
                SwipeScreen()
            }

    }
}
</code>```

SwipeScreen.kt

```<code>package com.example.stackoverflowexample

import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

@Composable
fun SwipeScreen() {

    if (celebListParam.isEmpty()) {
        Text(
            text = "bad fire base didnt got the data...",
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        )
    } else {
        Text(
            text = "good fire base got the data...",
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        )
    }

}
</code>```

Screen (sealed class)

```<code>package com.example.stackoverflowexample

sealed class Screen(val route: String) {
    object SwipeScreen : Screen("swipe")
}

</code>```

Body:
I am building an app with nested navigation and a screen that fetch profile of celebrities from firestore I have a problem fetching the data before the screen is already loaded and shown. the await() function doesn't make the program wait for the data.

Every time I go to the celeb screen, I want to fetch the fetch the user collection to get the categories of celebs i am intrested in. fetch the userVote collection so that i wont show a Celeb that is already been voted,
then fetch the Celebs collection and filter out the celebs that i dont want to show.

all happen in

retrieveUserVotes()
retrieveCelebs()

i have mad a simple yet complicated example because i need to show the complexity of the code.

also if you think that the way i wrote the code is bad can you explain to me how could i have been write it better?

i am using the navigation explained by phillip lancker youtube
https://www.youtube.com/watch?v=4gUeyNkGE3g&list=PLQkwcJG4YTCSpJ2NLhDTHhi6XBNfk9WiC&index=18&ab_channel=PhilippLackner

github source code
https://github.com/dolev146/stackoverflowexample

i have also made a demo database

MainActivity.kt

data class Celeb(
    var Company: String,
    var FirstName: String,
    var LastName: String,
    val BirthDate: Long,
    var ImgUrl: String,
    val CelebInfo: String,
    val Category: String,
    var RightVotes: Long = 0,
    var LeftVotes: Long = 0
)

val userVotesCollectionRef = Firebase.firestore.collection("userVotes")
val userCollectionRef = Firebase.firestore.collection("users")
val celebCollectionRef = Firebase.firestore.collection("celebs")
val celebListFilterNames = mutableListOf<String>()
var celebListParam = mutableListOf<Celeb>()

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            Navigation()

        }
    }
}

fun retrieveUserVotes()= CoroutineScope(Dispatchers.IO).launch {
    try {
        val auth = FirebaseAuth.getInstance()
        var userEmail = auth.currentUser?.email.toString()
        userEmail = "v@v.com" // for testing purposes only it is user that already exists in the database
        userVotesCollectionRef.whereEqualTo("userEmail" , userEmail).get().addOnSuccessListener {
                documents ->
            for (document in documents) {
                val celebName = document.getString("celebFullName")
                celebListFilterNames.add(celebName.toString())
            }
        }
        println(celebListFilterNames)
    }
    catch (e: Exception) {
        withContext(Dispatchers.Main) {
            Log.d("Error", "Error: ${e.message}")
        }
    }
}

fun retrieveCelebs() = CoroutineScope(Dispatchers.IO).launch {
    val auth = FirebaseAuth.getInstance()
    val user = auth.currentUser?.email.toString()
    val userPref = mutableListOf<String>()
    try {
        val docRef = userCollectionRef.document(user)
        val doc = docRef.get().await()
        for (document in doc.data?.entries!!) {
            if (document.key == "userPref") {
                userPref.addAll(document.value as List<String>)
            }
        }
        println(userPref)
    } catch (e: Exception) {
        Log.e("retrieveCelebs", "Error: ${e.message}")
    }

        try {
            val querySnapshot = celebCollectionRef.get().await()
            for (document in querySnapshot.documents) {
                val celebDocument = document
                val celebCompany = celebDocument.data?.get("company").toString()
                val celebFirstName = celebDocument.data?.get("firstName").toString()
                val celebLastName = celebDocument.data?.get("lastName").toString()
                val fullName = "$celebFirstName $celebLastName"
                if(celebListFilterNames.contains(fullName)){
                    continue
                }
                val celebBirthDate = celebDocument.data?.get("birthDate").toString().toLong()
                val celebImgUrl = celebDocument.data?.get("imgUrl").toString()
                val celebInfo = celebDocument.data?.get("celebInfo").toString()
                val celebCategory = celebDocument.data?.get("category").toString()
                if (!userPref.contains(celebCategory)) {
                    continue
                }
                val celebRightVotes = celebDocument.data?.get("rightVotes").toString().toLong()
                val celebLeftVotes = celebDocument.data?.get("leftVotes").toString().toLong()
                val celebObject = Celeb(
                    Company = celebCompany,
                    FirstName = celebFirstName,
                    LastName = celebLastName,
                    BirthDate = celebBirthDate,
                    ImgUrl = celebImgUrl,
                    CelebInfo = celebInfo,
                    Category = celebCategory,
                    RightVotes = celebRightVotes,
                    LeftVotes = celebLeftVotes
                )
                celebListParam.add(celebObject)
            }
            celebListParam.shuffle()

        } catch (e: Exception) {
            Log.d("error celeb", e.toString())
        }

}

Navigation.kt

package com.example.stackoverflowexample

import androidx.compose.runtime.*
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController

@Composable
fun Navigation() {
    val navController = rememberNavController()
    NavHost(navController = navController, startDestination = Screen.SwipeScreen.route) {

        composable(route = Screen.SwipeScreen.route) {
                celebListFilterNames.clear()
                retrieveUserVotes()
                celebListParam.clear()
                retrieveCelebs()
                SwipeScreen()
            }

    }
}

SwipeScreen.kt

package com.example.stackoverflowexample

import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

@Composable
fun SwipeScreen() {

    if (celebListParam.isEmpty()) {
        Text(
            text = "bad fire base didnt got the data...",
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        )
    } else {
        Text(
            text = "good fire base got the data...",
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        )
    }

}

Screen (sealed class)

package com.example.stackoverflowexample

sealed class Screen(val route: String) {
    object SwipeScreen : Screen("swipe")
}


问:
BabylonJS compute ArcRotateCamera rotation to look at point on sphere
How do I compute the alpha and beta for ArcRotateCamera to look a point on a sphere? My playground has a ray from sphere origin to point on surface. Ultimately, I would like to animate from current point to ray.

const vecToLocal = (vector, mesh) => {
    var m = mesh.getWorldMatrix();
    var v = BABYLON.Vector3.TransformCoordinates(vector, m);
    return v;
}
const createScene = () => {

    const scene = new BABYLON.Scene(engine);
    const camera = new BABYLON.ArcRotateCamera("Camera", 0, 0, 10, new BABYLON.Vector3(0, 0, 0), scene);
    camera.setPosition(new BABYLON.Vector3(0, 0, -10));
    camera.attachControl(canvas, true);

    const sphere = BABYLON.MeshBuilder.CreateSphere("sphere", {
        diameter: 1
    },scene);
    sphere.material = new BABYLON.StandardMaterial('sphere-material')
    sphere.material.emissiveColor = BABYLON.Color3.White()

    const origin = sphere.position;
    const forward = vecToLocal(new BABYLON.Vector3(1, 1, 0), sphere);

    const direction = BABYLON.Vector3.Normalize(forward.subtract(origin));
    const ray = new BABYLON.Ray(origin, direction, 2);

    BABYLON.RayHelper.CreateAndShow(ray, scene, new BABYLON.Color3(1, 0, 0));

    return scene;

};

```

https://playground.babylonjs.com/#SRZRWV#1225

Body:
How do I compute the alpha and beta for ArcRotateCamera to look a point on a sphere? My playground has a ray from sphere origin to point on surface. Ultimately, I would like to animate from current point to ray.

const vecToLocal = (vector, mesh) => {
    var m = mesh.getWorldMatrix();
    var v = BABYLON.Vector3.TransformCoordinates(vector, m);
    return v;
}
const createScene = () => {

    const scene = new BABYLON.Scene(engine);
    const camera = new BABYLON.ArcRotateCamera("Camera", 0, 0, 10, new BABYLON.Vector3(0, 0, 0), scene);
    camera.setPosition(new BABYLON.Vector3(0, 0, -10));
    camera.attachControl(canvas, true);

    const sphere = BABYLON.MeshBuilder.CreateSphere("sphere", {
        diameter: 1
    },scene);
    sphere.material = new BABYLON.StandardMaterial('sphere-material')
    sphere.material.emissiveColor = BABYLON.Color3.White()

    const origin = sphere.position;
    const forward = vecToLocal(new BABYLON.Vector3(1, 1, 0), sphere);

    const direction = BABYLON.Vector3.Normalize(forward.subtract(origin));
    const ray = new BABYLON.Ray(origin, direction, 2);

    BABYLON.RayHelper.CreateAndShow(ray, scene, new BABYLON.Color3(1, 0, 0));

    return scene;

};

https://playground.babylonjs.com/#SRZRWV#1225


问:
How can I create a new dataframe out of a json column in a pyspark dataframe?
I have a pyspark dataframe where some of the columns are nested json objects, because I created it from a jsonl file. The schema looks like this:

```<code>root
 |-- _corrupt_record: string (nullable = true)
 |-- meeting: struct (nullable = true)
 |    |-- meeting_id: string (nullable = true)
 |    |-- meeting_name: string (nullable = true)
 |    |-- meeting_url: string (nullable = true)
 |    |-- time: long (nullable = true)
 |-- category: struct (nullable = true)
 |    |-- city: string (nullable = true)
 |    |-- country: string (nullable = true)
 |    |-- category_id: long (nullable = true)
 |    |-- category_lat: double (nullable = true)
 |    |-- category_lon: double (nullable = true)
 |    |-- category_name: string (nullable = true)
 |    |-- category_state: string (nullable = true)
 |    |-- category_topics: array (nullable = true)
 |    |    |-- element: struct (containsNull = true)
 |    |    |    |-- topic_name: string (nullable = true)
 |    |    |    |-- urlkey: string (nullable = true)
 |    |-- category_urlname: string (nullable = true)
</code>```

What I need to do is filter on some of the root level columns, and then create a new dataframe from the category_topics struct (this is a json object column). After this I imagine I would have to do a pivot and count in order to see how many times a topic appears. I have not found any examples of how to do this directly with dataframe operations, and I don't want to extract the column as a list and then create a new data frame out of it (unless that's the only possible way)

Any help would be much appreciated.

Body:
I have a pyspark dataframe where some of the columns are nested json objects, because I created it from a jsonl file. The schema looks like this:

root
 |-- _corrupt_record: string (nullable = true)
 |-- meeting: struct (nullable = true)
 |    |-- meeting_id: string (nullable = true)
 |    |-- meeting_name: string (nullable = true)
 |    |-- meeting_url: string (nullable = true)
 |    |-- time: long (nullable = true)
 |-- category: struct (nullable = true)
 |    |-- city: string (nullable = true)
 |    |-- country: string (nullable = true)
 |    |-- category_id: long (nullable = true)
 |    |-- category_lat: double (nullable = true)
 |    |-- category_lon: double (nullable = true)
 |    |-- category_name: string (nullable = true)
 |    |-- category_state: string (nullable = true)
 |    |-- category_topics: array (nullable = true)
 |    |    |-- element: struct (containsNull = true)
 |    |    |    |-- topic_name: string (nullable = true)
 |    |    |    |-- urlkey: string (nullable = true)
 |    |-- category_urlname: string (nullable = true)

What I need to do is filter on some of the root level columns, and then create a new dataframe from the category_topics struct (this is a json object column). After this I imagine I would have to do a pivot and count in order to see how many times a topic appears. I have not found any examples of how to do this directly with dataframe operations, and I don't want to extract the column as a list and then create a new data frame out of it (unless that's the only possible way)

Any help would be much appreciated.


问:
iFrame Resizer stalling and flickering
I'm adding multiple iframes to an html page and using iframe resizer to resize them appropriately.

http://davidjbradshaw.github.io/iframe-resizer/

However, they frequently get stuck in this "stuck state" and never properly resize. In addition to this, there is a noticeable flicker on page load. I'm not applying any custom options to the resizer and I'm using the cdn links right now.

I've got this script in the head of my page that I've added the iframes to:

```<code><script src="https://cdn.jsdelivr.net/npm/iframe-resizer@4.3.2/js/iframeResizer.min.js" integrity="sha256-oBWDuxBG1C5U0t3xjmZZ1UAlt9sKeSRk26KiVy4jxpY=" crossorigin="anonymous"></script>
</code>```

I've got this script added to the bottom of my iframe html page:

```<code><script src="https://cdn.jsdelivr.net/npm/iframe-resizer@4.3.2/js/iframeResizer.contentWindow.min.js" integrity="sha256-rbC2imHDJIBYUIXvf+XiYY+2cXmiSlctlHgI+rrezQo=" crossorigin="anonymous"></script>
</code>```

Then I call iFrameResize() one time at the bottom of my main html file that includes the iframes

Here is a screen shot after page load. Two of the iframes didn't resize at all and one (on the left) has a small sliver off white still showing.

Thanks for the help! Let me know if you have any other questions.

Title: iFrame Resizer stalling and flickering

Body:
I'm adding multiple iframes to an html page and using iframe resizer to resize them appropriately.

http://davidjbradshaw.github.io/iframe-resizer/

However, they frequently get stuck in this "stuck state" and never properly resize. In addition to this, there is a noticeable flicker on page load. I'm not applying any custom options to the resizer and I'm using the cdn links right now.

I've got this script in the head of my page that I've added the iframes to:

I've got this script added to the bottom of my iframe html page:

Then I call iFrameResize() one time at the bottom of my main html file that includes the iframes

Here is a screen shot after page load. Two of the iframes didn't resize at all and one (on the left) has a small sliver off white still showing.

Thanks for the help! Let me know if you have any other questions.


问:
Does TensorFlow Distributed Training support cross-network communication?
I've been trying to set up a distributed computing network to train my TensorFlow models. Esentially, my goal is to run a script on my host computer that delegates portions of the training process to other client computers via model parallel training. Each client node would also be running their own script, and they are allowed to dynamically join/leave during training.

I have already port forwarded my network so that I can establish socket connections with client nodes. However, in the TensorFlow documentation for the "MultiWorkerMirroredStrategy," the use of socket connections and/or connections between computers on different desktops seems to be unsupported. Each example they have is of TF_CONFIGs of localhost devices.

Is there any easy way to establish communication between two (or more) devices on separate networks for TensorFlow distributed training?


问:
Django Channels AsyncWebSocketConsumer ConnectionClosedError 1005
I am writing a django channels application and noticed an exception when handling a heartbeat function related to websocket status code which I haven't been able to find any existing issues for. This is in an AsyncWebsocketConsumer backed by redis.

ConnectionClosedError: websockets.exceptions.ConnectionClosedError: received 1005 (no status code [internal]); then sent 1005 (no status code [internal])

    async def receive(self, text_data):
        try:
            if text_data == "healthcheck":
                await self.send(
                    text_data=json.dumps({"type": "healthcheck", "data": self.group_name})
                )
            else:
                logger.info(f"Unsupported WS Event: {text_data}")
                pass
        except:
            logger.exception("Failed to handle message from client")
```
<p>Also receive this error</p>
<p><code>RuntimeError: RuntimeError: Unexpected ASGI message 'websocket.send', after sending 'websocket.close'.</code></p>
<p>My <code>disconnect</code> implementation is</p>
<pre class="lang-py prettyprint-override"><code>   async def disconnect(self, close_code):
        try:
            # Leave room group
            await self.channel_layer.group_discard(self.group_name, self.channel_name)

            await self.log_request("disconnect")
        except:
            logger.exception("Failed to disconnect user from socket")
</code>```

Body:
I am writing a django channels application and noticed an exception when handling a heartbeat function related to websocket status code which I haven't been able to find any existing issues for. This is in an AsyncWebsocketConsumer backed by redis.

ConnectionClosedError: websockets.exceptions.ConnectionClosedError: received 1005 (no status code [internal]); then sent 1005 (no status code [internal])

    async def receive(self, text_data):
        try:
            if text_data == "healthcheck":
                await self.send(
                    text_data=json.dumps({"type": "healthcheck", "data": self.group_name})
                )
            else:
                logger.info(f"Unsupported WS Event: {text_data}")
                pass
        except:
            logger.exception("Failed to handle message from client")

Also receive this error

RuntimeError: RuntimeError: Unexpected ASGI message 'websocket.send', after sending 'websocket.close'.

My disconnect implementation is

   async def disconnect(self, close_code):
        try:
            # Leave room group
            await self.channel_layer.group_discard(self.group_name, self.channel_name)

            await self.log_request("disconnect")
        except:
            logger.exception("Failed to disconnect user from socket")


问:
Attempting to copy specific columns from one sheet and paste on new sheet side by side
I've been struggling with this for a while now, but I am trying to use VBA to copy 2 specific columns from multiple sheets and then paste them into a new sheet. I will attach a copy of the code I've been using. However, it will paste each copied column under the previous column instead of pasting the columns side by side.</p>
```<code>Sub test1()

Dim ws As Worksheet
Dim ws_a As Worksheet
Dim ws_b As Worksheet
Dim HeaderRow_A As Long
Dim HeaderLastColumn_A As Long
Dim TableColStart_A As Long
Dim Q As Object
Dim SourceDataStart As Long
Dim SourceLastRow As Long
Dim Source As Variant
Dim k As Long
Dim ws_B_lastCol As Long
Dim NextEntryline As Long
Dim SourceCol_A As Long
Dim P As Long
Dim m As Long

Set Q = CreateObject("Scripting.Dictionary")
Set ws_b = Worksheets(2)

m = 3
Set ws_a = Worksheets(m)

For Each ws In Worksheets

With ws_a
    SourceDataStart = 2
    HeaderRow_A = 2
    TableColStart_A = 1
    HeaderLastColumn_A = .Cells(HeaderRow_A, columns.Count).End(xlToLeft).Column

    For k = TableColStart_A To HeaderLastColumn_A
        If Not Q.Exists((.Cells(HeaderRow_A, k).Value)) Then
             Q.Add (.Cells(HeaderRow_A, k).Value), k
        End If
    Next k
End With

With ws_b
    ws_B_lastCol = .Cells(HeaderRow_A, columns.Count).End(xlToLeft).Column
    For k = 1 To ws_B_lastCol
        SourceCol_A = Q((.Cells(2, k).Value))

        If SourceCol_A <> 0 Then
            SourceLastRow = ws_a.Cells(Rows.Count, SourceCol_A).End(xlUp).Row
            Set Source = ws_a.Range(ws_a.Cells(SourceDataStart, SourceCol_A), ws_a.Cells(SourceLastRow, SourceCol_A))
            NextEntryline = .Cells(Rows.Count, k).End(xlUp).Row + 1
            .Range(.Cells(NextEntryline, k), _
                   .Cells(NextEntryline, k)) _
                   .Resize(Source.Rows.Count, Source.columns.Count).Cells.Value = Source.Cells.Value
        End If

    Next k
End With

m = m + 1

Next ws

End Sub
</code>```

Body:
I've been struggling with this for a while now, but I am trying to use VBA to copy 2 specific columns from multiple sheets and then paste them into a new sheet. I will attach a copy of the code I've been using. However, it will paste each copied column under the previous column instead of pasting the columns side by side.

Sub test1()

Dim ws As Worksheet
Dim ws_a As Worksheet
Dim ws_b As Worksheet
Dim HeaderRow_A As Long
Dim HeaderLastColumn_A As Long
Dim TableColStart_A As Long
Dim Q As Object
Dim SourceDataStart As Long
Dim SourceLastRow As Long
Dim Source As Variant
Dim k As Long
Dim ws_B_lastCol As Long
Dim NextEntryline As Long
Dim SourceCol_A As Long
Dim P As Long
Dim m As Long

Set Q = CreateObject("Scripting.Dictionary")
Set ws_b = Worksheets(2)

m = 3
Set ws_a = Worksheets(m)

For Each ws In Worksheets

With ws_a
    SourceDataStart = 2
    HeaderRow_A = 2
    TableColStart_A = 1
    HeaderLastColumn_A = .Cells(HeaderRow_A, columns.Count).End(xlToLeft).Column

    For k = TableColStart_A To HeaderLastColumn_A
        If Not Q.Exists((.Cells(HeaderRow_A, k).Value)) Then
             Q.Add (.Cells(HeaderRow_A, k).Value), k
        End If
    Next k
End With

With ws_b
    ws_B_lastCol = .Cells(HeaderRow_A, columns.Count).End(xlToLeft).Column
    For k = 1 To ws_B_lastCol
        SourceCol_A = Q((.Cells(2, k).Value))

        If SourceCol_A <> 0 Then
            SourceLastRow = ws_a.Cells(Rows.Count, SourceCol_A).End(xlUp).Row
            Set Source = ws_a.Range(ws_a.Cells(SourceDataStart, SourceCol_A), ws_a.Cells(SourceLastRow, SourceCol_A))
            NextEntryline = .Cells(Rows.Count, k).End(xlUp).Row + 1
            .Range(.Cells(NextEntryline, k), _
                   .Cells(NextEntryline, k)) _
                   .Resize(Source.Rows.Count, Source.columns.Count).Cells.Value = Source.Cells.Value
        End If

    Next k
End With

m = m + 1

Next ws

End Sub


问:
How can I get the series of an indicator using IMF API?
The IMF docs does not tell how we can achieve that. It only says "GetMaxSeriesInResult method returns the maximum number of time series that can be returned by CompactData.
In order to obtain the data use the following request:

```<code>http://dataservices.imf.org/REST/SDMX_JSON.svc/GetMaxSeriesInResult
</code>```

and CompactData is this, basically:

```<code>http://dataservices.imf.org/REST/SDMX_JSON.svc/CompactData/{database ID}/{frequency}.{item1 from
dimension1}+{item2 from dimension1}+{item N from dimension1}.{item1 from
dimension2}+{item2 from dimension2}+{item M from dimension2}?startPeriod={start
date}&endPeriod={end date}
</code>```

Somehow, we have to merge GetMaxSeriesInResults with CompactData service

I tried to attach the indicator id as a query param like this, between other things, does not work.

```<code>http://dataservices.imf.org/REST/SDMX_JSON.svc/GetMaxSeriesInResult?REER.PC
</code>```

Body:
The IMF docs does not tell how we can achieve that. It only says "GetMaxSeriesInResult method returns the maximum number of time series that can be returned by CompactData.
In order to obtain the data use the following request:

http://dataservices.imf.org/REST/SDMX_JSON.svc/GetMaxSeriesInResult

and CompactData is this, basically:

http://dataservices.imf.org/REST/SDMX_JSON.svc/CompactData/{database ID}/{frequency}.{item1 from
dimension1}+{item2 from dimension1}+{item N from dimension1}.{item1 from
dimension2}+{item2 from dimension2}+{item M from dimension2}?startPeriod={start
date}&endPeriod={end date}

Somehow, we have to merge GetMaxSeriesInResults with CompactData service

I tried to attach the indicator id as a query param like this, between other things, does not work.

http://dataservices.imf.org/REST/SDMX_JSON.svc/GetMaxSeriesInResult?REER.PC


问:
Why is it printing symbols instead of char
// I want to print char like a marquee and it is printing like this, But the compiler is printing unnecessary symbols instead...

```<code>int main(){
    int i, j;
    j = 0;
    char str[100] = "DEV SONWANI";
    char startArray[100];
    char endArray[100];

    for(i = 135; i >= 0; i--){
        startArray[j] = str[j];
        coutSpace(i);
        cout<<startArray;
        sleep(1);
        system("cls");
        j++;
    }
return 9;
}

int coutSpace(int a){
    for(int i = 1; i <= a; i++){
        cout<<" ";
    }
}
</code>```

It is printing like the image..
console image

Body:
// I want to print char like a marquee and it is printing like this, But the compiler is printing unnecessary symbols instead...

int main(){
    int i, j;
    j = 0;
    char str[100] = "DEV SONWANI";
    char startArray[100];
    char endArray[100];

    for(i = 135; i >= 0; i--){
        startArray[j] = str[j];
        coutSpace(i);
        cout<<startArray;
        sleep(1);
        system("cls");
        j++;
    }
return 9;
}

int coutSpace(int a){
    for(int i = 1; i <= a; i++){
        cout<<" ";
    }
}

It is printing like the image..
console image


问:
Problems running BPTK-Py
I am trying to run the systems dynamics package BPTK-Py.
I am able to download it successfully and when I do list in the terminal it does show up as installed under the name BPTK-Py.

But when I try to run

```<code>from BPTK-Py  import Model
from BPTK-Py  import sd_functions as sd
</code>```

I get

```<code> File "/var/folders/8v/zkdpsxrj3l389d2bxhgyxjn80000gn/T/ipykernel_17344/3538218278.py", line 2
    from BPTK-Py  import Model
             ^
SyntaxError: invalid syntax
</code>```

I have also tried the syntax recommended in the documentation which is from BPTK_PY import Model but I am having no more luck with that one. Any advice to solve the problem would be much appreciated.

Title: Problems running BPTK-Py

Body:
I am trying to run the systems dynamics package BPTK-Py.
I am able to download it successfully and when I do list in the terminal it does show up as installed under the name BPTK-Py.

But when I try to run

from BPTK-Py  import Model
from BPTK-Py  import sd_functions as sd

I get

 File "/var/folders/8v/zkdpsxrj3l389d2bxhgyxjn80000gn/T/ipykernel_17344/3538218278.py", line 2
    from BPTK-Py  import Model
             ^
SyntaxError: invalid syntax

I have also tried the syntax recommended in the documentation which is from BPTK_PY import Model but I am having no more luck with that one. Any advice to solve the problem would be much appreciated.


问:
Power Query - Jira API transformation
Am trying to access Jira API's using Power query - but what i see is i have 500+ "Records table" and inside this table there are multiple "Nested Records Tables" again - Am trying to find a way to expand Record and List's all at once ? Attached 2 images

I end up doing it manually - which is very time consuming
Am trying to find a way to expand Record and List's all at once ?

Title: Power Query - Jira API transformation


问:
Collage multiple files to a single plot
I am trying to arrange plots from pdf to a single plot as grid. Here is the code and error:

```<code>pdffiles <-
  list.files(
    path = here::here("/Users/test/"),
    recursive = TRUE,
    pattern = "\\.pdf$",
    full.names = T
  )

magick::image_read_pdf(pdffiles) %>%
  magick::image_montage(tile = "2x5", geometry = "x500+10+5") %>%
  magick::image_write(
    format = ".pdf", path = here::here(paste(name,"_All.pdf",sep="")),
    quality = 100
  )
</code>```
```<code>Error in file(con, "rb") : invalid 'description' argument
In addition: Warning messages:
1: In if (is_svg(path)) return(path) :
  the condition has length > 1 and only the first element will be used
2: In if (is_url(path)) { :
  the condition has length > 1 and only the first element will be used
3: In if (grepl("^[^/\\]+:($|[^/\\])", path)) { :
  the condition has length > 1 and only the first element will be used
</code>```

Can anyone help?

Thanks!

Title: Collage multiple files to a single plot

Body:
I am trying to arrange plots from pdf to a single plot as grid. Here is the code and error:

pdffiles <-
  list.files(
    path = here::here("/Users/test/"),
    recursive = TRUE,
    pattern = "\\.pdf$",
    full.names = T
  )

magick::image_read_pdf(pdffiles) %>%
  magick::image_montage(tile = "2x5", geometry = "x500+10+5") %>%
  magick::image_write(
    format = ".pdf", path = here::here(paste(name,"_All.pdf",sep="")),
    quality = 100
  )

Error in file(con, "rb") : invalid 'description' argument
In addition: Warning messages:
1: In if (is_svg(path)) return(path) :
  the condition has length > 1 and only the first element will be used
2: In if (is_url(path)) { :
  the condition has length > 1 and only the first element will be used
3: In if (grepl("^[^/\\]+:($|[^/\\])", path)) { :
  the condition has length > 1 and only the first element will be used

Can anyone help?

Thanks!