问:
Git Error - fatal: will not add file alias 'file/path/index.html' ('file/path/index.html' already exists in index)
I keep getting this error whenever I try to stage both (index.html) files at once.

I'm using VS Code and every time I make changes to the file it appears twice on the git source control tab. I have double-checked to make sure the containing folder only contains one file named index.html and I have also made sure no other similar file exists named in a different casing like (INDEX.html)

I'm only able to stage, commit and push one of the duplicate (index.html) files.
The other one is stuck there, unable to even be staged.
Please help.

答:
I glean from the question that you have a change you want and one that you do not want (the duplicate).

Attempt to stash the change that you do want, so that you may use it after you've deleted the duplicate. This leaves you with just the change you'd like to get rid of.

Sometimes, things get stuck at this point:

```<code>Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working
directory)
</code>```

This can be resolved by forcing git to ignore the change you do not want. To do this run:

```<code>git ls-files -m | xargs -i git update-index --assume-unchanged "{}"
</code>```

if on Windows.
Credits for above command: Git: How to revert 2 files that are stubbornly stuck at "Changed but not committed"?

Body:
I glean from the question that you have a change you want and one that you do not want (the duplicate).

Attempt to stash the change that you do want, so that you may use it after you've deleted the duplicate. This leaves you with just the change you'd like to get rid of.

Sometimes, things get stuck at this point:

Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working
directory)

This can be resolved by forcing git to ignore the change you do not want. To do this run:

git ls-files -m | xargs -i git update-index --assume-unchanged "{}"

if on Windows.
Credits for above command: Git: How to revert 2 files that are stubbornly stuck at "Changed but not committed"?


来源: stackexchange

问:
help in uniquely identifying combine columns
How can I uniquely identify two or more columns, that I have used table named address in the database, now address is has fields like street name, suite name and street num.

strnum   | strnam  |  sutname

1        | xyz     | 32

1        | xyz     | 32

now how can I uniquely these three columns. That is I want to check whether these three column are already inserted or not. If any field valus is changed than its ok, it will insert new one. but in case all three similar field..Help me to combinely identify these three fields.

答: just add them as unique keys in table structure and you'll not be able to insert two of them</p>

ContentLicense: CC BY-SA 3.0


问:
I want to Itrate JSON and convert into rows from postgresql
Basically I want to itrate JSON till its length from table but rest of values of remains same till current JSON ends.
My Table format is like this

id
line
txndate
metadata
docnumber

363
[{"Id": "0", "Amount": 135000.0, "DetailType": "JournalEntryLineDetail", "Description": "Paid Office Rent Of Office", "JournalEntryLineDetail": {"AccountRef": {"name": "Rent or lease payments", "value": "57"}, "PostingType": "Debit"}}, {"Id": "1", "Amount": 135000.0, "DetailType": "JournalEntryLineDetail", "Description": "Paid Office Rent Of Office", "JournalEntryLineDetail": {"AccountRef": {"name": "Cash and cash equivalents:Bank", "value": "83"}, "PostingType": "Credit"}}]
2021-08-16 00:00:00.000000 +00:00
{"CreateTime": "2021-08-20T05:39:38.000000Z", "LastUpdatedTime": "2021-08-20T05:39:38.000000Z"}
332

610
[{"Id": "0", "Amount": 4138088.25, "DetailType": "JournalEntryLineDetail", "Description": "Deposit in Bank", "JournalEntryLineDetail": {"AccountRef": {"name": "Cash and cash equivalents:Bank", "value": "83"}, "PostingType": "Debit"}}, {"Id": "1", "Amount": 4138088.25, "DetailType": "JournalEntryLineDetail", "Description": "Deposit in Bank", "JournalEntryLineDetail": {"AccountRef": {"name": "Share capital", "value": "8"}, "PostingType": "Credit"}}, {"Id": "2", "DetailType": "DescriptionOnly", "Description": "Deposit in  Bank"}]
2021-10-11 00:00:00.000000 +00:00
{"CreateTime": "2021-10-13T10:44:09.000000Z", "LastUpdatedTime": "2021-10-13T10:44:09.000000Z"}
560

381
[{"Id": "0", "Amount": 30000.0, "DetailType": "JournalEntryLineDetail", "Description": "Paid to Punkish", "JournalEntryLineDetail": {"AccountRef": {"name": "Advance Against Salary", "value": "103"}, "PostingType": "Debit"}}, {"Id": "1", "Amount": 30000.0, "DetailType": "JournalEntryLineDetail", "Description": "Paid to Punkish", "JournalEntryLineDetail": {"AccountRef": {"name": "Cash and cash equivalents:Bank", "value": "83"}, "PostingType": "Credit"}}]
2021-07-01 00:00:00.000000 +00:00
{"CreateTime": "2021-08-23T05:31:42.000000Z", "LastUpdatedTime": "2021-08-23T05:47:03.000000Z"}
521

But I want to extract information like following table

id
line_id
Amount
Description
name
value
posting_type
txndate
CreatedTime
LastUpdatedTime

363
0
13500
Paid Office Rent Of Office
Rent or lease payments
57
Debit
2021-08-16 00:00:00.000000 +00:00
2021-08-20T05:39:38.000000Z
2021-08-20T05:39:38.000000Z

363
1
13500
Paid Office Rent Of Office
Cash and cash equivalents:Bank
83
Cebit
2021-08-16 00:00:00.000000 +00:00
2021-08-20T05:39:38.000000Z
2021-08-20T05:39:38.000000Z

610
0
4138088.25
Deposit in Bank
Cash and cash equivalents:Bank
83
Debit
2021-10-11 00:00:00.000000 +00:00
2021-10-13T10:44:09.000000Z
2021-10-13T10:44:09.000000Z

610
1
4138088.25
..........
..
...
...
2021-10-11 00:00:00.000000 +00:00
2021-10-13T10:44:09.000000Z
2021-10-13T10:44:09.000000Z

610
2
4138088.25
..........
..
...
...
2021-10-11 00:00:00.000000 +00:00
2021-10-13T10:44:09.000000Z
2021-10-13T10:44:09.000000Z

610
3
4138088.25
..........
..
...
...
2021-10-11 00:00:00.000000 +00:00
2021-10-13T10:44:09.000000Z
2021-10-13T10:44:09.000000Z

I want to convert JSON column enteries into rows but want preserve id, txndate, CreatedTime, and LastUpdatedTime same till the length of JSON column which is line in my case.

Please guide me with solution if possible.
Note: I am using Postgresql and datatype of line column is jsonb

答:
Here you go, You can use jsonb_array_elements function to convert an array of JSON to row and then query on each row

Demo

select
  t.id,
  e.value ->> 'Id' as line_id,
  e.value ->> 'Amount' as amount,
  e.value ->> 'Description' as description,
  e.value -> 'JournalEntryLineDetail' -> 'AccountRef' ->> 'name' as name,
  e.value -> 'JournalEntryLineDetail' -> 'AccountRef' ->> 'value' as value,
  e.value -> 'JournalEntryLineDetail' ->> 'PostingType' as posting_type,
  t.txndate,
  t.metadata ->> 'CreateTime' as CreatedTime,
  t.metadata ->> 'LastUpdatedTime' as LastUpdatedTime
from
  test t
  cross join jsonb_array_elements(t.line) e
```

ContentLicense: CC BY-SA 4.0


问:
Flutter: How to make a button like this?
I tried to use TextButton.Icon to make the effect as following.
But I found that the words can only be at the left or right of the icon. How can I put the words under the icon like this?

答:
the simplest way to create such things is to use column and row widget properly.

i added a full code with the screenshot check it below
[1]: https://i.stack.imgur.com/hRzy9.png

created a reusable widget for icon with button and added it in my main class i.e test class

```<code>class Test extends StatelessWidget {
  const Test({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Container(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            const SizedBox(height: 10,),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                IconWithTextButton(icon:const Icon(Icons.lock, color: Colors.red,),text: "Lock",onClicked: (){},),
                IconWithTextButton(icon:const Icon(Icons.alarm, color: Colors.amber),text: "Alarm",onClicked: (){},),
                IconWithTextButton(icon:const Icon(Icons.call, color: Colors.green),text: "call",onClicked: (){},),
                IconWithTextButton(icon:const Icon(Icons.wrong_location_sharp, color: Colors.greenAccent),text: "location",onClicked: (){},),
                IconWithTextButton(icon:const Icon(Icons.add, color: Colors.tealAccent),text: "Add",onClicked: (){},),
              ],
            ),
            const SizedBox(height: 20,),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                IconWithTextButton(icon: const Icon(Icons.lock, color: Colors.red,),text: "Lock",onClicked: (){},),
                IconWithTextButton(icon:const Icon(Icons.alarm, color: Colors.amber),text: "Alarm",onClicked: (){},),
                IconWithTextButton(icon:const Icon(Icons.call, color: Colors.green),text: "call",onClicked: (){},),
                IconWithTextButton(icon:const Icon(Icons.wrong_location_sharp, color: Colors.greenAccent),text: "location",onClicked: (){},),
                IconWithTextButton(icon:const Icon(Icons.add, color: Colors.tealAccent),text: "Add",onClicked: (){},),
              ],
            )
          ],
        ),
      ),
    );
  }
}
</code>```

this is reusable widget with reusable text, reusable onclick and reusable icon

```<code>class IconWithTextButton extends StatelessWidget {
  String text;
  Icon icon;
  VoidCallback onClicked;
  IconWithTextButton({Key? key, required this.text, required this.onClicked, required this.icon}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onClicked,
      child: Container(
        child: Column(
          children: [
            icon,
            const SizedBox(height: 10,),
            Text(text),
          ],
        ),
      ),
    );
  }
}

