问:
Oracle replace comma, but only if no space after
I'm finding examples for other languages, but I really don't understand regular expressions, so it's hard to convert to Oracle syntax.

I think I want to use REGEXP_REPLACE, and I want to replace a comma with a dash, but only if there is no space after the comma.  So, for example:

TABLE TREE,TREE SPECIES, MAPLE

would replace the first comma, but not the second:

TABLE TREE-TREE SPECIES, MAPLE

I can do a simple REGEXP_REPLACE, but only the opposite of what I want:

```<code>REGEXP_REPLACE(FieldToChange, ', ', '-')
</code>```

That's the same as a straight REPLACE, which I do understand.

```<code>REGEXP_REPLACE(FieldToChange, ',[^ ]', '-')
</code>```

That grabs only the comma that doesn't have a space after, but it is taking the next character too, resulting in:

TABLE TREE-REE SPECIES, MAPLE

I'm reading the Oracle docs, but like many docs, you need to understand quite a bit before the docs make any sense.  Therefore, I'd really like an explanation, rather than a simple answer.  (The other answers I've found, for other languages, are just giving the answer, which isn't helping me convert this to Oracle.)

答:
Your regex in REGEXP_REPLACE(FieldToChange, ',[^ ]', '-') matches a comma with , and any char other than a space with the [^ ] negated bracket expression. The matched text is replaced with -, your replacement pattern.

In regex, a position not followed with some other pattern is usually matched (or "asserted") with the help of a negative lookahead (like (?! )). However, Oracle regex engine is POSIX based, and does not support lookarounds.

You may rely on the capturing mechanism here:

```<code>REGEXP_REPLACE(FieldToChange, ',([^ ])', '-\1')
</code>```

Now, ([^ ]) captures any char but space into Group 1 and you may reference the value in the group with a \1 in the replacement pattern. \1 is a numeric replacement backreference. You may have up to 9 groups in your pattern, POSIX \1-like pbackreferences do not allow more (from 1 to 9).

If you want to also match a comma at the end of the string, you need to use an alternation in the group:

```<code>REGEXP_REPLACE(FieldToChange, ',([^ ]|$)', '-\1')
</code>```

The ([^ ]|$) capturing group matches either any char but space or end of string. You can't use [^ $] because $ loses its end-of-string anchor meaning inside the bracket expression and [^ $] matches any char but space and dollar symbol.

Body:
I'm finding examples for other languages, but I really don't understand regular expressions, so it's hard to convert to Oracle syntax.

I think I want to use REGEXP_REPLACE, and I want to replace a comma with a dash, but only if there is no space after the comma.  So, for example:

TABLE TREE,TREE SPECIES, MAPLE

would replace the first comma, but not the second:

TABLE TREE-TREE SPECIES, MAPLE

I can do a simple REGEXP_REPLACE, but only the opposite of what I want:

REGEXP_REPLACE(FieldToChange, ', ', '-')

That's the same as a straight REPLACE, which I do understand.

REGEXP_REPLACE(FieldToChange, ',[^ ]', '-')

That grabs only the comma that doesn't have a space after, but it is taking the next character too, resulting in:

TABLE TREE-REE SPECIES, MAPLE

I'm reading the Oracle docs, but like many docs, you need to understand quite a bit before the docs make any sense.  Therefore, I'd really like an explanation, rather than a simple answer.  (The other answers I've found, for other languages, are just giving the answer, which isn't helping me convert this to Oracle.)

Body:
Your regex in REGEXP_REPLACE(FieldToChange, ',[^ ]', '-') matches a comma with , and any char other than a space with the [^ ] negated bracket expression. The matched text is replaced with -, your replacement pattern.

In regex, a position not followed with some other pattern is usually matched (or "asserted") with the help of a negative lookahead (like (?! )). However, Oracle regex engine is POSIX based, and does not support lookarounds.

You may rely on the capturing mechanism here:

REGEXP_REPLACE(FieldToChange, ',([^ ])', '-\1')

Now, ([^ ]) captures any char but space into Group 1 and you may reference the value in the group with a \1 in the replacement pattern. \1 is a numeric replacement backreference. You may have up to 9 groups in your pattern, POSIX \1-like pbackreferences do not allow more (from 1 to 9).

If you want to also match a comma at the end of the string, you need to use an alternation in the group:

REGEXP_REPLACE(FieldToChange, ',([^ ]|$)', '-\1')

The ([^ ]|$) capturing group matches either any char but space or end of string. You can't use [^ $] because $ loses its end-of-string anchor meaning inside the bracket expression and [^ $] matches any char but space and dollar symbol.


来源: stackexchange

问:
What does "ask" mean in Haskell and what's the difference of it and "asks" function?
I can't understand how to use the ask function, I know how to use the asks function, but I don't know if they're related.

I was reading the "What I wish I knew when learning Haskell" of Stephen and I found this example:

