问:
How to enqueue old messages into a new queue in RabbitMQ Exchange?
I have an exchange with a type of topic that only redirects messages to queue payments

Somewhere in the future, I will decide to add another queue payment_analyze to analyze all old and new messages that have been enqueued.

durable exchanges and queues survive rabbit MQ restarts, persistent messages get written to disk but when binding a new queue to an old durable exchange, old messages do not get redirected (only new ones do get redirected)

From my understanding, this is the intended behavior as exchanges do not store messages and only act as a "proxy"

How do I achieve this?

Possible Solution

Creating a queue named parking and adding every enqueued message to it, whenever a new queue is added, consume messages from parking without acknowledging to keep the new queue "semi" up to date.

答:
Even though your configured persistent messages on the payments queue, this just means messages will survive a broker restart - once a message has been consumed and acknowledged it would be removed.

If you know you're going to need the payment_analyze queue at some point in the future, is it viable to just create this queue/binding upfront and route messages to both payment_analyze and payments? Messages on the payment_analyze will bank up until you're ready to start consuming them. Note: If you're producing a large number of messages this approach might result in storage issues...

As an alternative, you could write the messages to BLOB storage (or some other data store) as part of your payments queue consumer (or a different queue/consumer altogether) and then when you're ready to introduce the payment_analyze queue, you could write a script to read all the old messages from BLOB storage and send them to the RabbitMQ exchange. With 'topic' exchanges - see here - you can probably be clever with wildcards and routing keys in your queue bindings to ensure both old messages (from BLOB storage) as well as new messages are both routed to the payment_analyze queue, but only new messages are routed to the payments queue (so that your payments queue consumer is not reprocessing old messages).

Another option (assuming you're not overly invested in RabbitMQ) could be to consider Apache Kafka instead which deals with this scenario quite nicely as messages aren't automatically removed from a partition once they've been processed by a subscriber.

Anyways, just a few options to consider...


来源: stackexchange

问:
New Line not being written on file (Qt)
i am keeping a log of activities in my software using qtextedit. later when i want to save it as a text using toPlainText(), the resulting text file is a single line without any line breaks.
I start logging by plainText() and add subsequent additions using append().

```<code>void rocketscience::saveLog(){
QFile logFile;
QTextStream logOut;
QString logfName;

QSettings prevSet("us","fr");

    if (defaultDir.exists(prevSet.value("settings/logPath").toString()))
        logfName= QFileDialog::getSaveFileName(this,"Save File",fName,"Text (*.txt");

    if (logfName!=NULL){

    logFile.setFileName(logfName);
    logFile.open(QIODevice::WriteOnly);
    logOut.setDevice(&logFile);
    logOut<<ui.statusReport->toPlainText();
    logFile.close();
}
</code>```

}

答:
From the QTextStream class reference (that line is a bit hidden):

Note: On Windows, all '\n' characters are written as '\r\n' if QTextStream's device or string is opened using the QIODevice::Text flag.

where '\n' is the UNIX line ending and '\r\n' is the Windows line ending (CR/LF).

Remove the QTextStream initialisation at the start of your method and change the if statement to this:

```<code>if (!logfName.isEmpty())
{
    logFile.setFileName(logfName);
    logFile.open(QIODevice::WriteOnly);
    QTextStream logOut(&logFile, QIODevice::Text);
    logOut<<ui.statusReport->toPlainText();
    logFile.close();
}
</code>```

Also note how I changed the if condition. logfName is by default set to "", I'm not sure if comparing to NULL will work. You're better off using the QString::isEmpty() function

ContentLicense: CC BY-SA 3.0

Title: New Line not being written on file (Qt)

Body:
i am keeping a log of activities in my software using qtextedit. later when i want to save it as a text using toPlainText(), the resulting text file is a single line without any line breaks.
I start logging by plainText() and add subsequent additions using append().

void rocketscience::saveLog(){
QFile logFile;
QTextStream logOut;
QString logfName;

QSettings prevSet("us","fr");

    if (defaultDir.exists(prevSet.value("settings/logPath").toString()))
        logfName= QFileDialog::getSaveFileName(this,"Save File",fName,"Text (*.txt");

    if (logfName!=NULL){

    logFile.setFileName(logfName);
    logFile.open(QIODevice::WriteOnly);
    logOut.setDevice(&logFile);
    logOut<<ui.statusReport->toPlainText();
    logFile.close();
}

}

Body:
From the QTextStream class reference (that line is a bit hidden):

Note: On Windows, all '\n' characters are written as '\r\n' if QTextStream's device or string is opened using the QIODevice::Text flag.

where '\n' is the UNIX line ending and '\r\n' is the Windows line ending (CR/LF).

Remove the QTextStream initialisation at the start of your method and change the if statement to this:

if (!logfName.isEmpty())
{
    logFile.setFileName(logfName);
    logFile.open(QIODevice::WriteOnly);
    QTextStream logOut(&logFile, QIODevice::Text);
    logOut<<ui.statusReport->toPlainText();
    logFile.close();
}

Also note how I changed the if condition. logfName is by default set to "", I'm not sure if comparing to NULL will work. You're better off using the QString::isEmpty() function


问:
DrRacket – Finding total number of vowels in list of characters
I am using DrRacket on the Beginner Language mode.

Code below:

```<code>(define vowels '(#\a #\e #\i #\o #\u))

(define total 0)

(define (any-in-list lst check)
  (cond
    [(empty? lst) (+ 0 total)]
    [(member? (first lst) check) (add1 total)]
    [else (any-in-list (rest lst) check)]))

(define (count-vowels string)
  (any-in-list (string->list string) vowels))

(count-vowels "how do i do this?")
</code>```

The total value stays stuck at 1. After debugging, I realized that the 2nd cond statement evaluates to #true and then stops. How can I keep it going for the rest of the list after updating the total value?

答:
molbdnilo's answer explains the OP's issue and provides a correct solution;
since "Beginner Language" is mentioned, it may be worth
looking at how a solution might be constructed using the method
for which BSL (Beginning Student language) in DrRacket is apparently intended.

Following the HtDF (How to Design Functions) recipe, one can write the following
stub, incorporating signature and purpose, and "check-expect" examples:

(Note: layout differs slightly from HtDF conventions)

```<code>(define (count-vowels str)  ;; String -> Natural   ) *stub define* ;; *signature*
  ;; produce the count of vowel characters in str  ) *purpose statement*
  0 )                                              ) *stub body* (a valid result)

(check-expect (count-vowels "")   0 )              ) *examples*
(check-expect (count-vowels "a")  1 )              )
(check-expect (count-vowels "b")  0 )              )
(check-expect (count-vowels "ab") 1 )              )
(check-expect (count-vowels "ae") 2 )              )
</code>```

The first check-expect already passes; now write inventory and template;
count-vowels will have to do something with each character in the string, but there is no
standard BSL function or template for this. However there is a template for doing something
with the elements of a list:

```<code>(define (fn lox)  ;; (Listof X) -> Y               ) *template*
  (cond                                            )
    [(empty? lox) ... ]  #|base case|# ;; Y        )
    [else (...           #|something|# ;; X Y -> Y )
            (first lox) (fn (rest lox))) ]))       )

(define vowels (list #\a #\e #\i #\o #\u))         ) *inventory*
(member? x lox)     ;; X (Listof X) -> Bool        )
(string->list str)  ;; String -> (Listof Char)     )
</code>```

So count-vowels can be a composition of string->list with a function derived from this
template, for which stub, signature, and check-expects are:

```<code>(define (count-vowels-in-list loc)  ;; (Listof Char) -> Natural
  0)
(check-expect (count-vowels-in-list          empty)  0 )
(check-expect (count-vowels-in-list (cons #\a '()))  1 )  ;; (+ 1 0)
(check-expect (count-vowels-in-list (cons #\b '()))  0 )  ;; (+ 0 0)
(check-expect (count-vowels-in-list (list #\a #\b))  1 )
(check-expect (count-vowels-in-list (list #\a #\e))  2 )
</code>```

Expanding the template and looking at the first check-expect, the |base case| can be filled in:

```<code>(define (count-vowels-in-list loc)  ;; (Listof Char) -> Natural
  (cond
    [(empty? loc) 0 ]
    [else (|something| (first loc) (count-vowels-in-list (rest loc))) ]))
</code>```