</code>```

Body:
the simplest way to create such things is to use column and row widget properly.

i added a full code with the screenshot check it below
[1]: https://i.stack.imgur.com/hRzy9.png

created a reusable widget for icon with button and added it in my main class i.e test class

class Test extends StatelessWidget {
  const Test({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Container(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            const SizedBox(height: 10,),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                IconWithTextButton(icon:const Icon(Icons.lock, color: Colors.red,),text: "Lock",onClicked: (){},),
                IconWithTextButton(icon:const Icon(Icons.alarm, color: Colors.amber),text: "Alarm",onClicked: (){},),
                IconWithTextButton(icon:const Icon(Icons.call, color: Colors.green),text: "call",onClicked: (){},),
                IconWithTextButton(icon:const Icon(Icons.wrong_location_sharp, color: Colors.greenAccent),text: "location",onClicked: (){},),
                IconWithTextButton(icon:const Icon(Icons.add, color: Colors.tealAccent),text: "Add",onClicked: (){},),
              ],
            ),
            const SizedBox(height: 20,),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                IconWithTextButton(icon: const Icon(Icons.lock, color: Colors.red,),text: "Lock",onClicked: (){},),
                IconWithTextButton(icon:const Icon(Icons.alarm, color: Colors.amber),text: "Alarm",onClicked: (){},),
                IconWithTextButton(icon:const Icon(Icons.call, color: Colors.green),text: "call",onClicked: (){},),
                IconWithTextButton(icon:const Icon(Icons.wrong_location_sharp, color: Colors.greenAccent),text: "location",onClicked: (){},),
                IconWithTextButton(icon:const Icon(Icons.add, color: Colors.tealAccent),text: "Add",onClicked: (){},),
              ],
            )
          ],
        ),
      ),
    );
  }
}

this is reusable widget with reusable text, reusable onclick and reusable icon

class IconWithTextButton extends StatelessWidget {
  String text;
  Icon icon;
  VoidCallback onClicked;
  IconWithTextButton({Key? key, required this.text, required this.onClicked, required this.icon}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onClicked,
      child: Container(
        child: Column(
          children: [
            icon,
            const SizedBox(height: 10,),
            Text(text),
          ],
        ),
      ),
    );
  }
}


问:
Enum default value for Java enum annotation value
Java allows enum as values for annotation values. How can I define a kind of generic default enum value for an enum annotation value?

I have considered the following, but it won't compile:

```<code>@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public <T extends Enum<T>> @interface MyAnnotation<T> {

    T defaultValue();

}
</code>```

Is there a solution to this issue or not?

BOUNTY

Is does not seem like there is a direct solution to this Java corner case. So, I am starting a bounty to find the most elegant solution to this issue.

The ideal solution should ideally meet the following criteria:

One annotation reusable on all enums

Minimum effort/complexity to retrieve the default enum value as an enum from annotation instances

BEST SOLUTION SO FAR

By Dunes:

```<code>@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyAnnotation {

    // By not specifying default,
    // we force the user to specify values
    Class<? extends Enum<?>> enumClazz();
    String defaultValue();

}

...

public enum MyEnumType {
    A, B, D, Q;
}

...

// Usage
@MyAnnotation(enumClazz=MyEnumType.class, defaultValue="A");
private MyEnumType myEnumField;
</code>```

Of course, we can't force the user to specify a valid default value at compile time. However, any annotation pre-processing can verify this with valueOf().

IMPROVEMENT

Arian provides an elegant solution to get rid of clazz in annotated fields:

```<code>@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyAnnotation {

}

...

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@MyAnnotation()
public @interface MyEnumAnnotation {

    MyEnumType value(); // no default has user define default value

}

...

@MyEnumAnnotation(MyEnum.FOO)
private MyEnumType myValue;
</code>```

The annotation processor should search for both MyEnumAnnotation on fields for the provided default value.

This requires the creation of one annotation type per enum type, but guarantees compile time checked type safety.

答:
Frameworks using annotations can really profit from using apt. It's a preprocesor contained in javac, which will let you analyse declarations and their annotations (but not local declarations inside methods).

For your problem you would need to write an AnnotationProcessor (a class used as starting point for preprocessing) to analyse the annotation by using the Mirror API. Actually Dunes' annotation is pretty close to what is needed here. Too bad enum names aren't constant expressions, otherwise Dunes' solution would be pretty nice.

```<code>@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.FIELD)
public @interface MyAnnotation {
    Class<? extends Enum<?>> clazz();
    String name() default "";
}
</code>```

And here's an example enum: enum MyEnum { FOO, BAR, BAZ, ; }

When using a modern IDE, you can display errors on directly on the annotation element (or the annotation's value), if the name isn't a valid enum constant. You can even provide auto complete hints, so when a user writes @MyAnnotation(clazz = MyEnum.class, name = "B") and hits the hotkeys for auto-completion after writing B, you can provide him a list to choose from, containing all the constants starting with B: BAR and BAZ.

My suggestion to implement the default value is to create a marker annotation to declare an enum constant as default value for that enum. The user would still need to provide the enum type, but could omit the name. There are probably other ways though, to make a value the default one.

Here's a tutorial about apt and here the AbstractProcessor which should be extended to override the getCompletions method.

Body:
Java allows enum as values for annotation values. How can I define a kind of generic default enum value for an enum annotation value?

I have considered the following, but it won't compile:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public <T extends Enum<T>> @interface MyAnnotation<T> {

    T defaultValue();

}

Is there a solution to this issue or not?

BOUNTY

Is does not seem like there is a direct solution to this Java corner case. So, I am starting a bounty to find the most elegant solution to this issue.

The ideal solution should ideally meet the following criteria:

One annotation reusable on all enums

Minimum effort/complexity to retrieve the default enum value as an enum from annotation instances

BEST SOLUTION SO FAR

By Dunes:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyAnnotation {

    // By not specifying default,
    // we force the user to specify values
    Class<? extends Enum<?>> enumClazz();
    String defaultValue();

}

...

public enum MyEnumType {
    A, B, D, Q;
}

...

// Usage
@MyAnnotation(enumClazz=MyEnumType.class, defaultValue="A");
private MyEnumType myEnumField;

Of course, we can't force the user to specify a valid default value at compile time. However, any annotation pre-processing can verify this with valueOf().

IMPROVEMENT

Arian provides an elegant solution to get rid of clazz in annotated fields:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyAnnotation {

}

...

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@MyAnnotation()
public @interface MyEnumAnnotation {

    MyEnumType value(); // no default has user define default value

}

...

@MyEnumAnnotation(MyEnum.FOO)
private MyEnumType myValue;

The annotation processor should search for both MyEnumAnnotation on fields for the provided default value.

This requires the creation of one annotation type per enum type, but guarantees compile time checked type safety.

Body:
Frameworks using annotations can really profit from using apt. It's a preprocesor contained in javac, which will let you analyse declarations and their annotations (but not local declarations inside methods).

For your problem you would need to write an AnnotationProcessor (a class used as starting point for preprocessing) to analyse the annotation by using the Mirror API. Actually Dunes' annotation is pretty close to what is needed here. Too bad enum names aren't constant expressions, otherwise Dunes' solution would be pretty nice.

@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.FIELD)
public @interface MyAnnotation {
    Class<? extends Enum<?>> clazz();
    String name() default "";
}

And here's an example enum: enum MyEnum { FOO, BAR, BAZ, ; }

When using a modern IDE, you can display errors on directly on the annotation element (or the annotation's value), if the name isn't a valid enum constant. You can even provide auto complete hints, so when a user writes @MyAnnotation(clazz = MyEnum.class, name = "B") and hits the hotkeys for auto-completion after writing B, you can provide him a list to choose from, containing all the constants starting with B: BAR and BAZ.

My suggestion to implement the default value is to create a marker annotation to declare an enum constant as default value for that enum. The user would still need to provide the enum type, but could omit the name. There are probably other ways though, to make a value the default one.

Here's a tutorial about apt and here the AbstractProcessor which should be extended to override the getCompletions method.


问:
RAM-efficient set of 1 billion of short strings, and fast lookup
I want to be able to test, as fast as possible, if a given string is a member of a set S of 1 billion of strings:

each string is of length 10 on average, so the whole data is ~ 10 GB, the max length is 100

99% of the strings uses only a-z A-Z 0-9 + a few special chars (.!-;\/), in some rare cases there are other chars

if necessary, the data could be sorted:

```<code>aaaaa
...
helloworld
hellu
help
...
zzzzz
</code>```

and we could maybe use a prefix tree / trie, but I'm not sure if it's the best solution here.

Question: Is there a way to work with an in-memory compressed set with Python, possibly with the standard library, with fast lookup?

The goal is to test 'hello' in S as fast as possible.

I know how to do this with 10 GB of RAM, but out of curiosity, I'd like to know if this is possible with, say, only 1 or 2 GB of RAM:

```<code>S = set()
with open('db.txt', 'r') as f:
   for l in f:
       S.add(l)
print('hello' in S)
</code>```

答:
No.

Unless there is some massive redundancy in the data you're not telling us about, you can expect to compress the 10 GB down to maybe 6 or 7 GB, even sorted. A data structure like you suggest would make it massively larger, not smaller.

As suggested in another answer, you can make it fast with a hashing approach. But not reduce the storage by a factor of five to ten.

Body:
I want to be able to test, as fast as possible, if a given string is a member of a set S of 1 billion of strings:

each string is of length 10 on average, so the whole data is ~ 10 GB, the max length is 100

99% of the strings uses only a-z A-Z 0-9 + a few special chars (.!-;\/), in some rare cases there are other chars

if necessary, the data could be sorted:

aaaaa
...
helloworld
hellu
help
...
zzzzz

and we could maybe use a prefix tree / trie, but I'm not sure if it's the best solution here.

Question: Is there a way to work with an in-memory compressed set with Python, possibly with the standard library, with fast lookup?

The goal is to test 'hello' in S as fast as possible.

I know how to do this with 10 GB of RAM, but out of curiosity, I'd like to know if this is possible with, say, only 1 or 2 GB of RAM:

S = set()
with open('db.txt', 'r') as f:
   for l in f:
       S.add(l)
print('hello' in S)


问:
Hadoop 3.3.0: RPC response has invalid length
I just installed PySpark via Homebrew and I'm currently trying to put stuff into Hadoop.

The Problem

Any interaction with Hadoop is failing.

I followed a tutorial to set up Hadoop3.3.0 on MacOS.

It somehow didn't work out even though the only things I fixed where some versions (specific JDK, MySQL etc).

Whenever I try to run any command related to Hadoop, I receive this:

```<code>▶ hadoop fs -ls /
2021-05-12 07:45:44,647 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
ls: RPC response has invalid length
</code>```

Running this code in a notebook:

```<code>from pyspark.sql.session import SparkSession

# https://saagie.zendesk.com/hc/en-us/articles/360029759552-PySpark-Read-and-Write-Files-from-HDFS
sparkSession = SparkSession.builder.appName("example-pyspark-read-and-write").getOrCreate()
# Create data
data = [('First', 1), ('Second', 2), ('Third', 3), ('Fourth', 4), ('Fifth', 5)]
df = sparkSession.createDataFrame(data)

# Write into HDFS
df.write.csv("hdfs://localhost:9000/cluster/example.csv")
# Read from HDFS
df_load = sparkSession.read.csv("hdfs://localhost:9000/cluster/example.csv")
df_load.show()

sc.stop()
</code>```

throws me

```<code>Py4JJavaError                             Traceback (most recent call last)
<ipython-input-5-e25cae5a6cac> in <module>
      8
      9 # Write into HDFS
---> 10 df.write.csv("hdfs://localhost:9000/cluster/example.csv")
     11 # Read from HDFS
     12 df_load = sparkSession.read.csv("hdfs://localhost:9000/cluster/example.csv")

/usr/local/Cellar/apache-spark/3.1.1/libexec/python/pyspark/sql/readwriter.py in csv(self, path, mode, compression, sep, quote, escape, header, nullValue, escapeQuotes, quoteAll, dateFormat, timestampFormat, ignoreLeadingWhiteSpace, ignoreTrailingWhiteSpace, charToEscapeQuoteEscaping, encoding, emptyValue, lineSep)
   1369                        charToEscapeQuoteEscaping=charToEscapeQuoteEscaping,
   1370                        encoding=encoding, emptyValue=emptyValue, lineSep=lineSep)