{-# LANGUAGE GeneralizedNewtypeDeriving #-}

import Control.Monad.Reader
import Control.Monad.Writer
import Control.Monad.State

type Stack = [Int]
type Output = [Int]
type Program = [Instr]

type VM a = ReaderT Program (WriterT Output (State Stack)) a

newtype Comp a = Comp { unComp :: VM a }
    deriving (Functor, Applicative, Monad,
                MonadReader Program, MonadWriter Output,
                  MonadState Stack)

data Instr = Push Int
            | Pop
            | Puts

evalInstr :: Instr -> Comp ()
evalInstr instr = case instr of
                    Pop -> modify tail
                    Push n -> modify (n:)
                    Puts -> do
                        tos <- gets head
                        tell [tos]

eval :: Comp ()
eval = do
    instr <- ask
    case instr of
      [] -> return ()
      (i:is) -> evalInstr i >> local (const is) eval

execVM :: Program -> Output
execVM = flip evalState [] . execWriterT . runReaderT (unComp eval)

program :: Program
program = [
        Push 42,
        Push 27,
        Puts,
        Pop,
        Puts,
        Pop
    ]

main :: IO ()
main = mapM_ print $ execVM program
```

So, my question is: from where the list was taken?

答:
ask is asks id. While in...

```<code>do
    x <- asks f
    -- etc.
</code>```

... x will be the result of applying f to the environment of your MonadReader computation, in...

```<code>do
    x <- ask
    -- etc.
</code>```

... x will be the environment itself.

ContentLicense: CC BY-SA 4.0

Body:
I can't understand how to use the ask function, I know how to use the asks function, but I don't know if they're related.

I was reading the "What I wish I knew when learning Haskell" of Stephen and I found this example:

{-# LANGUAGE GeneralizedNewtypeDeriving #-}

import Control.Monad.Reader
import Control.Monad.Writer
import Control.Monad.State

type Stack = [Int]
type Output = [Int]
type Program = [Instr]

type VM a = ReaderT Program (WriterT Output (State Stack)) a

newtype Comp a = Comp { unComp :: VM a }
    deriving (Functor, Applicative, Monad,
                MonadReader Program, MonadWriter Output,
                  MonadState Stack)

data Instr = Push Int
            | Pop
            | Puts

evalInstr :: Instr -> Comp ()
evalInstr instr = case instr of
                    Pop -> modify tail
                    Push n -> modify (n:)
                    Puts -> do
                        tos <- gets head
                        tell [tos]

eval :: Comp ()
eval = do
    instr <- ask
    case instr of
      [] -> return ()
      (i:is) -> evalInstr i >> local (const is) eval

execVM :: Program -> Output
execVM = flip evalState [] . execWriterT . runReaderT (unComp eval)

program :: Program
program = [
        Push 42,
        Push 27,
        Puts,
        Pop,
        Puts,
        Pop
    ]

main :: IO ()
main = mapM_ print $ execVM program

So, my question is: from where the list was taken?

Body:
ask is asks id. While in...

do
    x <- asks f
    -- etc.

... x will be the result of applying f to the environment of your MonadReader computation, in...

do
    x <- ask
    -- etc.

... x will be the environment itself.


问:
Is it possible to set expiry time using Apache Ignite in C++?
I am using the C++ thin client API and I want to have the data deleted from the cache after 5 minutes. I am connecting to ignite through docker and using the persistence storage. In the documentation for the C++ libraries, I cannot find anything relating to "expiry" and I tried adding the expiry option into the config xml file that my docker container reads in, but that didn't seem to work either. I put data into the cache and checked for the data after 5 minutes (I also checked 10, 20, 30 minutes later) and the data was still there.

Here is my config xml file:

```<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"
       xsi:schemaLocation="
               http://www.springframework.org/schema/beans
               http://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="ignite.cfg" class="org.apache.ignite.configuration.IgniteConfiguration">

    <!-- Enabling Apache Ignite Persistent Store. -->
    <property name="dataStorageConfiguration">
      <bean class="org.apache.ignite.configuration.DataStorageConfiguration">
        <property name="defaultDataRegionConfiguration">
          <bean class="org.apache.ignite.configuration.DataRegionConfiguration">
            <property name="persistenceEnabled" value="true"/>
        <property name="name" value="Default_Region" />
          </bean>
        </property>
      </bean>
    </property>

    <property name="discoverySpi">
      <bean class="org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi">
        <property name="ipFinder">
          <!-- Uncomment static IP finder to enable static-based discovery of initial nodes. -->
          <!--<bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder">-->
          <bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.multicast.TcpDiscoveryMulticastIpFinder">
            <property name="addresses">
              <list>
                <!-- In distributed environment, replace with actual host IP address. -->
                <value>127.0.0.1:47500..47502</value>
              </list>
            </property>
          </bean>
        </property>
      </bean>
    </property>

  </bean>

  <bean class="org.apache.ignite.configuration.CacheConfiguration">

    <property name="expiryPolicyFactory">
      <bean class="javax.cache.expiry.CreatedExpiryPolicy" factory-method="factoryOf">
        <constructor-arg>
          <bean class="javax.cache.expiry.Duration">
            <constructor-arg value="MINUTES"/>
            <constructor-arg value="5"/>
          </bean>
        </constructor-arg>
      </bean>
    </property>

  </bean>

</beans>
</code>```

答:
Yes, the c++ thin client doesn't support this feature at the moment.

I think you could either define a cache with expiration completely on the server-side or to define only a cache template https://apacheignite.readme.io/docs/cache-template with expiry policy and use it from a client.

Body:
I am using the C++ thin client API and I want to have the data deleted from the cache after 5 minutes. I am connecting to ignite through docker and using the persistence storage. In the documentation for the C++ libraries, I cannot find anything relating to "expiry" and I tried adding the expiry option into the config xml file that my docker container reads in, but that didn't seem to work either. I put data into the cache and checked for the data after 5 minutes (I also checked 10, 20, 30 minutes later) and the data was still there.

Here is my config xml file:

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

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
               http://www.springframework.org/schema/beans
               http://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="ignite.cfg" class="org.apache.ignite.configuration.IgniteConfiguration">

    <property name="dataStorageConfiguration">
      <bean class="org.apache.ignite.configuration.DataStorageConfiguration">
        <property name="defaultDataRegionConfiguration">
          <bean class="org.apache.ignite.configuration.DataRegionConfiguration">
            <property name="persistenceEnabled" value="true"/>
        <property name="name" value="Default_Region" />
          </bean>
        </property>
      </bean>
    </property>

    <property name="discoverySpi">
      <bean class="org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi">
        <property name="ipFinder">

          <bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.multicast.TcpDiscoveryMulticastIpFinder">
            <property name="addresses">
              <list>

                <value>127.0.0.1:47500..47502</value>
              </list>
            </property>
          </bean>
        </property>
      </bean>
    </property>

  </bean>

  <bean class="org.apache.ignite.configuration.CacheConfiguration">

    <property name="expiryPolicyFactory">
      <bean class="javax.cache.expiry.CreatedExpiryPolicy" factory-method="factoryOf">
        <constructor-arg>
          <bean class="javax.cache.expiry.Duration">
            <constructor-arg value="MINUTES"/>
            <constructor-arg value="5"/>
          </bean>
        </constructor-arg>
      </bean>
    </property>

  </bean>

</beans>


问:
Console.log output vs return output not the same?
Ive never experienced this and maybe someone could explain to me whats happening?

```<code>const columns = Object.values(props[1]).map((x, i) =>{
            console.log(x) <- output: {name: "companyName", label: "Company", dataType: "string", width: 200, tooltip: "", …}
            return x
        })

console.log(columns) <- output: (4) [{…}, {…}, {…}, {…}]
</code>```

Why are they outputting differently? I need it to look like the console.log(x) inside the map.
I assumed console.log(x) and console.log(columns) would be the same.

答:
you are presumably mapping 4 values in props[1] to be {name:....} and assigning it to columns thus getting [{...}, {...}, {...}, {...}]

of-course, columns is not same as x but [ x, x, x, x]

Body:
Ive never experienced this and maybe someone could explain to me whats happening?

const columns = Object.values(props[1]).map((x, i) =>{
            console.log(x) <- output: {name: "companyName", label: "Company", dataType: "string", width: 200, tooltip: "", …}
            return x
        })

console.log(columns) <- output: (4) [{…}, {…}, {…}, {…}]

Why are they outputting differently? I need it to look like the console.log(x) inside the map.
I assumed console.log(x) and console.log(columns) would be the same.


问:
Why does Python take so long to process my Regex?
I'm making a Python program that matches all the emails in a string and returns them to the user:

```<code>emailRegex = re.compile(r'((.*)+@(.*)+\.(.*){3})')
text = "John Smith, Vice Provost for Undergraduate Studies\n123-456-7890\njohn.smith@email.edu"
emailList = emailRegex.findall(text)
clipOut = []
for tup in emailList:
     clipOut.append(tup[0])
print(clipOut)
</code>```

I ran this program for over 9 minutes without any output

Strangely enough, changing the text string to "John\n123-456-7890\njohn.smith@email.edu" causes the Regex to match nearly instantly.

Adding more text to the first line in the text string makes the Regex take increasingly longer to match. The string John Smith, Vice Provost\n123-456-7890\njohn.smith@email.edu takes just over 10 seconds to run on my laptop. Reducing the amount of characters before the email increases matching speed. Changing the characters used does not increase matching speed. However, removing all new lines makes the program run at expected speeds, regardless of the amount of characters before email.

Finally, changing the regex to:

emailRegex = re.compile(r'([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+(\.[a-zA-Z]{2,4}))')

Makes the program run just fine, regardless of string length.

I understand that my Regex was flawed, but I don't understand why it causes my program to take so long to run

答: The error was presumably caused by the + after (.*). Changing the regex to emailRegex = re.compile(r'((.+)@(.+)\.(.){2,4})') causes the program to run as expected. Thank you for the help!

Body:
I'm making a Python program that matches all the emails in a string and returns them to the user:

emailRegex = re.compile(r'((.*)+@(.*)+\.(.*){3})')
text = "John Smith, Vice Provost for Undergraduate Studies\n123-456-7890\njohn.smith@email.edu"
emailList = emailRegex.findall(text)
clipOut = []
for tup in emailList:
     clipOut.append(tup[0])
print(clipOut)

I ran this program for over 9 minutes without any output

Strangely enough, changing the text string to "John\n123-456-7890\njohn.smith@email.edu" causes the Regex to match nearly instantly.

Adding more text to the first line in the text string makes the Regex take increasingly longer to match. The string John Smith, Vice Provost\n123-456-7890\njohn.smith@email.edu takes just over 10 seconds to run on my laptop. Reducing the amount of characters before the email increases matching speed. Changing the characters used does not increase matching speed. However, removing all new lines makes the program run at expected speeds, regardless of the amount of characters before email.

Finally, changing the regex to:

emailRegex = re.compile(r'([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+(\.[a-zA-Z]{2,4}))')

Makes the program run just fine, regardless of string length.

I understand that my Regex was flawed, but I don't understand why it causes my program to take so long to run


问:
FuzzyWuzzy's fuzz.ratio not behaving as expected
I am using fuzzywuzzy to do fuzzy matching and expect fuzz.ratio to work the same/yield the same results when it's used independently vs. when it is used as the 'scorer' parameter in the process module. However, it does not.

I have tried testing all other scorers using them independently as well as in process.extract, and the give the same results.

```<code>fuzz.ratio('So','SO)
>> 50
</code>```

When using it in process module where on of the comparisons is the following:

```<code>...process.extract('So',['SO'])
>> 100
</code>```

答:
If you look at the source code here and here, it seems that process.extract() forces everything to lower case, while running fuzz.ratio() directly does not.

If you use the flag processor=None, you get the expected results.

```<code>process.extract('So', ['SO'], processor=None, scorer=fuzz.ratio)
>> [('SO', 50)]
</code>```

Body:
I am using fuzzywuzzy to do fuzzy matching and expect fuzz.ratio to work the same/yield the same results when it's used independently vs. when it is used as the 'scorer' parameter in the process module. However, it does not.

I have tried testing all other scorers using them independently as well as in process.extract, and the give the same results.

fuzz.ratio('So','SO)
>> 50

When using it in process module where on of the comparisons is the following:

...process.extract('So',['SO'])
>> 100

Body:
If you look at the source code here and here, it seems that process.extract() forces everything to lower case, while running fuzz.ratio() directly does not.

If you use the flag processor=None, you get the expected results.

process.extract('So', ['SO'], processor=None, scorer=fuzz.ratio)
>> [('SO', 50)]


问:
How to cancel an Dialog themed like Activity when touched outside the window?
I have an activity with a Dialog theme and I would like to close (finish) this activity when someone touches the screen anywhere outside this activity's window ? How can I do this ?</p>

答:
Just use this theme. Activity will be dismissed on touch outside.</p>

```<code><style name="DialogTheme" parent="Theme.MaterialComponents.DayNight.Dialog">
    <item name="android:windowIsTranslucent">true</item>
</style>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Just use this theme. Activity will be dismissed on touch outside.

<style name="DialogTheme" parent="Theme.MaterialComponents.DayNight.Dialog">
    <item name="android:windowIsTranslucent">true</item>
</style>


问:
AWS Lex: An error has occurred: Invalid Lambda Response: Lambda response elicited for an invalid slot name
Using a validation hook for AWS lex. If i try to elicit slot, lex fails with:

An error has occurred: Invalid Lambda Response: Lambda response elicited for an invalid slot name

Below is my lex event and response from my lambda function. I have 2 slots, topping and crust. Topping was the first slot already given by client. Crust was the missing slot.

I have reviewed most of AWS documentation, stackoverflow and other tutorials but I can't seem to break past this..anyone have any idea?

LexEvent:

```<code>{
    "messageVersion": "1.0",
    "invocationSource": "DialogCodeHook",
    "userId": "cbzn2ql6dl59dro",
    "sessionAttributes": {},
    "outputDialogMode": "Text",
    "currentIntent": {
        "name": "Pizza",
        "slots": {
            "topping": "Chicken"
        },
        "confirmationStatus": "None"
    },
    "bot": {
        "name": "PizzaMaker",
        "alias": "$LATEST",
        "version": "$LATEST"
    }
}
</code>```

Response from Lambda

```<code>{
    "sessionAttributes": {},
    "dialogAction": {
        "type": "ElicitSlot",
        "message": {
            "contentType": "PlainText",
            "content": "What type of crust do you want?"
        },
        "intentName": "Pizza",
        "slotToElicit": "Curst",
        "slots": {
            "topping": "Chicken"
        }
    }
}
</code>```

答: I tried validating your Lambda response structure using JSONLint and noticed that there is an additional symbol included in the value for the slotToElicit key which is otherwise invisible. This would point to why Lex is unable to find the slot name.

Body:
Using a validation hook for AWS lex. If i try to elicit slot, lex fails with:

An error has occurred: Invalid Lambda Response: Lambda response elicited for an invalid slot name

Below is my lex event and response from my lambda function. I have 2 slots, topping and crust. Topping was the first slot already given by client. Crust was the missing slot.

I have reviewed most of AWS documentation, stackoverflow and other tutorials but I can't seem to break past this..anyone have any idea?

LexEvent:

{
    "messageVersion": "1.0",
    "invocationSource": "DialogCodeHook",
    "userId": "cbzn2ql6dl59dro",
    "sessionAttributes": {},
    "outputDialogMode": "Text",
    "currentIntent": {
        "name": "Pizza",
        "slots": {
            "topping": "Chicken"
        },
        "confirmationStatus": "None"
    },
    "bot": {
        "name": "PizzaMaker",
        "alias": "$LATEST",
        "version": "$LATEST"
    }
}

Response from Lambda

{
    "sessionAttributes": {},
    "dialogAction": {
        "type": "ElicitSlot",
        "message": {
            "contentType": "PlainText",
            "content": "What type of crust do you want?"
        },
        "intentName": "Pizza",
        "slotToElicit": "Curst",
        "slots": {
            "topping": "Chicken"
        }
    }
}


问:
Angular 9 -- Multiple Children inside Parent
Can someone explain to me, why the appropriate child switch won't update properly?
Click on the second child and the first child updates, but the console shows the correct method being called. Is it not possible to call the same child component in the parent like I am?

https://stackblitz.com/edit/angular-ivy-ch65ks

答:
You have hardcoded id in the child component when you use it multiple times, the same id will be repeated and that's what causing the issue.

You need to pass the id as an input.

in child.component.ts

add Id to the inputs array:

inputs: ['textOne', 'textTwo', 'checkedValue', 'isDisabled', 'Id'],
```

<p>and define the Id</p>

<pre class="lang-js prettyprint-override"><code>Id: string;
</code>```

In in child.component.html, bind the id to Id

<input type="checkbox" [id]="Id" [disabled]="isDisabled">

{{textOne}}

{{textTwo}}

```

<p>and pass the Id from <code>parent.component.html</code></p>

<pre class="lang-html prettyprint-override"><code><app-child
    name="one"
    id="one"
    textOne="Yes"
    [Id]="'first'"
    textTwo="No"
    [checkedValue]="test1"
    (checkToEmit)="test1Checked($event)"
>
</app-child>

<app-child
    name="two"
    id="two"
    textOne="Yes"
    [Id]="'second'"
    textTwo="No"
    [checkedValue]="test2"
    (checkToEmit)="test2Checked($event)"
>
</app-child>
</code>```

Body:
You have hardcoded id in the child component when you use it multiple times, the same id will be repeated and that's what causing the issue.

You need to pass the id as an input.

in child.component.ts

add Id to the inputs array:

inputs: ['textOne', 'textTwo', 'checkedValue', 'isDisabled', 'Id'],

and define the Id

Id: string;

In in child.component.html, bind the id to Id

<input type="checkbox" [id]="Id" [disabled]="isDisabled">
<label class="toggle-button-switch" [for]="Id" (click)="toggleCheck()"></label>
<div class="toggle-button-text">
    <div class="toggle-button-text-on">{{textOne}}</div>
    <div class="toggle-button-text-off">{{textTwo}}</div>
</div>

and pass the Id from parent.component.html

<app-child
    name="one"
    id="one"
    textOne="Yes"
    [Id]="'first'"
    textTwo="No"
    [checkedValue]="test1"
    (checkToEmit)="test1Checked($event)"
>
</app-child>

<app-child
    name="two"
    id="two"
    textOne="Yes"
    [Id]="'second'"
    textTwo="No"
    [checkedValue]="test2"
    (checkToEmit)="test2Checked($event)"
>
</app-child>


问:
need assistance with css layout

  I am having css layout issues.  I am attempting to align the Required! message to the right of the input elements

Keeping the flow:

Species:

input element    error-message

Breed:

input element    error-message

I tried various nested divs with-out success.

Link:

http://jsfiddle.net/d0773d/BpqyT/

答:
Quote:  "I am attempting to align the Required! message to the right of the input elements"

You have a line break
 in between which puts "Required!" on another line below the input element.

ContentLicense: CC BY-SA 3.0

Title: need assistance with css layout

Body:
Quote:  "I am attempting to align the Required! message to the right of the input elements"

You have a line break <br /> in between which puts "Required!" on another line below the input element.


问:
Playing multiple sounds at contact - Xcode Scene Kit
here's a challenging one I have not found the answer for. This is why I ended up creating an account, stop lurking and being part of the community:

I am coding a game where, when you shake your phone, 5 SCNNodes (boxes with textures of dice) are given an impulse to bounce inside a frame formed by 2 SCNNodes: box & floor. It emulates a poker dice game.

I have coded a contact delegate where I play a sound every time a die hits another die or the box, but only the first die contacting any of the bodies, once the impulse starts, will be the one playing the sound.

I am not able to play the same sound simultaneously every time any of the dice contact with each other, the floor or the frame. I am not able to have that satisfying 'cascade of sounds' when only being able to code with nodeA and nodeB. Many contacts take place at the same time but only one plays the sound.

This is what my code looks like:

```<code>extension GameViewController : SCNPhysicsContactDelegate {
func physicsWorld(_ world: SCNPhysicsWorld, didBegin contact: SCNPhysicsContact) {

    if (contact.nodeA.physicsBody?.categoryBitMask == BodyType.die.rawValue && contact.nodeB.physicsBody?.categoryBitMask == BodyType.die.rawValue){

        do{
            audioPlayer?.play()
        }catch{
        }
    }else if (contact.nodeB.physicsBody?.categoryBitMask == BodyType.box.rawValue && contact.nodeA.physicsBody?.categoryBitMask == BodyType.die.rawValue){

        do{
            audioPlayer?.play()
        }catch{
        }

}}}
</code>```

The AVaudioPlayer is prepared at the ViewLoad. I have not bothered filling in the catch instances.

Here I have an enum of categorybitmasks so I can test for contact:

```<code>enum BodyType:Int {

case die = 1
case box = 2
case floor = 4
</code>```

}

How can I play the sound anytime any die hits another die, the floor or the frame?

Thank you very much!

答:
I solved it a bit differently, but maybe this will help:

Opinions vary, but I found that SK sound worked better for something like this, so I added an SKOverlay and just used it for sound. Added a couple of sound nodes to spread the usage as I had 100's of objects playing at the same time.  Created a sound class something like:

```<code>var explosions = [gameTypes: SKAction]()
let vAction = SKAction.playSoundFileName(vName, waitForCompletion: False)
audioNodeAction.run(explosions[soundType]
</code>```

Preload the actions/sounds and then play the sounds below like (enemyMissileHit)

On contacts, I used names of nodes but several ways to do this:

```<code>guard let nodeNameA = contact.nodeA.name else { return }
guard let nodeNameB = contact.nodeB.name else { return }

if(nodeNameA.prefix(5) == "Explo" && nodeNameB.prefix(5) == "Missi")
{
 gameControl.enemyMissileHit(vIndex: Int(nodeNameB.suffix(4))!)
}
if(nodeNameA.prefix(5) == "Missi" && nodeNameB.prefix(5) == "Explo")
{
 gameControl.enemyMissileHit(vIndex: Int(nodeNameA.suffix(4))!)
}
if(nodeNameA.prefix(5) == "Explo" && nodeNameB.prefix(5) == "Hive ")
{
 gameControl.enemyHiveHit(vIndex: Int(nodeNameB.suffix(4))!)
}
if(nodeNameA.prefix(5) == "Hive " && nodeNameB.prefix(5) == "Explo")
{
 gameControl.enemyHiveHit(vIndex: Int(nodeNameA.suffix(4))!)
}
</code>```

For yours, just name all of your nodes (like Floor) and hopefully that helps.  I had to type this in, so please forgive syntax errors.

Body:
here's a challenging one I have not found the answer for. This is why I ended up creating an account, stop lurking and being part of the community:

I am coding a game where, when you shake your phone, 5 SCNNodes (boxes with textures of dice) are given an impulse to bounce inside a frame formed by 2 SCNNodes: box & floor. It emulates a poker dice game.

I have coded a contact delegate where I play a sound every time a die hits another die or the box, but only the first die contacting any of the bodies, once the impulse starts, will be the one playing the sound.

I am not able to play the same sound simultaneously every time any of the dice contact with each other, the floor or the frame. I am not able to have that satisfying 'cascade of sounds' when only being able to code with nodeA and nodeB. Many contacts take place at the same time but only one plays the sound.

This is what my code looks like:

extension GameViewController : SCNPhysicsContactDelegate {
func physicsWorld(_ world: SCNPhysicsWorld, didBegin contact: SCNPhysicsContact) {

    if (contact.nodeA.physicsBody?.categoryBitMask == BodyType.die.rawValue && contact.nodeB.physicsBody?.categoryBitMask == BodyType.die.rawValue){

        do{
            audioPlayer?.play()
        }catch{
        }
    }else if (contact.nodeB.physicsBody?.categoryBitMask == BodyType.box.rawValue && contact.nodeA.physicsBody?.categoryBitMask == BodyType.die.rawValue){

        do{
            audioPlayer?.play()
        }catch{
        }

}}}

The AVaudioPlayer is prepared at the ViewLoad. I have not bothered filling in the catch instances.

Here I have an enum of categorybitmasks so I can test for contact:

enum BodyType:Int {

case die = 1
case box = 2
case floor = 4

}

How can I play the sound anytime any die hits another die, the floor or the frame?

Thank you very much!

Body:
I solved it a bit differently, but maybe this will help:

Opinions vary, but I found that SK sound worked better for something like this, so I added an SKOverlay and just used it for sound. Added a couple of sound nodes to spread the usage as I had 100's of objects playing at the same time.  Created a sound class something like:

var explosions = [gameTypes: SKAction]()
let vAction = SKAction.playSoundFileName(vName, waitForCompletion: False)
audioNodeAction.run(explosions[soundType]

Preload the actions/sounds and then play the sounds below like (enemyMissileHit)

On contacts, I used names of nodes but several ways to do this:

guard let nodeNameA = contact.nodeA.name else { return }
guard let nodeNameB = contact.nodeB.name else { return }

if(nodeNameA.prefix(5) == "Explo" && nodeNameB.prefix(5) == "Missi")
{
 gameControl.enemyMissileHit(vIndex: Int(nodeNameB.suffix(4))!)
}
if(nodeNameA.prefix(5) == "Missi" && nodeNameB.prefix(5) == "Explo")
{
 gameControl.enemyMissileHit(vIndex: Int(nodeNameA.suffix(4))!)
}
if(nodeNameA.prefix(5) == "Explo" && nodeNameB.prefix(5) == "Hive ")
{
 gameControl.enemyHiveHit(vIndex: Int(nodeNameB.suffix(4))!)
}
if(nodeNameA.prefix(5) == "Hive " && nodeNameB.prefix(5) == "Explo")
{
 gameControl.enemyHiveHit(vIndex: Int(nodeNameA.suffix(4))!)
}

For yours, just name all of your nodes (like Floor) and hopefully that helps.  I had to type this in, so please forgive syntax errors.


问:
Can't execute any async method from the callback listeners in firebase
I am having trouble in executing any async task from inside the onCompleted function of onCompletedListener.

I want to execute 2 things

Upload the pic to firebase storage and obtain a downloadable link. (Done)

Update that downloadable link in my user table in firestore. (Not getting executed)

My approach was to obtain the downloadString in the onCompleteListener of the UploadTask. And then pass it as input to another Worker thread to update my user table. The new worker thread is launched from the onCompleteListener of the first task.

Here's a snippet of my code.

```<code>uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
            @Override
            public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                if (!task.isSuccessful()) {
                    throw task.getException(); //TODO catch it later
                }
                return finalPicStorageReference.getDownloadUrl();
            }
        }).addOnCompleteListener(new OnCompleteListener<Uri>() {
            @Override
            public void onComplete(@NonNull Task<Uri> task) {
                if (task.isSuccessful()) {
                    Uri downloadUri = task.getResult();
                    Log.d(TAG, "onComplete: Successfully Uploaded");
                    if (downloadUri != null) {
                        String picDownloadString = downloadUri.toString();
                        Constraints.Builder builder = new Constraints.Builder();
                        Data.Builder data = new Data.Builder();
                        if (profileBoolean) {
                            data.putBoolean("profileBoolean", true);
                        } else if (coverBoolean) {
                            data.putBoolean("coverBoolean", true);
                        }
                        data.putString("picDownloadString", picDownloadString);
                        /*OneTimeWorkRequest updatePicEntryAtDB = new OneTimeWorkRequest
                                .Builder(UpdateUserDatabaseWorker.class)
                                .addTag("Updating pic in database")
                                .setInputData(data.build())
                                .build();
                        WorkManager.getInstance(getApplicationContext()).beginUniqueWork("picUpdationInDB", ExistingWorkPolicy.APPEND,
                                updatePicEntryAtDB).enqueue();
                        */results[0] = Result.success();
                    }
                } else {
                    results[0] = Result.failure();
                }
            }
        });
</code>```

The code uploads the pic perfectly when it is commented like this. But on removing the comment to allow updating of the user table, the code stops working altogether. That is, the pic doesn't get uploaded too.

答:
Answering with the workaround I implemented

For the starters, I managed to work around using the Tasks.await method. But the drawback here is that you'll have to much strain on your main thread.
Second option is to have a WorkManager which will work just fine. You can design two separate work class. The first one will take the Image as input, and upload the pic on firebase storage and generate the downloadable link, and the other one will take this downloadable link as input and then update the users profile database.

Body:
I am having trouble in executing any async task from inside the onCompleted function of onCompletedListener.

I want to execute 2 things

Upload the pic to firebase storage and obtain a downloadable link. (Done)

Update that downloadable link in my user table in firestore. (Not getting executed)

My approach was to obtain the downloadString in the onCompleteListener of the UploadTask. And then pass it as input to another Worker thread to update my user table. The new worker thread is launched from the onCompleteListener of the first task.

Here's a snippet of my code.

uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
            @Override
            public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                if (!task.isSuccessful()) {
                    throw task.getException(); //TODO catch it later
                }
                return finalPicStorageReference.getDownloadUrl();
            }
        }).addOnCompleteListener(new OnCompleteListener<Uri>() {
            @Override
            public void onComplete(@NonNull Task<Uri> task) {
                if (task.isSuccessful()) {
                    Uri downloadUri = task.getResult();
                    Log.d(TAG, "onComplete: Successfully Uploaded");
                    if (downloadUri != null) {
                        String picDownloadString = downloadUri.toString();
                        Constraints.Builder builder = new Constraints.Builder();
                        Data.Builder data = new Data.Builder();
                        if (profileBoolean) {
                            data.putBoolean("profileBoolean", true);
                        } else if (coverBoolean) {
                            data.putBoolean("coverBoolean", true);
                        }
                        data.putString("picDownloadString", picDownloadString);
                        /*OneTimeWorkRequest updatePicEntryAtDB = new OneTimeWorkRequest
                                .Builder(UpdateUserDatabaseWorker.class)
                                .addTag("Updating pic in database")
                                .setInputData(data.build())
                                .build();
                        WorkManager.getInstance(getApplicationContext()).beginUniqueWork("picUpdationInDB", ExistingWorkPolicy.APPEND,
                                updatePicEntryAtDB).enqueue();
                        */results[0] = Result.success();
                    }
                } else {
                    results[0] = Result.failure();
                }
            }
        });