For the next two check-expects, (rest loc) will be '(), so (|something| #\a 0) => 1 but
(|something| #\b 0) => 0

What distinguishes #\a from #\b is that (member? #\a vowels) => #true but
(member? #\b vowels) => #false so a descriptive name for |something| is add-1-if-vowel:

```<code>(define (add-1-if-vowel chr n)  ;; Char Natural -> Natural
  (if (member? chr vowels)
      (add1 n)
      n))
</code>```

So a complete solution developed by following this systematic design method is:

```<code>(define vowels (list #\a #\e #\i #\o #\u))

(define (add-1-if-vowel chr n)      ;; Char Natural -> Natural
  (if (member? chr vowels)
      (add1 n)
      n))

(define (count-vowels-in-list loc)  ;; (Listof Char) -> Natural
  (cond
    [(empty? loc) 0 ]
    [else (add-1-if-vowel (first loc) (count-vowels-in-list (rest loc))) ]))

(define (count-vowels str)          ;; String -> Natural
  (count-vowels-in-list (string->list str)))

(check-expect (count-vowels "")   0 )
(check-expect (count-vowels "a")  1 )
(check-expect (count-vowels "b")  0 )
(check-expect (count-vowels "ab") 1 )
(check-expect (count-vowels "ae") 2 )
(check-expect (count-vowels "how do i do this?") 5 )  ;; ^ (this is how :) ^
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using DrRacket on the Beginner Language mode.

Code below:

(define vowels '(#\a #\e #\i #\o #\u))

(define total 0)

(define (any-in-list lst check)
  (cond
    [(empty? lst) (+ 0 total)]
    [(member? (first lst) check) (add1 total)]
    [else (any-in-list (rest lst) check)]))

(define (count-vowels string)
  (any-in-list (string->list string) vowels))

(count-vowels "how do i do this?")

The total value stays stuck at 1. After debugging, I realized that the 2nd cond statement evaluates to #true and then stops. How can I keep it going for the rest of the list after updating the total value?

Body:
molbdnilo's answer explains the OP's issue and provides a correct solution;
since "Beginner Language" is mentioned, it may be worth
looking at how a solution might be constructed using the method
for which BSL (Beginning Student language) in DrRacket is apparently intended.

Following the HtDF (How to Design Functions) recipe, one can write the following
stub, incorporating signature and purpose, and "check-expect" examples:

(Note: layout differs slightly from HtDF conventions)

(define (count-vowels str)  ;; String -> Natural   ) *stub define* ;; *signature*
  ;; produce the count of vowel characters in str  ) *purpose statement*
  0 )                                              ) *stub body* (a valid result)

(check-expect (count-vowels "")   0 )              ) *examples*
(check-expect (count-vowels "a")  1 )              )
(check-expect (count-vowels "b")  0 )              )
(check-expect (count-vowels "ab") 1 )              )
(check-expect (count-vowels "ae") 2 )              )

The first check-expect already passes; now write inventory and template;
count-vowels will have to do something with each character in the string, but there is no
standard BSL function or template for this. However there is a template for doing something
with the elements of a list:

(define (fn lox)  ;; (Listof X) -> Y               ) *template*
  (cond                                            )
    [(empty? lox) ... ]  #|base case|# ;; Y        )
    [else (...           #|something|# ;; X Y -> Y )
            (first lox) (fn (rest lox))) ]))       )

(define vowels (list #\a #\e #\i #\o #\u))         ) *inventory*
(member? x lox)     ;; X (Listof X) -> Bool        )
(string->list str)  ;; String -> (Listof Char)     )

So count-vowels can be a composition of string->list with a function derived from this
template, for which stub, signature, and check-expects are:

(define (count-vowels-in-list loc)  ;; (Listof Char) -> Natural
  0)
(check-expect (count-vowels-in-list          empty)  0 )
(check-expect (count-vowels-in-list (cons #\a '()))  1 )  ;; (+ 1 0)
(check-expect (count-vowels-in-list (cons #\b '()))  0 )  ;; (+ 0 0)
(check-expect (count-vowels-in-list (list #\a #\b))  1 )
(check-expect (count-vowels-in-list (list #\a #\e))  2 )

Expanding the template and looking at the first check-expect, the |base case| can be filled in:

(define (count-vowels-in-list loc)  ;; (Listof Char) -> Natural
  (cond
    [(empty? loc) 0 ]
    [else (|something| (first loc) (count-vowels-in-list (rest loc))) ]))

For the next two check-expects, (rest loc) will be '(), so (|something| #\a 0) => 1 but
(|something| #\b 0) => 0

What distinguishes #\a from #\b is that (member? #\a vowels) => #true but
(member? #\b vowels) => #false so a descriptive name for |something| is add-1-if-vowel:

(define (add-1-if-vowel chr n)  ;; Char Natural -> Natural
  (if (member? chr vowels)
      (add1 n)
      n))

So a complete solution developed by following this systematic design method is:

(define vowels (list #\a #\e #\i #\o #\u))

(define (add-1-if-vowel chr n)      ;; Char Natural -> Natural
  (if (member? chr vowels)
      (add1 n)
      n))

(define (count-vowels-in-list loc)  ;; (Listof Char) -> Natural
  (cond
    [(empty? loc) 0 ]
    [else (add-1-if-vowel (first loc) (count-vowels-in-list (rest loc))) ]))

(define (count-vowels str)          ;; String -> Natural
  (count-vowels-in-list (string->list str)))

(check-expect (count-vowels "")   0 )
(check-expect (count-vowels "a")  1 )
(check-expect (count-vowels "b")  0 )
(check-expect (count-vowels "ab") 1 )
(check-expect (count-vowels "ae") 2 )
(check-expect (count-vowels "how do i do this?") 5 )  ;; ^ (this is how :) ^


问:
How to use types with module declaration locally?
I am working on a package that will be published in npm.
The package has a default exported js class. I want to provide typings for this class.
So what I've tried:

```<code>// src/index.ts
export default class SomeClass {
  test(data: string) {
    console.log(data)
  }
}

// types.d.ts
declare module 'some-module' {
  export default class SomeClass {
    test(data: string): void
  }
}
</code>```

This approach works well if it is an npm module. When I import it like import SomeClass from 'some-module' it is imported with types.

But I can't use types from types.d.ts locally (in src/index.ts)

Is there a way to use types locally as well as in npm module?

答:
Found a solution.</p>
```<code>// src/index.ts
import SomeClassType from '../types'

export default class SomeClass implements SomeClassType {
  test(data: string) {
    console.log(data)
  }
}
</code>```

Body:
I am working on a package that will be published in npm.
The package has a default exported js class. I want to provide typings for this class.
So what I've tried:

// src/index.ts
export default class SomeClass {
  test(data: string) {
    console.log(data)
  }
}

// types.d.ts
declare module 'some-module' {
  export default class SomeClass {
    test(data: string): void
  }
}

This approach works well if it is an npm module. When I import it like import SomeClass from 'some-module' it is imported with types.

But I can't use types from types.d.ts locally (in src/index.ts)

Is there a way to use types locally as well as in npm module?

Body:
Found a solution.

// src/index.ts
import SomeClassType from '../types'

export default class SomeClass implements SomeClassType {
  test(data: string) {
    console.log(data)
  }
}


问:
H2 database column name "GROUP" is a reserved word
How do I create a table in H2 with a column named GROUP? I saw an example that used something like [*] a while ago, but I can't seem to find it.</p>

答:
I've been facing the same problem recently, my table has columns "key" and "level", both of which are keywords. So instead of renaming the actual tables or bastardising the DB/configuration in any other way, just for the coughing test, the fix was to put the following in the driver configuration in application.properties:

jdbc.url=jdbc:h2:mem:db;NON_KEYWORDS=KEY,LEVEL

And beyond that, I did not have to change a thing in Hibernate/entity settings and JPA was happy and never complained again.

see details here:
https://www.h2database.com/html/commands.html#set_non_keywords


问:
How can I exclude some items from a merged enum in TypeScript?
I defined the following enums:

```<code>enum myEnum {
    a = 1,
    b = 2
}

enum mySecondEnum {
    c = 3,
    d = 4
}
</code>```

and later on merged them together, to form a single enum:

```<code>const mergedEnum = {...myEnum, ...mySecondEnum};
type mergedEnum = typeof mergedEnum;
</code>```

If I now want to exclude a specific value from the merged enum, I get a strange typescript error, which I can not comprehend:

```<code>/** Type '{ [x: number]: string; c: mySecondEnum.c; d: mySecondEnum.d; a: myEnum.a; b: myEnum.b; }' does not satisfy the constraint 'string | number | symbol'.
  Type '{ [x: number]: string; c: mySecondEnum.c; d: mySecondEnum.d; a: myEnum.a; b: myEnum.b; }' is not assignable to type 'symbol'.(2344) **/
const mergedOmitedEnum: Record<Exclude<mergedEnum, 1>, number> = {
    ...
}
**/
</code>```

However, using the same approach, with a non merged enum, works as expected:

```<code>/** This does work as expected, it omits the "1" from "myEnum" */
const simpleOmitedEnum: Record<Exclude<myEnum, 1>, number> = {
    "2": 1
}
</code>```

How can I merge multiple enums, and later on omit some values from the merged result set?

Here's a playground link

答:
Consider this line:

const mergedEnum = { ...myEnum, ...mySecondEnum }
```
<p>as an anti patterns. <code>enums</code> are statically known objects, you should not do any operations on them.</p>
<p>You should be aware that compiled version of enum is more wider than code representation. It is bidirectional data structure.</p>
<p>If you still want to merge these data structure, you should use immutable object instead.</p>
<pre class="lang-js prettyprint-override"><code>const MyEnum = {
    a: 1,
    b: 2
} as const

const MySecondEnum = {
    c: 3,
    d: 4
} as const

const MergedEnum = { ...MyEnum, ...MySecondEnum };
type MergedEnum = typeof MergedEnum;
</code>```

Also, please keep in mind that TS type system does not allow you to create dynamic enum data structure.

If you want to do some type manipulations with enum type you can try this:

enum MyEnum {
    a = 1,
    b = 2
}

type Enum = `${MyEnum}`

type EnumType = Record<string | number, string | number>

type EnumToObj<Enum extends EnumType> = Pick<
    {
        [Prop in keyof Enum]:
        (Enum[Prop] extends string | number
            ? `${Enum[Prop]}`
            : never)
    }, keyof Enum
>

// type Result = {
//     readonly a: "1";
//     readonly b: "2";
// }
type Result = EnumToObj<typeof MyEnum>
```
<p>Playground</p>
<p>If you are interested in bidirectional type, check this:</p>
<pre class="lang-js prettyprint-override"><code>enum MyEnum {
    a = 1,
    b = 2
}

type Enum = `${MyEnum}`

type EnumType = Record<string | number, string | number>

type ToBidirectional<Obj extends EnumType> = {
    [Prop in keyof Obj as Obj[Prop]]: Prop
}
type EnumToObj<Enum extends EnumType> = Pick<
    {
        [Prop in keyof Enum]:
        (Enum[Prop] extends string | number
            ? `${Enum[Prop]}`
            : never)
    }, keyof Enum
>

type Bidirectional<T extends EnumType> = T & ToBidirectional<T>

type PseudoEnum = Bidirectional<EnumToObj<typeof MyEnum>>

// type Test = {
//     readonly a: "1";
//     readonly b: "2";
//     readonly 1: "a";
//     readonly 2: "b";
// }
type Test = {
    [Prop in keyof PseudoEnum]: PseudoEnum[Prop]
}
</code>```

Playground

Now it is easy to omit keys:

type CustomType=Omit<PseudoEnum, 1>
```

More information about using type representation of enum you can find in my article

Body:
I defined the following enums:

enum myEnum {
    a = 1,
    b = 2
}

enum mySecondEnum {
    c = 3,
    d = 4
}

and later on merged them together, to form a single enum:

const mergedEnum = {...myEnum, ...mySecondEnum};
type mergedEnum = typeof mergedEnum;

If I now want to exclude a specific value from the merged enum, I get a strange typescript error, which I can not comprehend:

/** Type '{ [x: number]: string; c: mySecondEnum.c; d: mySecondEnum.d; a: myEnum.a; b: myEnum.b; }' does not satisfy the constraint 'string | number | symbol'.
  Type '{ [x: number]: string; c: mySecondEnum.c; d: mySecondEnum.d; a: myEnum.a; b: myEnum.b; }' is not assignable to type 'symbol'.(2344) **/
const mergedOmitedEnum: Record<Exclude<mergedEnum, 1>, number> = {
    ...
}
**/

However, using the same approach, with a non merged enum, works as expected:

/** This does work as expected, it omits the "1" from "myEnum" */
const simpleOmitedEnum: Record<Exclude<myEnum, 1>, number> = {
    "2": 1
}

How can I merge multiple enums, and later on omit some values from the merged result set?

Here's a <a href="https://www.typescriptlang.org/play?ssl=17&ssc=2&pln=14&pc=1#code/KYOwrgtgBBCeCi5oG8CwAoKWoEMoF4oBGAGg2ygCMCoAmDAXww1EhlgGVgBjAexAAmiNmkzZuNAMxkxWATQAsjZuj4gAzgBcYwAE4BzYEKQ1kAOgtxhEElAtm4XNccgMA3Bk2wADsB0GjaxovX14AM39DFwgPdAwAegAqRKgAFQALAEt1KAFeYByAd15dAGtcHOAAD19uTSNbTO1eCCaczXS-ACIiLqgw3RaoLqskPsT4jDUtKHVMiG8AG2AAeVb66IAuKAAlHhKBAB54Ku5FsAFgQ9HIWyIAPlskSj1703JsLtou7aJlOPQSRSGWyUH0mQAbgVcFBCsBMrp5HpBrooABaKDpXiFKB8MCLeQASSgLSas1qmTCmQk3kGvl0mky0IGQzwED0USgrAgAH4oBMpvwZuyAgI1k1Akhtns%20IjjqdzpdrhzJbdiI8oM9Xu9ZHYLIwgA" rel="nofollow noreferrer">playground link

Body:
Consider this line:

const mergedEnum = { ...myEnum, ...mySecondEnum }

as an anti patterns. enums are statically known objects, you should not do any operations on them.

You should be aware that compiled version of enum is more wider than code representation. It is bidirectional data structure.

If you still want to merge these data structure, you should use immutable object instead.

const MyEnum = {
    a: 1,
    b: 2
} as const

const MySecondEnum = {
    c: 3,
    d: 4
} as const

const MergedEnum = { ...MyEnum, ...MySecondEnum };
type MergedEnum = typeof MergedEnum;

Also, please keep in mind that TS type system does not allow you to create dynamic enum data structure.

If you want to do some type manipulations with enum type you can try this:

enum MyEnum {
    a = 1,
    b = 2
}

type Enum = `${MyEnum}`

type EnumType = Record<string | number, string | number>

type EnumToObj<Enum extends EnumType> = Pick<
    {
        [Prop in keyof Enum]:
        (Enum[Prop] extends string | number
            ? `${Enum[Prop]}`
            : never)
    }, keyof Enum
>

// type Result = {
//     readonly a: "1";
//     readonly b: "2";
// }
type Result = EnumToObj<typeof MyEnum>

Playground

If you are interested in bidirectional type, check this:

enum MyEnum {
    a = 1,
    b = 2
}

type Enum = `${MyEnum}`

type EnumType = Record<string | number, string | number>

type ToBidirectional<Obj extends EnumType> = {
    [Prop in keyof Obj as Obj[Prop]]: Prop
}
type EnumToObj<Enum extends EnumType> = Pick<
    {
        [Prop in keyof Enum]:
        (Enum[Prop] extends string | number
            ? `${Enum[Prop]}`
            : never)
    }, keyof Enum
>

type Bidirectional<T extends EnumType> = T & ToBidirectional<T>

type PseudoEnum = Bidirectional<EnumToObj<typeof MyEnum>>

// type Test = {
//     readonly a: "1";
//     readonly b: "2";
//     readonly 1: "a";
//     readonly 2: "b";
// }
type Test = {
    [Prop in keyof PseudoEnum]: PseudoEnum[Prop]
}

Playground

Now it is easy to omit keys:

type CustomType=Omit<PseudoEnum, 1>

More information about using type representation of enum you can find in my article


问:
Would it be possible to create a script which would search and highlight multiple words within a Google doc?
So I would like to be able to have the ability to search up to 30+ phrases within a Google doc. Currently I have to do this process manually with find and replace tool.

But could a script automate this process in someway where it would search for the words and highlight them within the doc for me to review.

答:
Issue:

If I understand you correctly, you want to highlight (by highlight, I assume you mean changing the background color) certain sentences if they are present in your document.

Solution:

For each sentence, use Body.findText(sentence) to find its first occurrence in the document.

Retrieve the start and end offset of the resulting RangeElement.

Check whether the corresponding element can be edited as text and obtain a text version of it (see editAsText()).

Change the background color using setBackgroundColor.

Code sample:

```<code>const sentences = ["First sentence", "Second"]; // Your sentences

function highlightSentences() {
  const doc = DocumentApp.getActiveDocument();
  const body = doc.getBody();
  sentences.forEach(sentence => {
    const rangeElement = body.findText(sentence);
    if (rangeElement) {
      const startOffset = rangeElement.getStartOffset();
      const endOffset = rangeElement.getEndOffsetInclusive();
      const element = rangeElement.getElement();
      if (element.editAsText) {
        const textElement = element.editAsText();
        textElement.setBackgroundColor(startOffset, endOffset, "#fcfc03");
      }
    }
  });
}
</code>```

Body:
Issue:

If I understand you correctly, you want to highlight (by highlight, I assume you mean changing the background color) certain sentences if they are present in your document.

Solution:

For each sentence, use Body.findText(sentence) to find its first occurrence in the document.

Retrieve the start and end offset of the resulting RangeElement.

Check whether the corresponding element can be edited as text and obtain a text version of it (see editAsText()).

Change the background color using setBackgroundColor.

Code sample:

const sentences = ["First sentence", "Second"]; // Your sentences

function highlightSentences() {
  const doc = DocumentApp.getActiveDocument();
  const body = doc.getBody();
  sentences.forEach(sentence => {
    const rangeElement = body.findText(sentence);
    if (rangeElement) {
      const startOffset = rangeElement.getStartOffset();
      const endOffset = rangeElement.getEndOffsetInclusive();
      const element = rangeElement.getElement();
      if (element.editAsText) {
        const textElement = element.editAsText();
        textElement.setBackgroundColor(startOffset, endOffset, "#fcfc03");
      }
    }
  });
}


答:
The simplest way to create the mergedEnum type would be to just union the two different enums

```<code>type mergedEnum = myEnum | mySecondEnum;
</code>```

Playground Link

Normally you would want to get type of values in the mergedEnum constant, typeof mergedEnum is the type of the constant itself. To get the types of all values normally we could do typeof mergedEnum[keyof typeof mergedEnum]. But because the enum objects have index signatures from number to string, the merged object will also have this signature. Since the original enums are number enums, we could just remove the extra string in the union we get from typeof mergedEnum[keyof typeof mergedEnum]

```<code>type mergedEnum =  Exclude<typeof mergedEnum [keyof typeof mergedEnum ], string>;

</code>```

Playground Link

Title: How can I exclude some items from a merged enum in TypeScript?

Body:
The simplest way to create the mergedEnum type would be to just union the two different enums

type mergedEnum = myEnum | mySecondEnum;

<a href="https://www.typescriptlang.org/play?#code/KYOwrgtgBBCeCi5oG8CwAoKWoEMoF4oBGAGg2ygCMCoAmDAXww1EhlgGVgBjAexAAmiNmkzZuNAMxkxWATQAsjZuj4gAzgBcYwAE4BzYEKQ1kAOgtxhEElAtm4XNccgMA3Bk2wADsB0GjaxorEwAfdid+FwgPdAB6ACoEqAAVAAsAS3UoAV5gbIB3Xl0Aa1xs4AAPX25NI1sM7V4IRuzNNL8AIiJOqAAzXWaoTpDIXoS4jDUtKHUMiG8AG2AAeRa66IAuKAAlHmKBAB54Su5FsAFgQ9GbYgA+WyRKPTvTcmxO2k7tomV0DESyXSWSg+gyADd8rgoAVgBldPI9INdFAALRQNK8ApQPhgRbyACSUGajVmNQyfQyEm8g18uk0GShAyGeAgekMiKQAH4oBMpvwZmyAgI1o1Akhtns+AjjqdzpdruzxZBbEQHlAni83rJhl8fjIKJ1JN9iAaPgoTb90AwgA" rel="nofollow noreferrer">Playground Link

Normally you would want to get type of values in the mergedEnum constant, typeof mergedEnum is the type of the constant itself. To get the types of all values normally we could do typeof mergedEnum[keyof typeof mergedEnum]. But because the enum objects have index signatures from number to string, the merged object will also have this signature. Since the original enums are number enums, we could just remove the extra string in the union we get from typeof mergedEnum[keyof typeof mergedEnum]

type mergedEnum =  Exclude<typeof mergedEnum [keyof typeof mergedEnum ], string>;

Playground Link


问:
R dbWriteTable More Than One Class Warning
I've had a working R script that uses the dbWriteTable command to write to a SQL Server table. It has worked well without issue for a while ... until the last few days.

Now when I run the dbWriteTable command, I get the following warning:

```<code>Found more than one class "blob" in cache; using the first, from namespace 'blob'
Also defined by ‘jsonlite’
</code>```

Interestingly enough the table appears to write successfully.

Here is some sample code:

```<code>library("DBI")

db_test <- dbConnect(
  odbc(),
  driver = "SQL Server",
  server = "test_server",
  port = 1234,
  database = "test_db"
)

dbWriteTable(
  conn = db_test,
  name = SQL("dbo.swc_test_write_table"),
  value = df_test,
  overwrite = TRUE
)
</code>```

I've tried explicitly naming the package, DBI::dbWriteTable, but it throws the same warning. For reference, I'm not using using the jsonlite package, but I have it installed.

Any thoughts on why this is happening?

答:
This seems to be a bug, which is caused by the jsonlite package in its latest release 1.7.3.
See the bug report https://github.com/jeroen/jsonlite/issues/373
It seems to be fixed upstream and as of now there's also an updated version available, Changelog from 1.7.3 to 1.8.0.

Body:
I've had a working R script that uses the dbWriteTable command to write to a SQL Server table. It has worked well without issue for a while ... until the last few days.

Now when I run the dbWriteTable command, I get the following warning:

Found more than one class "blob" in cache; using the first, from namespace 'blob'
Also defined by ‘jsonlite’

Interestingly enough the table appears to write successfully.

Here is some sample code:

library("DBI")

db_test <- dbConnect(
  odbc(),
  driver = "SQL Server",
  server = "test_server",
  port = 1234,
  database = "test_db"
)

dbWriteTable(
  conn = db_test,
  name = SQL("dbo.swc_test_write_table"),
  value = df_test,
  overwrite = TRUE
)

I've tried explicitly naming the package, DBI::dbWriteTable, but it throws the same warning. For reference, I'm not using using the jsonlite package, but I have it installed.

Any thoughts on why this is happening?


问:
how to write .js file to read from xml file
I went through the example but my xml file is somewhat different from the file used in example
My xml file looks like this :

```<code><?xml version="1.0" encoding="UTF-8"?>
<response>

<lst name="responseHeader">
  <int name="status">0</int>
  <int name="QTime">3</int>
  <lst name="params">
    <str name="facet">on</str>
    <str name="indent">on</str>
    <str name="start">0</str>
    <str name="q">*:*</str>
    <str name="facet.field">ISS_RATE_TXT</str>
    <str name="rows">10</str>
    <str name="version">2.2</str>
  </lst>
</lst>
<result name="response" numFound="2627" start="0">
  <doc>
    <str name="ASSET_CLASS_MNEM">OTHER     </str>
    <str name="ISS_RATE_TXT">OTH ASSETS</str>
    <str name="RCD_ID">4127      </str>
    <str name="RCD_NUM">1</str>
  </doc>
  <doc>
    <str name="ASSET_CLASS_MNEM">EQUITY    </str>
    <str name="ISS_RATE_TXT">INTL OIL</str>
    <str name="RCD_ID">4142      </str>
    <str name="RCD_NUM">2</str>
  </doc>
  <doc>
    <str name="ASSET_CLASS_MNEM">BALANCE   </str>
    <str name="ISS_RATE_TXT">CASH</str>
    <str name="RCD_ID">4145      </str>
    <str name="RCD_NUM">3</str>
  </doc>
  <doc>
    <str name="ASSET_CLASS_MNEM">REC/PAY   </str>
    <str name="ISS_RATE_TXT">CASH</str>
    <str name="RCD_ID">4149      </str>
    <str name="RCD_NUM">4</str>
  </doc>
  <doc>
    <str name="ASSET_CLASS_MNEM">BALANCE   </str>
    <str name="ISS_RATE_TXT">CASH</str>
    <str name="RCD_ID">4146      </str>
    <str name="RCD_NUM">5</str>
  </doc>
  <doc>
    <str name="ASSET_CLASS_MNEM">REC/PAY   </str>
    <str name="ISS_RATE_TXT">CASH</str>
    <str name="RCD_ID">4148      </str>
    <str name="RCD_NUM">6</str>
  </doc>
  <doc>
    <str name="ASSET_CLASS_MNEM">EQUITY    </str>
    <str name="ISS_RATE_TXT">EQ FUNDS</str>
    <str name="RCD_ID">4143      </str>
    <str name="RCD_NUM">7</str>
  </doc>
  <doc>
    <str name="ASSET_CLASS_MNEM">EQUITY    </str>
    <str name="ISS_RATE_TXT">EQ FUNDS</str>
    <str name="RCD_ID">4144      </str>
    <str name="RCD_NUM">8</str>
  </doc>
  <doc>
    <str name="ASSET_CLASS_MNEM">EQUITY    </str>
    <str name="ISS_RATE_TXT">PUB/BRD</str>
    <str name="RCD_ID">4135      </str>
    <str name="RCD_NUM">9</str>
  </doc>
  <doc>
    <str name="ASSET_CLASS_MNEM">EQUITY    </str>
    <str name="ISS_RATE_TXT">OTH FIN</str>
    <str name="RCD_ID">4134      </str>
    <str name="RCD_NUM">10</str>
  </doc>
</result>
</response>
</code>```

Could someone please tell how to modify the xml-grid.js file in the example

答:
First of all; to request the XML file it needs to be in the same web server as your javascript file (or else the browser will fail to load the XML file).

To load the XML file to javascript you need to use the XMLHttpRequest object, though if you want support in IE5 and IE6 you need to do some ActiveX control magic. Here is an example of how to do it with XMLHttpRequest:

```<code>var request = new XMLHttpRequest();
  // create the request object

request.open('GET', '/xml-grid.js', false);
  // open http session to the file

request.send(null);
  // Send the request (with nothing)

if (request.status == 200) {
  // if request was okay

    console.log(request.responseText);
      // write to console the response in text

}
</code>```

Body:
I went through the example but my xml file is somewhat different from the file used in example
My xml file looks like this :

<?xml version="1.0" encoding="UTF-8"?>
<response>

<lst name="responseHeader">
  <int name="status">0</int>
  <int name="QTime">3</int>
  <lst name="params">
    <str name="facet">on</str>
    <str name="indent">on</str>
    <str name="start">0</str>
    <str name="q">*:*</str>
    <str name="facet.field">ISS_RATE_TXT</str>
    <str name="rows">10</str>
    <str name="version">2.2</str>
  </lst>
</lst>
<result name="response" numFound="2627" start="0">
  <doc>
    <str name="ASSET_CLASS_MNEM">OTHER     </str>
    <str name="ISS_RATE_TXT">OTH ASSETS</str>
    <str name="RCD_ID">4127      </str>
    <str name="RCD_NUM">1</str>
  </doc>
  <doc>
    <str name="ASSET_CLASS_MNEM">EQUITY    </str>
    <str name="ISS_RATE_TXT">INTL OIL</str>
    <str name="RCD_ID">4142      </str>
    <str name="RCD_NUM">2</str>
  </doc>
  <doc>
    <str name="ASSET_CLASS_MNEM">BALANCE   </str>
    <str name="ISS_RATE_TXT">CASH</str>
    <str name="RCD_ID">4145      </str>
    <str name="RCD_NUM">3</str>
  </doc>
  <doc>
    <str name="ASSET_CLASS_MNEM">REC/PAY   </str>
    <str name="ISS_RATE_TXT">CASH</str>
    <str name="RCD_ID">4149      </str>
    <str name="RCD_NUM">4</str>
  </doc>
  <doc>
    <str name="ASSET_CLASS_MNEM">BALANCE   </str>
    <str name="ISS_RATE_TXT">CASH</str>
    <str name="RCD_ID">4146      </str>
    <str name="RCD_NUM">5</str>
  </doc>
  <doc>
    <str name="ASSET_CLASS_MNEM">REC/PAY   </str>
    <str name="ISS_RATE_TXT">CASH</str>
    <str name="RCD_ID">4148      </str>
    <str name="RCD_NUM">6</str>
  </doc>
  <doc>
    <str name="ASSET_CLASS_MNEM">EQUITY    </str>
    <str name="ISS_RATE_TXT">EQ FUNDS</str>
    <str name="RCD_ID">4143      </str>
    <str name="RCD_NUM">7</str>
  </doc>
  <doc>
    <str name="ASSET_CLASS_MNEM">EQUITY    </str>
    <str name="ISS_RATE_TXT">EQ FUNDS</str>
    <str name="RCD_ID">4144      </str>
    <str name="RCD_NUM">8</str>
  </doc>
  <doc>
    <str name="ASSET_CLASS_MNEM">EQUITY    </str>
    <str name="ISS_RATE_TXT">PUB/BRD</str>
    <str name="RCD_ID">4135      </str>
    <str name="RCD_NUM">9</str>
  </doc>
  <doc>
    <str name="ASSET_CLASS_MNEM">EQUITY    </str>
    <str name="ISS_RATE_TXT">OTH FIN</str>
    <str name="RCD_ID">4134      </str>
    <str name="RCD_NUM">10</str>
  </doc>
</result>
</response>

Could someone please tell how to modify the xml-grid.js file in the example

Body:
First of all; to request the XML file it needs to be in the same web server as your javascript file (or else the browser will fail to load the XML file).

To load the XML file to javascript you need to use the XMLHttpRequest object, though if you want support in IE5 and IE6 you need to do some ActiveX control magic. Here is an example of how to do it with XMLHttpRequest:

var request = new XMLHttpRequest();
  // create the request object

request.open('GET', '/xml-grid.js', false);
  // open http session to the file

request.send(null);
  // Send the request (with nothing)

if (request.status == 200) {
  // if request was okay

    console.log(request.responseText);
      // write to console the response in text

}


问:
how to run a django-upgrade command to whole django project?
I am using a library django-upgrade to convert the code from django 1.11 to django 3.24

the command is like

django-upgrade --target-version 3.2 example/core/models.py

I want to know that how can I run this command so that it runs on whole django project.

答: I am clear on the question but if you are asking how to upgrade Django then in your virtual environment run pip sudo pip install --upgrade django==3.2


问:
Error in spring application context schema
I have a maven-spring project in Eclipse and I have this annoying error message in one of my spring contexts:

Referenced file contains errors (jar:file:/M2_HOME/repository/org/springframework/spring-beans/3.1.2.RELEASE/spring-beans-3.1.2.RELEASE.jar!/org/springframework/beans/
   factory/xml/spring-tool-3.1.xsd). For more information, right click on the message in the Problems View and select "Show Details..."

The show setails leads to this:

I using spring-data-jpa 1.2.0.RELEASE and the rest of my spring jars are 3.1.3.RELEASE. Regarding spring-data-commons-core - I don't even have a dependency to this jar in my pom but I can see it in my m2 repository along with spring-data-commons-parent and both of version 1.4.0.RELEASE, I don't know why (maybe those are part of spring-data-jpa?).

My application context schema:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="
   http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
   http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.2.xsd">
</code>```

I don't understand why I keep getting this error. Basically it has no effect what so ever, The app compiles, deployed and runs just fine, it is just this annoying red error mark in Eclipse that drives me crazy :)

答: Make sure that the jar files have been properly added then go here for the rest</p>

Body:
I have a maven-spring project in Eclipse and I have this annoying error message in one of my spring contexts:

Referenced file contains errors (jar:file:/M2_HOME/repository/org/springframework/spring-beans/3.1.2.RELEASE/spring-beans-3.1.2.RELEASE.jar!/org/springframework/beans/
   factory/xml/spring-tool-3.1.xsd). For more information, right click on the message in the Problems View and select "Show Details..."

The show setails leads to this:

I using spring-data-jpa 1.2.0.RELEASE and the rest of my spring jars are 3.1.3.RELEASE. Regarding spring-data-commons-core - I don't even have a dependency to this jar in my pom but I can see it in my m2 repository along with spring-data-commons-parent and both of version 1.4.0.RELEASE, I don't know why (maybe those are part of spring-data-jpa?).

My application context schema:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="
   http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
   http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.2.xsd">

I don't understand why I keep getting this error. Basically it has no effect what so ever, The app compiles, deployed and runs just fine, it is just this annoying red error mark in Eclipse that drives me crazy :)


问:
How do I connect to a remote Cassandra instance running in Docker to retrieve data using Java?
I'm trying to connect to a remote machine which has docker installed. I want to exec into the docker container and connect to database and then fetch a table data using java.

Following are my commands that i'm trying to execute.

docker exec it containerID - to login to docker container
cqlsh -u username -p password -- to connect to cassandra DB
use keyspace; ---to connect to cassandra keyspace
desc tables; --- to view the tables that are available in keyspace.

Following is the Java code that I'm trying. Can someone let me know if this approach is correct or what should i do to make this code work. I'm completely new to java code.

```<code>import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class ExecuteanyCommands {

    public static void main(String[] args) throws JSchException, InterruptedException, IOException {

            //JSch
            JSch jsch = new JSch();
            Session session = jsch.getSession("cambi", "10.10.96.20", 22);
            session.setPassword("axone");
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();

            Channel channel = session.openChannel("exec");

            InputStream in = channel.getInputStream();
            ((ChannelExec) channel).setCommand("docker exec -it containerID; cqlsh -u username -p password; use keyspace; desc tables;");

            channel.connect();

            BufferedReader reader = new BufferedReader(new InputStreamReader(in));

            String line;

            while((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            channel.disconnect();
            session.disconnect();
    }

}
</code>```

答:
If you want to connect to a container from a remote machine over SSH, then the way to do it is to define an SSH tunnel, external to your Java program.

In addition, the idea of interacting with Cassandra by running cqlsh on the host is very unusual.
It's better to use the official Cassandra Java driver for that purpose.

To summarize:

Create an SSH tunnel between the client and the docker host

Write a Java program that uses the Java Driver to query Cassandra

Body:
I'm trying to connect to a remote machine which has docker installed. I want to exec into the docker container and connect to database and then fetch a table data using java.

Following are my commands that i'm trying to execute.

docker exec it containerID - to login to docker container
cqlsh -u username -p password -- to connect to cassandra DB
use keyspace; ---to connect to cassandra keyspace
desc tables; --- to view the tables that are available in keyspace.

Following is the Java code that I'm trying. Can someone let me know if this approach is correct or what should i do to make this code work. I'm completely new to java code.

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class ExecuteanyCommands {

    public static void main(String[] args) throws JSchException, InterruptedException, IOException {

            //JSch
            JSch jsch = new JSch();
            Session session = jsch.getSession("cambi", "10.10.96.20", 22);
            session.setPassword("axone");
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();

            Channel channel = session.openChannel("exec");

            InputStream in = channel.getInputStream();
            ((ChannelExec) channel).setCommand("docker exec -it containerID; cqlsh -u username -p password; use keyspace; desc tables;");

            channel.connect();

            BufferedReader reader = new BufferedReader(new InputStreamReader(in));

            String line;

            while((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            channel.disconnect();
            session.disconnect();
    }

}


问:
Saving PDF for sharing using iText with backwards compatibility
A problem with saving a PDF file on Android has been bugging me for weeks, making every Google search I do result in a list of purple links.

I have attempted numerous approaches, but have only managed to save a PDF file using the built in PDF creator, which does not fulfill my purpose.

I have a number of questions that I seek an answer to, and hope some of you can help.

Question 1: Where should you save a PDF file you intend to share and then delete immediately after?

Q1 a) Is a ContentResolver & ContentProvider required, or is this only when sharing a 'directory' between apps?

Intuitively it makes most sense for me to save the PDF in the internal cache directory, share it from there and then delete it.

Question 2: What is the approach for storing files with backwards compatibility?

From what I have read, different SDK levels require different approaches for file storage, being:

<= SDK 28 uses traditional storage methods, which is (using File API)?

<= SDK 29 you should request permission for legacy storage, if using external storage

>= SDK 30 Android enforces scoped storage

Using SAF (Storage Access Framework) seems to be the recommended way to store documents like PDFs. However, I don't intend to display a file picker to the user, when they are simply generating and sharing a PDF.

I am encountering this very generic exception, which occurs when iText closes the output stream. Below are some code examples and their resulting errors.

SDK 30 File API test

fun createPdfInternalSDK30(context: Context) {
    val fileName = "test.pdf"

    //  MODE_PRIVATE creates in internal storage, right?
    val out = context.openFileOutput(fileName, Context.MODE_PRIVATE)
    // out path: /data/user/0/dk.overlevelsesguiden.de10her/files/test.pdf

    try {
        val writer = PdfWriter(out)
        val pdf = PdfDocument(writer)

        Document(pdf, PageSize.A4, false).apply {
            add(Paragraph("Test"))
            close()
        }
    } catch (e: IOException) {
        e.printStackTrace()
    }
}
```
<p><em><strong>Error</strong></em></p>
```java.lang.ExceptionInInitializerError
        at com.itextpdf.commons.actions.producer.ProducerBuilder.modifyProducer(ProducerBuilder.java:97)
        at com.itextpdf.kernel.actions.events.FlushPdfDocumentEvent.doAction(FlushPdfDocumentEvent.java:103)
        at com.itextpdf.commons.actions.EventManager.onEvent(EventManager.java:71)
        at com.itextpdf.kernel.pdf.PdfDocument.close(PdfDocument.java:849)
        at com.itextpdf.layout.Document.close(Document.java:117)
        at dk.overlevelsesguiden.de10her.business.PDFService.createPdfInternalSDK30(PDFService.kt:118)
    Caused by: java.util.regex.PatternSyntaxException: Syntax error in regexp pattern near index 12
        \$\{([^}]*)}
```
<p><strong>SDK 29+ Scoped Storage test</strong></p>
<pre class="lang-kotlin prettyprint-override"><code>    @RequiresApi(api = Build.VERSION_CODES.Q)
    fun createPdfSharedSDK29plus(context: Context) {
        val pdfCollection = MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)

        val contentValues = ContentValues().apply {
            put(MediaStore.MediaColumns.DISPLAY_NAME, "title")
            put(MediaStore.MediaColumns.MIME_TYPE, "application/pdf")
        }

        var uri: Uri? = null

        try {
            uri = context.contentResolver.insert(pdfCollection, contentValues) ?: throw IOException("Failed to create new MediaStore record")
            val out = context.contentResolver.openOutputStream(uri)
            val writer = PdfWriter(out)
            val pdf = PdfDocument(writer)
            Document(pdf, PageSize.A4, false).apply {
                add(Paragraph("Test"))
                close()
            }
        } catch (e: IOException) {
            uri?.let { orphanUri ->
                context.contentResolver.delete(orphanUri, null, null)
            }
        }
    }
</code>```

Error

```<code>java.lang.ExceptionInInitializerError
        at com.itextpdf.commons.actions.producer.ProducerBuilder.modifyProducer(ProducerBuilder.java:97)
        at com.itextpdf.kernel.actions.events.FlushPdfDocumentEvent.doAction(FlushPdfDocumentEvent.java:103)
        at com.itextpdf.commons.actions.EventManager.onEvent(EventManager.java:71)
        at com.itextpdf.kernel.pdf.PdfDocument.close(PdfDocument.java:849)
        at com.itextpdf.layout.Document.close(Document.java:117)
        at dk.overlevelsesguiden.de10her.business.PDFService.finalTest(PDFService.kt:118)
    Caused by: java.util.regex.PatternSyntaxException: Syntax error in regexp pattern near index 12
        \$\{([^}]*)}
</code>```

Manifest permissions

```<code><!-- Without this folders will be inaccessible in Android-11 and above devices -->
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />

<!-- Without this entry storage-permission entry will not be visible under app-info permissions list Android-10 and below -->
<uses-permission
    android:name="android.permission.WRITE_EXTERNAL_STORAGE"
    android:maxSdkVersion="28"
/>
</code>```

答:
You brought up a number of issues. This answer focuses on the actual errors you show.

The actual errors you show both cause a

java.util.regex.PatternSyntaxException: Syntax error in regexp pattern near index 12
        \$\{([^}]*)}
```
<p>during initialization of the iText class <code>ProducerBuilder</code>. It happens here:</p>
<pre class="lang-java prettyprint-override"><code>private static final String PATTERN_STRING = "\\$\\{([^}]*)}";
private static final Pattern PATTERN = Pattern.compile(PATTERN_STRING);
</code>```

Actually here regular expressions in JREs differ from those in Android. In plain Java the regular expression \$\{([^}]*)} is accepted, a } meant as a character needs not to be escaped if there was no unescaped opening { before. Android, on the other hand, requires it to be escaped even then.

A fix for this has been committed yesterday - https://github.com/itext/itext7/commit/32bf2552770866dce4516798e7b11f26631ae92f - the pattern string now is:

private static final String PATTERN_STRING = "\\$\\{([^}]*)\\}";
```

Thus, in the next iText release (or in a really current SNAPSHOT) that very error won't occur anymore.

Body:
A problem with saving a PDF file on Android has been bugging me for weeks, making every Google search I do result in a list of purple links.

I have attempted numerous approaches, but have only managed to save a PDF file using the built in PDF creator, which does not fulfill my purpose.

I have a number of questions that I seek an answer to, and hope some of you can help.

Question 1: Where should you save a PDF file you intend to share and then delete immediately after?

Q1 a) Is a ContentResolver & ContentProvider required, or is this only when sharing a 'directory' between apps?

Intuitively it makes most sense for me to save the PDF in the internal cache directory, share it from there and then delete it.

Question 2: What is the approach for storing files with backwards compatibility?

From what I have read, different SDK levels require different approaches for file storage, being:

<= SDK 28 uses traditional storage methods, which is (using File API)?

<= SDK 29 you should request permission for legacy storage, if using external storage

>= SDK 30 Android enforces scoped storage

Using SAF (Storage Access Framework) seems to be the recommended way to store documents like PDFs. However, I don't intend to display a file picker to the user, when they are simply generating and sharing a PDF.

I am encountering this very generic exception, which occurs when iText closes the output stream. Below are some code examples and their resulting errors.

SDK 30 File API test

fun createPdfInternalSDK30(context: Context) {
    val fileName = "test.pdf"

    //  MODE_PRIVATE creates in internal storage, right?
    val out = context.openFileOutput(fileName, Context.MODE_PRIVATE)
    // out path: /data/user/0/dk.overlevelsesguiden.de10her/files/test.pdf

    try {
        val writer = PdfWriter(out)
        val pdf = PdfDocument(writer)

        Document(pdf, PageSize.A4, false).apply {
            add(Paragraph("Test"))
            close()
        }
    } catch (e: IOException) {
        e.printStackTrace()
    }
}

Error

java.lang.ExceptionInInitializerError
        at com.itextpdf.commons.actions.producer.ProducerBuilder.modifyProducer(ProducerBuilder.java:97)
        at com.itextpdf.kernel.actions.events.FlushPdfDocumentEvent.doAction(FlushPdfDocumentEvent.java:103)
        at com.itextpdf.commons.actions.EventManager.onEvent(EventManager.java:71)
        at com.itextpdf.kernel.pdf.PdfDocument.close(PdfDocument.java:849)
        at com.itextpdf.layout.Document.close(Document.java:117)
        at dk.overlevelsesguiden.de10her.business.PDFService.createPdfInternalSDK30(PDFService.kt:118)
    Caused by: java.util.regex.PatternSyntaxException: Syntax error in regexp pattern near index 12
        \$\{([^}]*)}