-> 1371         self._jwrite.csv(path)
   1372
   1373     def orc(self, path, mode=None, partitionBy=None, compression=None):

/usr/local/lib/python3.9/site-packages/py4j/java_gateway.py in __call__(self, *args)
   1307
   1308         answer = self.gateway_client.send_command(command)
-> 1309         return_value = get_return_value(
   1310             answer, self.gateway_client, self.target_id, self.name)
   1311

/usr/local/Cellar/apache-spark/3.1.1/libexec/python/pyspark/sql/utils.py in deco(*a, **kw)
    109     def deco(*a, **kw):
    110         try:
--> 111             return f(*a, **kw)
    112         except py4j.protocol.Py4JJavaError as e:
    113             converted = convert_exception(e.java_exception)

/usr/local/lib/python3.9/site-packages/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)
    324             value = OUTPUT_CONVERTER[type](answer[2:], gateway_client)
    325             if answer[1] == REFERENCE_TYPE:
--> 326                 raise Py4JJavaError(
    327                     "An error occurred while calling {0}{1}{2}.\n".
    328                     format(target_id, ".", name), value)

Py4JJavaError: An error occurred while calling o99.csv.
: java.io.IOException: Failed on local exception: org.apache.hadoop.ipc.RpcException: RPC response has invalid length; Host Details : local host is: "blkpingu16-MBP.fritz.box/192.xxx.xxx.xx"; destination host is: "localhost":9000;
    at org.apache.hadoop.net.NetUtils.wrapException(NetUtils.java:816)
    at org.apache.hadoop.ipc.Client.getRpcResponse(Client.java:1515)
    ...
    at org.apache.spark.sql.DataFrameWriter.csv(DataFrameWriter.scala:979)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    ...
    at java.base/java.lang.Thread.run(Thread.java:830)
Caused by: org.apache.hadoop.ipc.RpcException: RPC response has invalid length
    at org.apache.hadoop.ipc.Client$IpcStreams.readResponse(Client.java:1827)
    at org.apache.hadoop.ipc.Client$Connection.receiveRpcResponse(Client.java:1173)
    at org.apache.hadoop.ipc.Client$Connection.run(Client.java:1069)
</code>```

There it is: RPC response has invalid length

I have configured and verified all my paths in various config files like

core-site.xml

```<code><configuration>
<property>
<name>fs.defaultFS</name>
<value>hdfs://localhost:9000</value>
</property>
<property>
<name>ipc.maximum.data.length</name>
<value>134217728</value>
</property>
</configuration>
</code>```

.zshrc

```<code>JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home"

...

## JAVA env variablesexport JAVA_HOME="/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home"
export PATH=$PATH:$JAVA_HOME/bin

## HADOOP env variables
export HADOOP_HOME="/usr/local/Cellar/hadoop/3.3.0/libexec"
export PATH=$PATH:$HADOOP_HOME/bin
export PATH=$PATH:$HADOOP_HOME/sbin
export HADOOP_CONF_DIR=$HADOOP_HOME/etc/hadoop
export HADOOP_MAPRED_HOME=$HADOOP_HOME
export HADOOP_COMMON_HOME=$HADOOP_HOME
export HADOOP_HDFS_HOME=$HADOOP_HOME
export YARN_HOME=$HADOOP_HOME
export HADOOP_COMMON_LIB_NATIVE_DIR=$HADOOP_HOME/lib/native
export HADOOP_OPTS="-Djava.library.path=$HADOOP_HOME/lib"
export HADOOP_CLASSPATH=${JAVA_HOME}/lib/tools.jar

## HIVE env variables
export HIVE_HOME=/usr/local/Cellar/hive/3.1.2_3/libexec
export PATH=$PATH:/$HIVE_HOME/bin

## MySQL ENV
export PATH=$PATH:/usr/local/Cellar/mysql/8.0.23_1/bin
</code>```

Hdfs-site.xml

```<code><configuration>
<property>
<name>dfs.replication</name>
<value>1</value>
</property>
</configuration>
</code>```

hadoop-env.sh

```<code>export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_141.jdk/Contents/Home
</code>```

if I start Hadoop it seems to start all nodes:

```<code>▶ $HADOOP_HOME/sbin/start-all.sh
Starting namenodes on [localhost]
Starting datanodes
Starting secondary namenodes [blkpingu16-MBP.fritz.box]
2021-05-12 08:18:15,786 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
Starting resourcemanager
Starting nodemanagers
</code>```

jps shows that Hadoop stuff is running, along some Spark Stuff

```<code>▶ jps
166 Jps
99750 ResourceManager
99544 SecondaryNameNode
99851 NodeManager
98154 SparkSubmit
99405 DataNode
39326 Master
</code>```

http://localhost:8088/cluster is available and shows the Hadoop dashboard (Yarn, according to the tutorial I followed)
http://localhost:8080 is available and shows the Spark dashboard
http://localhost:9870 is not available (should show me something Hadoop related)

My main problem is that I don't know why my namenode is not there, because it should and subsequently why I can't communicate with the HDFS in order to interact with it via command line (put data in it) or request data via notebooks.
Something Hadoop related is broken and I can't figure out how to fix it.

答:
I faced the same issue today and would like to note it here if anyone faced a similar issue. A quick command jps show me that the NameNode process is not there - although there is no warning or error show up.

As I discovered in the .log file of the NameNode in Hadoop, there was a java.net.BindException: Problem binding to [localhost:9000], which made me think that the port 9000 is used by another process. I use the command from this source to check open ports, indeed it is used by a python process (I ran only PySpark at that time). (sudo lsof -i -P -n | grep LISTEN for anyone needs by the way)

The solution is pretty straightforward: change the port number in fs.defaultFS field in etc/core-site.xml to another port that is not in used (mine is 9900).

Body:
I just installed PySpark via Homebrew and I'm currently trying to put stuff into Hadoop.

The Problem

Any interaction with Hadoop is failing.

I followed a tutorial to set up Hadoop3.3.0 on MacOS.

It somehow didn't work out even though the only things I fixed where some versions (specific JDK, MySQL etc).

Whenever I try to run any command related to Hadoop, I receive this:

▶ hadoop fs -ls /
2021-05-12 07:45:44,647 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
ls: RPC response has invalid length

Running this code in a notebook:

from pyspark.sql.session import SparkSession

# https://saagie.zendesk.com/hc/en-us/articles/360029759552-PySpark-Read-and-Write-Files-from-HDFS
sparkSession = SparkSession.builder.appName("example-pyspark-read-and-write").getOrCreate()
# Create data
data = [('First', 1), ('Second', 2), ('Third', 3), ('Fourth', 4), ('Fifth', 5)]
df = sparkSession.createDataFrame(data)

# Write into HDFS
df.write.csv("hdfs://localhost:9000/cluster/example.csv")
# Read from HDFS
df_load = sparkSession.read.csv("hdfs://localhost:9000/cluster/example.csv")
df_load.show()

sc.stop()

throws me

Py4JJavaError                             Traceback (most recent call last)
<ipython-input-5-e25cae5a6cac> in <module>
      8
      9 # Write into HDFS
---> 10 df.write.csv("hdfs://localhost:9000/cluster/example.csv")
     11 # Read from HDFS
     12 df_load = sparkSession.read.csv("hdfs://localhost:9000/cluster/example.csv")

/usr/local/Cellar/apache-spark/3.1.1/libexec/python/pyspark/sql/readwriter.py in csv(self, path, mode, compression, sep, quote, escape, header, nullValue, escapeQuotes, quoteAll, dateFormat, timestampFormat, ignoreLeadingWhiteSpace, ignoreTrailingWhiteSpace, charToEscapeQuoteEscaping, encoding, emptyValue, lineSep)
   1369                        charToEscapeQuoteEscaping=charToEscapeQuoteEscaping,
   1370                        encoding=encoding, emptyValue=emptyValue, lineSep=lineSep)
-> 1371         self._jwrite.csv(path)
   1372
   1373     def orc(self, path, mode=None, partitionBy=None, compression=None):

/usr/local/lib/python3.9/site-packages/py4j/java_gateway.py in __call__(self, *args)
   1307
   1308         answer = self.gateway_client.send_command(command)
-> 1309         return_value = get_return_value(
   1310             answer, self.gateway_client, self.target_id, self.name)
   1311

/usr/local/Cellar/apache-spark/3.1.1/libexec/python/pyspark/sql/utils.py in deco(*a, **kw)
    109     def deco(*a, **kw):
    110         try:
--> 111             return f(*a, **kw)
    112         except py4j.protocol.Py4JJavaError as e:
    113             converted = convert_exception(e.java_exception)

/usr/local/lib/python3.9/site-packages/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)
    324             value = OUTPUT_CONVERTER[type](answer[2:], gateway_client)
    325             if answer[1] == REFERENCE_TYPE:
--> 326                 raise Py4JJavaError(
    327                     "An error occurred while calling {0}{1}{2}.\n".
    328                     format(target_id, ".", name), value)

Py4JJavaError: An error occurred while calling o99.csv.
: java.io.IOException: Failed on local exception: org.apache.hadoop.ipc.RpcException: RPC response has invalid length; Host Details : local host is: "blkpingu16-MBP.fritz.box/192.xxx.xxx.xx"; destination host is: "localhost":9000;
    at org.apache.hadoop.net.NetUtils.wrapException(NetUtils.java:816)
    at org.apache.hadoop.ipc.Client.getRpcResponse(Client.java:1515)
    ...
    at org.apache.spark.sql.DataFrameWriter.csv(DataFrameWriter.scala:979)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    ...
    at java.base/java.lang.Thread.run(Thread.java:830)
Caused by: org.apache.hadoop.ipc.RpcException: RPC response has invalid length
    at org.apache.hadoop.ipc.Client$IpcStreams.readResponse(Client.java:1827)
    at org.apache.hadoop.ipc.Client$Connection.receiveRpcResponse(Client.java:1173)
    at org.apache.hadoop.ipc.Client$Connection.run(Client.java:1069)

There it is: RPC response has invalid length

I have configured and verified all my paths in various config files like

core-site.xml

<configuration>
<property>
<name>fs.defaultFS</name>
<value>hdfs://localhost:9000</value>
</property>
<property>
<name>ipc.maximum.data.length</name>
<value>134217728</value>
</property>
</configuration>

.zshrc

JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home"

...

## JAVA env variablesexport JAVA_HOME="/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home"
export PATH=$PATH:$JAVA_HOME/bin

## HADOOP env variables
export HADOOP_HOME="/usr/local/Cellar/hadoop/3.3.0/libexec"
export PATH=$PATH:$HADOOP_HOME/bin
export PATH=$PATH:$HADOOP_HOME/sbin
export HADOOP_CONF_DIR=$HADOOP_HOME/etc/hadoop
export HADOOP_MAPRED_HOME=$HADOOP_HOME
export HADOOP_COMMON_HOME=$HADOOP_HOME
export HADOOP_HDFS_HOME=$HADOOP_HOME
export YARN_HOME=$HADOOP_HOME
export HADOOP_COMMON_LIB_NATIVE_DIR=$HADOOP_HOME/lib/native
export HADOOP_OPTS="-Djava.library.path=$HADOOP_HOME/lib"
export HADOOP_CLASSPATH=${JAVA_HOME}/lib/tools.jar

## HIVE env variables
export HIVE_HOME=/usr/local/Cellar/hive/3.1.2_3/libexec
export PATH=$PATH:/$HIVE_HOME/bin

## MySQL ENV
export PATH=$PATH:/usr/local/Cellar/mysql/8.0.23_1/bin

Hdfs-site.xml

<configuration>
<property>
<name>dfs.replication</name>
<value>1</value>
</property>
</configuration>

hadoop-env.sh

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_141.jdk/Contents/Home

if I start Hadoop it seems to start all nodes:

▶ $HADOOP_HOME/sbin/start-all.sh
Starting namenodes on [localhost]
Starting datanodes
Starting secondary namenodes [blkpingu16-MBP.fritz.box]
2021-05-12 08:18:15,786 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
Starting resourcemanager
Starting nodemanagers

jps shows that Hadoop stuff is running, along some Spark Stuff

▶ jps
166 Jps
99750 ResourceManager
99544 SecondaryNameNode
99851 NodeManager
98154 SparkSubmit
99405 DataNode
39326 Master

http://localhost:8088/cluster is available and shows the Hadoop dashboard (Yarn, according to the tutorial I followed)
http://localhost:8080 is available and shows the Spark dashboard
http://localhost:9870 is not available (should show me something Hadoop related)

My main problem is that I don't know why my namenode is not there, because it should and subsequently why I can't communicate with the HDFS in order to interact with it via command line (put data in it) or request data via notebooks.
Something Hadoop related is broken and I can't figure out how to fix it.


问:
How to prevent html2canvas to take screenshots after show my pdf?
I'm using jspdf autotable and html2canvas in React.js to create and show a pdf on my page. Everything works well but after My pdf is showen on teh pop-Up then an extra screenshot is added at below on my page. I want to prevent this screenshot.

When you look at the first picture , everything works well and I can see my pdf on the pop-up. But When I close that pop-up then a screenshot is created at below. You can see it at second picture. Is there any way to prevent it?

Here is my code:

```<code>doc.autoTable({
        showHead:'firstPage',
        margin:5,
        startY: 60,
        body: bodyData,
        columns: [
          { header: 'Sıra', dataKey: 'Count' },
          { header: 'Gelir Tipi', dataKey: 'AccrumentTypeName' },
          { header: 'Gelir Türü', dataKey: 'RevenueName' },
          { header: 'Tahakkuk Tutarı', dataKey: 'TotalAmount' },
        ],
        styles: {
            font: 'NotoSans-Regular',
            lineWidth: 0.2,
            lineColor: 0,
            fontSize:7,
          },
        didParseCell: function (data) {
            var rows = data.table.body;
            if (data.row.index === rows.length - 1) {
                data.cell.styles.fillColor = [176, 224, 230];
            }
        }
    })