The code uploads the pic perfectly when it is commented like this. But on removing the comment to allow updating of the user table, the code stops working altogether. That is, the pic doesn't get uploaded too.


问:
How to convert 24 hr format time in to 12 hr Format?
In my application i want to convert the given CDT formatted 24 hr string in to CDT formatted 12 hr string, How to convert a given 24 hr format string in to 12 hr format string??</p>

答:
For converting any Date date to 12 hour format with AM and PM you can use

```<code>new SimpleDateFormat("dd MMM yyyy KK:mm:ss a").format(date)
</code>```

Here KK signifies 00-12 and a signifies AM and PM

Body:
For converting any Date date to 12 hour format with AM and PM you can use

new SimpleDateFormat("dd MMM yyyy KK:mm:ss a").format(date)

Here KK signifies 00-12 and a signifies AM and PM


问:
Difference between two date strings in java
I am trying to calculate difference between two date strings both of which are taken from user through a html form in format (yyyy/MM/dd)
Code:

```<code>public boolean diffDate() throws ParseException
 {
     date1 = getissuedate();
     date2 = getduedate();
         Calendar cal1 = Calendar.getInstance();
    Calendar cal2 = Calendar.getInstance();
    SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy/MM/dd");
    SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy/MM/dd");
Date date_old = formatter1.parse(date1);
Date date_new = formatter2.parse(date2);
long milis1 = date_old.getTime();
long milis2 = date_new.getTime();

long diff = milis2 - milis1;

    if( diff<3 || diff>3)
    {
        return true;
    }
    else
    {
        return false;
    }
 }
</code>```