SDK 29+ Scoped Storage test

    @RequiresApi(api = Build.VERSION_CODES.Q)
    fun createPdfSharedSDK29plus(context: Context) {
        val pdfCollection = MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)

        val contentValues = ContentValues().apply {
            put(MediaStore.MediaColumns.DISPLAY_NAME, "title")
            put(MediaStore.MediaColumns.MIME_TYPE, "application/pdf")
        }

        var uri: Uri? = null

        try {
            uri = context.contentResolver.insert(pdfCollection, contentValues) ?: throw IOException("Failed to create new MediaStore record")
            val out = context.contentResolver.openOutputStream(uri)
            val writer = PdfWriter(out)
            val pdf = PdfDocument(writer)
            Document(pdf, PageSize.A4, false).apply {
                add(Paragraph("Test"))
                close()
            }
        } catch (e: IOException) {
            uri?.let { orphanUri ->
                context.contentResolver.delete(orphanUri, null, null)
            }
        }
    }

Error

java.lang.ExceptionInInitializerError
        at com.itextpdf.commons.actions.producer.ProducerBuilder.modifyProducer(ProducerBuilder.java:97)
        at com.itextpdf.kernel.actions.events.FlushPdfDocumentEvent.doAction(FlushPdfDocumentEvent.java:103)
        at com.itextpdf.commons.actions.EventManager.onEvent(EventManager.java:71)
        at com.itextpdf.kernel.pdf.PdfDocument.close(PdfDocument.java:849)
        at com.itextpdf.layout.Document.close(Document.java:117)
        at dk.overlevelsesguiden.de10her.business.PDFService.finalTest(PDFService.kt:118)
    Caused by: java.util.regex.PatternSyntaxException: Syntax error in regexp pattern near index 12
        \$\{([^}]*)}