const pageCount = doc.internal.getNumberOfPages();
    doc.setFontSize(8)
    for (var i = 1; i <= pageCount; i++) {
        doc.setPage(i)
        doc.text('Sayfa ' + String(i) + ' / ' + String(pageCount), doc.internal.pageSize.width / 2, 294, {
            align: 'center'
        })
    }

    //Create screenshot of body
    html2canvas(document.body, {scale: 2,scrollY: 0,height: window.outerHeight + window.innerHeight, windowHeight: window.outerHeight + window.innerHeight, }).then(canvas => {
       document.body.appendChild(canvas);
       let output = doc.output('bloburl');
       document.getElementById("pdfObj").height = canvas.height / 4;
       document.getElementById("pdfObj").data = output;
    });
</code>```

答:
I've solved my problem. The problem is that html2canvas is creating  as a screenshot in index.html every time I call it. Therefore I set

```<code><style>
  canvas{
    display: none !important;
  }
</style>
</code>```

in index.html. Then it works!

Body:
I'm using jspdf autotable and html2canvas in React.js to create and show a pdf on my page. Everything works well but after My pdf is showen on teh pop-Up then an extra screenshot is added at below on my page. I want to prevent this screenshot.

When you look at the first picture , everything works well and I can see my pdf on the pop-up. But When I close that pop-up then a screenshot is created at below. You can see it at second picture. Is there any way to prevent it?

Here is my code:

doc.autoTable({
        showHead:'firstPage',
        margin:5,
        startY: 60,
        body: bodyData,
        columns: [
          { header: 'Sıra', dataKey: 'Count' },
          { header: 'Gelir Tipi', dataKey: 'AccrumentTypeName' },
          { header: 'Gelir Türü', dataKey: 'RevenueName' },
          { header: 'Tahakkuk Tutarı', dataKey: 'TotalAmount' },
        ],
        styles: {
            font: 'NotoSans-Regular',
            lineWidth: 0.2,
            lineColor: 0,
            fontSize:7,
          },
        didParseCell: function (data) {
            var rows = data.table.body;
            if (data.row.index === rows.length - 1) {
                data.cell.styles.fillColor = [176, 224, 230];
            }
        }
    })

const pageCount = doc.internal.getNumberOfPages();
    doc.setFontSize(8)
    for (var i = 1; i <= pageCount; i++) {
        doc.setPage(i)
        doc.text('Sayfa ' + String(i) + ' / ' + String(pageCount), doc.internal.pageSize.width / 2, 294, {
            align: 'center'
        })
    }

    //Create screenshot of body
    html2canvas(document.body, {scale: 2,scrollY: 0,height: window.outerHeight + window.innerHeight, windowHeight: window.outerHeight + window.innerHeight, }).then(canvas => {
       document.body.appendChild(canvas);
       let output = doc.output('bloburl');
       document.getElementById("pdfObj").height = canvas.height / 4;
       document.getElementById("pdfObj").data = output;
    });

Body:
I've solved my problem. The problem is that html2canvas is creating  as a screenshot in index.html every time I call it. Therefore I set

<style>
  canvas{
    display: none !important;
  }
</style>

in index.html. Then it works!


问:
Unable to Start Talend Tool JAVA Version incompatibility
My Talend tool version is 5.6. As mentioned in Talend documentation it needs Java Runtime Environment 7 i.e jdk1.7, which is installed - along with set java_home in my environment variables. As per me it should work.
However I have jdk1.8 installed too, but I'm correctly pointing jdk1.7 path at environment variable.

Alternatively I have tried giving jdk1.7 path in Talend's Talend-Studio-win-x86_64.ini file. It's still giving me error.

Below is snapshot: in cmd the installed version shows jdk1.8 where in echo %JAVA_HOME% it shows path of jdk1.7

While starting tool this error comes:

答:
try to make changes in TOS_DI-win-x86_64.ini file

add line

```<code>-vm
C:\Program Files\Java\jdk-11.0.14\bin\javaw.exe
</code>```

And update or confirm the version as below.

```<code>-Dosgi.requiredJavaVersion=11.0.14
</code>```

Hope it'll help to fix the issue

Body:
try to make changes in TOS_DI-win-x86_64.ini file

add line

-vm
C:\Program Files\Java\jdk-11.0.14\bin\javaw.exe

And update or confirm the version as below.

-Dosgi.requiredJavaVersion=11.0.14

Hope it'll help to fix the issue


问:
GDB issue when using enum with type definition in c++
I have an enum with an explicit underlying type definition like this:

```<code>enum test : uint16_t
{
    test_x = 0x7fff, // 0111 1111 1111 1111
    test_y = 0x8000  // 1000 0000 0000 0000
};
</code>```

And variables in my code that are assigned the enum values like this:

```<code>test num1 = test_x;
test num2 = test_y;
</code>```

When I try to look at the value using GDB, I get this kind of result:

```<code>(gdb) print num1
$1 = test_x
(gdb) print num2
$2 = (test_y | unknown: -65536)
</code>```

Why is num2 acting so strange? Its value is in the range of the type I declared,
so what is wrong with this configuration?

I will also point out that this happens not just with uint16_t but with uint32_t and the values test_x = 0x7fffffff, test_y = 0x80000000.

Edit

I am compiling with GNU GCC version: 9.3.0 on ARM processor platform and using GDB version 8.1.0.

答:
I will answer my own question after getting some helpful pointers in the comments.

This turned out to really be a bug in the GDB version I was using.
upgrading to a newer version solves this issue.
(I upgraded from 8.1 to 10.2)

```<code>(gdb) print num1
$1 = test_x
(gdb) print num2
$2 = test_y
(gdb) show version
GNU gdb (GDB; JetBrains IDE bundle; build 157) 10.2
...
</code>```

Body:
I have an enum with an explicit underlying type definition like this:

enum test : uint16_t
{
    test_x = 0x7fff, // 0111 1111 1111 1111
    test_y = 0x8000  // 1000 0000 0000 0000
};

And variables in my code that are assigned the enum values like this:

test num1 = test_x;
test num2 = test_y;

When I try to look at the value using GDB, I get this kind of result:

(gdb) print num1
$1 = test_x
(gdb) print num2
$2 = (test_y | unknown: -65536)

Why is num2 acting so strange? Its value is in the range of the type I declared,
so what is wrong with this configuration?

I will also point out that this happens not just with uint16_t but with uint32_t and the values test_x = 0x7fffffff, test_y = 0x80000000.

Edit

I am compiling with GNU GCC version: 9.3.0 on ARM processor platform and using GDB version 8.1.0.

Body:
I will answer my own question after getting some helpful pointers in the comments.

This turned out to really be a bug in the GDB version I was using.
upgrading to a newer version solves this issue.
(I upgraded from 8.1 to 10.2)

(gdb) print num1
$1 = test_x
(gdb) print num2
$2 = test_y
(gdb) show version
GNU gdb (GDB; JetBrains IDE bundle; build 157) 10.2
...


问:
How to run method in every 5 minute in .net core windows background service
I have created windows background service using .net core. So I need to run following Get method in every 5 minute using timer.

```<code>public async Task<ActionResult> Get()
    {
        var result = new List<string>();
        var client = new HttpClient();
        var payload = "{\r\n  \"api\": {\r\n \"NAME\":\"QUERY\"\r\n},\r\n\"header\" : {\r\n\"QUERY\":\"select UPLOAD_RECEIPT_HEADER.INTERFACE_RECORD_ID, UPLOAD_RECEIPT_HEADER.USER_DEF3 As SOURCE_TRANSACTION_ID,UPLOAD_RECEIPT_DETAIL.ERP_ORDER_LINE_NUM, UPLOAD_RECEIPT_DETAIL.ITEM, UPLOAD_RECEIPT_DETAIL.USER_DEF3 As FULLFILLMENT_LINE_ID from UPLOAD_RECEIPT_HEADER join UPLOAD_RECEIPT_DETAIL on UPLOAD_RECEIPT_DETAIL.INTERFACE_LINK_ID = UPLOAD_RECEIPT_HEADER.INTERFACE_RECORD_ID where UPLOAD_RECEIPT_HEADER.Close_date is not null and UPLOAD_RECEIPT_DETAIL.USER_DEF6 is null\"\r\n }\r\n}";
        var stringContent = new StringContent(payload, Encoding.UTF8, "application/json");
        var baseUrl = iniFile.GetValue("GLOBAL", "DB_DATA_SERVICE", null);
        var response = await client.PostAsync(baseUrl, stringContent);
        var json = await response.Content.ReadAsStringAsync();
        if (response.IsSuccessStatusCode)
        {
            var uploadOrder = JsonConvert.DeserializeObject<UploadOrder>(json);
            var details = uploadOrder.LineItems.GroupBy(x => x.INTERFACE_RECORD_ID);
            foreach (var obj in details)
            {
                if (obj.Any())
                {
                    var order = new Order();
                    order.SourceTransactionId = obj.FirstOrDefault().SOURCE_TRANSACTION_ID;
                    order.Lines = new List<Line>();
                    foreach (var line in obj)
                    {
                        var l = new Line();
                        l.FullfillmentLineId = line.FULLFILLMENT_LINE_ID;
                        l.LineNumber = line.ERP_ORDER_LINE_NUM;
                        l.ItemNumber = line.ITEM;
                        l.StatusCode = "SHIPPED";
                        l.Status = "Shipped";
                        order.Lines.Add(l);
                    }
                    var orders = new Orders();
                    orders.orders = new List<Order>();
                    orders.orders.Add(order);
                    var a = await OicCall(orders, obj.Key);
                    result.Add(a);
                }
            }
        }
        return Ok(String.Join(", ", result));
    }

 private void PublishEvent(object? state){
    // need to use Get method in here
 }