Now am using an if condition to report error in my webpage if difference between the date is not equal to 3.
Code:

```<code>try {
        if(diffDate())
        {
            errors.add("duedate", new ActionMessage("error.duedate.required"));
        }
    } catch (ParseException ex) {
        Logger.getLogger(IssueBookForm.class.getName()).log(Level.SEVERE, null, ex);
    }
</code>```

where error.duedate.required is mapped to "check date"

So, the issue is "check date" error is printed for any value of both date string.

答: You're testing if two dates differ by 3 milliseconds, which will almost always be true.  If you really want 3 days, the value should be 3*86400*1000.  If you care about what happens with leap-seconds and daylight-savings-time changes, then the problem gets more complex.</p>

Body:
I am trying to calculate difference between two date strings both of which are taken from user through a html form in format (yyyy/MM/dd)
Code:

public boolean diffDate() throws ParseException
 {
     date1 = getissuedate();
     date2 = getduedate();
         Calendar cal1 = Calendar.getInstance();
    Calendar cal2 = Calendar.getInstance();
    SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy/MM/dd");
    SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy/MM/dd");
Date date_old = formatter1.parse(date1);
Date date_new = formatter2.parse(date2);
long milis1 = date_old.getTime();
long milis2 = date_new.getTime();

long diff = milis2 - milis1;

    if( diff<3 || diff>3)
    {
        return true;
    }
    else
    {
        return false;
    }
 }

Now am using an if condition to report error in my webpage if difference between the date is not equal to 3.
Code:

try {
        if(diffDate())
        {
            errors.add("duedate", new ActionMessage("error.duedate.required"));
        }
    } catch (ParseException ex) {
        Logger.getLogger(IssueBookForm.class.getName()).log(Level.SEVERE, null, ex);
    }

where error.duedate.required is mapped to "check date"

So, the issue is "check date" error is printed for any value of both date string.


问:
Disable Side Menu in Ionic Cordova App Splash/Intro Screen
I am trying to disable/hide the side menu on the Splash/Intro page only.

I tried adding this code to intro.ts:

```<code>import {  MenuController } from '@ionic/angular';

 constructor( public menuCtrl: MenuController,){ }
     ionViewWillEnter() {
        this.menuCtrl.enable(false);
  }
</code>```

But while building it throws error:

```<code>import {  MenuController } from '@ionic/angular';
       constructor( public menuCtrl: MenuController,){ }
        ionViewWillEnter() {
        this.menuCtrl.enable(false);
     }
</code>```

Is there any way to do this. I am using:
Ionic:

```<code>   Ionic CLI          : 5.4.16 (/usr/local/lib/node_modules/ionic)
   Ionic Framework    : ionic-angular 3.9.2
   @ionic/app-scripts : 3.2.4
</code>```

Thanks in advance.

This is the full page code of intro.ts

```<code>    import { Component,ViewChild } from '@angular/core';
import { NavController, Slides } from 'ionic-angular';
import { ConfigService } from '../../services/config';
import { Storage } from '@ionic/storage';
import { TabsPage } from '../tabs/tabs';
import { MultiselectorPage } from '../multiselector/multiselector';

@Component({
  selector: 'page-intro',
  templateUrl: 'intro.html'
})
export class Intro {
  @ViewChild('IntroTabs') introTabs: Slides;
  multiselectorpage = MultiselectorPage;
    tabsPage = TabsPage;
    constructor(
        public navCtrl: NavController,
      private config:ConfigService,
        private storage:Storage) {
    }
  ngOnInit(){
    console.log(this.config);
  }
  goToHome(){
    if(this.config.multisite.enable_multisite){
       this.navCtrl.push(this.multiselectorpage);
    }else{
        this.storage.set('introShown', true);
        this.config.initialize();
        this.navCtrl.setRoot(this.tabsPage);
    }

  }
  proceed(){
    let index = this.introTabs.getActiveIndex();
    index++;
    this.introTabs.slideTo(index, 500);
  }
}
</code>```

答:
you can get the ion-menu-button off the toolbar and instead of using:

```<code>this.menuCtrl.enable(false);
</code>```

you can use:

```<code>this.menuCtrl.swipeEnable(false);
</code>```

after doing this, there's no way to open menu by tapping or swiping.
Good Luck!

Body:
I am trying to disable/hide the side menu on the Splash/Intro page only.

I tried adding this code to intro.ts:

import {  MenuController } from '@ionic/angular';

 constructor( public menuCtrl: MenuController,){ }
     ionViewWillEnter() {
        this.menuCtrl.enable(false);
  }

But while building it throws error:

import {  MenuController } from '@ionic/angular';
       constructor( public menuCtrl: MenuController,){ }
        ionViewWillEnter() {
        this.menuCtrl.enable(false);
     }

Is there any way to do this. I am using:
Ionic:

   Ionic CLI          : 5.4.16 (/usr/local/lib/node_modules/ionic)
   Ionic Framework    : ionic-angular 3.9.2
   @ionic/app-scripts : 3.2.4

Thanks in advance.

This is the full page code of intro.ts

    import { Component,ViewChild } from '@angular/core';
import { NavController, Slides } from 'ionic-angular';
import { ConfigService } from '../../services/config';
import { Storage } from '@ionic/storage';
import { TabsPage } from '../tabs/tabs';
import { MultiselectorPage } from '../multiselector/multiselector';

@Component({
  selector: 'page-intro',
  templateUrl: 'intro.html'
})
export class Intro {
  @ViewChild('IntroTabs') introTabs: Slides;
  multiselectorpage = MultiselectorPage;
    tabsPage = TabsPage;
    constructor(
        public navCtrl: NavController,
      private config:ConfigService,
        private storage:Storage) {
    }
  ngOnInit(){
    console.log(this.config);
  }
  goToHome(){
    if(this.config.multisite.enable_multisite){
       this.navCtrl.push(this.multiselectorpage);
    }else{
        this.storage.set('introShown', true);
        this.config.initialize();
        this.navCtrl.setRoot(this.tabsPage);
    }

  }
  proceed(){
    let index = this.introTabs.getActiveIndex();
    index++;
    this.introTabs.slideTo(index, 500);
  }
}

Body:
you can get the ion-menu-button off the toolbar and instead of using:

this.menuCtrl.enable(false);

you can use:

this.menuCtrl.swipeEnable(false);

after doing this, there's no way to open menu by tapping or swiping.
Good Luck!


问:
Mysql Join with max date and first row
I have 2 tables properties and property_history
structure some thing like that

```<code>proerties -
id | property_address | owner
1  | abc              | xyz
2  | 123              | efg

property_history-

id | property_id |   date1    |   date2    |   date3    |    date4
1  | 1           | 2012-05-01 | 0000-00-00 | 2002-06-11 | 2006-06-11 |
2  | 1           | 2019-05-01 | 0000-00-00 | 2003-06-11 | 2007-06-11 |
3  | 1           | 0000-00-00 | 2011-06-11 | 2004-06-11 | 2011-06-11 |
4  | 1           | 0000-00-00 | 2020-01-31 | 2005-06-11 | 0000-00-11 |
</code>```

I need to join these two table as

All rows from properties table

Only 1 row form property history with latest date from any of the date column as latest date
for eg. latest date between( date1, date2, date3, date4) as latest_date as one column

If property_history not have any row with respect property id then latest_date should be null

答:
Please try this query