Manifest permissions

<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />

<uses-permission
    android:name="android.permission.WRITE_EXTERNAL_STORAGE"
    android:maxSdkVersion="28"
/>

Body:
You brought up a number of issues. This answer focuses on the actual errors you show.

The actual errors you show both cause a

java.util.regex.PatternSyntaxException: Syntax error in regexp pattern near index 12
        \$\{([^}]*)}

during initialization of the iText class ProducerBuilder. It happens here:

private static final String PATTERN_STRING = "\\$\\{([^}]*)}";
private static final Pattern PATTERN = Pattern.compile(PATTERN_STRING);

Actually here regular expressions in JREs differ from those in Android. In plain Java the regular expression \$\{([^}]*)} is accepted, a } meant as a character needs not to be escaped if there was no unescaped opening { before. Android, on the other hand, requires it to be escaped even then.

A fix for this has been committed yesterday - https://github.com/itext/itext7/commit/32bf2552770866dce4516798e7b11f26631ae92f - the pattern string now is:

private static final String PATTERN_STRING = "\\$\\{([^}]*)\\}";

Thus, in the next iText release (or in a really current SNAPSHOT) that very error won't occur anymore.


问:
How to get "tag name", "attribute name", "attribute value" in regex?
I'm trying to write a regular expression that needs to return every tag name, attribute name, and attribute value

Here is the code example

```<code>Hello, My name is Jack, This is my selfie:
[img id='4' src="imageurl"]
Below is the quick-link to my profile
[profile username='jackisbest']
</code>```

I need to get any text enclosed in [ ]

Also I need javascript regex to parse them and match them this way

```<code>> Match 1: img

> Match 2: id='4'
  Group 1: id
  Group 2: 4

> Match 3: src="imageurl"
  Group 1: src
  Group 2: imageurl
</code>```

This is the regex I am using, but it can only match attributes and value

```<code>(\S+)=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']
</code>```

Thanks!!

答:
You can use

/\[([a-zA-Z]\w*)|([^=\s]+)=["'](.*?)["']/g
```

See the regex demo. Details:

\[([a-zA-Z]\w*) - a [ char and then a letter followed with zero or more word chars (letters, digits, underscores)

| or

([^=\s]+) - one or more chars other than = and whitespace

= - a = char

["'](.*?)["'] - " or ', then any zero or more chars as few as possible (captured into Group 3), and then a " or ' char.

Body:
I'm trying to write a regular expression that needs to return every tag name, attribute name, and attribute value

Here is the code example

Hello, My name is Jack, This is my selfie:
[img id='4' src="imageurl"]
Below is the quick-link to my profile
[profile username='jackisbest']

I need to get any text enclosed in [ ]

Also I need javascript regex to parse them and match them this way

> Match 1: img

> Match 2: id='4'
  Group 1: id
  Group 2: 4

> Match 3: src="imageurl"
  Group 1: src
  Group 2: imageurl

This is the regex I am using, but it can only match attributes and value

(\S+)=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']

Thanks!!

Body:
You can use

/\[([a-zA-Z]\w*)|([^=\s]+)=["'](.*?)["']/g

See the regex demo. Details:

\[([a-zA-Z]\w*) - a [ char and then a letter followed with zero or more word chars (letters, digits, underscores)

| or

([^=\s]+) - one or more chars other than = and whitespace

= - a = char

["'](.*?)["'] - " or ', then any zero or more chars as few as possible (captured into Group 3), and then a " or ' char.


问:
Python - How can I check if a CSV file has a comma or a semicolon as a separator?
I have a bunch of CSV files that I would like to read with Python Pandas. Some of them have a comma as a delimiter, hence I use the following command to read them:

import pandas as pd
df = pd.read_csv('file_with_commas.csv')
```
<p>However I have others CSVs that have a semicolon as a delimiter. Hence, since the default separator is the comma, I now need to specify it and therefore use the following command:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
df = pd.read_csv('file_with_semicolons.csv', sep=';')
</code>```

I would like to write a piece of code that recognises if the CSV file has a comma or a semicolon as a delimiter (before I read it) so that I do not have to change the code every time. How can this be done?

Note: I have checked this similar question on Stack Overflow but it is helpless since it is applicable to R, rather than Python.

答:
Say that you would like to read an arbitrary CSV, named input.csv, and you do not know whether the separator is a comma or a semicolon.

You could open your file using the csv module. The Sniffer class is then used to deduce its format, like in the following code:

import csv
with open(input.csv, newline='') as csvfile:
    dialect = csv.Sniffer().sniff(csvfile.read())
```
<p>For this module, the <code>dialect</code> class is a container class whose attributes contain information for how to handle delimiters (among other things like doublequotes, whitespaces, etc). You can check the <code>delimiter</code> attribute by using the following code:</p>
<pre class="lang-py prettyprint-override"><code>print(dialect.delimiter)
# This will be either a comma or a semicolon, depending on what the input is
</code>```

Therefore, in order to do a smart CSV reading, you could use something like the following:

if dialect.delimiter == ',':
    df = pd.read_csv(input.csv)            # Import the csv with a comma as the separator
elif dialect.delimiter == ';':
    df = pd.read_csv(input.csv, sep=';')   # Import the csv with a semicolon as the separator
```

More information can be found here.

Body:
I have a bunch of CSV files that I would like to read with Python Pandas. Some of them have a comma as a delimiter, hence I use the following command to read them:

import pandas as pd
df = pd.read_csv('file_with_commas.csv')

However I have others CSVs that have a semicolon as a delimiter. Hence, since the default separator is the comma, I now need to specify it and therefore use the following command:

import pandas as pd
df = pd.read_csv('file_with_semicolons.csv', sep=';')

I would like to write a piece of code that recognises if the CSV file has a comma or a semicolon as a delimiter (before I read it) so that I do not have to change the code every time. How can this be done?

Note: I have checked this similar question on Stack Overflow but it is helpless since it is applicable to R, rather than Python.

Body:
Say that you would like to read an arbitrary CSV, named input.csv, and you do not know whether the separator is a comma or a semicolon.

You could open your file using the csv module. The Sniffer class is then used to deduce its format, like in the following code:

import csv
with open(input.csv, newline='') as csvfile:
    dialect = csv.Sniffer().sniff(csvfile.read())

For this module, the dialect class is a container class whose attributes contain information for how to handle delimiters (among other things like doublequotes, whitespaces, etc). You can check the delimiter attribute by using the following code:

print(dialect.delimiter)
# This will be either a comma or a semicolon, depending on what the input is

Therefore, in order to do a smart CSV reading, you could use something like the following:

if dialect.delimiter == ',':
    df = pd.read_csv(input.csv)            # Import the csv with a comma as the separator
elif dialect.delimiter == ';':
    df = pd.read_csv(input.csv, sep=';')   # Import the csv with a semicolon as the separator

More information can be found here.


问:
How to perform Apache 2 config migration from Linux SUSE to Ubuntu?
I'm a newbie with Apache configurations. I need to migrate a web tool running on Linux SUSE with Apache 2 to Ubuntu. It is currently using an external httpd.conf located in some other place on the machine, set as APACHE_HTTPD_CONF variable in /etc/sysconfig/apache2. It looks like there is no /etc/sysconfig/apache2, and also no APACHE_HTTPD_CONF variable in any of the files in /etc/apache2/ on Ubuntu.
How can I configure it correctly?

答:
In ubuntu, at /etc/apache2 you have the possibility to config several criteria of things, such as:

conf

mods

sites

These have a folder of -available (sites-available, for example) and a folder of -enabled (sites-enabled, for example). You will definitely need to define your sitename.conf file in sites-available and then run

```<code>sudo a2ensite sitename
</code>```

to enable it. Similarly, you will need to enable mods and conf. Whenever you performed some large change and intend to test or use Apache, restart it:

```<code>sudo service apache2 restart
</code>```

There is also an apache2.conf file for general Apache settings.

In your scenario I would recommend copying the content of your httpd.conf into /etc/apache2/sites-available/sitename.conf and then run

```<code>sudo a2ensite sitename
sudo service apache2 restart
</code>```

This copies the config file from /etc/apache2/sites-available to /etc/apache2/sites-enabled and restarts Apache. You will also need to edit /etc/hosts to define your sitename to be loaded from 127.0.0.1.

Body:
In ubuntu, at /etc/apache2 you have the possibility to config several criteria of things, such as:

conf

mods

sites

These have a folder of -available (sites-available, for example) and a folder of -enabled (sites-enabled, for example). You will definitely need to define your sitename.conf file in sites-available and then run

sudo a2ensite sitename

to enable it. Similarly, you will need to enable mods and conf. Whenever you performed some large change and intend to test or use Apache, restart it:

sudo service apache2 restart

There is also an apache2.conf file for general Apache settings.

In your scenario I would recommend copying the content of your httpd.conf into /etc/apache2/sites-available/sitename.conf and then run

sudo a2ensite sitename
sudo service apache2 restart

This copies the config file from /etc/apache2/sites-available to /etc/apache2/sites-enabled and restarts Apache. You will also need to edit /etc/hosts to define your sitename to be loaded from 127.0.0.1.


问:
convert string to char c
I am working on a project where I can to convert a api digit to a char. I have used an array of string pointers to get the conversion. However, I want to return just a single ch, as my api that I am using will only accept a char. So ap_five will return "5". But I want to five to be a single char '5'.

I thought maybe I could cast to a char in the return. However, I just get rubbish.

I am sure there is other ways to solve this, how I am just wondering how can I solve with my present program.

```<code>char *digits_conversion[][2]=
{
    {"ap_zero", "0"},
    {"ap_one", "1"},
    {"ap_two", "2"},
    {"ap_three", "3"},
    {"ap_four", "4"},
    {"ap_five", "5"},
    {"ap_six", "6"},
    {"ap_seven", "7"},
    {"ap_eight", "8"},
    {"ap_nine", "9"},
    {"ap_star", "*"},
    {"ap_hash", "#"},
    {NULL, NULL}
};

char convert_to_char(const char *digit)
{
    int i = 0;
    for(i = 0; *digits_conversion[i][1]; i++)
    {
        if(strcmp(digits_conversion[i][0], digit) == 0)
        {
            return (char) digits_conversion[i][1];
        }
    }

    return '\0';
}

int main(void)
{
    char ch;

    ch = convert_to_char("ap_five");

    printf("Converted digit: %c\n", ch);

    return 0;
}
</code>```

答:
The simplest fix to your existing code is just to change:

```<code>return (char) digits_conversion[i][1];
</code>```

into

```<code>return digits_conversion[i][1][0];
</code>```

However, you might find that changing digits_conversion into an array of structures will give you code that is easier to understand and maintain.  For example:

```<code>struct digit_mapping {
    char *api_name;
    char digit;
};
struct digit_mapping conversion_table[] = {
    { "ap_zero", '0' },
    {"ap_one", '1'},
    {"ap_two", '2'},
    {"ap_three", '3'},
    {"ap_four", '4'},
    {"ap_five", '5'},
    {"ap_six", '6'},
    {"ap_seven", '7'},
    {"ap_eight", '8'},
    {"ap_nine", '9'},
    {"ap_star", '*'},
    {"ap_hash", '#'},
    {NULL, '\0'}
};

char convert_to_char(const char *digit)
{
    int i = 0;
    for(i = 0; conversion_table[i].digit; i++)
    {
            if(strcmp(conversion_table[i].api_name, digit) == 0)
            {
                    return conversion_table[i].digit;
            }
    }

    return '\0';
}

int main(void)
{
    char ch;

    ch = convert_to_char("ap_five");

    printf("Converted digit: %c\n", ch);

    return 0;
}
</code>```

OwnerDisplayName: robUK

Title: convert string to char c

Body:
I am working on a project where I can to convert a api digit to a char. I have used an array of string pointers to get the conversion. However, I want to return just a single ch, as my api that I am using will only accept a char. So ap_five will return "5". But I want to five to be a single char '5'.

I thought maybe I could cast to a char in the return. However, I just get rubbish.

I am sure there is other ways to solve this, how I am just wondering how can I solve with my present program.

char *digits_conversion[][2]=
{
    {"ap_zero", "0"},
    {"ap_one", "1"},
    {"ap_two", "2"},
    {"ap_three", "3"},
    {"ap_four", "4"},
    {"ap_five", "5"},
    {"ap_six", "6"},
    {"ap_seven", "7"},
    {"ap_eight", "8"},
    {"ap_nine", "9"},
    {"ap_star", "*"},
    {"ap_hash", "#"},
    {NULL, NULL}
};

char convert_to_char(const char *digit)
{
    int i = 0;
    for(i = 0; *digits_conversion[i][1]; i++)
    {
        if(strcmp(digits_conversion[i][0], digit) == 0)
        {
            return (char) digits_conversion[i][1];
        }
    }

    return '\0';
}

int main(void)
{
    char ch;

    ch = convert_to_char("ap_five");

    printf("Converted digit: %c\n", ch);

    return 0;
}

LastEditorDisplayName: robUK

Body:
The simplest fix to your existing code is just to change:

return (char) digits_conversion[i][1];

into

return digits_conversion[i][1][0];

However, you might find that changing digits_conversion into an array of structures will give you code that is easier to understand and maintain.  For example:

struct digit_mapping {
    char *api_name;
    char digit;
};
struct digit_mapping conversion_table[] = {
    { "ap_zero", '0' },
    {"ap_one", '1'},
    {"ap_two", '2'},
    {"ap_three", '3'},
    {"ap_four", '4'},
    {"ap_five", '5'},
    {"ap_six", '6'},
    {"ap_seven", '7'},
    {"ap_eight", '8'},
    {"ap_nine", '9'},
    {"ap_star", '*'},
    {"ap_hash", '#'},
    {NULL, '\0'}
};

char convert_to_char(const char *digit)
{
    int i = 0;
    for(i = 0; conversion_table[i].digit; i++)
    {
            if(strcmp(conversion_table[i].api_name, digit) == 0)
            {
                    return conversion_table[i].digit;
            }
    }

    return '\0';
}

int main(void)
{
    char ch;

    ch = convert_to_char("ap_five");

    printf("Converted digit: %c\n", ch);

    return 0;
}

OwnerDisplayName: Eric Melski

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Evan Teran


问:
restructure array in php
I have the following source array which I'm trying to restructure using group_name to give me the require output below.

Any help or pointers appreciated.
Thanks, Lk

Source:

```<code>Array
(
[field_a] => Array
    (
        [type] => text
        [group_name] =>
    )

[field_b] => Array
    (
        [type] => number_integer
        [group_name] => group_other
    )

[field_c] => Array
    (
        [type] => text
        [group_name] =>
    )

[field_d] => Array
    (
        [type] => link
        [group_name] => group_web_links
    )

[field_e] => Array
    (
        [type] => link
        [group_name] => group_web_links
    )

[field_f] => Array
    (
        [type] => text
        [group_name] => group_web_links
    )

)
</code>```

Output:

```<code>Array
(
[group_other] => Array
    (
        [field_b] => Array
           (
               [type] => number_integer
               [group_name] => group_other
           )
    )

[group_web_links] => Array
    (
        [field_d] => Array
            (
                [type] => link
                [group_name] => group_web_links
            )

        [field_e] => Array
            (
                [type] => link
                [group_name] => group_web_links
            )

        [field_f] => Array
            (
                [type] => text
                [group_name] => group_web_links
            )
    )

[field_a] => Array
    (
        [type] => text
        [group_name] =>
    )

[field_c] => Array
    (
        [type] => text
        [group_name] =>
    )
)
</code>```

答:
If key order of new array is not so important:</p>

```<code>$new_array = array();
foreach ($old_array as $key => $value) {
    if (empty($value['group_name'])) $new_array[$key] = $value;
    else {
        if (!array_key_exists($value['group_name'], $new_array) $new_array[$value['group_name']] = array();
        $new_array[$value['group_name']][$key] = $value;
    }
}
</code>```

Title: restructure array in php

Body:
I have the following source array which I'm trying to restructure using group_name to give me the require output below.

Any help or pointers appreciated.
Thanks, Lk

Source:

Array
(
[field_a] => Array
    (
        [type] => text
        [group_name] =>
    )

[field_b] => Array
    (
        [type] => number_integer
        [group_name] => group_other
    )

[field_c] => Array
    (
        [type] => text
        [group_name] =>
    )

[field_d] => Array
    (
        [type] => link
        [group_name] => group_web_links
    )

[field_e] => Array
    (
        [type] => link
        [group_name] => group_web_links
    )

[field_f] => Array
    (
        [type] => text
        [group_name] => group_web_links
    )

)

Output:

Array
(
[group_other] => Array
    (
        [field_b] => Array
           (
               [type] => number_integer
               [group_name] => group_other
           )
    )

[group_web_links] => Array
    (
        [field_d] => Array
            (
                [type] => link
                [group_name] => group_web_links
            )

        [field_e] => Array
            (
                [type] => link
                [group_name] => group_web_links
            )

        [field_f] => Array
            (
                [type] => text
                [group_name] => group_web_links
            )
    )

[field_a] => Array
    (
        [type] => text
        [group_name] =>
    )

[field_c] => Array
    (
        [type] => text
        [group_name] =>
    )
)

Body:
If key order of new array is not so important:

$new_array = array();
foreach ($old_array as $key => $value) {
    if (empty($value['group_name'])) $new_array[$key] = $value;
    else {
        if (!array_key_exists($value['group_name'], $new_array) $new_array[$value['group_name']] = array();
        $new_array[$value['group_name']][$key] = $value;
    }
}


问:
Javascript find matched sentence with predefined words
Hello guys I need help to figure out an expression. I got phrases like

const phrases = [
  "This is dummy sentences of example 05",
  "It needs help of your example 2022",
  "This dummy datas will be used for any example of matched needs "
]
var target = "example dummy datas 01"

expectedOutput = "This dummy datas will be used for any example of matched needs "```
</div>
</div>
</p>
<p>As you see above, target's three words matches with last sentence. The purpose is to find sentence includes most matched words.</p>
<p>I did like</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const phrases = [
  "This is dummy sentences of example 05",
  "It needs help of your example 2022",
  "This dummy datas will be used for any example of matched needs "
]
var target = "example dummy datas 01"

target = target.split(' ')

const expectedOutput = phrases.filter(sentence => {

  return target.every(word => {
    return sentence.indexOf(word) !== -1
  })
})
console.log(expectedOutput)</code>```

But it gives nothing

答:
You need to filter out the elements from the target string which are numeric:

```<code>target = target.split(' ').filter(w => isNaN(w))
</code>```

This works as below:

const phrases = [
  "This is dummy sentences of example 05",
  "It needs help of your example 2022",
  "This dummy datas will be used for any example of matched needs "
]
var target = "example dummy datas 01"

target = target.split(' ').filter(w => isNaN(w))

const expectedOutput = phrases.filter(sentence => {
  return target.every(word => {
    return sentence.indexOf(word) !== -1
  })
})
console.log(expectedOutput)```

Body:
Hello guys I need help to figure out an expression. I got phrases like

const phrases = [
  "This is dummy sentences of example 05",
  "It needs help of your example 2022",
  "This dummy datas will be used for any example of matched needs "
]
var target = "example dummy datas 01"

expectedOutput = "This dummy datas will be used for any example of matched needs "

As you see above, target's three words matches with last sentence. The purpose is to find sentence includes most matched words.

I did like

const phrases = [
  "This is dummy sentences of example 05",
  "It needs help of your example 2022",
  "This dummy datas will be used for any example of matched needs "
]
var target = "example dummy datas 01"

target = target.split(' ')

const expectedOutput = phrases.filter(sentence => {

  return target.every(word => {
    return sentence.indexOf(word) !== -1
  })
})
console.log(expectedOutput)

But it gives nothing

Body:
You need to filter out the elements from the target string which are numeric:

target = target.split(' ').filter(w => isNaN(w))

This works as below:

const phrases = [
  "This is dummy sentences of example 05",
  "It needs help of your example 2022",
  "This dummy datas will be used for any example of matched needs "
]
var target = "example dummy datas 01"

target = target.split(' ').filter(w => isNaN(w))

const expectedOutput = phrases.filter(sentence => {
  return target.every(word => {
    return sentence.indexOf(word) !== -1
  })
})
console.log(expectedOutput)


问:
Can I deploy both python 2 django 1.9 and python 3.9 and django 3.2 apps with same apache server
i have developed one project using python 3.9 and django 3.2.

and also one existing project is there that was developed python version 2 and Django 1.9.4. it was deployed in apache server it is working fine.

problems are raised when we trying to deploy latest project like python 3.9 and Django 3.2 in current servers(which have already python 2 and django 1.9.4 project is running).

答:
Yes you can. You should have the two versions of Python installed on your server and two virtual environments with the different Django versions installed to isolate your projects.

Related: How to use virtualenv with Python?


问:
Not allowing me to pass false value while using child to parent component interaction
Argument of type 'boolean' is not assignable to parameter of type 'string | symbol'.ts(2345)</p>
```<code>cancel() {
this.cancelRegister.emit(false);
}
</code>```

答:
Your are trying to pass a boolean value to an EventEmitter that is expecting a string or symbol.

Make sure that cancelRegister is defined like:

```<code>cancelRegister = new EventEmitter<boolean>();
</code>```

OR leave it as is and pass a string value to emit

Body:
Argument of type 'boolean' is not assignable to parameter of type 'string | symbol'.ts(2345)

cancel() {
this.cancelRegister.emit(false);
}

Body:
Your are trying to pass a boolean value to an EventEmitter that is expecting a string or symbol.

Make sure that cancelRegister is defined like:

cancelRegister = new EventEmitter<boolean>();

OR leave it as is and pass a string value to emit


问:
How to assign auto elastic IP in AWS auto scaling when new instance create based on load
I have an application which is based on bank payment API. I have configured AWS auto scaling used Application load balancer. Now Bank is asking us to provide live servers public IP to whitelist to use bank API. Now question is that how can I provide a IP list to them because when any new server will create in auto scaling based on load it does not set predefined elastic IP.

So is there any way to Auto set elastic IP on newly created servers?

Also my second question, is there any way to save apache2 access and error logs files based on host dynamic.

I am using EC2 ubuntu 20.04 with apache version 2.4

Please help me for these two queries.

答:
Create some EIPs and give them same label such as "group:whitelistforPayment".

Create a IAM role, which  allow your server can list EIPs and attachEIPs.

Install AWS CLI in your AMI and attach IAM role when server started.

Prepared "attachEIP" shell script and upload it to s3.
in this scripts, you can use aws cli such as:
aws ec2 describe-addresses ( list EIPs ...)
aws ec2 associate-address  ( attach EIP)

Modify userdata.
download and run the shell scripts when server start.


问:
list of dicts swagger python
I want to specify a List of dict
and the keys of that dicts also in my swagger documentation,

```<code>class GetCustomerDetailsByIdPOUT(BaseModel):
    profileData: Customer
    scanData : Reports
    Scan: list

</code>```

Currently, I am getting this

```<code> "Scan": [
    "string"
  ]
</code>```

You can also see in the image

I want something like this

```<code>"scans": [
                {
                "id": 0,
                "cameraId": 0,
                "reportId": 0,
                "sequenceNo": 1,
                "raw": [
                    "string"
                ],
                "spectrum": 1,
                "view": 1
                }
            ]
</code>```

答:
I think that you don't provide the information on what list will contain. I don't know what you want to have in there, but for example:

from typing import List

class GetCustomerDetailsByIdPOUT(BaseModel):
    profileData: Customer
    scanData : Reports
    Scan: List[MyScan]
```

within the type hinting you can provide the type - you class or build-in type, like List[float].

For python <= 3.8 you should use typing module, for 3.9+ you don't have to. More on typing aliases.

Also, if possible, think of aligning your naming convention to PEP8. For example profileData -> profile_data.

Title: list of dicts swagger python

Body:
I want to specify a List of dict
and the keys of that dicts also in my swagger documentation,

class GetCustomerDetailsByIdPOUT(BaseModel):
    profileData: Customer
    scanData : Reports
    Scan: list

Currently, I am getting this

 "Scan": [
    "string"
  ]

You can also see in the image

I want something like this

"scans": [
                {
                "id": 0,
                "cameraId": 0,
                "reportId": 0,
                "sequenceNo": 1,
                "raw": [
                    "string"
                ],
                "spectrum": 1,
                "view": 1
                }
            ]

Body:
I think that you don't provide the information on what list will contain. I don't know what you want to have in there, but for example:

from typing import List

class GetCustomerDetailsByIdPOUT(BaseModel):
    profileData: Customer
    scanData : Reports
    Scan: List[MyScan]

within the type hinting you can provide the type - you class or build-in type, like List[float].

For python <= 3.8 you should use typing module, for 3.9+ you don't have to. More on typing aliases.

Also, if possible, think of aligning your naming convention to PEP8. For example profileData -> profile_data.


问:
.NET: Get all Outlook calendar items
How can I get all items from a specific calendar (for a specific date).
Lets say for instance that I have a calendar with a recurring item every Monday evening. When I request all items like this:

```<code>CalendarItems = CalendarFolder.Items;
CalendarItems.IncludeRecurrences = true;
</code>```

I only get 1 item...

Is there an easy way to get all items (main item + derived items) from a calendar?
In my specific situation it can be possible to set a date limit but it would be cool just to get all items (my recurring items are time limited themselves).

I'm using the Microsoft Outlook 12 Object library (Microsoft.Office.Interop.Outlook).

答:
If you need want to access the shared folder from your friend, then you can set your friend as the recipient. Requirement: his calendar must be shared first. </p>

```<code>// Set recepient
Outlook.Recipient oRecip = (Outlook.Recipient)oNS.CreateRecipient("abc@yourmail.com");

// Get calendar folder
Outlook.MAPIFolder oCalendar = oNS.GetSharedDefaultFolder(oRecip, Outlook.OlDefaultFolders.olFolderCalendar);
</code>```

OwnerDisplayName: Qinnie

LastEditorDisplayName: Qinnie

Title: .NET: Get all Outlook calendar items

Body:
How can I get all items from a specific calendar (for a specific date).
Lets say for instance that I have a calendar with a recurring item every Monday evening. When I request all items like this:

CalendarItems = CalendarFolder.Items;
CalendarItems.IncludeRecurrences = true;

I only get 1 item...

Is there an easy way to get all items (main item + derived items) from a calendar?
In my specific situation it can be possible to set a date limit but it would be cool just to get all items (my recurring items are time limited themselves).

I'm using the Microsoft Outlook 12 Object library (Microsoft.Office.Interop.Outlook).

Body:
If you need want to access the shared folder from your friend, then you can set your friend as the recipient. Requirement: his calendar must be shared first.

// Set recepient
Outlook.Recipient oRecip = (Outlook.Recipient)oNS.CreateRecipient("abc@yourmail.com");

// Get calendar folder
Outlook.MAPIFolder oCalendar = oNS.GetSharedDefaultFolder(oRecip, Outlook.OlDefaultFolders.olFolderCalendar);


问:
Plotly Treemap Customdata not aligned with labels/ids
I am trying to add custom data to a treemap visual, but I cannot get the custom data to be aligned with the right categories. Here is what I have so far:

As you can see, the ''Name" does not match with the label (top right-corner).
Looking at fig.data[0].labels and fig.data[0].customdata I can see that they are not the same order, but I'm not sure how to fix this.

Thank you for your help.

```<code>df = pd.read_excel(this_dir/'Clean Tech'/FILE,
              sheet_name=0,
              skiprows=1)
df_plot = df.groupby(['Category','Sub-Category','Company']).size().reset_index()
df_plot.rename(columns={0:"Count"},inplace=True)

df_plot.fillna('TBD', inplace=True)

df_plot.sort_values(by=['Category','Sub-Category','Company'], inplace=True)

fig = px.treemap(df_plot,
             values='Count',
             color='Company',
             path=['Category','Sub-Category','Company'],
             color_discrete_map={'Arolytics': 'navy',
                                 'Wastewater Treatment': 'lightblue'}, #discrete color assignment
             color_discrete_sequence =['lightgray', 'lightblue', 'teal'],
             template = 'plotly_white',
             title = 'The CleanTech Universe',
             branchvalues="total"
           )

fig.update_traces(root_color='white')

fig.update_layout(font_family='Trebuchet',
              margin = dict(t=50, l=25, r=25, b=25),
             width=1200,
             height=700,
             uniformtext=dict(minsize=10))

companies = df_plot['Company'].tolist()
categories = df_plot['Category'].tolist()

fig.data[0].customdata = np.column_stack([categories, companies,])
fig.data[0].texttemplate = "%{label}<br>%{value}<br>%{customdata[0]}<br>%{customdata[2]}<br>"

fig.show()
</code>```

答:
using plotly example of creating a Treemap from a data frame as I can't imply what your data

the simplest way to populate customdata with Plotly Express is use hover_data argument

then it's a simple case of changing texttemplate

```<code>import plotly.express as px
df = px.data.tips()
fig = px.treemap(df, path=[px.Constant("all"), 'day', 'time', 'sex'], values='total_bill', hover_data=["sex","smoker","time"])
fig.update_traces(root_color="lightgrey")
fig.update_layout(margin = dict(t=50, l=25, r=25, b=25))
fig.data[0].texttemplate = "%{label}<br>%{value}<br>%{customdata[0]}<br>%{customdata[2]}<br>"
fig

</code>```

Body:
I am trying to add custom data to a treemap visual, but I cannot get the custom data to be aligned with the right categories. Here is what I have so far:

As you can see, the ''Name" does not match with the label (top right-corner).
Looking at fig.data[0].labels and fig.data[0].customdata I can see that they are not the same order, but I'm not sure how to fix this.

Thank you for your help.

df = pd.read_excel(this_dir/'Clean Tech'/FILE,
              sheet_name=0,
              skiprows=1)
df_plot = df.groupby(['Category','Sub-Category','Company']).size().reset_index()
df_plot.rename(columns={0:"Count"},inplace=True)

df_plot.fillna('TBD', inplace=True)

df_plot.sort_values(by=['Category','Sub-Category','Company'], inplace=True)

fig = px.treemap(df_plot,
             values='Count',
             color='Company',
             path=['Category','Sub-Category','Company'],
             color_discrete_map={'Arolytics': 'navy',
                                 'Wastewater Treatment': 'lightblue'}, #discrete color assignment
             color_discrete_sequence =['lightgray', 'lightblue', 'teal'],
             template = 'plotly_white',
             title = 'The CleanTech Universe',
             branchvalues="total"
           )

fig.update_traces(root_color='white')

fig.update_layout(font_family='Trebuchet',
              margin = dict(t=50, l=25, r=25, b=25),
             width=1200,
             height=700,
             uniformtext=dict(minsize=10))

companies = df_plot['Company'].tolist()
categories = df_plot['Category'].tolist()

fig.data[0].customdata = np.column_stack([categories, companies,])
fig.data[0].texttemplate = "%{label}
%{value}
%{customdata[0]}
%{customdata[2]}
"

fig.show()

Body:
using plotly example of creating a Treemap from a data frame as I can't imply what your data

the simplest way to populate customdata with Plotly Express is use hover_data argument

then it's a simple case of changing texttemplate

import plotly.express as px
df = px.data.tips()
fig = px.treemap(df, path=[px.Constant("all"), 'day', 'time', 'sex'], values='total_bill', hover_data=["sex","smoker","time"])
fig.update_traces(root_color="lightgrey")
fig.update_layout(margin = dict(t=50, l=25, r=25, b=25))
fig.data[0].texttemplate = "%{label}<br>%{value}<br>%{customdata[0]}<br>%{customdata[2]}<br>"
fig


问:
Need assistance on function to determine largest list Haskell
I need to create a function that reads from a list of courses (such as the one shown below), and return which courses has the largest number of programming languages.

Here is the list

```<code>progLanguages =
     [ ("CptS121" , ["C"]),
     ("CptS122" , ["C++"]),
     ("CptS223" , ["C++"]),
     ("CptS233" , ["Java"]),
     ("CptS321" , ["C#"]),
     ("CptS322" , ["Python", "JavaScript"]),
     ("CptS355" , ["Haskell", "Python", "PostScript", "Java"]),
     ("CptS360" , ["C"]),
     ("CptS370" , ["Java"]),
     ("CptS315" , ["Python"]),
     ("CptS411" , ["C", "C++"]),
     ("CptS451" , ["Python", "C#", "SQL"]),
     ("CptS475" , ["Python", "R"])
     ]
</code>```

It needs to be compatible with the following

```<code>The type of the max_count function should be compatible with one of the following:
max_count :: [(a1, [a2])] -> (a1, Int)
max_count :: Foldable t => [(a1, t a2)] -> (a1, Int)
</code>```

So far, I have attempted the following code

```<code>max_count [] = error "bad"
max_count [x] = x
max_count (x:xs) = x max_helper (max_count xs)
     where
     max_helper (a,b) (a',b')
          | length b > length b' = (a, length b)
          | otherwise = (a', length b')
</code>```

This has not worked in the slightest, and I am at a blank for what to do. Any help is appreciated.

答:
In this case, function foldr is best. Your approach is also feasible. It is only necessary to thoroughly understand the error messages of the compiler. In this case, I would advise you not to use the where clause and implement the function max_helper globally. I don't know if you intended

```<code>max_helper1 :: Foldable t => (a1, t a2) -> (a1, Int) -> (a1, Int)
</code>```

or

```<code>max_helper2 :: (a1, Int) -> (a1, Int) -> (a1, Int)
</code>```

There are many possibilities. The second parameter is good to have the same as the output value of the max_count, because of recursion.

The left side of the max_count can then look like this:

```<code>max_count (x:xs)
</code>```

or

```<code>max_count ((x,y):xs)
</code>```

.

The right side could probably contain:

```<code>max_helper12 ... (max_count xs)
</code>```

The periods must be replaced with x or (x,length y) according to the variant.

I also noticed that for max_helper1, there could be a double calculation of the length, and it isn't efficient in Haskell. Therefore, I would recommend counting only once in where:

```<code>max_helper1 (a,b) (a',b')
          | b'' > b' = (a, b'')
          | otherwise = (a', b')
  where
    b'' = length b
</code>```

Also, try to correct the termination rule:

 max_count [(x,y)] = (x,length y)

Body:
I need to create a function that reads from a list of courses (such as the one shown below), and return which courses has the largest number of programming languages.

Here is the list

progLanguages =
     [ ("CptS121" , ["C"]),
     ("CptS122" , ["C++"]),
     ("CptS223" , ["C++"]),
     ("CptS233" , ["Java"]),
     ("CptS321" , ["C#"]),
     ("CptS322" , ["Python", "JavaScript"]),
     ("CptS355" , ["Haskell", "Python", "PostScript", "Java"]),
     ("CptS360" , ["C"]),
     ("CptS370" , ["Java"]),
     ("CptS315" , ["Python"]),
     ("CptS411" , ["C", "C++"]),
     ("CptS451" , ["Python", "C#", "SQL"]),
     ("CptS475" , ["Python", "R"])
     ]

It needs to be compatible with the following

The type of the max_count function should be compatible with one of the following:
max_count :: [(a1, [a2])] -> (a1, Int)
max_count :: Foldable t => [(a1, t a2)] -> (a1, Int)

So far, I have attempted the following code

max_count [] = error "bad"
max_count [x] = x
max_count (x:xs) = x max_helper (max_count xs)
     where
     max_helper (a,b) (a',b')
          | length b > length b' = (a, length b)
          | otherwise = (a', length b')

This has not worked in the slightest, and I am at a blank for what to do. Any help is appreciated.

Body:
In this case, function foldr is best. Your approach is also feasible. It is only necessary to thoroughly understand the error messages of the compiler. In this case, I would advise you not to use the where clause and implement the function max_helper globally. I don't know if you intended

max_helper1 :: Foldable t => (a1, t a2) -> (a1, Int) -> (a1, Int)

or

max_helper2 :: (a1, Int) -> (a1, Int) -> (a1, Int)

There are many possibilities. The second parameter is good to have the same as the output value of the max_count, because of recursion.

The left side of the max_count can then look like this:

max_count (x:xs)

or

max_count ((x,y):xs)

.

The right side could probably contain:

max_helper12 ... (max_count xs)

The periods must be replaced with x or (x,length y) according to the variant.

I also noticed that for max_helper1, there could be a double calculation of the length, and it isn't efficient in Haskell. Therefore, I would recommend counting only once in where:

max_helper1 (a,b) (a',b')
          | b'' > b' = (a, b'')
          | otherwise = (a', b')
  where
    b'' = length b

Also, try to correct the termination rule:

 max_count [(x,y)] = (x,length y)