public void start() {
   // _timer = new Timer(PublishEvent, null, TimeSpan.Zero,TimeSpan.FromMinutes(this.TimePeriod));
   // Need to use PublishEvent in here
}
</code>```

答:
```<code>public class Processor : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken token)
    {
        await Task.Yield();

        while (token.IsCancellationRequested == false)
        {
            await Task.Delay(300000, token);
            await ExecuteGetMethod();
        }
    }
}

// Startup.cs
services.AddHostedService<Processor>();
</code>```

Body:
I have created windows background service using .net core. So I need to run following Get method in every 5 minute using timer.

public async Task<ActionResult> Get()
    {
        var result = new List<string>();
        var client = new HttpClient();
        var payload = "{\r\n  \"api\": {\r\n \"NAME\":\"QUERY\"\r\n},\r\n\"header\" : {\r\n\"QUERY\":\"select UPLOAD_RECEIPT_HEADER.INTERFACE_RECORD_ID, UPLOAD_RECEIPT_HEADER.USER_DEF3 As SOURCE_TRANSACTION_ID,UPLOAD_RECEIPT_DETAIL.ERP_ORDER_LINE_NUM, UPLOAD_RECEIPT_DETAIL.ITEM, UPLOAD_RECEIPT_DETAIL.USER_DEF3 As FULLFILLMENT_LINE_ID from UPLOAD_RECEIPT_HEADER join UPLOAD_RECEIPT_DETAIL on UPLOAD_RECEIPT_DETAIL.INTERFACE_LINK_ID = UPLOAD_RECEIPT_HEADER.INTERFACE_RECORD_ID where UPLOAD_RECEIPT_HEADER.Close_date is not null and UPLOAD_RECEIPT_DETAIL.USER_DEF6 is null\"\r\n }\r\n}";
        var stringContent = new StringContent(payload, Encoding.UTF8, "application/json");
        var baseUrl = iniFile.GetValue("GLOBAL", "DB_DATA_SERVICE", null);
        var response = await client.PostAsync(baseUrl, stringContent);
        var json = await response.Content.ReadAsStringAsync();
        if (response.IsSuccessStatusCode)
        {
            var uploadOrder = JsonConvert.DeserializeObject<UploadOrder>(json);
            var details = uploadOrder.LineItems.GroupBy(x => x.INTERFACE_RECORD_ID);
            foreach (var obj in details)
            {
                if (obj.Any())
                {
                    var order = new Order();
                    order.SourceTransactionId = obj.FirstOrDefault().SOURCE_TRANSACTION_ID;
                    order.Lines = new List<Line>();
                    foreach (var line in obj)
                    {
                        var l = new Line();
                        l.FullfillmentLineId = line.FULLFILLMENT_LINE_ID;
                        l.LineNumber = line.ERP_ORDER_LINE_NUM;
                        l.ItemNumber = line.ITEM;
                        l.StatusCode = "SHIPPED";
                        l.Status = "Shipped";
                        order.Lines.Add(l);
                    }
                    var orders = new Orders();
                    orders.orders = new List<Order>();
                    orders.orders.Add(order);
                    var a = await OicCall(orders, obj.Key);
                    result.Add(a);
                }
            }
        }
        return Ok(String.Join(", ", result));
    }

 private void PublishEvent(object? state){
    // need to use Get method in here
 }

public void start() {
   // _timer = new Timer(PublishEvent, null, TimeSpan.Zero,TimeSpan.FromMinutes(this.TimePeriod));
   // Need to use PublishEvent in here
}


问:
Extracting substring with awk if the string includes regular expressions
I have many strings like this

```<code>i=./M1/CustomersList/HTP/Boston/FCT/output_GetCaseList_abs.txt
</code>```

I need to extract the M1 code and the FCT but I am unable to do so, likely due to the regular expressions. FCT I can do with echo ${i:30:3}, but for M1 nothing seems to work - my last try was grep -oP '.*\K(?<=.\/)\w+(?=\/Cus)' $i ;

The length of the string can vary (but it always starts with /F) and /M1/ is always in the same position

Hope somebody can help. Thanks!

答:
Another option with awk is split() to split the path components into an array. The array a[] is filled by the command below and the 2nd and 6th elements ("M1", and "FCT")

awk '{split($1,a,"/"); print a[2]", "a[6]}'
```
<p><strong>Example Use/Output</strong></p>
<pre class="lang-sh prettyprint-override"><code>$ i=./M1/CustomersList/HTP/Boston/FCT/output_GetCaseList_abs.txt; echo "$i" |
awk '{split($1,a,"/"); print a[2]", "a[6]}'
M1, FCT
</code>```

Body:
I have many strings like this

i=./M1/CustomersList/HTP/Boston/FCT/output_GetCaseList_abs.txt

I need to extract the M1 code and the FCT but I am unable to do so, likely due to the regular expressions. FCT I can do with echo ${i:30:3}, but for M1 nothing seems to work - my last try was grep -oP '.*\K(?<=.\/)\w+(?=\/Cus)' $i ;

The length of the string can vary (but it always starts with /F) and /M1/ is always in the same position

Hope somebody can help. Thanks!

Body:
Another option with awk is split() to split the path components into an array. The array a[] is filled by the command below and the 2nd and 6th elements ("M1", and "FCT")

awk '{split($1,a,"/"); print a[2]", "a[6]}'

Example Use/Output

$ i=./M1/CustomersList/HTP/Boston/FCT/output_GetCaseList_abs.txt; echo "$i" |
awk '{split($1,a,"/"); print a[2]", "a[6]}'
M1, FCT


问:
Extract values from multiple elements and format them on the clipboard to paste into spreadsheet - JavaScript
I have a form with 21 elements of types 'input', 'select' and 'textArea', and I have an array of 21 element id's that correspond to these elements.

I'm trying to extract the 21 values of these elements and concatenate them into one long string, with a tab inserted between each value. The intention is to put this string on the clipboard and manually paste it into a row on a spreadsheet.

In the (non working) code below, at the line 'nextValue = ...' , the console says that nextElement is null, indicating that an element with that id doesn't exist.  But it does exist.  Could someone please point out what I'm doing wrong here?  Thanks.

```<code>//this function is called by the onclick event of a button.
function clipToExcel() {
     let element_Ids = ['id1', 'id2', 'id3', 'id4', 'id5', 'id6', 'id7', 'id8',
                        'id9', 'id10',  'id11', 'id12', 'id13',  'id14', 'id15',
                        'id16', 'id17', 'id18', 'id19', 'id20', 'id21'];

     let nextElement, nextValue, valueString = "";
     for (let i = 0;  i < element_Ids.length;  i++) {
       nextElement = document.getElementById(element_Ids[i]);
       nextValue = nextElement.value;
// console.log(nextValue);
       valueString += nextValue + "\t";
     }
     navigator.clipboard.writeText(valueString);

     alert('Data is now on the Clipboard in a format that can be Pasted into Excel');
}
</code>```

答:
You have everything in a <form> then it's easier than you think. Details are commented in example below. For more info on the form interface read on .elements property.

// Reference the form
const form = document.forms[0];
// Reference all fields of form
const io = form.elements;
// this is just to generate inputs for demo
for (let i = 0; i < 21; i++) {
  io[i].value = i;
}

/*
Gather all form controls into a
HTMLCollection then convert it into an array
*/
const allFieldsNamedA = io.A;

// Iterate with .map()
const str = [...allFieldsNamedA].map(inp => inp.value + '\t');

// Then .join() the array into one string
console.log(str.join(''));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-row::after {
  width: 0;
  font-size: 0;
}

.as-console-row-code {
  width: 100%;
  word-break: break-word;
}</code>```

<form>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
</form>```

Body:
I have a form with 21 elements of types 'input', 'select' and 'textArea', and I have an array of 21 element id's that correspond to these elements.

I'm trying to extract the 21 values of these elements and concatenate them into one long string, with a tab inserted between each value. The intention is to put this string on the clipboard and manually paste it into a row on a spreadsheet.

In the (non working) code below, at the line 'nextValue = ...' , the console says that nextElement is null, indicating that an element with that id doesn't exist.  But it does exist.  Could someone please point out what I'm doing wrong here?  Thanks.

//this function is called by the onclick event of a button.
function clipToExcel() {
     let element_Ids = ['id1', 'id2', 'id3', 'id4', 'id5', 'id6', 'id7', 'id8',
                        'id9', 'id10',  'id11', 'id12', 'id13',  'id14', 'id15',
                        'id16', 'id17', 'id18', 'id19', 'id20', 'id21'];

     let nextElement, nextValue, valueString = "";
     for (let i = 0;  i < element_Ids.length;  i++) {
       nextElement = document.getElementById(element_Ids[i]);
       nextValue = nextElement.value;
// console.log(nextValue);
       valueString += nextValue + "\t";
     }
     navigator.clipboard.writeText(valueString);

     alert('Data is now on the Clipboard in a format that can be Pasted into Excel');
}

Body:
You have everything in a <form> then it's easier than you think. Details are commented in example below. For more info on the form interface read on .elements property.

// Reference the form
const form = document.forms[0];
// Reference all fields of form
const io = form.elements;
// this is just to generate inputs for demo
for (let i = 0; i < 21; i++) {
  io[i].value = i;
}

/*
Gather all form controls into a
HTMLCollection then convert it into an array
*/
const allFieldsNamedA = io.A;

// Iterate with .map()
const str = [...allFieldsNamedA].map(inp => inp.value + '\t');

// Then .join() the array into one string
console.log(str.join(''));

.as-console-row::after {
  width: 0;
  font-size: 0;
}

.as-console-row-code {
  width: 100%;
  word-break: break-word;
}

<form>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
</form>


问:
How to create Kafka-python producer with ssl configuration
I'm trying to create kafka producer with ssl. I need information on how to set SSL parameters in the constructor, the information provided in kafka-python client is not descriptive enough.

What are the ssl_certfile, ssl_cafile, ssl_keyfile parameters. I'm not sure where to look for these files.

```<code>producer = KafkaProducer(bootstrap_servers=kafka_broker,
  value_serializer=lambda v: json.dumps(v).encode('utf-8'),
  security_protocol='SSL',
  api_version=(0,10),
  ssl_cafile='ca-certs.pem',ssl_certfile='server.pem',
  ssl_keyfile='server.pem',ssl_password='xxx')