```<code>Select proerties.id,proerties.property_address,proerties.owner from proerties
left join ( Select Case when date(date1)>=date(date2) and date(date1)>=date(date3) and date(date1)>=date(date4) then date1 when date(date2)>=date(date1) and date(date2)>=date(date3) and date(date2)>=date(date4) then date2  when date(date3)>=date(date1) and date(date3)>=date(date2) and date(date3)>=date(date4) then date3  when date(date4)>=date(date1) and date(date4)>=date(date2) and date(date4)>=date(date3) then date3 END AS max_date,property_id  from property_history) as update_history on update_history.property_id=proerties.id
</code>```

And let me know if you are getting expected result or not.

Title: Mysql Join with max date and first row

Body:
I have 2 tables properties and property_history
structure some thing like that

proerties -
id | property_address | owner
1  | abc              | xyz
2  | 123              | efg

property_history-

id | property_id |   date1    |   date2    |   date3    |    date4
1  | 1           | 2012-05-01 | 0000-00-00 | 2002-06-11 | 2006-06-11 |
2  | 1           | 2019-05-01 | 0000-00-00 | 2003-06-11 | 2007-06-11 |
3  | 1           | 0000-00-00 | 2011-06-11 | 2004-06-11 | 2011-06-11 |
4  | 1           | 0000-00-00 | 2020-01-31 | 2005-06-11 | 0000-00-11 |

I need to join these two table as

All rows from properties table

Only 1 row form property history with latest date from any of the date column as latest date
for eg. latest date between( date1, date2, date3, date4) as latest_date as one column

If property_history not have any row with respect property id then latest_date should be null

Body:
Please try this query

Select proerties.id,proerties.property_address,proerties.owner from proerties
left join ( Select Case when date(date1)>=date(date2) and date(date1)>=date(date3) and date(date1)>=date(date4) then date1 when date(date2)>=date(date1) and date(date2)>=date(date3) and date(date2)>=date(date4) then date2  when date(date3)>=date(date1) and date(date3)>=date(date2) and date(date3)>=date(date4) then date3  when date(date4)>=date(date1) and date(date4)>=date(date2) and date(date4)>=date(date3) then date3 END AS max_date,property_id  from property_history) as update_history on update_history.property_id=proerties.id

And let me know if you are getting expected result or not.


问:
React BootstrapTable how to set row count per page?
I am using react react-bootstrap-table. The default count of row is 10 per page. I want to change it to 5. How can I do this?

答:
react-bootstrap-table has this follow attributes to change the limit per page.

```<code>sizePerPageList: [20, 50, 100],
onSizePerPageList: this.onSizePerPageList.bind(this), //number of items to be displayed
onPageChange: this.onPageChange.bind(this), //pagination tours
</code>```

you can use  bind a function on onSizePerPageList to  change the state variable that holds your limit.

Body:
react-bootstrap-table has this follow attributes to change the limit per page.

sizePerPageList: [20, 50, 100],
onSizePerPageList: this.onSizePerPageList.bind(this), //number of items to be displayed
onPageChange: this.onPageChange.bind(this), //pagination tours

you can use  bind a function on onSizePerPageList to  change the state variable that holds your limit.


问:
How do I load files with ModelicaSystem in OMPython?
I have a Modelica model that calls other functions, written in other files for modulation. When I use OMPython to create a ModelicaSystem object using the following:

```<code>from OMPython import ModelicaSystem
model = ModelicaSystem("MyModel.mo", "MyModel")
</code>```

I get the following error:

Error: Class MyFunction not found in scope MyModel (looking for a function or record).
```

<p>MyModel uses in some of his equations other classes and functions, such as <code>MyFunction</code>, but I don't know how to load <code>MyFunction</code> and the other files the model uses in order for MyModel to be instantiated. </p>

<p>I tried to use the <code>ModelicaSystem</code> object constructor on the functions first, but I get:</p>

<pre class="lang-none prettyprint-override"><code>Cannot instantiate MyFunction due to class specialization FUNCTION.
</code>```

I tried loading the files using OMCSession() but it doesn't work.
Every file is in the same directory.

How can I load the files to solve the problem?

答:
You can try coding as follows:</p>

```<code>from OMPython import OMCSessionZMQ
omc = OMCSessionZMQ()
model_path=omc.sendExpression("getInstallationDirectoryPath()") + "<Modelica file path>"
from OMPython import ModelicaSystem
mod=ModelicaSystem(model_path + "FileName.mo","ModelName")
</code>```

Body:
I have a Modelica model that calls other functions, written in other files for modulation. When I use OMPython to create a ModelicaSystem object using the following:

from OMPython import ModelicaSystem
model = ModelicaSystem("MyModel.mo", "MyModel")

I get the following error:

Error: Class MyFunction not found in scope MyModel (looking for a function or record).

MyModel uses in some of his equations other classes and functions, such as MyFunction, but I don't know how to load MyFunction and the other files the model uses in order for MyModel to be instantiated.

I tried to use the ModelicaSystem object constructor on the functions first, but I get:

Cannot instantiate MyFunction due to class specialization FUNCTION.

I tried loading the files using OMCSession() but it doesn't work.
Every file is in the same directory.

How can I load the files to solve the problem?

Body:
You can try coding as follows:

from OMPython import OMCSessionZMQ
omc = OMCSessionZMQ()
model_path=omc.sendExpression("getInstallationDirectoryPath()") + "<Modelica file path>"
from OMPython import ModelicaSystem
mod=ModelicaSystem(model_path + "FileName.mo","ModelName")


Title: Group SKUs together based on similarity in PRICE

Body:
SKU_NUM       GEO_CD    GROUP_ID    PRICE   EXPECTED_OUTPUT
70907334        SV      1198094     0.84        5
70073557        SV      1198094     1.08        1
70073797        SV      1198094     1.20        1
70394170        SV      1198094     1.20        1
70395532        SV      1198094     1.20        1
70325533        SV      1198094     1.32        1
70393532        SV      1198094     1.38        4
70428444        CR      1198094     8.07        1
70428459        CR      1198094     8.07        1
70428536        CR      1198094     8.07        1
70424536        CR      1198094     7.97        1
70221536        CR      1198094     7.97        1
70428532        CR      1198094     7.52        2
70009265        CR      1198094     8.85        1
70009266        CR      1198094     8.85        1
70079602        CR      1198094     8.85        1
70079853        CR      1198094     8.85        1
70340656        CR      1198094     8.85        1
70340665        CR      1198094     8.85        1
70340325        CR      1198094     9.74        1
70343265        CR      1198094     10.18       3
70320665        CR      1198094     9.56        1
70548879        NI      1198094     23.81       6
70548879        NI      1198094     26.78       1
70271547        NI      1198094     29.76       1
70271547        NI      1198094     29.76       1
70271547        NI      1198094     32.74       1
70271547        NI      1198094     35.71       7

I am trying to group together SKUs with similar prices(+-10% of mode). Each GEO_CD has its own MODE, and so if the PRICE of an SKU lies within the +-10% range of the MODE, I'd like to group them together and assign them to the group EXPECTED_OUTPUT = 1, if not assign them any other number. Similarly, across all GEO_CD if the SKUs price lies within +-10% of their respective MODE, I'd assign them to group 1, and if not put them into any other group but 1.

I'd appreciate if someone can show me a way to handle this without for loops and multiple if conditions.

Body:
You can do something like this, I've taken the mode of PRICE:

mode = float(df['PRICE'].mode())
df['within_mode'] = abs((df['PRICE'] - mode)*100/df['PRICE']) < 10
df['EXPECTED_OUTPUT'] = np.where(df['within_mode']==True, 1, 0)
print(df)

Output:

     SKU_NUM GEO_CD  GROUP_ID  PRICE  EXPECTED_OUTPUT  within_mode
0   70907334     SV   1198094   0.84                0        False
1   70073557     SV   1198094   1.08                0        False
2   70073797     SV   1198094   1.20                0        False
3   70394170     SV   1198094   1.20                0        False
4   70395532     SV   1198094   1.20                0        False
5   70325533     SV   1198094   1.32                0        False
6   70393532     SV   1198094   1.38                0        False
7   70428444     CR   1198094   8.07                1         True
8   70428459     CR   1198094   8.07                1         True
9   70428536     CR   1198094   8.07                1         True
10  70424536     CR   1198094   7.97                0        False
11  70221536     CR   1198094   7.97                0        False
12  70428532     CR   1198094   7.52                0        False
13  70009265     CR   1198094   8.85                1         True
14  70009266     CR   1198094   8.85                1         True
15  70079602     CR   1198094   8.85                1         True
16  70079853     CR   1198094   8.85                1         True
17  70340656     CR   1198094   8.85                1         True
18  70340665     CR   1198094   8.85                1         True
19  70340325     CR   1198094   9.74                1         True
20  70343265     CR   1198094  10.18                0        False
21  70320665     CR   1198094   9.56                1         True
22  70548879     NI   1198094  23.81                0        False
23  70548879     NI   1198094  26.78                0        False
24  70271547     NI   1198094  29.76                0        False
25  70271547     NI   1198094  29.76                0        False
26  70271547     NI   1198094  32.74                0        False
27  70271547     NI   1198094  35.71                0        False


问:
Redirecting to error page if a partial view encounters an error
I'm rendering a partial view inside of a view:

```<code>@{
    Html.RenderAction("PartialViewAction", "SomeController");
}
</code>```

Is there a way to redirect the user to an error page if the partial view action encounters an error?

EDIT:  I'm looking for a server side kind of redirection.  This partial view is not loaded with AJAX.  It is rendered server side into a "big" view.  The "big" view has no idea that the partial view errored out.

答:
Depending on your logic, you might be able to control your application flow by using jQuery.ajax() to handle errors.

```<code>// this will render the GET request on page load
$(function() {
    $.ajax({
        url: '/Some/PartialViewAction',
        type: 'GET',
        dataType: 'json',                            /*edit*/
        success: function(xhr_data) {                /*edit*/
            // the following assumes you wrap
            // your partial view in div id="myDiv"
            $('#myDiv').html(xhr_data.html);         /*edit*/
            $('#myErrorDiv').html(xhr_data.error);   /*edit*/
        },
        error: function() {
            window.location.href='/Some/Error';
            // or similar page redirecting technique
        }
    });
});
</code>```

This will handle an error in the GET, but of course if you were to return some JSON or some other indicator in your action method, you could use the same window.location.href... in the success callback function.

Edit

Also see above edits to $.ajax

Your controller could do something like this:

```<code>public ActionResult PartialViewAction() {
    // handle error
    string message = "Evacuate, Immediately!";
    // not certain the html will render correctly,
    // but you could encode/parse/whatever easily enough
    return Json(new { html = "<div>some html</div>", error = message },
        JsonRequestBehavior.AllowGet);
}
</code>```

Body:
I'm rendering a partial view inside of a view:

@{
    Html.RenderAction("PartialViewAction", "SomeController");
}

Is there a way to redirect the user to an error page if the partial view action encounters an error?

EDIT:  I'm looking for a server side kind of redirection.  This partial view is not loaded with AJAX.  It is rendered server side into a "big" view.  The "big" view has no idea that the partial view errored out.

Body:
Depending on your logic, you might be able to control your application flow by using jQuery.ajax() to handle errors.