producer.send('rk976772_topic',{"test":0})
</code>```

Traceback (most recent call last):   File "", line 1, in
     File
  "/usr/lib/python2.7/site-packages/kafka/producer/kafka.py", line 543,
  in send
      self._wait_on_metadata(topic, self.config['max_block_ms'] / 1000.0)   File "/usr/lib/python2.7/site-packages/kafka/producer/kafka.py", line 664,
  in _wait_on_metadata
      "Failed to update metadata after %.1f secs." % max_wait) kafka.errors.KafkaTimeoutError: KafkaTimeoutError: Failed to update
  metadata after 60.0 secs.

答:
Thanks Alot. I was having jks file and my kafka-producer was giving continuously error SSL Certification verify error 897
Though converted the CARoot.pem file but it was not working.

What helped is I  converted using the below command and used on producer and it worked.

```<code>kafka.server.keystore.jks,
kafka.server.truststore.jks,
kafka.client.truststore.jks,
ca-cert,
ca-cert.srl,
ca-key, cert-file,
cert-signed,
CARoot.pem
</code>```

Body:
I'm trying to create kafka producer with ssl. I need information on how to set SSL parameters in the constructor, the information provided in kafka-python client is not descriptive enough.

What are the ssl_certfile, ssl_cafile, ssl_keyfile parameters. I'm not sure where to look for these files.

producer = KafkaProducer(bootstrap_servers=kafka_broker,
  value_serializer=lambda v: json.dumps(v).encode('utf-8'),
  security_protocol='SSL',
  api_version=(0,10),
  ssl_cafile='ca-certs.pem',ssl_certfile='server.pem',
  ssl_keyfile='server.pem',ssl_password='xxx')
producer.send('rk976772_topic',{"test":0})

Traceback (most recent call last):   File "", line 1, in
     File
  "/usr/lib/python2.7/site-packages/kafka/producer/kafka.py", line 543,
  in send
      self._wait_on_metadata(topic, self.config['max_block_ms'] / 1000.0)   File "/usr/lib/python2.7/site-packages/kafka/producer/kafka.py", line 664,
  in _wait_on_metadata
      "Failed to update metadata after %.1f secs." % max_wait) kafka.errors.KafkaTimeoutError: KafkaTimeoutError: Failed to update
  metadata after 60.0 secs.

Body:
Thanks Alot. I was having jks file and my kafka-producer was giving continuously error SSL Certification verify error 897
Though converted the CARoot.pem file but it was not working.

What helped is I  converted using the below command and used on producer and it worked.

kafka.server.keystore.jks,
kafka.server.truststore.jks,
kafka.client.truststore.jks,
ca-cert,
ca-cert.srl,
ca-key, cert-file,
cert-signed,
CARoot.pem


问:
Issue while adding a cookie in Chrome dev tools

I am getting this issue while adding a cookie in Chrome dev tools (it gets highlighted in red), so I am not able to add any cookies. I even tried to reset the Chrome browser, but it's not working.

答:
If you update your chrome or restart your laptop recently(10-Feb-2022), you cannot add cookies manually in chrome now. The reason is the newest update of Chome disable the SameSite by default cookies setting.

the solution is:

open this url in chrome: chrome://flags

search Partitioned cookies, and enable it


问:
Error on building a Cuda static library from Visual Studio 2019 on Windows 10
I am trying to build a cuda static library using Visual Studio 2019. My end goal is to link this .lib file from a Unreal Engine C++ script.

Expected result is a .lib file in the x64/Release folder but I am getting following error on building:

After downloading Cuda 11.6, I created a project using the Cuda template in VS2019. I was following steps from this blog. I split the default kernel.cu into cuda_ue.cu & cuda_ue.h as below:

cuda_ue.cu

```<code>#include "cuda_ue.h"

__global__ void addKernel(int *c, const int *a, const int *b)
{
    int i = threadIdx.x;
    c[i] = a[i] + b[i];
}

//int main()
//{
//    const int arraySize = 5;
//    const int a[arraySize] = { 1, 2, 3, 4, 5 };
//    const int b[arraySize] = { 10, 20, 30, 40, 50 };
//    int c[arraySize] = { 0 };
//
//    // Add vectors in parallel.
//    cudaError_t cudaStatus = addWithCuda(c, a, b, arraySize);
//    if (cudaStatus != cudaSuccess) {
//        fprintf(stderr, "addWithCuda failed!");
//        return 1;
//    }
//
//    printf("{1,2,3,4,5} + {10,20,30,40,50} = {%d,%d,%d,%d,%d}\n",
//        c[0], c[1], c[2], c[3], c[4]);
//
//    // cudaDeviceReset must be called before exiting in order for profiling and
//    // tracing tools such as Nsight and Visual Profiler to show complete traces.
//    cudaStatus = cudaDeviceReset();
//    if (cudaStatus != cudaSuccess) {
//        fprintf(stderr, "cudaDeviceReset failed!");
//        return 1;
//    }
//
//    return 0;
//}

// Helper function for using CUDA to add vectors in parallel.
cudaError_t addWithCuda(int* c, const int* a, const int* b, unsigned int size, std::string* error_message)
{
    int* dev_a = 0;
    int* dev_b = 0;
    int* dev_c = 0;
    cudaError_t cuda_status;

    // Choose which GPU to run on, change this on a multi-GPU system.
    cuda_status = cudaSetDevice(0);
    if (cuda_status != cudaSuccess) {
        *error_message = "cudaSetDevice failed!  Do you have a CUDA-capable GPU installed?";
        goto Error;
    }

    // Allocate GPU buffers for three vectors (two input, one output)    .
    cuda_status = cudaMalloc((void**)&dev_c, size * sizeof(int));
    if (cuda_status != cudaSuccess) {
        *error_message = "cudaMalloc failed!";
        goto Error;
    }

    cuda_status = cudaMalloc((void**)&dev_a, size * sizeof(int));
    if (cuda_status != cudaSuccess) {
        *error_message = "cudaMalloc failed!";
        goto Error;
    }

    cuda_status = cudaMalloc((void**)&dev_b, size * sizeof(int));
    if (cuda_status != cudaSuccess) {
        *error_message = "cudaMalloc failed!";
        goto Error;
    }

    // Copy input vectors from host memory to GPU buffers.
    cuda_status = cudaMemcpy(dev_a, a, size * sizeof(int), cudaMemcpyHostToDevice);
    if (cuda_status != cudaSuccess) {
        *error_message = "cudaMemcpy failed!";
        goto Error;
    }

    cuda_status = cudaMemcpy(dev_b, b, size * sizeof(int), cudaMemcpyHostToDevice);
    if (cuda_status != cudaSuccess) {
        *error_message = "cudaMemcpy failed!";
        goto Error;
    }

    // Launch a kernel on the GPU with one thread for each element.
    addKernel << <1, size >> > (dev_c, dev_a, dev_b);

    // Check for any errors launching the kernel
    cuda_status = cudaGetLastError();
    if (cuda_status != cudaSuccess) {
        *error_message = "addKernel launch failed: " + std::string(cudaGetErrorString(cuda_status));
        goto Error;
    }

    // cudaDeviceSynchronize waits for the kernel to finish, and returns
    // any errors encountered during the launch.
    cuda_status = cudaDeviceSynchronize();
    if (cuda_status != cudaSuccess) {
        *error_message = "cudaDeviceSynchronize returned error code " + std::to_string(cuda_status) + " after launching addKernel!";
        goto Error;
    }

    // Copy output vector from GPU buffer to host memory.
    cuda_status = cudaMemcpy(c, dev_c, size * sizeof(int), cudaMemcpyDeviceToHost);
    if (cuda_status != cudaSuccess) {
        *error_message = "cudaMemcpy failed!";
        goto Error;
    }

Error:
    cudaFree(dev_c);
    cudaFree(dev_a);
    cudaFree(dev_b);

    return cuda_status;
}
</code>```

cuda_ue.h

```<code>#include <string>
#include <stdio.h>
#include "cuda_runtime.h"
#include "device_launch_parameters.h"

cudaError_t addWithCuda(int* c, const int* a, const int* b, unsigned int size, std::string* error_message);