// this will render the GET request on page load
$(function() {
    $.ajax({
        url: '/Some/PartialViewAction',
        type: 'GET',
        dataType: 'json',                            /*edit*/
        success: function(xhr_data) {                /*edit*/
            // the following assumes you wrap
            // your partial view in div id="myDiv"
            $('#myDiv').html(xhr_data.html);         /*edit*/
            $('#myErrorDiv').html(xhr_data.error);   /*edit*/
        },
        error: function() {
            window.location.href='/Some/Error';
            // or similar page redirecting technique
        }
    });
});

This will handle an error in the GET, but of course if you were to return some JSON or some other indicator in your action method, you could use the same window.location.href... in the success callback function.

Edit

Also see above edits to $.ajax

Your controller could do something like this:

public ActionResult PartialViewAction() {
    // handle error
    string message = "Evacuate, Immediately!";
    // not certain the html will render correctly,
    // but you could encode/parse/whatever easily enough
    return Json(new { html = "<div>some html</div>", error = message },
        JsonRequestBehavior.AllowGet);
}


问:
.NET Core project is getting error while using CouchbaseNetClient 3.0.0 package
I've been trying to develop a webclient with dotnetcore(v3) on mac os x which can inject json formatted values into couchbase that lives in a docker container( at least for now). So after i installed couchbase .net core sdk version 3.0.0 and Couchbase.Extensions.DependencyInjection nuget packages, in my project folder at Startup.cs file i've been getting this same error.

Reference to type 'CouchbaseClientDefinition' claims it is defined in 'Couchbase.NetClient', but it could not be found (CS7069)

It is a new project so for now there is no developed code in other files either.

Thank you in advance.

答: After upgrading v3.0.1 problem has resolved.</p>


问:
Questions about boxing
I know that boxing is a popular concept with plenty of information available on it, but I have a few questions which I can't really find answers to:

1) If boxing leads to a value type (struct) being converted to an object (Reference type), or reference type, then why use a value type which will be boxed and incur a performance penalty? I am aware of the benefits and suitability in certain cases of either a struct or class. It is said (1) that values (value types) tend to live on the stack in a temporary storage space, but how long for? If I don't need the type, how can I ensure it is taken care of and disposed at that moment? Or is this where the disposable pattern comes into play? I assume the reason to use a struct will be due to its benefits.

Interestingly, if I use a struct to store two strings and a DateTime field, the struct will hold two references (strings) and the DateTime together. I obviously assume this is quicker than the values being scattered. Is there anything I need to be aware of in this design? (2).

1) http://en.csharp-online.net/Classes, Structs, and Objects—Boxing and Unboxing

2) http://dotnetperls.com/Content/Struct-Examples.aspx

I have done a search on here for the answers I am after, but no luck. I usually do searches on this site for topics such as GC, generics, exception handling, etc, as there is a lot of wisdom to learn and share.

Thanks for the (potential) education to all posters! Please excuse any potential naivety. Learning the internals takes me nicely to spending some time on understanding IL, etc (something to tackle, soon).

答:
If you never pass the value type into a reference variable then boxing will not occur. When you don't know then answer the following questions:

Act like primitive types.

Have an instance size under 16 bytes.

Are immutable.

Value semantics are desirable.

I also usually consider what is the lifetime of such a variable. If it is a local variable used within a method then I would tent to use struct (otherwise class).

OwnerDisplayName: GSS

Title: Questions about boxing

LastEditorDisplayName: jpalecek

OwnerDisplayName: David Pokluda


问:
How to get data out of an Arraylist
So in a previous quesiton I asked how i could merge multiple array list into one array list.

This answer worked (also listed below). However, I am having issues getting the records out.  How do I get the data out of this multi dimensional arraylist.  For example, what if I wanted to get just address out?

```<code>ArrayList Names = new ArrayList();
ArrayList Phone = new ArrayList();
ArrayList Address = new ArrayList();
ArrayList res = new ArrayList();
for(int i=0; i<Names.Count; i++)
{
  res.Add(new string[]{Names[i].ToString(), Phone[i].ToString(), Address[i].ToString()});
}
</code>```

答:
Can I ask why you are creating array lists like you are?  In my opinion, you're better off to create a custom object that has 3 properties -> Name, Phone and Address, and simply create a list of those objects:

Resident class:

```<code>public class Resident
{
  public string Name { get; set; }
  public string Phone { get; set; }
  public string Address { get; set; }
}
</code>```

Code:

```<code>List<Resident> residents = new List<Resident>();
// populate list

foreach (var res in residents)
  Console.WriteLine(res.Address);
</code>```

Title: How to get data out of an Arraylist

Body:
So in a previous quesiton I asked how i could merge multiple array list into one array list.

This answer worked (also listed below). However, I am having issues getting the records out.  How do I get the data out of this multi dimensional arraylist.  For example, what if I wanted to get just address out?

ArrayList Names = new ArrayList();
ArrayList Phone = new ArrayList();
ArrayList Address = new ArrayList();
ArrayList res = new ArrayList();
for(int i=0; i<Names.Count; i++)
{
  res.Add(new string[]{Names[i].ToString(), Phone[i].ToString(), Address[i].ToString()});
}

Body:
Can I ask why you are creating array lists like you are?  In my opinion, you're better off to create a custom object that has 3 properties -> Name, Phone and Address, and simply create a list of those objects:

Resident class:

public class Resident
{
  public string Name { get; set; }
  public string Phone { get; set; }
  public string Address { get; set; }
}

Code:

List<Resident> residents = new List<Resident>();
// populate list

foreach (var res in residents)
  Console.WriteLine(res.Address);


问:
I need better understanding on for loops
can someone explain me how this for loop works (Line 9 in code below), and also if you can show me a simple example with it can be very helpfull, thank you anyways!

```<code>1 #include <iostream>
2 #include <cstdlib>
3
4 using namespace std;

5 int main(){
6     int n, a , b , ma=0,mb=1000000001;
7     cin >> n ;
8     cin >> a;
9     for( n--; n ; --n ){
10         cin >> b;
11         if(abs(a-b) < abs(ma-mb))
12             ma=a , mb=b;
13         else
14             if(abs(a-b) == abs(ma-mb) && ma+mb > a+b)
15                 ma=a , mb=b;
16         a = b;
17     }
18     cout << ma << " " << mb;
19     return 0;
20 }
</code>```

答:
This code smells a lot. If you give to n the value 10,it gives