</code>```

As per the blog I changed Debug to Release as well configuration type to "Static library". I can't understand anything about the cause from this error message.

How can I build a cuda static library with configuration as Release?

I am also including the VS2019 output with verbosity level as 'Normal':

```<code>Build started...
1>------ Build started: Project: cuda_ue_vs, Configuration: Release x64 ------
1>Build started 2/9/2022 5:24:40 AM.
1>Target InitializeBuildStatus:
1>  Touching "x64\Release\cuda_ue_vs.tlog\unsuccessfulbuild".
1>Target CudaBuild:
1>  Target CudaBuildCore:
1>    Compiling CUDA source file cuda_ue.cu...
1>
1>    C:\Users\htic\Documents\Unreal Projects\cuda_ue_vs>"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.6\bin\nvcc.exe" -gencode=arch=compute_52,code=\"sm_52,compute_52\" --use-local-env -ccbin "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\bin\HostX86\x64" -x cu   -I"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.6\include" -I"C:\vcpkg\installed\x64-windows\include" -I"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.6\include"     --keep-dir x64\Release  -maxrregcount=0  --machine 64 --compile -cudart static    -DWIN32 -DWIN64 -DNDEBUG -D_CONSOLE -D_MBCS -Xcompiler "/EHsc /W3 /nologo /O2 /Fd"C:\Users\htic\Documents\Unreal Projects\cuda_ue_vs\x64\Release\cuda_ue_vs.pdb" /FS   /MD " -o x64\Release\cuda_ue.cu.obj "C:\Users\htic\Documents\Unreal Projects\cuda_ue_vs\cuda_ue.cu"
1>    nvcc fatal   : A single input file is required for a non-link phase when an outputfile is specified
1>    C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Microsoft\VC\v160\BuildCustomizations\CUDA 11.6.targets(790,9): error MSB3721: The command ""C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.6\bin\nvcc.exe" -gencode=arch=compute_52,code=\"sm_52,compute_52\" --use-local-env -ccbin "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\bin\HostX86\x64" -x cu   -I"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.6\include" -I"C:\vcpkg\installed\x64-windows\include" -I"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.6\include"     --keep-dir x64\Release  -maxrregcount=0  --machine 64 --compile -cudart static    -DWIN32 -DWIN64 -DNDEBUG -D_CONSOLE -D_MBCS -Xcompiler "/EHsc /W3 /nologo /O2 /Fd"C:\Users\htic\Documents\Unreal Projects\cuda_ue_vs\x64\Release\cuda_ue_vs.pdb" /FS   /MD " -o x64\Release\cuda_ue.cu.obj "C:\Users\htic\Documents\Unreal Projects\cuda_ue_vs\cuda_ue.cu"" exited with code 1.
1>  Done building target "CudaBuildCore" in project "cuda_ue_vs.vcxproj" -- FAILED.
1>
1>  Done building project "cuda_ue_vs.vcxproj" -- FAILED.
1>
1>Build FAILED.
1>
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Microsoft\VC\v160\BuildCustomizations\CUDA 11.6.targets(790,9): error MSB3721: The command ""C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.6\bin\nvcc.exe" -gencode=arch=compute_52,code=\"sm_52,compute_52\" --use-local-env -ccbin "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\bin\HostX86\x64" -x cu   -I"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.6\include" -I"C:\vcpkg\installed\x64-windows\include" -I"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.6\include"     --keep-dir x64\Release  -maxrregcount=0  --machine 64 --compile -cudart static    -DWIN32 -DWIN64 -DNDEBUG -D_CONSOLE -D_MBCS -Xcompiler "/EHsc /W3 /nologo /O2 /Fd"C:\Users\htic\Documents\Unreal Projects\cuda_ue_vs\x64\Release\cuda_ue_vs.pdb" /FS   /MD " -o x64\Release\cuda_ue.cu.obj "C:\Users\htic\Documents\Unreal Projects\cuda_ue_vs\cuda_ue.cu"" exited with code 1.
1>    0 Warning(s)
1>    1 Error(s)
1>
1>Time Elapsed 00:00:00.65
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
</code>```

答:
Solved myself:
It was a silly fix, folder names should not have a space. Seems like nvcc then consider it as two files.</p>

Body:
I am trying to build a cuda static library using Visual Studio 2019. My end goal is to link this .lib file from a Unreal Engine C++ script.

Expected result is a .lib file in the x64/Release folder but I am getting following error on building:

After downloading Cuda 11.6, I created a project using the Cuda template in VS2019. I was following steps from this blog. I split the default kernel.cu into cuda_ue.cu & cuda_ue.h as below:

cuda_ue.cu

#include "cuda_ue.h"

__global__ void addKernel(int *c, const int *a, const int *b)
{
    int i = threadIdx.x;
    c[i] = a[i] + b[i];
}

//int main()
//{
//    const int arraySize = 5;
//    const int a[arraySize] = { 1, 2, 3, 4, 5 };
//    const int b[arraySize] = { 10, 20, 30, 40, 50 };
//    int c[arraySize] = { 0 };
//
//    // Add vectors in parallel.
//    cudaError_t cudaStatus = addWithCuda(c, a, b, arraySize);
//    if (cudaStatus != cudaSuccess) {
//        fprintf(stderr, "addWithCuda failed!");
//        return 1;
//    }
//
//    printf("{1,2,3,4,5} + {10,20,30,40,50} = {%d,%d,%d,%d,%d}\n",
//        c[0], c[1], c[2], c[3], c[4]);
//
//    // cudaDeviceReset must be called before exiting in order for profiling and
//    // tracing tools such as Nsight and Visual Profiler to show complete traces.
//    cudaStatus = cudaDeviceReset();
//    if (cudaStatus != cudaSuccess) {
//        fprintf(stderr, "cudaDeviceReset failed!");
//        return 1;
//    }
//
//    return 0;
//}

// Helper function for using CUDA to add vectors in parallel.
cudaError_t addWithCuda(int* c, const int* a, const int* b, unsigned int size, std::string* error_message)
{
    int* dev_a = 0;
    int* dev_b = 0;
    int* dev_c = 0;
    cudaError_t cuda_status;

    // Choose which GPU to run on, change this on a multi-GPU system.
    cuda_status = cudaSetDevice(0);
    if (cuda_status != cudaSuccess) {
        *error_message = "cudaSetDevice failed!  Do you have a CUDA-capable GPU installed?";
        goto Error;
    }

    // Allocate GPU buffers for three vectors (two input, one output)    .
    cuda_status = cudaMalloc((void**)&dev_c, size * sizeof(int));
    if (cuda_status != cudaSuccess) {
        *error_message = "cudaMalloc failed!";
        goto Error;
    }

    cuda_status = cudaMalloc((void**)&dev_a, size * sizeof(int));
    if (cuda_status != cudaSuccess) {
        *error_message = "cudaMalloc failed!";
        goto Error;
    }

    cuda_status = cudaMalloc((void**)&dev_b, size * sizeof(int));
    if (cuda_status != cudaSuccess) {
        *error_message = "cudaMalloc failed!";
        goto Error;
    }

    // Copy input vectors from host memory to GPU buffers.
    cuda_status = cudaMemcpy(dev_a, a, size * sizeof(int), cudaMemcpyHostToDevice);
    if (cuda_status != cudaSuccess) {
        *error_message = "cudaMemcpy failed!";
        goto Error;
    }

    cuda_status = cudaMemcpy(dev_b, b, size * sizeof(int), cudaMemcpyHostToDevice);
    if (cuda_status != cudaSuccess) {
        *error_message = "cudaMemcpy failed!";
        goto Error;
    }

    // Launch a kernel on the GPU with one thread for each element.
    addKernel << <1, size >> > (dev_c, dev_a, dev_b);

    // Check for any errors launching the kernel
    cuda_status = cudaGetLastError();
    if (cuda_status != cudaSuccess) {
        *error_message = "addKernel launch failed: " + std::string(cudaGetErrorString(cuda_status));
        goto Error;
    }

    // cudaDeviceSynchronize waits for the kernel to finish, and returns
    // any errors encountered during the launch.
    cuda_status = cudaDeviceSynchronize();
    if (cuda_status != cudaSuccess) {
        *error_message = "cudaDeviceSynchronize returned error code " + std::to_string(cuda_status) + " after launching addKernel!";
        goto Error;
    }

    // Copy output vector from GPU buffer to host memory.
    cuda_status = cudaMemcpy(c, dev_c, size * sizeof(int), cudaMemcpyDeviceToHost);
    if (cuda_status != cudaSuccess) {
        *error_message = "cudaMemcpy failed!";
        goto Error;
    }

Error:
    cudaFree(dev_c);
    cudaFree(dev_a);
    cudaFree(dev_b);

    return cuda_status;
}

cuda_ue.h

#include <string>
#include <stdio.h>
#include "cuda_runtime.h"
#include "device_launch_parameters.h"

cudaError_t addWithCuda(int* c, const int* a, const int* b, unsigned int size, std::string* error_message);

As per the blog I changed Debug to Release as well configuration type to "Static library". I can't understand anything about the cause from this error message.

How can I build a cuda static library with configuration as Release?

I am also including the VS2019 output with verbosity level as 'Normal':

Build started...
1>------ Build started: Project: cuda_ue_vs, Configuration: Release x64 ------
1>Build started 2/9/2022 5:24:40 AM.
1>Target InitializeBuildStatus:
1>  Touching "x64\Release\cuda_ue_vs.tlog\unsuccessfulbuild".
1>Target CudaBuild:
1>  Target CudaBuildCore:
1>    Compiling CUDA source file cuda_ue.cu...
1>
1>    C:\Users\htic\Documents\Unreal Projects\cuda_ue_vs>"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.6\bin\nvcc.exe" -gencode=arch=compute_52,code=\"sm_52,compute_52\" --use-local-env -ccbin "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\bin\HostX86\x64" -x cu   -I"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.6\include" -I"C:\vcpkg\installed\x64-windows\include" -I"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.6\include"     --keep-dir x64\Release  -maxrregcount=0  --machine 64 --compile -cudart static    -DWIN32 -DWIN64 -DNDEBUG -D_CONSOLE -D_MBCS -Xcompiler "/EHsc /W3 /nologo /O2 /Fd"C:\Users\htic\Documents\Unreal Projects\cuda_ue_vs\x64\Release\cuda_ue_vs.pdb" /FS   /MD " -o x64\Release\cuda_ue.cu.obj "C:\Users\htic\Documents\Unreal Projects\cuda_ue_vs\cuda_ue.cu"
1>    nvcc fatal   : A single input file is required for a non-link phase when an outputfile is specified
1>    C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Microsoft\VC\v160\BuildCustomizations\CUDA 11.6.targets(790,9): error MSB3721: The command ""C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.6\bin\nvcc.exe" -gencode=arch=compute_52,code=\"sm_52,compute_52\" --use-local-env -ccbin "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\bin\HostX86\x64" -x cu   -I"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.6\include" -I"C:\vcpkg\installed\x64-windows\include" -I"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.6\include"     --keep-dir x64\Release  -maxrregcount=0  --machine 64 --compile -cudart static    -DWIN32 -DWIN64 -DNDEBUG -D_CONSOLE -D_MBCS -Xcompiler "/EHsc /W3 /nologo /O2 /Fd"C:\Users\htic\Documents\Unreal Projects\cuda_ue_vs\x64\Release\cuda_ue_vs.pdb" /FS   /MD " -o x64\Release\cuda_ue.cu.obj "C:\Users\htic\Documents\Unreal Projects\cuda_ue_vs\cuda_ue.cu"" exited with code 1.
1>  Done building target "CudaBuildCore" in project "cuda_ue_vs.vcxproj" -- FAILED.
1>
1>  Done building project "cuda_ue_vs.vcxproj" -- FAILED.
1>
1>Build FAILED.
1>
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Microsoft\VC\v160\BuildCustomizations\CUDA 11.6.targets(790,9): error MSB3721: The command ""C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.6\bin\nvcc.exe" -gencode=arch=compute_52,code=\"sm_52,compute_52\" --use-local-env -ccbin "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\bin\HostX86\x64" -x cu   -I"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.6\include" -I"C:\vcpkg\installed\x64-windows\include" -I"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.6\include"     --keep-dir x64\Release  -maxrregcount=0  --machine 64 --compile -cudart static    -DWIN32 -DWIN64 -DNDEBUG -D_CONSOLE -D_MBCS -Xcompiler "/EHsc /W3 /nologo /O2 /Fd"C:\Users\htic\Documents\Unreal Projects\cuda_ue_vs\x64\Release\cuda_ue_vs.pdb" /FS   /MD " -o x64\Release\cuda_ue.cu.obj "C:\Users\htic\Documents\Unreal Projects\cuda_ue_vs\cuda_ue.cu"" exited with code 1.
1>    0 Warning(s)
1>    1 Error(s)
1>
1>Time Elapsed 00:00:00.65
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========


问:
How to change the default folder of downloading (for browser)?
I am using this code to download songs from a Uri.

```<code>String url = "url of song that will download";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
Download.this.startActivity(intent);
Download.this.finish();
Toast.makeText(Download.this,
  "The file you are downloading will be saved in your SD Card downloads folder.",
  Toast.LENGTH_LONG).show();