9 (first time into loop, exectues n--)
every other iteration it executes --n till when n!=0 (which is the condition n

Body:
can someone explain me how this for loop works (Line 9 in code below), and also if you can show me a simple example with it can be very helpfull, thank you anyways!

1 #include <iostream>
2 #include <cstdlib>
3
4 using namespace std;

5 int main(){
6     int n, a , b , ma=0,mb=1000000001;
7     cin >> n ;
8     cin >> a;
9     for( n--; n ; --n ){
10         cin >> b;
11         if(abs(a-b) < abs(ma-mb))
12             ma=a , mb=b;
13         else
14             if(abs(a-b) == abs(ma-mb) && ma+mb > a+b)
15                 ma=a , mb=b;
16         a = b;
17     }
18     cout << ma << " " << mb;
19     return 0;
20 }


问:
Trouble posting multiple values for same key using requests in Python
I'm attempting to pass multiple values for the same key on a GET request using requests in python.  I have tried what I thought was the correct syntax, but the key is still being formatted twice in the url.

In the code that follows, I am looking to have ?tickers=ethusd,ethbtc in the url, but am getting ?tickers=ethusd?tickers=ethbtc instead:

```<code>import requests
import json
import psycopg2
from datetime import datetime
payload = {'tickers':['ethusd','ethbtc'], 'startDate': startdate, 'endDate': enddate, 'resampleFreq': resamplefreq, 'token':token}
    requestResponse = requests.get("https:mysite",params=payload, headers=headers)
</code>```

The formatted url from requests ends up as:

'https://mysite?tickers=ethusd&tickers=ethbtc&startDate=2020-05-26&endDate=2020-05-26&resampleFreq=1day&token=token'

instead of ?tickers=ethusd,ethbtc.

答:
Comma is not allowed in url. So you should encode url. I think it's a little bit complicated.
Even if you can achieve your goal, you should encode url again.
Why don't you convert array into string before setting a payload variable?

```<code>aa = ['ethusd','ethbtc']
payload = {'tickers': "-".join(aa), 'startDate': startdate, 'endDate': enddate, 'resampleFreq': resamplefreq, 'token':token}
requestResponse = requests.get("https:mysite",params=payload, headers=headers)
</code>```

And you can get this value after converting into string using split method.

Body:
I'm attempting to pass multiple values for the same key on a GET request using requests in python.  I have tried what I thought was the correct syntax, but the key is still being formatted twice in the url.

In the code that follows, I am looking to have ?tickers=ethusd,ethbtc in the url, but am getting ?tickers=ethusd?tickers=ethbtc instead:

import requests
import json
import psycopg2
from datetime import datetime
payload = {'tickers':['ethusd','ethbtc'], 'startDate': startdate, 'endDate': enddate, 'resampleFreq': resamplefreq, 'token':token}
    requestResponse = requests.get("https:mysite",params=payload, headers=headers)

The formatted url from requests ends up as:

'https://mysite?tickers=ethusd&tickers=ethbtc&startDate=2020-05-26&endDate=2020-05-26&resampleFreq=1day&token=token'

instead of ?tickers=ethusd,ethbtc.

Body:
Comma is not allowed in url. So you should encode url. I think it's a little bit complicated.
Even if you can achieve your goal, you should encode url again.
Why don't you convert array into string before setting a payload variable?

aa = ['ethusd','ethbtc']
payload = {'tickers': "-".join(aa), 'startDate': startdate, 'endDate': enddate, 'resampleFreq': resamplefreq, 'token':token}
requestResponse = requests.get("https:mysite",params=payload, headers=headers)

And you can get this value after converting into string using split method.


问:
Nullable in objective c
Is there a way to make nullable struct in objective C like in C# you can use Nullable<T>?

I need a CGPoint to be null when there is no applicable value. I cannot allocate a random invalid value for this like (-5000, -5000) because all values are valid for this.

答:
CGPoint is a struct and that has some different rules in objective-c than you might think. You should consider reading about structs in objective-c. </p>

<p>The way this is done most of the time is to wrap the struct in an object because that object can be set to null. NSValue will wrap a CGPoint. </p>

```<code>NSValue * v = [NSValue valueWithPoint:CGPointMake(1,9)];
NSVAlue * vNull = [NSValue valueWithPointer:nil];
if([v objCType] == @encode(CGPoint)) printf("v is an CGPoint");
</code>```

Title: Nullable in objective c

Body:
CGPoint is a struct and that has some different rules in objective-c than you might think. You should consider reading about structs in objective-c.

The way this is done most of the time is to wrap the struct in an object because that object can be set to null. NSValue will wrap a CGPoint.

NSValue * v = [NSValue valueWithPoint:CGPointMake(1,9)];
NSVAlue * vNull = [NSValue valueWithPointer:nil];
if([v objCType] == @encode(CGPoint)) printf("v is an CGPoint");


问:
Can JQuery do it?
I want to create a div and remove it after 5 seconds, the problem i have is that myscript is removing all the divs at the same time, and I want you to remove the divs in order of creation, one by one.

Here my script until now:

$(document).ready(function(){
  $(".create").click(function(){

  //HERE I CREATE THE DIVS
  $('.divs').append('
Hello
');
  //HERE FINISH CREATE THE DIVS

  });
});

//HERE I DELETE THE DIVS IF IT EXIST
var $auto_refresh = setInterval(function () {
    var $articleCount = $('.deleteon5seconds').length;

    while ($articleCount > 0) {
        $('.deleteon5seconds:last-child').remove();
        $articleCount = $('.deleteon5seconds').length;
    }

    $autoUpdate();
}, 5000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button class="create">Create</button>
<div class="divs"></div></code>```

All this is an example, the purpose of the code is to show alerts. I need help please!
Advanced thanks!!

答:
So if I understand what you are asking, for each div created, you will need to get a reference to that new div and then use setTimeout (not setInterval) for each one with an interval of 5 seconds that will remove that particular div. This make it so each new div will live for 5 seconds and  then disappear.

var count = 1;
$(document).ready(function(){
  $(".create").click(function(){

  //HERE I CREATE THE DIVS
  var div = $('.divs').append('
Hello' + count++ + '
');
  var elem = $('.divs div.deleteon5seconds').last();
  //HERE FINISH CREATE THE DIVS

  setTimeout(() => elem.remove(), 5000);

  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button class="create">Create</button>
<div class="divs"></div></code>```

I added the count part just to make it easier to keep track of which div is which.

Title: Can JQuery do it?

Body:
I want to create a div and remove it after 5 seconds, the problem i have is that myscript is removing all the divs at the same time, and I want you to remove the divs in order of creation, one by one.

Here my script until now:

$(document).ready(function(){
  $(".create").click(function(){

  //HERE I CREATE THE DIVS
  $('.divs').append('
Hello
');
  //HERE FINISH CREATE THE DIVS

  });
});

//HERE I DELETE THE DIVS IF IT EXIST
var $auto_refresh = setInterval(function () {
    var $articleCount = $('.deleteon5seconds').length;

    while ($articleCount > 0) {
        $('.deleteon5seconds:last-child').remove();
        $articleCount = $('.deleteon5seconds').length;
    }

    $autoUpdate();
}, 5000);

<button class="create">Create</button>

All this is an example, the purpose of the code is to show alerts. I need help please!
Advanced thanks!!

Body:
So if I understand what you are asking, for each div created, you will need to get a reference to that new div and then use setTimeout (not setInterval) for each one with an interval of 5 seconds that will remove that particular div. This make it so each new div will live for 5 seconds and  then disappear.

var count = 1;
$(document).ready(function(){
  $(".create").click(function(){

  //HERE I CREATE THE DIVS
  var div = $('.divs').append('<div class="deleteon5seconds">Hello' + count++ + '</div>');
  var elem = $('.divs div.deleteon5seconds').last();
  //HERE FINISH CREATE THE DIVS

  setTimeout(() => elem.remove(), 5000);

  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button class="create">Create</button>
<div class="divs"></div>

I added the count part just to make it easier to keep track of which div is which.


问:
How to use the method When in FluentAssertions
Sometimes I have to assert that two lists have the same items. With fluent assertions this can be done like this:

```<code>class MyObject { public string MyString {get; set;} }

var o1 = new MyObject { MyString = "1    " }
list1.Add(o1);

var o2 = new MyObject { MyString = "1" }
list2.Add(o2);

list1.Should().BeEquivalentTo(list2)
</code>```

But sometimes I want a specific property to be compared in a different way, like this:

```<code>list1.Should().BeEquivalentTo(list2, options => options
            .Using<string>(context => context.Subject.TrimEnd().Should().Be(context.Expectation))
            .When<string>( ??????? ));
</code>```

I have tried:

```<code>it => it.SelectedMemberInfo.Name == PropertyNameHere
</code>```

But SelectedMemberInfo can be null and it throws an exception when null and I dont know if I'm calling it the correct way.

Update 1: Tried, but null reference exception:

```<code>        options => options
        .Using<DateTime>(it => it.Subject.Should().BeCloseTo(DateTime.Now, TimeSpan.FromMinutes(1)))
        .When(it =>
            it != null
            && it.SelectedMemberInfo != null
            && it.SelectedMemberInfo.Name == nameof(Y.X)));
</code>```

答:
The problem here is that you are trying to access a member in an object that hasn't been instantiated. Because it.SelectedMemberInfo is null, there is no member Name to access. The .NET documentation on NullReferenceException has a good explanation of this.

https://learn.microsoft.com/en-us/dotnet/api/system.nullreferenceexception?view=netcore-3.1

Assuming there are no other special circumstances when SelectedMemberInfo is null, you will just want to make the expression in .When() null-safe. You can do this pretty easily with a single character (null propagation):

```<code>it => it.SelectedMemberInfo?.Name == PropertyNameHere
</code>```

The way null propagation works is if the object that precedes the question mark is null, it will evaluate as a null instance of the type at the end of the statement. So in this case, if it.SelectedMemberInfo is null, this will evaluate as (string) null.

If you like extra lines, you could also do this -

```<code>it => it.SelectedMemberInfo != null && it.SelectedMemberInfo.Name == PropertyNameHere)
</code>```

If there's a chance that you could have null items in the parent collection, you're also going to want a null check on that -

```<code>it => it?.SelectedMemberInfo?.Name == PropertyNameHere
</code>```

Body:
Sometimes I have to assert that two lists have the same items. With fluent assertions this can be done like this:

class MyObject { public string MyString {get; set;} }

var o1 = new MyObject { MyString = "1    " }
list1.Add(o1);

var o2 = new MyObject { MyString = "1" }
list2.Add(o2);

list1.Should().BeEquivalentTo(list2)

But sometimes I want a specific property to be compared in a different way, like this:

list1.Should().BeEquivalentTo(list2, options => options
            .Using<string>(context => context.Subject.TrimEnd().Should().Be(context.Expectation))
            .When<string>( ??????? ));

I have tried:

it => it.SelectedMemberInfo.Name == PropertyNameHere

But SelectedMemberInfo can be null and it throws an exception when null and I dont know if I'm calling it the correct way.

Update 1: Tried, but null reference exception:

        options => options
        .Using<DateTime>(it => it.Subject.Should().BeCloseTo(DateTime.Now, TimeSpan.FromMinutes(1)))
        .When(it =>
            it != null
            && it.SelectedMemberInfo != null
            && it.SelectedMemberInfo.Name == nameof(Y.X)));

Body:
The problem here is that you are trying to access a member in an object that hasn't been instantiated. Because it.SelectedMemberInfo is null, there is no member Name to access. The .NET documentation on NullReferenceException has a good explanation of this.

https://learn.microsoft.com/en-us/dotnet/api/system.nullreferenceexception?view=netcore-3.1

Assuming there are no other special circumstances when SelectedMemberInfo is null, you will just want to make the expression in .When() null-safe. You can do this pretty easily with a single character (null propagation):

it => it.SelectedMemberInfo?.Name == PropertyNameHere

The way null propagation works is if the object that precedes the question mark is null, it will evaluate as a null instance of the type at the end of the statement. So in this case, if it.SelectedMemberInfo is null, this will evaluate as (string) null.

If you like extra lines, you could also do this -

it => it.SelectedMemberInfo != null && it.SelectedMemberInfo.Name == PropertyNameHere)

If there's a chance that you could have null items in the parent collection, you're also going to want a null check on that -

it => it?.SelectedMemberInfo?.Name == PropertyNameHere


问:
Coverting webm to wav with ffmpeg
I've succesfully used ffmpeg in Python to convert mp3-files into wav so I can post them to Google Speech-To-Text. Now I have same situation with webm files and the old function I have doesn't work. It should convert the file into wav and split it into 15 second chunks. Can I do this from webm -file or do I need to convert it first into some other format?

The function I've used:

```<code>def convert_and_split(filename):
    command = ['ffmpeg', '-i', filename, '-f', 'segment', '-segment_time', '15', '-c', 'copy', 'parts/out%09d.wav']
    subprocess.run(command,stdout=subprocess.PIPE,stdin=subprocess.PIPE)
</code>```

EDIT. Forgot to mention what the function does at the moment with webm -files. It produces one wav -file out000000000.wav which is empty. In the console I get an error message like this:

```<code>[segment @ 0x55970b22fe80] Opening 'parts/out000000000.wav' for writing
[wav @ 0x55970b1ffbc0] opus codec not supported in WAVE format
Could not write header for output file #0 (incorrect codec parameters ?): Function not implemented
</code>```

EDIT2. I got it right I think but would like to hear if there's a better way to do this.

First I convert the file to a mono wav and then split it into chunks. Please feel free to point out any mistakes or errors.

```<code>def convert_webm_to_wav(file):
    command = ['ffmpeg', '-i', file, '-acodec', 'pcm_s16le', '-ac', '1', '-ar', '16000', '/home/janip/openvidu_files/' + file.name[:-5] + '.wav']
    subprocess.run(command,stdout=subprocess.PIPE,stdin=subprocess.PIPE)

def split_audio(filename):
    command = ['ffmpeg', '-i', filename, '-f', 'segment', '-segment_time', '15', '-c', 'copy', '/home/janip/work/Holda/Nut_ideas/voice_chat_demos/openvidu-tutorials/openvidu-js-node/python_scripts/parts/out%09d.wav']
    subprocess.run(command,stdout=subprocess.PIPE,stdin=subprocess.PIPE)
</code>```

EDIT3. I tried the function llogan offered and I get this error:

```<code>error:[segment @ 0x55f1c28d2740] Opening 'parts/out000000000.wav' for writing
[segment @ 0x55f1c28d2740] Failed to open segment 'parts/out000000000.wav'
Could not write header for output file #0 (incorrect codec parameters ?): No such file or directory
Error initializing output stream 0:0 --

error:Conversion failed!
</code>```

It works when I use two seperate functions but I think the audio quality is worse in wav than in the original webm. Anything I can do to that?

答:
No need to convert to WAV then do a separate command to segment. Just remove -c copy and do it all in one command:

```<code>def convert_and_split(filename):
    command = ['ffmpeg', '-i', filename, '-f', 'segment', '-segment_time', '15', 'out%09d.wav']
    subprocess.run(command,stdout=subprocess.PIPE,stdin=subprocess.PIPE)
</code>```

-c copy enables stream copy mode. It is like a copy and paste, but you can't put Opus audio into WAV. Removing -c copy will allow ffmpeg to convert Opus to WAV.

Title: Coverting webm to wav with ffmpeg

Body:
I've succesfully used ffmpeg in Python to convert mp3-files into wav so I can post them to Google Speech-To-Text. Now I have same situation with webm files and the old function I have doesn't work. It should convert the file into wav and split it into 15 second chunks. Can I do this from webm -file or do I need to convert it first into some other format?

The function I've used:

def convert_and_split(filename):
    command = ['ffmpeg', '-i', filename, '-f', 'segment', '-segment_time', '15', '-c', 'copy', 'parts/out%09d.wav']
    subprocess.run(command,stdout=subprocess.PIPE,stdin=subprocess.PIPE)

EDIT. Forgot to mention what the function does at the moment with webm -files. It produces one wav -file out000000000.wav which is empty. In the console I get an error message like this:

[segment @ 0x55970b22fe80] Opening 'parts/out000000000.wav' for writing
[wav @ 0x55970b1ffbc0] opus codec not supported in WAVE format
Could not write header for output file #0 (incorrect codec parameters ?): Function not implemented

EDIT2. I got it right I think but would like to hear if there's a better way to do this.

First I convert the file to a mono wav and then split it into chunks. Please feel free to point out any mistakes or errors.

def convert_webm_to_wav(file):
    command = ['ffmpeg', '-i', file, '-acodec', 'pcm_s16le', '-ac', '1', '-ar', '16000', '/home/janip/openvidu_files/' + file.name[:-5] + '.wav']
    subprocess.run(command,stdout=subprocess.PIPE,stdin=subprocess.PIPE)

def split_audio(filename):
    command = ['ffmpeg', '-i', filename, '-f', 'segment', '-segment_time', '15', '-c', 'copy', '/home/janip/work/Holda/Nut_ideas/voice_chat_demos/openvidu-tutorials/openvidu-js-node/python_scripts/parts/out%09d.wav']
    subprocess.run(command,stdout=subprocess.PIPE,stdin=subprocess.PIPE)

EDIT3. I tried the function llogan offered and I get this error:

error:[segment @ 0x55f1c28d2740] Opening 'parts/out000000000.wav' for writing
[segment @ 0x55f1c28d2740] Failed to open segment 'parts/out000000000.wav'
Could not write header for output file #0 (incorrect codec parameters ?): No such file or directory
Error initializing output stream 0:0 --

error:Conversion failed!

It works when I use two seperate functions but I think the audio quality is worse in wav than in the original webm. Anything I can do to that?

Body:
No need to convert to WAV then do a separate command to segment. Just remove -c copy and do it all in one command:

def convert_and_split(filename):
    command = ['ffmpeg', '-i', filename, '-f', 'segment', '-segment_time', '15', 'out%09d.wav']
    subprocess.run(command,stdout=subprocess.PIPE,stdin=subprocess.PIPE)

-c copy enables stream copy mode. It is like a copy and paste, but you can't put Opus audio into WAV. Removing -c copy will allow ffmpeg to convert Opus to WAV.


问:
Error When Creating an Unbounded Child Partition in PostgreSQL
I am running Postgres 12 and following examples from a book titled PostgreSQL: Up and Running published by O'Reilly Media. I am trying to create a partitioned table group like so:

```<code>CREATE TABLE logs (
    log_id int GENERATED BY DEFAULT AS IDENTITY,
    user_name varchar(50),
    description text,
    log_ts timestamp with time zone NOT NULL DEFAULT current_timestamp
) PARTITION BY RANGE (log_ts);
</code>```

The child partition is:

```<code>CREATE TABLE logs_gt_2011 PARTITION OF logs
FOR VALUES FROM ('2012-1-1') TO (unbounded);
</code>```

This returns the error:

```<code>ERROR:  cannot use column reference in partition bound expression
LINE 2: for values from ('2012-1-1') to (unbounded);
</code>```

which makes it seem like it thinks unbounded is a column name. I thought unbounded was a Postgres keyword. Can you help me figure out the correct way to create this child partition?

I am running Postgres on a Windows 10 machine, from Powershell.

答:
Not sure where the book gets it from, but according to the manual, that should be maxvalue:

The special values MINVALUE and MAXVALUE may be used when creating a range partition to indicate that there is no lower or upper bound on the column's value

```<code>CREATE TABLE logs_gt_2011 PARTITION OF logs
FOR VALUES FROM ('2012-01-01') TO (maxvalue);
</code>```

Body:
I am running Postgres 12 and following examples from a book titled PostgreSQL: Up and Running published by O'Reilly Media. I am trying to create a partitioned table group like so:

CREATE TABLE logs (
    log_id int GENERATED BY DEFAULT AS IDENTITY,
    user_name varchar(50),
    description text,
    log_ts timestamp with time zone NOT NULL DEFAULT current_timestamp
) PARTITION BY RANGE (log_ts);

The child partition is:

CREATE TABLE logs_gt_2011 PARTITION OF logs
FOR VALUES FROM ('2012-1-1') TO (unbounded);

This returns the error:

ERROR:  cannot use column reference in partition bound expression
LINE 2: for values from ('2012-1-1') to (unbounded);

which makes it seem like it thinks unbounded is a column name. I thought unbounded was a Postgres keyword. Can you help me figure out the correct way to create this child partition?

I am running Postgres on a Windows 10 machine, from Powershell.

Body:
Not sure where the book gets it from, but according to the manual, that should be maxvalue:

The special values MINVALUE and MAXVALUE may be used when creating a range partition to indicate that there is no lower or upper bound on the column's value

CREATE TABLE logs_gt_2011 PARTITION OF logs
FOR VALUES FROM ('2012-01-01') TO (maxvalue);


问:
iOS application Appstore submission issue which has having custom framework
I am facing iOS application submission issue.
In my application using bunch of nested custom frameworks which developed by me.

答:
I faced similar kind of problem. In short, I set the "Always Embed Swift Standard Libraries" setting to "No" in my targets. That worked for me.

You can try this

```<code>Always Embed Swift Standard Libraries: NO
</code>```

Body:
I faced similar kind of problem. In short, I set the "Always Embed Swift Standard Libraries" setting to "No" in my targets. That worked for me.

You can try this

Always Embed Swift Standard Libraries: NO


问:
Scala query need
Hi I am getting an error with following piece of code.

```<code>import org.apache.spark.sql._
import org.apache.spark.sql.types._
import org.apache.spark.sql.functions._
import org.apache.spark.sql.expressions._
import spark.implicits._

// Define case classe for input data
case class Article(articleId: Int, title: String, url: String, publisher: String,
                   category: String, storyId: String, hostname: String, timestamp: String)
// Read the input data
val articles = spark.read.
  schema(Encoders.product[Article].schema).
  option("delimiter", ",").
  csv("hdfs:///user/ashhall1616/bdc_data/t4/news-small.csv").
  as[Article]

articles.createOrReplaceTempView("articles")

val writeDf = spark.sql("""SELECT articles.storyId AS storyId1, articles.publisher AS publisher1
FROM articles
GROUP BY storyId
ORDER BY publisher1 ASC""")

</code>```

Error:

```<code>val writeDf = spark.sql("""SELECT articles.storyId AS storyId1, articles.publisher AS publisher1
     | FROM articles
     | GROUP BY storyId
     | ORDER BY publisher1 ASC""")
org.apache.spark.sql.AnalysisException: expression 'articles.`publisher`' is neither present in the group by, nor is it an aggregate function. Add to group by or w
rap in first() (or first_value) if you don't care which value you get.;;
Sort [publisher1#36 ASC NULLS FIRST], true
+- Aggregate [storyId#13], [storyId#13 AS storyId1#35, publisher#11 AS publisher1#36]
   +- SubqueryAlias articles
      +- Relation[articleId#8,title#9,url#10,publisher#11,category#12,storyId#13,hostname#14,timestamp#15] csv

</code>```

Data set looks like:

articleId   publisher   Category    storyId hostname

1   |  Los Angeles Times |  B | ddUyU0VZz0BRneMioxUPQVP6sIxvM  |  www.latimes.com

goal is to create a list of each story paired with each publisher that wrote at least one article for that story.

[ddUyU0VZz0BRneMioxUPQVP6sIxvM, Livemint]

[ddUyU0VZz0BRneMioxUPQVP6sIxvM, IFA Magazine]

[ddUyU0VZz0BRneMioxUPQVP6sIxvM, Moneynews]

[ddUyU0VZz0BRneMioxUPQVP6sIxvM, NASDAQ]

[dPhGU51DcrolUIMxbRm0InaHGA2XM, IFA Magazine]

[ddUyU0VZz0BRneMioxUPQVP6sIxvM, Los Angeles Times]

[dPhGU51DcrolUIMxbRm0InaHGA2XM, NASDAQ]

can someone suggest code improvement to get the desired output?

答:
Parser, compiler getting confused.

You have no AGGregate with the GROUP BY. Use DISTINCT on storyid, publisher.

Check if you also need storyId1 on GROUP BY as well.

Title: Scala query need

Body:
Hi I am getting an error with following piece of code.

import org.apache.spark.sql._
import org.apache.spark.sql.types._
import org.apache.spark.sql.functions._
import org.apache.spark.sql.expressions._
import spark.implicits._

// Define case classe for input data
case class Article(articleId: Int, title: String, url: String, publisher: String,
                   category: String, storyId: String, hostname: String, timestamp: String)
// Read the input data
val articles = spark.read.
  schema(Encoders.product[Article].schema).
  option("delimiter", ",").
  csv("hdfs:///user/ashhall1616/bdc_data/t4/news-small.csv").
  as[Article]

articles.createOrReplaceTempView("articles")

val writeDf = spark.sql("""SELECT articles.storyId AS storyId1, articles.publisher AS publisher1
FROM articles
GROUP BY storyId
ORDER BY publisher1 ASC""")

Error:

val writeDf = spark.sql("""SELECT articles.storyId AS storyId1, articles.publisher AS publisher1
     | FROM articles
     | GROUP BY storyId
     | ORDER BY publisher1 ASC""")
org.apache.spark.sql.AnalysisException: expression 'articles.`publisher`' is neither present in the group by, nor is it an aggregate function. Add to group by or w
rap in first() (or first_value) if you don't care which value you get.;;
Sort [publisher1#36 ASC NULLS FIRST], true
+- Aggregate [storyId#13], [storyId#13 AS storyId1#35, publisher#11 AS publisher1#36]
   +- SubqueryAlias articles
      +- Relation[articleId#8,title#9,url#10,publisher#11,category#12,storyId#13,hostname#14,timestamp#15] csv

Data set looks like:

articleId   publisher   Category    storyId hostname

1   |  Los Angeles Times |  B | ddUyU0VZz0BRneMioxUPQVP6sIxvM  |  www.latimes.com

goal is to create a list of each story paired with each publisher that wrote at least one article for that story.

[ddUyU0VZz0BRneMioxUPQVP6sIxvM, Livemint]

[ddUyU0VZz0BRneMioxUPQVP6sIxvM, IFA Magazine]

[ddUyU0VZz0BRneMioxUPQVP6sIxvM, Moneynews]

[ddUyU0VZz0BRneMioxUPQVP6sIxvM, NASDAQ]

[dPhGU51DcrolUIMxbRm0InaHGA2XM, IFA Magazine]

[ddUyU0VZz0BRneMioxUPQVP6sIxvM, Los Angeles Times]

[dPhGU51DcrolUIMxbRm0InaHGA2XM, NASDAQ]

can someone suggest code improvement to get the desired output?