</code>```

By default my songs saved in SDCards/Downloads folder.i want to save my songs in SDCards/Device folder.

Kindly suggest me, how can i change the downloading path of browser programmatically.

Thanks in Advance.

答: As far as I'm aware, you cannot change browser settings by code. Sorry.</p>

Body:
I am using this code to download songs from a Uri.

String url = "url of song that will download";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
Download.this.startActivity(intent);
Download.this.finish();
Toast.makeText(Download.this,
  "The file you are downloading will be saved in your SD Card downloads folder.",
  Toast.LENGTH_LONG).show();

By default my songs saved in SDCards/Downloads folder.i want to save my songs in SDCards/Device folder.

Kindly suggest me, how can i change the downloading path of browser programmatically.

Thanks in Advance.


问:
Identifying multiple instances of same component
I have two instances of the same component, say <parent>, on the same page. This  component has 3 child levels, lets call them, <childL1>, <childL2> and <childL3>. So, I have two instances of <childL3> as well.

Now, I want to identify which <childL3> belongs to which <parent> component. I don't want to pass parent id through 3 child levels using @Input decorator (which seems to be the only option I have currently). And using the service, we can't identify the child components because both childL3 would be subscribed to the same service.

I would really appreciate any suggestions.

答:
You can simply inject the correct parent component into your <childL3>. Just try:

```<code>@Component({
  selector: 'app-child-l3',
  templateUrl: './child-l3.component.html',
  styleUrls: ['./child-l3.component.scss']
})
export class ChildL3Component {

  constructor(private parent: ParentComponent) {

  }
}
</code>```

Each ChildL3 should get the correct parent from its own component tree.

Body:
You can simply inject the correct parent component into your <childL3>. Just try:

@Component({
  selector: 'app-child-l3',
  templateUrl: './child-l3.component.html',
  styleUrls: ['./child-l3.component.scss']
})
export class ChildL3Component {

  constructor(private parent: ParentComponent) {

  }
}

Each ChildL3 should get the correct parent from its own component tree.


问:
Cypress: Alternative for command 'wait'
I am looking for an alternative to the wait command.

As we all know, a page/component/etc. does not take the same time to load or simply be available every time it is called.
For this reason, I cannot rely on the 'wait' command with constant time specification.

So I am looking for an alternative.

Some people on the internet write that the command 'then' helps to wait until the condition is fulfilled.
Unfortunately, the following alternative does not work in my case:

```<code>cy.get(#element).should('exist').then(() =>{
   cy.get(#element).click();
});
</code>```

I am looking forward to your messages and alternatives to 'wait'.
Many greetings Janni

答:
My problem is not to wait till the page is successfully loaded, but till the content exist and is available/clickable etc.

With this command a small improvement is noted but is not the solution of my problem.

```<code>Cypress.config('defaultCommandTimeout', 50000);
</code>```

Title: Cypress: Alternative for command 'wait'

Body:
I am looking for an alternative to the wait command.

As we all know, a page/component/etc. does not take the same time to load or simply be available every time it is called.
For this reason, I cannot rely on the 'wait' command with constant time specification.

So I am looking for an alternative.

Some people on the internet write that the command 'then' helps to wait until the condition is fulfilled.
Unfortunately, the following alternative does not work in my case:

cy.get(#element).should('exist').then(() =>{
   cy.get(#element).click();
});

I am looking forward to your messages and alternatives to 'wait'.
Many greetings Janni

Body:
My problem is not to wait till the page is successfully loaded, but till the content exist and is available/clickable etc.

With this command a small improvement is noted but is not the solution of my problem.

Cypress.config('defaultCommandTimeout', 50000);


问:
How can I pass null from react native to java when I develop a module
I'm developing a native module for Android in React Native. I have two method with the same name but I can't use them in React Native because Java Script has not overloading directly. So I write a function which can get null as a paramater in React Native and try to handle it in Java.

React Native side:

```<code>    function a(arg=null){
       moduleName.b(arg)
    }
</code>```

Java side:

```<code>public void b(@Nullable Boolean arg, final Promise promise){
  if(arg == null){
    c()
  }else{
    c(arg)
  }
}
</code>```

Then I have not problem when I pass true or false to function a but when I pass nothing to funtion a I get an error on my phone like that:

What is the problem?

答:
This can be due to multiple things going wrong into code. Some areas which needs to look are:

use boolean instead of Boolean in your Java code.

try checking if your getIntent() function is not returning null intent , just before receiving intent from bundle.

You are trying to check Boolean with null , that's why it's throwing java.lang.Boolean on a null object reference.

Body:
I'm developing a native module for Android in React Native. I have two method with the same name but I can't use them in React Native because Java Script has not overloading directly. So I write a function which can get null as a paramater in React Native and try to handle it in Java.

React Native side:

    function a(arg=null){
       moduleName.b(arg)
    }

Java side:

public void b(@Nullable Boolean arg, final Promise promise){
  if(arg == null){
    c()
  }else{
    c(arg)
  }
}

Then I have not problem when I pass true or false to function a but when I pass nothing to funtion a I get an error on my phone like that:

What is the problem?


问:
Clang and GCC has an inconsistent interpretation to the case where the parameter name appears as an unevaluated operand

#include <iostream>
void fun(int a = sizeof(a)){
    std::cout<< a<<std::endl;
}
int main(){
   fun();
}
```

Consider this case. Clang accepts it while GCC rejects it. According to [dcl.fct.default] p9

A default argument is evaluated each time the function is called with no argument for the corresponding parameter. A parameter shall not appear as a potentially-evaluated expression in a default argument.

[basic.def.odr] p2

An expression or conversion is potentially evaluated unless it is an unevaluated operand

sizeof is not a potentially-evaluated expression and a can be found at this point. I wonder which one is correct for this case?

答:
GCC is wrong. It assumes that a is not yet in scope in the default argument, although generally the point of declaration is immediately after the declarator before the initializer and none of the exceptions apply here. [basic.scope.pdecl]/1

An older bug report for this is here.

Note however, that the bug report has equivalent code to yours, but claims it should be ill-formed. That is because it was written before CWG 2082 which allowed the use of a parameter in an unevaluated context in the default argument.

Related question regarding this GCC bug here.

Body:
#include <iostream>
void fun(int a = sizeof(a)){
    std::cout<< a<<std::endl;
}
int main(){
   fun();
}

Consider this case. Clang accepts it while GCC rejects it. According to [dcl.fct.default] p9

A default argument is evaluated each time the function is called with no argument for the corresponding parameter. A parameter shall not appear as a potentially-evaluated expression in a default argument.

[basic.def.odr] p2

An expression or conversion is potentially evaluated unless it is an unevaluated operand

sizeof is not a potentially-evaluated expression and a can be found at this point. I wonder which one is correct for this case?


问:
How to set IAP (Identity Aware Proxy) authentication for back-end API service running on a GKE cluster
I have an application that has react in the front-end and a node service in the back-end. The app is deployed in the GKE cluster. Both the apps are exposed as a NodePort Service, and the fan out ingress path is done as follows :

```<code>- host: example.com
   http:
     paths:
     - backend:
         serviceName: frontend-service
         servicePort: 3000
       path: /*
     - backend:
         serviceName: backend-service
         servicePort: 5000
       path: /api/*
</code>```

I have enabled authentication using IAP for both services. When enabling IAP for both the kubernetes services, new Client Id and Client Secret is created individually. But I need to provide authentication for the back-end API from the front-end, since they have 2 different accounts, its not possible, i.e when I call the back-end API service from the front-end the authentication fails because the cookies provided from the FE does not match in the back-end service.

What is the best way to handle this scenario. Is there a way to use the same client credentials for both these services and if so, Is that the right way to do it or Is there a way to authenticate the Rest API using IAP directly.

答:
If IAP is setup using BackendConfig, then you can have two separate BackendConfig objects for frontend and backend applications but both of them use the same secrete (secretName) for oauthclientCredentials.

For frontend app

```<code>apiVersion: cloud.google.com/v1beta1
kind: BackendConfig
metadata:
  name:  frontend-iap-config
  namespace: namespace-1
spec:
  iap:
    enabled: true
    oauthclientCredentials:
      secretName: common-iap-oauth-credentials
</code>```

For backend app

```<code>apiVersion: cloud.google.com/v1beta1
kind: BackendConfig
metadata:
  name:  backend-iap-config
  namespace: namespace-1
spec:
  iap:
    enabled: true
    oauthclientCredentials:
      secretName: common-iap-oauth-credentials
</code>```

Then refer these BackendConfigs from respective kubernetes service objects

Body:
I have an application that has react in the front-end and a node service in the back-end. The app is deployed in the GKE cluster. Both the apps are exposed as a NodePort Service, and the fan out ingress path is done as follows :

- host: example.com
   http:
     paths:
     - backend:
         serviceName: frontend-service
         servicePort: 3000
       path: /*
     - backend:
         serviceName: backend-service
         servicePort: 5000
       path: /api/*

I have enabled authentication using IAP for both services. When enabling IAP for both the kubernetes services, new Client Id and Client Secret is created individually. But I need to provide authentication for the back-end API from the front-end, since they have 2 different accounts, its not possible, i.e when I call the back-end API service from the front-end the authentication fails because the cookies provided from the FE does not match in the back-end service.

What is the best way to handle this scenario. Is there a way to use the same client credentials for both these services and if so, Is that the right way to do it or Is there a way to authenticate the Rest API using IAP directly.

Body:
If IAP is setup using BackendConfig, then you can have two separate BackendConfig objects for frontend and backend applications but both of them use the same secrete (secretName) for oauthclientCredentials.

For frontend app

apiVersion: cloud.google.com/v1beta1
kind: BackendConfig
metadata:
  name:  frontend-iap-config
  namespace: namespace-1
spec:
  iap:
    enabled: true
    oauthclientCredentials:
      secretName: common-iap-oauth-credentials

For backend app

apiVersion: cloud.google.com/v1beta1
kind: BackendConfig
metadata:
  name:  backend-iap-config
  namespace: namespace-1
spec:
  iap:
    enabled: true
    oauthclientCredentials:
      secretName: common-iap-oauth-credentials

Then refer these BackendConfigs from respective kubernetes service objects


问:
Struts1 - Passing objects between servlets and jsp
What is the best way to pass objects between servlets and JSP when using Struts1? Help needed.</p>

答: Set the object as an attribute on the session or request.</p>