问:
Macro produces negative font.colorindex values
Clues to possible reason at the end of this initial discussion.....

A simple VBA macro code line like:

```<code>FontCol = Cells(K, AmntCol).Font.ColorIndex
</code>```

reports, with the cursor hovering over "FontCol", the value "1"
- which is the index value for black.

yet when this value is "published" to the relevant (active) Excel spreadsheet with:

```<code>Cells(RowRef, ColRef) = FontCol
</code>```

the Cell addressed as above shows -5 instead of 1 (as one example of the problem)

"1" is what you expect to see for black, and I cannot even work out what "-5" relates to
let alone why it is also not what seems to be in play in the VBA code.
- and if I write "-5" into some code logic, no useful result would come from it, which confirms that the real underlying value is 1 and not -5.

It seems that no amount of formatting of the (landing) cell or changing the "Dimension as statement" for FontCol, to "integer" or "string" or "variant" changes what is published to the cell.

I've not been able to source any information on this issue. The closest was something about long numbers wrapping around shorter numbers in the index space and a residual driving things...whatever that is supposed to mean.

I really would to resolve this as I was intending to use ColorIndex values as a way of editing cell values safely.

Any wisdom would be greatly appreciated.

Additional to above - in response.

Changing Dim of variable/s from "integer" to "long" makes no difference.

In preparing to provide sample code as below I have determined part of the problem - its seems its speed related. But first the code.

''''
    Sub FontMacroIssue()

```<code>Dim I As Long
Dim FontCol As Long

For I = 36 To 51
    FontCol = Cells(I, 10).Font.ColorIndex
    If FontCol = 3 Then
        Cells(I, 18) = "Red"
        Cells(I, 19) = FontCol
    Else
        Cells(I, 18) = "Not Red"
        Cells(I, 19) = FontCol
    End If
Next I

End Sub
''''
</code>```

The above is being run on a Windows 10 64 bit machine (that dual boots into Linux)...this should not be relevant.

If the above is run as is then the output is mostly/all "not red" and the string of FontCol values print out as,

1 -5 -5 -5 -5 -7 -7 -7 -7 -7 -7 -7 -7 -7 -5 -7 - and if it is slowed, as
1  3  3  3  3  1  1  1  1  1  1  1  1  1  3  1

By slowed, I mean running the macro in debug mode with a break point at "Next I" or in a similar place, and then keying the F5 button (say) twice a second. The output for the full speed case is mostly/all "not red" but is the correct reporting of "red" and "not red" when slowed for the font being assessed.

So my question/s now are more, "is this behaviour normal", "how can I best slow things down to get a correct result" OR "what code is more effective" ?
edit...

I am inclined to agree with Fun Thomas as even 2 cycles/sec brings up the problem.
I do not have an answer but some comments that might help.
1.  My hard drive is a 2 TB SSD
2.  The spreadsheet concerned has over 46000 lines.
3.  It surely is more than coincidence that:
    8 -7 = 1  with both 1 and -7 being reported for black font, and
    8 -5 = 3  with both 3 and -5 being reported for red font.
Thanks

答:
The Font.ColorIndex returns:

The color is specified as an index value into the current color palette, or as one of the following XlColorIndex constants: xlColorIndexAutomatic or xlColorIndexNone.

The constants will show as integer values -4105 en -4142 respectively.

Body:
Clues to possible reason at the end of this initial discussion.....

A simple VBA macro code line like:

FontCol = Cells(K, AmntCol).Font.ColorIndex

reports, with the cursor hovering over "FontCol", the value "1"
- which is the index value for black.

yet when this value is "published" to the relevant (active) Excel spreadsheet with:

Cells(RowRef, ColRef) = FontCol

the Cell addressed as above shows -5 instead of 1 (as one example of the problem)

"1" is what you expect to see for black, and I cannot even work out what "-5" relates to
let alone why it is also not what seems to be in play in the VBA code.
- and if I write "-5" into some code logic, no useful result would come from it, which confirms that the real underlying value is 1 and not -5.

It seems that no amount of formatting of the (landing) cell or changing the "Dimension as statement" for FontCol, to "integer" or "string" or "variant" changes what is published to the cell.

I've not been able to source any information on this issue. The closest was something about long numbers wrapping around shorter numbers in the index space and a residual driving things...whatever that is supposed to mean.

I really would to resolve this as I was intending to use ColorIndex values as a way of editing cell values safely.

Any wisdom would be greatly appreciated.

Additional to above - in response.

Changing Dim of variable/s from "integer" to "long" makes no difference.

In preparing to provide sample code as below I have determined part of the problem - its seems its speed related. But first the code.

''''
    Sub FontMacroIssue()

Dim I As Long
Dim FontCol As Long

For I = 36 To 51
    FontCol = Cells(I, 10).Font.ColorIndex
    If FontCol = 3 Then
        Cells(I, 18) = "Red"
        Cells(I, 19) = FontCol
    Else
        Cells(I, 18) = "Not Red"
        Cells(I, 19) = FontCol
    End If
Next I

End Sub
''''

The above is being run on a Windows 10 64 bit machine (that dual boots into Linux)...this should not be relevant.

If the above is run as is then the output is mostly/all "not red" and the string of FontCol values print out as,

1 -5 -5 -5 -5 -7 -7 -7 -7 -7 -7 -7 -7 -7 -5 -7 - and if it is slowed, as
1  3  3  3  3  1  1  1  1  1  1  1  1  1  3  1

By slowed, I mean running the macro in debug mode with a break point at "Next I" or in a similar place, and then keying the F5 button (say) twice a second. The output for the full speed case is mostly/all "not red" but is the correct reporting of "red" and "not red" when slowed for the font being assessed.

So my question/s now are more, "is this behaviour normal", "how can I best slow things down to get a correct result" OR "what code is more effective" ?
edit...

I am inclined to agree with Fun Thomas as even 2 cycles/sec brings up the problem.
I do not have an answer but some comments that might help.
1.  My hard drive is a 2 TB SSD
2.  The spreadsheet concerned has over 46000 lines.
3.  It surely is more than coincidence that:
    8 -7 = 1  with both 1 and -7 being reported for black font, and
    8 -5 = 3  with both 3 and -5 being reported for red font.
Thanks


来源: stackexchange

问:
vba outlook unified inbox w/ ONLY Select Mailboxes (windows desktop version)
Unified for all mailboxes works with below code. I can't find right syntax or example to allow me to see some other mailboxes together.

Example: you have four mailboxes setup in outlook, A, B, C, D. The below code unifies/shows all inboxes with the VBA Search.

The Question: I would like to modify code to show/unifiy ONLY mailboxes B, C, & D. to combine a subset of mailboxes, not all.

I suspect I could set the value of currentfolder somehow...but this would only be one folder at a time?  Thanks!!!!!

I have searched for awhile for this, thanks for your time!!!

```<code>`    Sub UnifiedInboxThisWeek()
    Dim myOlApp As New Outlook.Application
    txtSearch = "folder:Inbox received: (this week)"
    myOlApp.ActiveExplorer.Search txtSearch, olSearchScopeAllFolders
    Set myOlApp = Nothing
    End Sub`
</code>```

答:
The Outlook object model doesn't provide anything for that. You can search in a single store, but not multiple profiles simultaneously. However, you can get access to shared mailboxes by using the GetSharedDefaultFolder method which returns a Folder object that represents the specified default folder for the specified user. So, you can run multiple searches against different stores.

Consider using the AdvancedSearch method of the Application class which has the following key benefits:

The search is performed in another thread. You don’t need to run another thread manually since the AdvancedSearch method runs it automatically in the background.

Possibility to search for any item types: mail, appointment, calendar, notes etc. in any location, i.e. beyond the scope of a certain folder. The Restrict and Find/FindNext methods can be applied to a particular Items collection (see the Items property of the Folder class in Outlook).

Full support for DASL queries (custom properties can be used for searching too). You can read more about this in the Filtering article in MSDN. To improve the search performance, Instant Search keywords can be used if Instant Search is enabled for the store (see the IsInstantSearchEnabled property of the Store class).

You can stop the search process at any moment using the Stop method of the Search class.

Using the Scope parameter, you can specify one or more folders in the same store, but you may not specify multiple folders in multiple stores. To specify multiple folders in the same store for the Scope parameter, use a comma character between each folder path and enclose each folder path in single quotes. For default folders such as Inbox or Sent Items, you can use the simple folder name instead of the full folder path. For example, the following two lines of code represent valid Scope parameters:

```<code>Scope = "'Inbox', 'Sent Items'"
</code>```

and you can also use the folder path:

```<code>Scope = "'" & Application.Session.GetDefaultFolder(olFolderInbox).FolderPath _
    & "','" & Application.Session.GetDefaultFolder(olFolderSentMail).FolderPath & "'"
</code>```

Read more about the AdvancedSearch method in the Advanced search in Outlook programmatically: C#, VB.NET article.

ContentLicense: CC BY-SA 4.0

Body:
Unified for all mailboxes works with below code. I can't find right syntax or example to allow me to see some other mailboxes together.

Example: you have four mailboxes setup in outlook, A, B, C, D. The below code unifies/shows all inboxes with the VBA Search.

The Question: I would like to modify code to show/unifiy ONLY mailboxes B, C, & D. to combine a subset of mailboxes, not all.

I suspect I could set the value of currentfolder somehow...but this would only be one folder at a time?  Thanks!!!!!

I have searched for awhile for this, thanks for your time!!!

`    Sub UnifiedInboxThisWeek()
    Dim myOlApp As New Outlook.Application
    txtSearch = "folder:Inbox received: (this week)"
    myOlApp.ActiveExplorer.Search txtSearch, olSearchScopeAllFolders
    Set myOlApp = Nothing
    End Sub`

Body:
The Outlook object model doesn't provide anything for that. You can search in a single store, but not multiple profiles simultaneously. However, you can get access to shared mailboxes by using the GetSharedDefaultFolder method which returns a Folder object that represents the specified default folder for the specified user. So, you can run multiple searches against different stores.

Consider using the AdvancedSearch method of the Application class which has the following key benefits:

The search is performed in another thread. You don’t need to run another thread manually since the AdvancedSearch method runs it automatically in the background.

Possibility to search for any item types: mail, appointment, calendar, notes etc. in any location, i.e. beyond the scope of a certain folder. The Restrict and Find/FindNext methods can be applied to a particular Items collection (see the Items property of the Folder class in Outlook).

Full support for DASL queries (custom properties can be used for searching too). You can read more about this in the Filtering article in MSDN. To improve the search performance, Instant Search keywords can be used if Instant Search is enabled for the store (see the IsInstantSearchEnabled property of the Store class).

You can stop the search process at any moment using the Stop method of the Search class.

Using the Scope parameter, you can specify one or more folders in the same store, but you may not specify multiple folders in multiple stores. To specify multiple folders in the same store for the Scope parameter, use a comma character between each folder path and enclose each folder path in single quotes. For default folders such as Inbox or Sent Items, you can use the simple folder name instead of the full folder path. For example, the following two lines of code represent valid Scope parameters:

Scope = "'Inbox', 'Sent Items'"

and you can also use the folder path:

Scope = "'" & Application.Session.GetDefaultFolder(olFolderInbox).FolderPath _
    & "','" & Application.Session.GetDefaultFolder(olFolderSentMail).FolderPath & "'"

Read more about the AdvancedSearch method in the Advanced search in Outlook programmatically: C#, VB.NET article.


问:
problem with declaring variable in php?
i have a variables like $srange0 , $srange1, $srange2 $srange3.

i am using to declare some value to each value using for loop.

```<code>for($i=0;$i<=3;$i++){
  $srange.$i = $i;
}
</code>```

but its not working ?

is there any alternative solution for this

答:
Use an array:

```<code>$srange = array();
for ($i = 0; $i <= 3; ++$i)
  $srange[$i] = $i;
</code>```

For the purpose of this particular task, you can also do this:

```<code>$srange = range(0, 3);
</code>```

That also builds the same array as my first code snippet.

ContentLicense: CC BY-SA 3.0

Title: problem with declaring variable in php?

Body:
i have a variables like $srange0 , $srange1, $srange2 $srange3.

i am using to declare some value to each value using for loop.

for($i=0;$i<=3;$i++){
  $srange.$i = $i;
}

but its not working ?

is there any alternative solution for this

Body:
Use an array:

$srange = array();
for ($i = 0; $i <= 3; ++$i)
  $srange[$i] = $i;

For the purpose of this particular task, you can also do this:

$srange = range(0, 3);

That also builds the same array as my first code snippet.


问:
Refresh previous screen after editing the state and going back
Alright, I know there's a lot of speculation online about how this should be done, but I'm not happy about most of them or they are outdated :)

This is a simplified representation of my setup:

```<code>// Navigator
const Stack = createStackNavigator();
<Stack.Navigator
    initialRouteName={"A"}
>
    <Stack.Screen
        name={"A"}
        component={A}
    />
    <Stack.Screen
        name={"B"}
        component={B}
    />
    <Stack.Screen
        name={"C"}
        component={C}
    />
</Stack.Navigator>
</code>```

Redux is my state manager of choice and it's working fine for my 3 dummy screens
Here's a dummy state and reducer:

```<code>const initialState = {
    items: [
        {prop: "a"},
        {prop: "b"},
        {prop: "c"},
    ]
}
const dummyReducer = (state = initialState, action) => {
    switch(action.type) {
        case "EDIT":
            const dummyEdit = state.items.pop();
            dummyEdit.prop = "c (edited)";
            return {
               items = [...state.items, dummyEdit]
            }
    }
}
</code>```

And here are my very innovative screens

```<code>// Class A
render() {
    return <A>
        <ListView ... data={state.items} />
    </A>
}

// Class B
render() {
    return <B>
        <Text>state.item.prop</Text>
    </B>
}

// Class C
render() {
    return <C>
        <Input value={state.item.prop}
            onChangeText={text => dispatch({type: EDIT})}
        ></Input>
    </C>
}
</code>```

So screen A is just a list that navigates to screen B which displays the item properties.
On screen B you can edit that item, which takes you to Screen C.
When you edit the item on screen C, the reducer updates the state. After that you navigation.goBack() to screen B.

All screens are connected to the same reducer and state.
When I place a breakpoint in the render function of screen B, I can see the state is indeed updated right after the C's input onTextChanged

What I (think I) know

On screen B, this doesn't help: shouldComponentUpdate() {return true;}

Redux compares object lazily so prevState.items === state.items is true and the screen doesn't update

Even though the render function is being called, that doesn't mean the screen will be updated

I can navigation.dispatch(StackActions.pop(2)); navigation.navigate("B"); to update screen B but this seems far-fetched and it leaves you with a back transition animation

Packages

```<code>"react": "16.9.0",
"react-native": "^0.61.5",
"react-navigation": "^4.2.2",
"@react-navigation/drawer": "^5.1.1",
"@react-navigation/native": "^5.0.9",
"@react-navigation/stack": "^5.1.1",
</code>```

Hopefully some of you recognize the problem I'm facing. Any help is greatly appreciated.

答:
Alright, so I managed to figure out what was wrong. I was wrong to assume that the problem was the StackNavigator
My screen B is a lot more complex than the example I gave, so I'll add some details.

```<code>// Class B
render() {
    return <B>
        <CustomTextContainer data={state.item}>
            <CustomText data={state.item.prop1} />
            <CustomText data={state.item.prop2} />
        </CustomTextContainer>
    </B>
}
</code>```

Both CustomTextContainer and CustomText are connected to the store and they both have a shouldComponentUpdate function.
Apparently, when the container's shouldComponentUpdate returns false, the children's shouldComponentUpdate function never gets called.

This was my mistake. I've read that when the child is connected to the store, it should receive it's props directly regardless of it's parent. That's not the case.

Body:
Alright, I know there's a lot of speculation online about how this should be done, but I'm not happy about most of them or they are outdated :)

This is a simplified representation of my setup:

// Navigator
const Stack = createStackNavigator();
<Stack.Navigator
    initialRouteName={"A"}
>
    <Stack.Screen
        name={"A"}
        component={A}
    />
    <Stack.Screen
        name={"B"}
        component={B}
    />
    <Stack.Screen
        name={"C"}
        component={C}
    />
</Stack.Navigator>

Redux is my state manager of choice and it's working fine for my 3 dummy screens
Here's a dummy state and reducer:

const initialState = {
    items: [
        {prop: "a"},
        {prop: "b"},
        {prop: "c"},
    ]
}
const dummyReducer = (state = initialState, action) => {
    switch(action.type) {
        case "EDIT":
            const dummyEdit = state.items.pop();
            dummyEdit.prop = "c (edited)";
            return {
               items = [...state.items, dummyEdit]
            }
    }
}

And here are my very innovative screens

// Class A
render() {
    return
        <ListView ... data={state.items} />

}

// Class B
render() {
    return
        <Text>state.item.prop</Text>

}

// Class C
render() {
    return <C>
        <Input value={state.item.prop}
            onChangeText={text => dispatch({type: EDIT})}
        ></Input>
    </C>
}

So screen A is just a list that navigates to screen B which displays the item properties.
On screen B you can edit that item, which takes you to Screen C.
When you edit the item on screen C, the reducer updates the state. After that you navigation.goBack() to screen B.

All screens are connected to the same reducer and state.
When I place a breakpoint in the render function of screen B, I can see the state is indeed updated right after the C's input onTextChanged

What I (think I) know

On screen B, this doesn't help: shouldComponentUpdate() {return true;}

Redux compares object lazily so prevState.items === state.items is true and the screen doesn't update

Even though the render function is being called, that doesn't mean the screen will be updated

I can navigation.dispatch(StackActions.pop(2)); navigation.navigate("B"); to update screen B but this seems far-fetched and it leaves you with a back transition animation

Packages

"react": "16.9.0",
"react-native": "^0.61.5",
"react-navigation": "^4.2.2",
"@react-navigation/drawer": "^5.1.1",
"@react-navigation/native": "^5.0.9",
"@react-navigation/stack": "^5.1.1",

Hopefully some of you recognize the problem I'm facing. Any help is greatly appreciated.

Body:
Alright, so I managed to figure out what was wrong. I was wrong to assume that the problem was the StackNavigator
My screen B is a lot more complex than the example I gave, so I'll add some details.

// Class B
render() {
    return <B>
        <CustomTextContainer data={state.item}>
            <CustomText data={state.item.prop1} />
            <CustomText data={state.item.prop2} />
        </CustomTextContainer>
    </B>
}

Both CustomTextContainer and CustomText are connected to the store and they both have a shouldComponentUpdate function.
Apparently, when the container's shouldComponentUpdate returns false, the children's shouldComponentUpdate function never gets called.

This was my mistake. I've read that when the child is connected to the store, it should receive it's props directly regardless of it's parent. That's not the case.


问:
Kinds of IPI for x86 architecture in Linux
I would like to know what are the different kinds of IPIs available for x86_64 in Linux. In particular, I want to find out the different interrupts handlers for IPI interrupts.

In Understanding the Linux Kernel, 3rd Edition by Daniel P. Bovet, Marco Cesati
https://www.oreilly.com/library/view/understanding-the-linux/0596005652/ch04s06.html
lists three kinds of IPIs:

```<code>CALL_FUNCTION_VECTOR
RESCHEDULE_VECTOR
INVALIDATE_TLB_VECTOR
</code>```

However in the latest kernels, I find the below comment in arch/x86/include/asm/entry_arch.h.

```<code> * This file is designed to contain the BUILD_INTERRUPT specifications for
 * all of the extra named interrupt vectors used by the architecture.
 * Usually this is the Inter Process Interrupts (IPIs)
 */

/*
 * The following vectors are part of the Linux architecture, there
 * is no hardware IRQ pin equivalent for them, they are triggered
 * through the ICC by us (IPIs)
</code>```

https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/arch/x86/include/asm/entry_arch.h?h=v5.6.15

Could someone confirm whether all those Vectors listed in the file are different kinds of IPI for x86_64.
For ARM I could find a unified handler - handle_IPI() for all the IPIs. A switch case is used to find out which IPI.

答:
On x86 any interrupt vector can be triggered by an IPI, so there isn't (or aren't) a designated interrupt vector.

The image above depicts the format of the register used to send IPIs, the Fixed mode uses the Vector field to make the target CPUs execute the interrupt service routine associated with that vector. It's like an int vector instruction was executed in the targets.

So Linux can, theoretically, directly invoke any interrupt on any other CPU.

However, kernel modules often need to run a function on specific CPUs; so Linux has a set of utility functions like smp_call_function_single that will make the life of the programmer easy.

These functions are implemented with a mechanism that's worth a chapter on its own, now I don't know the detail but it's not hard to image the basic idea behind: have a global queue of functions to execute and an interrupt vector that, once invoked, dequeues an item and executes it.

By calling that interrupt vector with an IPI, Linux can make the target CPUs execute the given function.

The interrupt vectors you found are used for this. You probably want to look at their 64 bits counterpart in entry_64.S and under the guard #ifdef CONFIG_SMP.

The acpiinterrupt and acpiinterrupt3 are just macros that define a label with the second argument, call interrupt_entry with the first argument (the vector number) NOTted  and call the function named in the third argument.

Be careful that the 32 bits analog does some nasty prefix-concatenation with the target function name.

apicinterrupt CALL_FUNCTION_SINGLE_VECTOR  call_function_single_interrupt  smp_call_function_single_interrupt is roughly equivalent to defining the function:

```<code>;Metadata stuff (e.g. section placement)

call_function_single_interrupt:               ;<-- first arg
  push ~CALL_FUNCTION_SINGLE_VECTOR           ;<-- second arg
  call interrupt_entry

  ;other stuff (tracing, flags, etc)
  call smp_call_function_single_interrupt     ;<-- third arg

  ;other stuff (like above, plus returning)
</code>```

The vector numbers are defined in irq_vectors.h and are, of course, also used in idt.c for the IDT.

The target functions (the interrupt handlers) are mostly (all? I didn't check) defined in smp.c and they probably are the closest thing to the ARM's handle_IPI handler.

Those seem to be the only vectors invoked through an IPI.

Body:
I would like to know what are the different kinds of IPIs available for x86_64 in Linux. In particular, I want to find out the different interrupts handlers for IPI interrupts.

In Understanding the Linux Kernel, 3rd Edition by Daniel P. Bovet, Marco Cesati
https://www.oreilly.com/library/view/understanding-the-linux/0596005652/ch04s06.html
lists three kinds of IPIs:

CALL_FUNCTION_VECTOR
RESCHEDULE_VECTOR
INVALIDATE_TLB_VECTOR

However in the latest kernels, I find the below comment in arch/x86/include/asm/entry_arch.h.

 * This file is designed to contain the BUILD_INTERRUPT specifications for
 * all of the extra named interrupt vectors used by the architecture.
 * Usually this is the Inter Process Interrupts (IPIs)
 */

/*
 * The following vectors are part of the Linux architecture, there
 * is no hardware IRQ pin equivalent for them, they are triggered
 * through the ICC by us (IPIs)

https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/arch/x86/include/asm/entry_arch.h?h=v5.6.15

Could someone confirm whether all those Vectors listed in the file are different kinds of IPI for x86_64.
For ARM I could find a unified handler - handle_IPI() for all the IPIs. A switch case is used to find out which IPI.

Body:
On x86 any interrupt vector can be triggered by an IPI, so there isn't (or aren't) a designated interrupt vector.

The image above depicts the format of the register used to send IPIs, the Fixed mode uses the Vector field to make the target CPUs execute the interrupt service routine associated with that vector. It's like an int vector instruction was executed in the targets.

So Linux can, theoretically, directly invoke any interrupt on any other CPU.

However, kernel modules often need to run a function on specific CPUs; so Linux has a set of utility functions like smp_call_function_single that will make the life of the programmer easy.

These functions are implemented with a mechanism that's worth a chapter on its own, now I don't know the detail but it's not hard to image the basic idea behind: have a global queue of functions to execute and an interrupt vector that, once invoked, dequeues an item and executes it.

By calling that interrupt vector with an IPI, Linux can make the target CPUs execute the given function.

The interrupt vectors you found are used for this. You probably want to look at their 64 bits counterpart in entry_64.S and under the guard #ifdef CONFIG_SMP.

The acpiinterrupt and acpiinterrupt3 are just macros that define a label with the second argument, call interrupt_entry with the first argument (the vector number) NOTted  and call the function named in the third argument.

Be careful that the 32 bits analog does some nasty prefix-concatenation with the target function name.

apicinterrupt CALL_FUNCTION_SINGLE_VECTOR  call_function_single_interrupt  smp_call_function_single_interrupt is roughly equivalent to defining the function:

;Metadata stuff (e.g. section placement)

call_function_single_interrupt:               ;<-- first arg
  push ~CALL_FUNCTION_SINGLE_VECTOR           ;<-- second arg
  call interrupt_entry

  ;other stuff (tracing, flags, etc)
  call smp_call_function_single_interrupt     ;<-- third arg

  ;other stuff (like above, plus returning)

The vector numbers are defined in irq_vectors.h and are, of course, also used in idt.c for the IDT.

The target functions (the interrupt handlers) are mostly (all? I didn't check) defined in smp.c and they probably are the closest thing to the ARM's handle_IPI handler.

Those seem to be the only vectors invoked through an IPI.


问:
How to not use Rails action parameter in controller
I am implementing a third party API for Shipworks in a Rails server and the Shipworks client app is posting an action param with Shipworks specific semantics.

However the Rails routing logic overwrites this param to be the name of the controller method.

Is there a custom route I could write to get the value of that action param without it being overwritten to be the name of my controller method?

答:
I figured it out.  There is a raw_post method in AbstractRequest.

So you can do this to parse the raw post params:

```<code>def raw_post_to_hash
  request.raw_post.split(/&/).inject({}) do |hash, setting|
    key, val = setting.split(/=/)
    hash[key.to_sym] = val
    hash
   end
end
</code>```

and then just call raw_post_to_hash[:action] to access the original action param or any other param.  There is probably an easier way.

Body:
I figured it out.  There is a raw_post method in AbstractRequest.

So you can do this to parse the raw post params:

def raw_post_to_hash
  request.raw_post.split(/&/).inject({}) do |hash, setting|
    key, val = setting.split(/=/)
    hash[key.to_sym] = val
    hash
   end
end

and then just call raw_post_to_hash[:action] to access the original action param or any other param.  There is probably an easier way.


问:
Dice rolling program with counter
I'm new to programming and I have a task that I can't figure out on my own.

The task is to make a program that let's you decide how many dices to throw, 1 to 5, with checking if you make a wrong input.
After every roll the number of the die will show and the total so far.
If the die rolls a 6 then it is not included in the total and you get to more rolls. This is where I'm stuck. I want my program to restart the loop if the die turns a 6 and just ad 2 rolls to the sumDices and continue the loop, but I can't get it to work.

here is my code:

```<code>import random
numDices=0
total = 0
print("------------")
print("DICE ROLLING")
print("------------")
print()
exit=False
reset=False
while True:
    while True:
        numDices=int(input("How many dices to throw? (1-5) "))
        if numDices<1 or numDices>5:
            print("Wrong input, try again")
            break
        while True:
            if reset==True:
                break
            for i in range(numDices):
                dicesArray = list(range(numDices))
                dicesArray[i] = random.randint(1, 6)
                print(dicesArray[i])
                total += dicesArray[i]
                if dicesArray[i] == 1:
                    print("You rolled a one, the total is: ",str(total))
                elif dicesArray[i] == 2:
                    print("You rolled a two, the total is: ",str(total))
                elif dicesArray[i] == 3:
                    print("You rolled a three, the total is: ",str(total))
                elif dicesArray[i] == 4:
                    print("You rolled a four, the total is: ",str(total))
                elif dicesArray[i] == 5:
                    print("You rolled a five, the total is: ",str(total))
                elif dicesArray[i] == 6:
                    total-=6
                    numDices+=2
                    print("You rolled a six, rolling two new dices")
                    reset=True
        print("The total sum is",str(total),"with",numDices,"number of rolls.")
        print()
        restart=(input("Do you want to restart press Enter, to quit press 9. "))
        if restart=="9":
            exit=True
            break
        else:
            print()
            break
    if exit==True:
        break
</code>```

答:
Using a recursive function </p>

```<code>import random

total = 0
diceRollList = []

# Define dice rolling function
def rollDice():
    rollResult = random.randint(1, 6)
    if rollResult == 6:
        # If 6 Rolled run two more rolls and sum the results
        print("Rolled a 6 Rolling 2 more")
        return sum([rollDice() for _ in range(2)])
    # If 6 not rolled return the result
    print(f"Rolled a {rollResult}")
    return rollResult

while True:

    numberOfDice = int(input("How many Die to throw: "))

    if numberOfDice not in range(1, 6):
        print("Number of dice should be between 1 and 5")
        break

    for dice in range(numberOfDice):
        print(f"Rolling Dice {dice}")
        # Add result to the total
        total += rollDice()
        print(f"Running Total: {total}")
</code>```

Title: Dice rolling program with counter

Body:
I'm new to programming and I have a task that I can't figure out on my own.

The task is to make a program that let's you decide how many dices to throw, 1 to 5, with checking if you make a wrong input.
After every roll the number of the die will show and the total so far.
If the die rolls a 6 then it is not included in the total and you get to more rolls. This is where I'm stuck. I want my program to restart the loop if the die turns a 6 and just ad 2 rolls to the sumDices and continue the loop, but I can't get it to work.

here is my code:

import random
numDices=0
total = 0
print("------------")
print("DICE ROLLING")
print("------------")
print()
exit=False
reset=False
while True:
    while True:
        numDices=int(input("How many dices to throw? (1-5) "))
        if numDices<1 or numDices>5:
            print("Wrong input, try again")
            break
        while True:
            if reset==True:
                break
            for i in range(numDices):
                dicesArray = list(range(numDices))
                dicesArray[i] = random.randint(1, 6)
                print(dicesArray[i])
                total += dicesArray[i]
                if dicesArray[i] == 1:
                    print("You rolled a one, the total is: ",str(total))
                elif dicesArray[i] == 2:
                    print("You rolled a two, the total is: ",str(total))
                elif dicesArray[i] == 3:
                    print("You rolled a three, the total is: ",str(total))
                elif dicesArray[i] == 4:
                    print("You rolled a four, the total is: ",str(total))
                elif dicesArray[i] == 5:
                    print("You rolled a five, the total is: ",str(total))
                elif dicesArray[i] == 6:
                    total-=6
                    numDices+=2
                    print("You rolled a six, rolling two new dices")
                    reset=True
        print("The total sum is",str(total),"with",numDices,"number of rolls.")
        print()
        restart=(input("Do you want to restart press Enter, to quit press 9. "))
        if restart=="9":
            exit=True
            break
        else:
            print()
            break
    if exit==True:
        break

Body:
Using a recursive function

import random

total = 0
diceRollList = []

# Define dice rolling function
def rollDice():
    rollResult = random.randint(1, 6)
    if rollResult == 6:
        # If 6 Rolled run two more rolls and sum the results
        print("Rolled a 6 Rolling 2 more")
        return sum([rollDice() for _ in range(2)])
    # If 6 not rolled return the result
    print(f"Rolled a {rollResult}")
    return rollResult

while True:

    numberOfDice = int(input("How many Die to throw: "))

    if numberOfDice not in range(1, 6):
        print("Number of dice should be between 1 and 5")
        break

    for dice in range(numberOfDice):
        print(f"Rolling Dice {dice}")
        # Add result to the total
        total += rollDice()
        print(f"Running Total: {total}")


问:
A FreeRTOS task suddenly does nothing
I'm developing a real time system with FreeRTOS on an
STM3240G
board.

The system contains some different tasks ( GUI, KB, ModBus, Ctrl, etc . . )

The tasks have different priorities.

The GUI seems to display a little slowly.

So I use a Profiler software to see what is going on between the different tasks
during a run. This profiler shows me which task was running at each moment ( microsecond) and what interrupts had arrived.

This profiler enables me to "mark" different locations on the code so I know
when it was there. So I run the program and make a record.

I looked at the record and I saw that (for example) Ctrl task was between two
lines of code for 15 milliseconds (this time change in size) there was not any
task change no interrupt arrived and after this time the system continues normally from this point according to the record and my marks.

I tried closing disabling different interrupts without any success.
Has anyone any idea what it could be?

答:
On the eval board, there is a MIPI connector that supports ETM trace - a considerable luxury/advantage over other development boards!
If you also have one of the more expensive debug adapters that also support ETM trace (like for example, uTrace or J-Trace or
ULINKpro or I-jet Trace), you should use it to trace the entire control flow without having to instrument tasks and ISRs.

Otherwise, you should re-check if really every IRQ handler has been instrumented (credits to @RealtimeRik, who pointed this out) at a low-enough level so that the profiler can really spot it.
Especially if you are using third-party libraries, it may be that some IRQs are serviced by handlers you (or the profiler) doesn't have the code of.
As I had to make this experience once myself, I suggest you review the NVIC settings carefully to re-check if there is an ISR you haven't been aware of.

Another question is how the profiler internally works.
If it is based on ETM/TPIU or ITM/SWO tracing, see above.
If it creates and counts a huge number of snapshots, there might be some systematic cases which prevent snapshots to be made in a particular part of the software:

Could it be that a non-maskable interrupt or exception handler is running in a way that cannot be interrupted by the mechanism that collects snapshots?
Could it be that the timing of the control task correlates (by some coincidence) to a timing signal used for snapshots?
What happens if you insert some time-consuming extra code in front of the unexpected "profiling gap" (e.g., some hundreds or thousands of NOPs)?

Title: A FreeRTOS task suddenly does nothing


问:
FileNotFoundException but File present at right path
I'm new to programming, every time I try to read a file. I get FileNOtFoundException.

Where could I be going wrong?

```<code>import java.io.*;
import java.util.Scanner;

public class ReadFile
{
    public ReadFile()
    {
        readFile();
    }
    public void readFile()
    {
        String filename = "trees.txt";
        System.out.println(new File(".").getAbsolutePath()); //file is at this path.
        String name = "";
        try
        {
            FileReader inputFile = new FileReader(filename);
            Scanner parser = new Scanner(inputFile);
            while (parser.hasNextLine())
            {
                name = parser.nextLine();
                System.out.println(name);
            }
            inputFile.close();
        }
        catch (FileNotFoundException exception)
        {
            System.out.println(filename + " not found");
        }
    }
}
</code>```

Is there any other way I could read the file?

答:
Try printing the path of the file you are actually trying to open so you can be sure that the file exists in the right location

String filename = "trees.txt";
File file = new File(filename);
System.out.println(file.getAbsolutePath());
```

Also, you are closing the FileReader inside the try, and not closing the Scanner, if some error ever occurs those resources will never be closed, you need to put those close statements in a finally block, or better use try with resources

Body:
I'm new to programming, every time I try to read a file. I get FileNOtFoundException.

Where could I be going wrong?

import java.io.*;
import java.util.Scanner;

public class ReadFile
{
    public ReadFile()
    {
        readFile();
    }
    public void readFile()
    {
        String filename = "trees.txt";
        System.out.println(new File(".").getAbsolutePath()); //file is at this path.
        String name = "";
        try
        {
            FileReader inputFile = new FileReader(filename);
            Scanner parser = new Scanner(inputFile);
            while (parser.hasNextLine())
            {
                name = parser.nextLine();
                System.out.println(name);
            }
            inputFile.close();
        }
        catch (FileNotFoundException exception)
        {
            System.out.println(filename + " not found");
        }
    }
}

Is there any other way I could read the file?

Body:
Try printing the path of the file you are actually trying to open so you can be sure that the file exists in the right location

String filename = "trees.txt";
File file = new File(filename);
System.out.println(file.getAbsolutePath());

Also, you are closing the FileReader inside the try, and not closing the Scanner, if some error ever occurs those resources will never be closed, you need to put those close statements in a finally block, or better use try with resources


问:
text-transform: uppercase and chrome
I have a situation in Google Chrome where the element's innerText is getting directly changed by my css's text-transform: uppercase. The mutation event is set off by a switch to and from contenteditable on a parent div.

innerText is initially "xyz", but after the switching,  element.innerText is returning "XYZ" (still xyz in innerHTML).

let doct = document.getElementById("docTitle");

var changeDocumentTitle = function(e) {
  console.log('changeDocumentTitle: ' + document.getElementById("docTitle").innerText);
};

//  TODO: code for using mutation observer. Works in Firefox, ends up capitalizing the title in google
var observer = new MutationObserver(changeDocumentTitle);
var config = {
  attributes: true,
  childList: true,
  subtree: true
};
observer.observe(doct, config);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#docTitle {
  display: block;
  font-size: 32px;
  font-weight: 900;
  color: inherit;
  margin: 0.67em 0;
  page-break-after: avoid font-family: Arial, sans-serif;
  text-align: center;
  text-transform: uppercase;
}</code>```

xyz
```

I am seeing this in Chrome, but not in Firefox. Is this a bug in chrome? Is there a workaround? I thought of just trying to strip the html tag parts out of .innerHTML... Is that my best bet?

答: Guy Incognito answered this question in his first comment noting that I was using .innerText incorrectly, and that I should be using (and am now using) .textContent to get an element's -er- text content.</p>

Title: text-transform: uppercase and chrome

Body:
I have a situation in Google Chrome where the element's innerText is getting directly changed by my css's text-transform: uppercase. The mutation event is set off by a switch to and from contenteditable on a parent div.

innerText is initially "xyz", but after the switching,  element.innerText is returning "XYZ" (still xyz in innerHTML).

let doct = document.getElementById("docTitle");

var changeDocumentTitle = function(e) {
  console.log('changeDocumentTitle: ' + document.getElementById("docTitle").innerText);
};

//  TODO: code for using mutation observer. Works in Firefox, ends up capitalizing the title in google
var observer = new MutationObserver(changeDocumentTitle);
var config = {
  attributes: true,
  childList: true,
  subtree: true
};
observer.observe(doct, config);

#docTitle {
  display: block;
  font-size: 32px;
  font-weight: 900;
  color: inherit;
  margin: 0.67em 0;
  page-break-after: avoid font-family: Arial, sans-serif;
  text-align: center;
  text-transform: uppercase;
}

xyz

I am seeing this in Chrome, but not in Firefox. Is this a bug in chrome? Is there a workaround? I thought of just trying to strip the html tag parts out of .innerHTML... Is that my best bet?


问:
What's the difference between vector and array in DolphinDB database?
I find the following two methods when I use DolphinDB's C++ API:

```<code>Constant.isVector()
Constant.isArray()
</code>```

When I try:

```<code>ConstantSP v = conn.run("1 2 3 4 5")
v.isVector()
v.isArray()
</code>```

They are both true, so what's the difference between vector and array in DolphinDB? Are they the same type?

答: isVector returns true if a constant object is array, pair, or matrix while isArray returns true only if the object is an array.</p>

Body:
I find the following two methods when I use DolphinDB's C++ API:

Constant.isVector()
Constant.isArray()

When I try:

ConstantSP v = conn.run("1 2 3 4 5")
v.isVector()
v.isArray()

They are both true, so what's the difference between vector and array in DolphinDB? Are they the same type?


问:
Optimize DB requests in Django
I have a page view in Django set up as follows:

```<code>    blog = get_object_or_404(Blog, subdomain=extracted.subdomain)
    all_posts = Post.objects.filter(
        blog=blog, publish=True).order_by('-published_date')
    nav = all_posts.filter(is_page=True)
    posts = all_posts.filter(is_page=False)
</code>```

This causes the DB to be accessed 3 times. I'm trying to optimize this to only access the DB once. The following snippet reduces the number of calls to 2, but I'm sure there is a better way than this that I don't know about.

```<code>blog = get_object_or_404(Blog, subdomain=extracted.subdomain)
all_posts = Post.objects.filter(
    blog=blog, publish=True).order_by('-published_date')
nav = []
posts = []
for post in all_posts:
    if post.is_page:
        nav.append(post)
    else:
        posts.append(post)
</code>```

As far as I understand, prefetch_related and select_related work inversely and I'm unsure how to implement them in this context.

My models are set up as follows:

```<code>class Blog(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True)
    title = models.CharField(max_length=200)
    ...

class Post(models.Model):
    blog = models.ForeignKey(
        Blog,
        on_delete=models.CASCADE,
        related_name='post')
    title = models.CharField(max_length=200)
    ...
</code>```

Thanks in advance!

Edit:

And for some reason this executes 3 DB requests

```<code>blog = get_object_or_404(Blog.objects.prefetch_related('post_set'), subdomain=extracted.subdomain)

posts = blog.post_set.filter(publish=True).order_by('-published_date')
</code>```

答:
Some things:

Separating them into two querysets or lists is a bad idea. Use the template to inspect is_page and only render it in the nav section or posts section.

Optimizing queries like this is not where you gain the big chunks of performance. You want to get rid of queries that happen when iterating the queryset (so in the for loops) and that is what prefetch and select related are for.

That said, to get rid of the extra query:

posts = Post.objects.filter(
    blog__subdomain=extracted_subdomain, publish=True
).order_by('-published_date')
if not posts:
   raise Http404('no posts for subdomain')
```

<p>And to make sure you have access to Blog properties from Posts without querying with each iteration:</p>

<pre class="lang-py prettyprint-override"><code>posts = Post.objects.filter(
    blog__subdomain=extracted_subdomain, publish=True
).select_related('blog').order_by('-published_date')
</code>```

Title: Optimize DB requests in Django

Body:
I have a page view in Django set up as follows:

    blog = get_object_or_404(Blog, subdomain=extracted.subdomain)
    all_posts = Post.objects.filter(
        blog=blog, publish=True).order_by('-published_date')
    nav = all_posts.filter(is_page=True)
    posts = all_posts.filter(is_page=False)

This causes the DB to be accessed 3 times. I'm trying to optimize this to only access the DB once. The following snippet reduces the number of calls to 2, but I'm sure there is a better way than this that I don't know about.

blog = get_object_or_404(Blog, subdomain=extracted.subdomain)
all_posts = Post.objects.filter(
    blog=blog, publish=True).order_by('-published_date')
nav = []
posts = []
for post in all_posts:
    if post.is_page:
        nav.append(post)
    else:
        posts.append(post)

As far as I understand, prefetch_related and select_related work inversely and I'm unsure how to implement them in this context.

My models are set up as follows:

class Blog(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True)
    title = models.CharField(max_length=200)
    ...

class Post(models.Model):
    blog = models.ForeignKey(
        Blog,
        on_delete=models.CASCADE,
        related_name='post')
    title = models.CharField(max_length=200)
    ...

Thanks in advance!

Edit:

And for some reason this executes 3 DB requests

blog = get_object_or_404(Blog.objects.prefetch_related('post_set'), subdomain=extracted.subdomain)

posts = blog.post_set.filter(publish=True).order_by('-published_date')

Body:
Some things:

Separating them into two querysets or lists is a bad idea. Use the template to inspect is_page and only render it in the nav section or posts section.

Optimizing queries like this is not where you gain the big chunks of performance. You want to get rid of queries that happen when iterating the queryset (so in the for loops) and that is what prefetch and select related are for.

That said, to get rid of the extra query:

posts = Post.objects.filter(
    blog__subdomain=extracted_subdomain, publish=True
).order_by('-published_date')
if not posts:
   raise Http404('no posts for subdomain')

And to make sure you have access to Blog properties from Posts without querying with each iteration:

posts = Post.objects.filter(
    blog__subdomain=extracted_subdomain, publish=True
).select_related('blog').order_by('-published_date')


问:
unable to spawn process (Argument list too long) after pod install Firebase Analytics pod Xcode
I'm trying to install the Firebase Analytics pod into my project using Cocoapods. After successfully running pod install and then building my project I get the build error unable to spawn process (Argument list too long).

From my understanding this error has to do with the header search path arguments being too long. When I set my workspace to use the legacy build system the project builds just fine. I however, only want to use the new build system.

It seems to fail when running the shell script "Check Pods Manifest.lock" step of the build process.

```<code>PhaseScriptExecution [CP]\ Check\ Pods\ Manifest.lock /Users/xxx/Library/Developer/Xcode/DerivedData/xxx/Build/Intermediates.noindex/xxx.build/Debug\ (Staging)-iphonesimulator/OV.build/Script-05BB3CCD2FBD4842F78B0F4F.sh (in target 'xxx' from project 'xxx')
    cd /Users/xxx/Documents/Projects/ov-ios
    /bin/sh -c /Users/xxx/Library/Developer/Xcode/DerivedData/xxx/Build/Intermediates.noindex/xxx.build/Debug\\\ \\\(Staging\\\)-iphonesimulator/xxx.build/Script-05BB3CCD2FBD4842F78B0F4F.sh

error: unable to spawn process (Argument list too long) (in target 'xxx' from project 'xxx')
</code>```

It should be noted that I have multiple build configurations for my project like so. Unsure if this could be a cause of the argument list being too long.

```<code>Debug (Local)
Debug (Staging)
Debug (Production)
Release (Local)
Release (Staging)
Release (Production)
</code>```

Pod File:

```<code>platform :ios, '13.0'
use_frameworks!

def my_pods
    pod "Apollo", '0.16.0'
    pod 'AlamofireImage', '3.5.2'
    pod 'KeychainAccess', '4.1.0'
    pod 'SwiftUIRefresh', '0.0.1'
    pod 'Firebase/Analytics', '6.14.0'
end

target 'MY Project' do
  my_pods
end
</code>```

答: Open 'File -> Workspace Settings' and set Build System to Legacy Build System. This solved my issue with Firebase CocoaPods installation.</p>

Body:
I'm trying to install the Firebase Analytics pod into my project using Cocoapods. After successfully running pod install and then building my project I get the build error unable to spawn process (Argument list too long).

From my understanding this error has to do with the header search path arguments being too long. When I set my workspace to use the legacy build system the project builds just fine. I however, only want to use the new build system.

It seems to fail when running the shell script "Check Pods Manifest.lock" step of the build process.

PhaseScriptExecution [CP]\ Check\ Pods\ Manifest.lock /Users/xxx/Library/Developer/Xcode/DerivedData/xxx/Build/Intermediates.noindex/xxx.build/Debug\ (Staging)-iphonesimulator/OV.build/Script-05BB3CCD2FBD4842F78B0F4F.sh (in target 'xxx' from project 'xxx')
    cd /Users/xxx/Documents/Projects/ov-ios
    /bin/sh -c /Users/xxx/Library/Developer/Xcode/DerivedData/xxx/Build/Intermediates.noindex/xxx.build/Debug\\\ \\\(Staging\\\)-iphonesimulator/xxx.build/Script-05BB3CCD2FBD4842F78B0F4F.sh

error: unable to spawn process (Argument list too long) (in target 'xxx' from project 'xxx')

It should be noted that I have multiple build configurations for my project like so. Unsure if this could be a cause of the argument list being too long.

Debug (Local)
Debug (Staging)
Debug (Production)
Release (Local)
Release (Staging)
Release (Production)

Pod File:

platform :ios, '13.0'
use_frameworks!

def my_pods
    pod "Apollo", '0.16.0'
    pod 'AlamofireImage', '3.5.2'
    pod 'KeychainAccess', '4.1.0'
    pod 'SwiftUIRefresh', '0.0.1'
    pod 'Firebase/Analytics', '6.14.0'
end

target 'MY Project' do
  my_pods
end


问:
ActionScript 3 Alpha Tweening
I am building a custom preloader which is different than the "traditional" sliding bar that is common in RIAs. The preloader uses 100 white laser lights which are in a straight line, and collectively they indicate the progress bar. Let me describe how this works before I ask my question:

........................,,,,,,,,,:::::::::::::::::::::::::BBBBBBBB and so on...

The above string captures the spirit of the preloader indicator. In this illustration, the bigger and fatter the character, the brighter the laser light in my actual preloader:

The farthest laser to the right indicates the currently loaded percentage. This is also the brightest laser light.

All other trailing lasers get increasingly dimmer until they become completely black, as if they had burned a whole in the back of the screen.

Step "2" is where things get tricky. For some reason, the trialing lasers do not get darker, except for a few random lasers. Here is a snippet of the code controlling the brightness (or, as I used it, the alpha property) of the dot:

```<code>... more code ...

//Build the dots according the configuration and load status parameters
  private function buildDots(x:int, y:int):void {
  //Draw the dot, details not shown
    var dot:Shape = new Shape();

  //Begin the transitioning
    this.fadeOn(dot);
  }

//Fade a dot to full brightness
  private function fadeOn(dot:Shape):void {
    var fadeOn:Tween = new Tween(dot, "alpha", None.easeNone, 0, 1, this.fadeOnTime, true);

      fadeOn.addEventListener(TweenEvent.MOTION_FINISH, fadeOff);
  }

//Fade a dot to black
  private function fadeOff(e:TweenEvent):void {
    var fadeOff:Tween = new Tween(e.target.obj, "alpha", None.easeNone, 1, .2, this.fadeOffTime, true);
  }

... more code ...
</code>```

Could someone please show me where I am going wrong? These details may help:

This entire preloader is inside of a custom class.

The laser lights are created completely by code, without access to the library.

Please let me know if I can provide any more details. I will reward a good answer/feedback with as many points as I can.

Thank you for all your time!

答:
The only thing I'm seeing, offhand, is that you aren't removing an event listener from your fadeOn variable. That's the first thing I'd check out - I don't know much about tweening, but I do know that your event listener will cause the variable "fadeOn" to exist longer than it should, as it has a reference to it.

You might need to post more code, though. Perhaps someone with more tween experience can shed some more light.

Title: ActionScript 3 Alpha Tweening

Body:
I am building a custom preloader which is different than the "traditional" sliding bar that is common in RIAs. The preloader uses 100 white laser lights which are in a straight line, and collectively they indicate the progress bar. Let me describe how this works before I ask my question:

........................,,,,,,,,,:::::::::::::::::::::::::BBBBBBBB and so on...

The above string captures the spirit of the preloader indicator. In this illustration, the bigger and fatter the character, the brighter the laser light in my actual preloader:

The farthest laser to the right indicates the currently loaded percentage. This is also the brightest laser light.

All other trailing lasers get increasingly dimmer until they become completely black, as if they had burned a whole in the back of the screen.

Step "2" is where things get tricky. For some reason, the trialing lasers do not get darker, except for a few random lasers. Here is a snippet of the code controlling the brightness (or, as I used it, the alpha property) of the dot:

... more code ...

//Build the dots according the configuration and load status parameters
  private function buildDots(x:int, y:int):void {
  //Draw the dot, details not shown
    var dot:Shape = new Shape();

  //Begin the transitioning
    this.fadeOn(dot);
  }

//Fade a dot to full brightness
  private function fadeOn(dot:Shape):void {
    var fadeOn:Tween = new Tween(dot, "alpha", None.easeNone, 0, 1, this.fadeOnTime, true);

      fadeOn.addEventListener(TweenEvent.MOTION_FINISH, fadeOff);
  }

//Fade a dot to black
  private function fadeOff(e:TweenEvent):void {
    var fadeOff:Tween = new Tween(e.target.obj, "alpha", None.easeNone, 1, .2, this.fadeOffTime, true);
  }

... more code ...

Could someone please show me where I am going wrong? These details may help:

This entire preloader is inside of a custom class.

The laser lights are created completely by code, without access to the library.

Please let me know if I can provide any more details. I will reward a good answer/feedback with as many points as I can.

Thank you for all your time!


问:
Simple censor function does not work in python
I have created a function that takes a text and a word to censor in the text. It should return the text but with the censor word replaced with ****.
But it does not censor the word.

```<code>def censor(text,word):
  if word in text:
    word="*"*len(word)
  return text
</code>```

What's wrong with the code?

答:
This is a solution, without the replace() method, if you want something similar:

```<code>def censor(text,word):
    censor_block = '*'*len(word)
    text_words = text.split(' ')
    return ' '.join(
        [text_word if text_word != word else censor_block for text_word in text_words]
        )
</code>```

You need to split the text into words, then you need to iterate over those words and if you find the given word, you need to replace it with censor_block. Finally, you need to join the list of words into a text and return it. With a for loop, you need to use indexes, because a string is non-mutable. Instead of this, I used a list comprehension.

In place of text_word and censor_block, you can use functions instead, handling more complex tasks.

```<code>[f(x) if condition else g(x) for x in sequence]
[f(x) for x in sequence if condition]
[f(x) for x in sequence]
</code>```

These will work.

Hope it helps :)

Body:
I have created a function that takes a text and a word to censor in the text. It should return the text but with the censor word replaced with ****.
But it does not censor the word.

def censor(text,word):
  if word in text:
    word="*"*len(word)
  return text

What's wrong with the code?

Body:
This is a solution, without the replace() method, if you want something similar:

def censor(text,word):
    censor_block = '*'*len(word)
    text_words = text.split(' ')
    return ' '.join(
        [text_word if text_word != word else censor_block for text_word in text_words]
        )

You need to split the text into words, then you need to iterate over those words and if you find the given word, you need to replace it with censor_block. Finally, you need to join the list of words into a text and return it. With a for loop, you need to use indexes, because a string is non-mutable. Instead of this, I used a list comprehension.

In place of text_word and censor_block, you can use functions instead, handling more complex tasks.

[f(x) if condition else g(x) for x in sequence]
[f(x) for x in sequence if condition]
[f(x) for x in sequence]

These will work.

Hope it helps :)


问:
Failed to set () user defined inspected property on (UIButton)
In a simple ViewController, I added one UIButton.
I would like to use "User Defined Runtime Attributes". For now I added the default Bool attribute.

The button is an @IBOutlet:

```<code>@IBOutlet var button:UIButton!
</code>```

The link in the storyboard is done.

I have nothing else in my app.

I got this error:

```<code>2017-03-26 20:31:44.935319+0200 ISAMG[357:47616] Failed to set (keyPath) user defined inspected property on (UIButton):
[<UIButton 0x15e3a780> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key keyPath.
</code>```

I don't understand what I'm missing.

EDIT 1

Following the advices @timaktimak, I created a custom UIButton class:

```<code>@IBDesignable
class ChoiceButton: UIButton {

    @IBInspectable var keyPath: Bool! {
        didSet {
            print("didSet viewLabel, viewLabel = \(self.keyPath)")
        }
    }

    required init(coder aDecoder: NSCoder)  {
        super.init(coder: aDecoder)!
    }
}
</code>```

The error is the same:

```<code>2017-03-26 22:32:27.389126+0200 ISAMG[429:71565] Failed to set (keyPath) user defined inspected property on (ISAMG.ChoiceButton):
[<ISAMG.ChoiceButton 0x14e8f040> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key keyPath.
</code>```

答: Compare @IBInspectable(in sub class) and Key Path(identity inspector). Remove key value which is not in @IBInspectable.

Body:
In a simple ViewController, I added one UIButton.
I would like to use "User Defined Runtime Attributes". For now I added the default Bool attribute.

The button is an @IBOutlet:

@IBOutlet var button:UIButton!

The link in the storyboard is done.

I have nothing else in my app.

I got this error:

2017-03-26 20:31:44.935319+0200 ISAMG[357:47616] Failed to set (keyPath) user defined inspected property on (UIButton):
[<UIButton 0x15e3a780> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key keyPath.

I don't understand what I'm missing.

EDIT 1

Following the advices @timaktimak, I created a custom UIButton class:

@IBDesignable
class ChoiceButton: UIButton {

    @IBInspectable var keyPath: Bool! {
        didSet {
            print("didSet viewLabel, viewLabel = \(self.keyPath)")
        }
    }

    required init(coder aDecoder: NSCoder)  {
        super.init(coder: aDecoder)!
    }
}

The error is the same:

2017-03-26 22:32:27.389126+0200 ISAMG[429:71565] Failed to set (keyPath) user defined inspected property on (ISAMG.ChoiceButton):
[<ISAMG.ChoiceButton 0x14e8f040> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key keyPath.


问:
Transform Numpy Arrays to specific 2 dimensional Form
Currently I work with numpy and have to transform large data sets. Starting point are some one-dimensional arrays. These should be combined to a large 2 dimensional array. I attach a small example how it should look like.

# Returns 16 arrays with four numbers in each array (from 0 to 3)
array = [np.arange(4) for i in range(16)]

# Each of these arrays should be transformed to become a two-dimensional shape=(2,2)
array.reshape((2,2))

1. Step:
# Subsequently, the first of all of them are to be brought together:
[[0,1,0,1,0,1,0,1,0,1, ...,0,1],
[2,3,2,3,2,3,2,3,2,3, ...,2,3]]

2. Step:
# Afterwards, the arrays are to be wrapped on the basis of a length (let's say 8). The result should look like this:
[[0,1,0,1,0,1,0,1],
[2,3,2,3,2,3,2,3],
[0,1,0,1,0,1,0,1],
[2,3,2,3,2,3,2,3]]

```

This is only a miniature example. I'm actually working with an array with the length of 64 that is to be converted to an array with the shape=(8, 8). And at the end I want to create a 2 dimensional array with the dimensions 416x416.

Edit: So my current question is, how do I get to the first and second step in the example above?

Body:
Currently I work with numpy and have to transform large data sets. Starting point are some one-dimensional arrays. These should be combined to a large 2 dimensional array. I attach a small example how it should look like.

# Returns 16 arrays with four numbers in each array (from 0 to 3)
array = [np.arange(4) for i in range(16)]

# Each of these arrays should be transformed to become a two-dimensional shape=(2,2)
array.reshape((2,2))

1. Step:
# Subsequently, the first of all of them are to be brought together:
[[0,1,0,1,0,1,0,1,0,1, ...,0,1],
[2,3,2,3,2,3,2,3,2,3, ...,2,3]]

2. Step:
# Afterwards, the arrays are to be wrapped on the basis of a length (let's say 8). The result should look like this:
[[0,1,0,1,0,1,0,1],
[2,3,2,3,2,3,2,3],
[0,1,0,1,0,1,0,1],
[2,3,2,3,2,3,2,3]]

This is only a miniature example. I'm actually working with an array with the length of 64 that is to be converted to an array with the shape=(8, 8). And at the end I want to create a 2 dimensional array with the dimensions 416x416.

Edit: So my current question is, how do I get to the first and second step in the example above?

Body:
You can use np.pad, with mode='wrap':

final_width = 8
final_height = 8

a = np.arange(4).reshape(2,2)
np.pad(a, ((0, final_height-a.shape[0]),(0, final_width-a.shape[1])), mode='wrap')
a

out:
array([[0, 1, 0, 1, 0, 1, 0, 1],
       [2, 3, 2, 3, 2, 3, 2, 3],
       [0, 1, 0, 1, 0, 1, 0, 1],
       [2, 3, 2, 3, 2, 3, 2, 3],
       [0, 1, 0, 1, 0, 1, 0, 1],
       [2, 3, 2, 3, 2, 3, 2, 3],
       [0, 1, 0, 1, 0, 1, 0, 1],
       [2, 3, 2, 3, 2, 3, 2, 3]])


问:
Any HTML-element with display style "inline-block" as it's default?
SPAN elements have by default display type "inline". DIV elements have "block". But are there any container elements with "inline-block" as it's default display style?

UPDATE:
I look for "container-only" elements that are not input controls or image.

答:
img, button, textarea, input, and select are all inline-block

You can have a look at this fiddle: http://jsfiddle.net/Vgyxs/3/


问:
LinkedIn sharing SHARE_URL#HASH URL Param
I am faced with a LinkedIn sharing issue.
This issue probably reproducible from March 1st 2019.

I share some url e.g. https://www.linkedin.com/sharing/share-offsite/?url=SHARE_URL#HASH
Worked before: link in post(href) - SHARE_URL#HASH
Works now: link in post(href) - value of og:url meta tag from SHARE_URL#HASH page

So we lose request parameters in SHARE_URL and #HASH

How we can pass link for LinkedIn post into request?

答:
You need to do URL-encoding with parameters you are feeding to another URL.  So, this is what you should want...

```<code>https://www.linkedin.com/sharing/share-offsite/?url=SHARE_URL%23HASH
</code>```

Remember, URL's use things like ? and # to indicate a special argument occurring after this character.  So, for instance, example.com/share.php?title=thisistitleright?&..., how would the browser know that the first ? indicates the GET param and the second ? is a part of the title argument?  Easy: URL encoding.

In case you want to know more: Official LinkedIn Share Documentation

Body:
You need to do URL-encoding with parameters you are feeding to another URL.  So, this is what you should want...

https://www.linkedin.com/sharing/share-offsite/?url=SHARE_URL%23HASH

Remember, URL's use things like ? and # to indicate a special argument occurring after this character.  So, for instance, example.com/share.php?title=thisistitleright?&..., how would the browser know that the first ? indicates the GET param and the second ? is a part of the title argument?  Easy: URL encoding.

In case you want to know more: Official LinkedIn Share Documentation


问:
Navbar: when I fixed the navbar to the top, my components are also fixed to the top
I work on a personnal project with Angular. I want to have a top fixed navbar to write "fixed-top" in . The navbar is fixed but the probleme is that my components are also fixed to the top which is a big issue that I don't know how to resolve.
Has you can see in my screen, my component movie list is also fixed to the top so the top of the component is hide by the navbar. It is that probleme with all components/pages.

[This is a screen of my app.]1

This is my navbar template

    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

    </button>

            Search

            Movie
            Tv Show

          Movies

          Tv Shows

```
</div>
</div>
</p>

<p>This is the css</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>nav {
-webkit-box-shadow: 0px 5px 4px -1px rgba(173,161,173,1);
-moz-box-shadow: 0px 5px 4px -1px rgba(173,161,173,1);
box-shadow: 0px 5px 4px -1px rgba(173,161,173,1);
height: 60px;
width: 100%;
}</code>```

This is my app component calling the navbar

<app-header></app-header>
<router-outlet></router-outlet>```

If you have some idea please help me.

Thanks

答:
Here is the problem:

```<code><nav class=". . . fixed-top . . .">
</code>```

You have specified the fixed-top class. That implies that navbar will overlap beneath contents.

You could try removing that class. Or, if you want that specific class, try adding a padding: body { padding-top: 80px; } (80px or what you find it more confortable for web content shown).

Body:
I work on a personnal project with Angular. I want to have a top fixed navbar to write "fixed-top" in . The navbar is fixed but the probleme is that my components are also fixed to the top which is a big issue that I don't know how to resolve.
Has you can see in my screen, my component movie list is also fixed to the top so the top of the component is hide by the navbar. It is that probleme with all components/pages.

[This is a screen of my app.]1

This is my navbar template

    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

    </button>

            Search

            Movie
            Tv Show

          Movies

          Tv Shows

This is the css

nav {
-webkit-box-shadow: 0px 5px 4px -1px rgba(173,161,173,1);
-moz-box-shadow: 0px 5px 4px -1px rgba(173,161,173,1);
box-shadow: 0px 5px 4px -1px rgba(173,161,173,1);
height: 60px;
width: 100%;
}

This is my app component calling the navbar

<app-header></app-header>
<router-outlet></router-outlet>

If you have some idea please help me.

Thanks

Body:
Here is the problem:

<nav class=". . . fixed-top . . .">

You have specified the fixed-top class. That implies that navbar will overlap beneath contents.

You could try removing that class. Or, if you want that specific class, try adding a padding: body { padding-top: 80px; } (80px or what you find it more confortable for web content shown).


问:
Payara Refuses to Start: java.security.KeyStoreException: JCEKS not found
Running a Java EE 8 web Application on Payara 5.194. it has been a while since I started Payara and the application.

When I start the server: I gets messages for 6 expired certificates.

```<code> Subject: CN=Staat der Nederlanden Root CA - G2, O=Staat der Nederlanden, C=NL
 Subject: CN=Staat der Nederlanden Root CA - G2, O=Staat der Nederlanden, C=NL
 Subject: CN=AddTrust Qualified CA Root, OU=AddTrust TTP Network, O=AddTrust AB, C=SE
 Subject: CN=AddTrust Class 1 CA Root, OU=AddTrust TTP Network, O=AddTrust AB, C=SE
 Subject: CN=KEYNECTIS ROOT CA, OU=ROOT, O=KEYNECTIS, C=FR
 Subject: CN=Entrust.net Certification Authority (2048), OU=(c) 1999 Entrust.net Limited, OU=www.entrust.net/CPS_2048 incorp. by ref. (limits liab.), O=Entrust.net
</code>```

After that I get this exception

```<code>[#|2020-05-30T10:47:11.755+0000|INFO|Payara 5.194|javax.enterprise.system.core|_ThreadID=22;_ThreadName=RunLevelControllerThread-1590835619275;_TimeMillis=1590835631755;_LevelValue=800;_MessageID=NCLS-CORE-00015;|
  Shutdown requested
MultiException stack 1 of 2
java.lang.RuntimeException: java.lang.RuntimeException: java.security.KeyStoreException: JCEKS not found
        at org.glassfish.security.services.impl.JCEKSPasswordAliasStore.containsKey(JCEKSPasswordAliasStore.java:169)
        at fish.payara.nucleus.microprofile.config.source.PasswordAliasConfigSource.getValue(PasswordAliasConfigSource.java:84)
        at fish.payara.nucleus.microprofile.config.spi.PayaraConfig.getValue(PayaraConfig.java:166)
        at fish.payara.nucleus.microprofile.config.spi.PayaraConfig.getOptionalValue(PayaraConfig.java:88)
        at fish.payara.microprofile.healthcheck.HealthCheckService.postConstruct(HealthCheckService.java:120)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.glassfish.hk2.utilities.reflection.ReflectionHelper.invoke(ReflectionHelper.java:1268)
        at org.jvnet.hk2.internal.ClazzCreator.postConstructMe(ClazzCreator.java:309)
        at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:351)
        at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:463)
        at org.glassfish.hk2.runlevel.internal.AsyncRunLevelContext.findOrCreate(AsyncRunLevelContext.java:281)
        at org.glassfish.hk2.runlevel.RunLevelContext.findOrCreate(RunLevelContext.java:65)
        at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2102)
        at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:93)
        at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:67)
        at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.oneJob(CurrentTaskFuture.java:1213)
        at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.run(CurrentTaskFuture.java:1144)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.RuntimeException: java.security.KeyStoreException: JCEKS not found
        at org.glassfish.security.services.impl.JCEKSPasswordAliasStore.pa(JCEKSPasswordAliasStore.java:103)
        at org.glassfish.security.services.impl.JCEKSPasswordAliasStore.containsKey(JCEKSPasswordAliasStore.java:167)
        ... 22 more
Caused by: java.security.KeyStoreException: JCEKS not found
        at java.security.KeyStore.getInstance(KeyStore.java:851)
        at com.sun.enterprise.security.store.PasswordAdapter.loadKeyStore(PasswordAdapter.java:131)
        at com.sun.enterprise.security.store.PasswordAdapter.<init>(PasswordAdapter.java:110)
        at org.glassfish.security.services.impl.JCEKSPasswordAliasStore.pa(JCEKSPasswordAliasStore.java:101)
        ... 23 more
Caused by: java.security.NoSuchAlgorithmException: JCEKS KeyStore not available
        at sun.security.jca.GetInstance.getInstance(GetInstance.java:159)
        at java.security.Security.getImpl(Security.java:697)
        at java.security.KeyStore.getInstance(KeyStore.java:848)
</code>```

No Code has been changed, nothing. Payara just won't start.

答: So I found the issue. I did upgrade to JDK 9 and so my JAVA_HOME and path env variables were pointing to the JDK 9. So I changed them to point back to JDK 8 for the time being. and everything works.

Body:
Running a Java EE 8 web Application on Payara 5.194. it has been a while since I started Payara and the application.

When I start the server: I gets messages for 6 expired certificates.

 Subject: CN=Staat der Nederlanden Root CA - G2, O=Staat der Nederlanden, C=NL
 Subject: CN=Staat der Nederlanden Root CA - G2, O=Staat der Nederlanden, C=NL
 Subject: CN=AddTrust Qualified CA Root, OU=AddTrust TTP Network, O=AddTrust AB, C=SE
 Subject: CN=AddTrust Class 1 CA Root, OU=AddTrust TTP Network, O=AddTrust AB, C=SE
 Subject: CN=KEYNECTIS ROOT CA, OU=ROOT, O=KEYNECTIS, C=FR
 Subject: CN=Entrust.net Certification Authority (2048), OU=(c) 1999 Entrust.net Limited, OU=www.entrust.net/CPS_2048 incorp. by ref. (limits liab.), O=Entrust.net

After that I get this exception

[#|2020-05-30T10:47:11.755+0000|INFO|Payara 5.194|javax.enterprise.system.core|_ThreadID=22;_ThreadName=RunLevelControllerThread-1590835619275;_TimeMillis=1590835631755;_LevelValue=800;_MessageID=NCLS-CORE-00015;|
  Shutdown requested
MultiException stack 1 of 2
java.lang.RuntimeException: java.lang.RuntimeException: java.security.KeyStoreException: JCEKS not found
        at org.glassfish.security.services.impl.JCEKSPasswordAliasStore.containsKey(JCEKSPasswordAliasStore.java:169)
        at fish.payara.nucleus.microprofile.config.source.PasswordAliasConfigSource.getValue(PasswordAliasConfigSource.java:84)
        at fish.payara.nucleus.microprofile.config.spi.PayaraConfig.getValue(PayaraConfig.java:166)
        at fish.payara.nucleus.microprofile.config.spi.PayaraConfig.getOptionalValue(PayaraConfig.java:88)
        at fish.payara.microprofile.healthcheck.HealthCheckService.postConstruct(HealthCheckService.java:120)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.glassfish.hk2.utilities.reflection.ReflectionHelper.invoke(ReflectionHelper.java:1268)
        at org.jvnet.hk2.internal.ClazzCreator.postConstructMe(ClazzCreator.java:309)
        at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:351)
        at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:463)
        at org.glassfish.hk2.runlevel.internal.AsyncRunLevelContext.findOrCreate(AsyncRunLevelContext.java:281)
        at org.glassfish.hk2.runlevel.RunLevelContext.findOrCreate(RunLevelContext.java:65)
        at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2102)
        at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:93)
        at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:67)
        at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.oneJob(CurrentTaskFuture.java:1213)
        at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.run(CurrentTaskFuture.java:1144)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.RuntimeException: java.security.KeyStoreException: JCEKS not found
        at org.glassfish.security.services.impl.JCEKSPasswordAliasStore.pa(JCEKSPasswordAliasStore.java:103)
        at org.glassfish.security.services.impl.JCEKSPasswordAliasStore.containsKey(JCEKSPasswordAliasStore.java:167)
        ... 22 more
Caused by: java.security.KeyStoreException: JCEKS not found
        at java.security.KeyStore.getInstance(KeyStore.java:851)
        at com.sun.enterprise.security.store.PasswordAdapter.loadKeyStore(PasswordAdapter.java:131)
        at com.sun.enterprise.security.store.PasswordAdapter.<init>(PasswordAdapter.java:110)
        at org.glassfish.security.services.impl.JCEKSPasswordAliasStore.pa(JCEKSPasswordAliasStore.java:101)
        ... 23 more
Caused by: java.security.NoSuchAlgorithmException: JCEKS KeyStore not available
        at sun.security.jca.GetInstance.getInstance(GetInstance.java:159)
        at java.security.Security.getImpl(Security.java:697)
        at java.security.KeyStore.getInstance(KeyStore.java:848)

No Code has been changed, nothing. Payara just won't start.


问:
Should I end an expression with ; inside a loop?
I just started learning Rust and I often have some questions that I can't find any answer. I don't really know how and where to post my question, so I'll try SO.

I started to read the Rust documentation on the website and I did the Guessing game example.

I realized that the match cmp expression inside the loop could be turned into a statement and everything still works. So I wonder why and what version should really be preferred?

use rand::Rng;
use std::cmp::Ordering;
use std::io;

fn main() {
    println!("Guess the number!");

    let secret_number = rand::thread_rng().gen_range(1, 101);

    loop {
        println!("Please input your guess.");

        let mut guess = String::new();

        io::stdin()
            .read_line(&mut guess)
            .expect("Failed to read line");

        let guess: u32 = match guess.trim().parse() {
            Ok(num) => num,
            Err(_) => continue,
        };

        println!("You guessed: {}", guess);

        match guess.cmp(&secret_number) {
            Ordering::Less => println!("Too small!"),
            Ordering::Greater => println!("Too big!"),
            Ordering::Equal => {
                println!("You win!");
                break;
            }
        } // <=== here should it be ended as statement (;) or not?
    }
}
```

答:
match, if, loop, and other expressions that have {} blocks are treated specially by the Rust compiler. When these expressions occur as expression statements, that is, not as part of a larger expression, and the type of the expression that has the block is (), you do not have to put ; after it to separate it from a following statement.

This is not the case for expression statements without blocks, which always must be separated from the following statement (if one exists) by ;, even if their type is ().

Because this rule exists, it is usual in Rust not to put ; after match, if, unsafe, etc. when they are used only for side effects, or after for and while loops (which are always used only for side effects, since they always return ()).

That said, both rustfmt and Clippy seem to be fine with the extra ;, so if you prefer it there for aesthetic reasons, you're unlikely to offend anyone by using it.


问:
Angular Project Structure with separate package.json files
I saw this Project Structure in Angular with Node.js as backend, where the Angular node modules and package.json were in the "app" folder, while the node.js' node modules and package.json were in the root of the project. (watch picture)

How do i get the requested outcome?

答:
The node_modules folders should be seperated between the Angular front end and the Node backend.
E.g A standard project structure for a full stack angaulr/node app should be something like.

```<code>.
├── ProjectName
|   ├── angular-app-name
|   └── server
</code>```

For a Project structure like this run

mkdir ProjectName //Create project root directory

mkdir server //Create node server folder

cd server

npm init //Initialize npm

touch server.js //Create server js file for node backenk

cd .. //Back to Project root

ng new {app-name} //Create angular project

From what I can tell you want something like this, with your angular app sitting within the node backend.

```<code>.
├── ProjectName
|   ├── angular-app-name
|   └── server.js
|   └── node_modules
</code>```

mkdir ProjectName //Create project root directory

npm init //Initialize npm

touch server.js //Create server js file for node backenk

ng new {app-name} //Create angular project

I personally think the more standard project-> backend/frontend structure makes more sense, but both will work fine.

Body:
The node_modules folders should be seperated between the Angular front end and the Node backend.
E.g A standard project structure for a full stack angaulr/node app should be something like.

.
├── ProjectName
|   ├── angular-app-name
|   └── server

For a Project structure like this run

mkdir ProjectName //Create project root directory

mkdir server //Create node server folder

cd server

npm init //Initialize npm

touch server.js //Create server js file for node backenk

cd .. //Back to Project root

ng new {app-name} //Create angular project

From what I can tell you want something like this, with your angular app sitting within the node backend.

.
├── ProjectName
|   ├── angular-app-name
|   └── server.js
|   └── node_modules

mkdir ProjectName //Create project root directory

npm init //Initialize npm

touch server.js //Create server js file for node backenk

ng new {app-name} //Create angular project

I personally think the more standard project-> backend/frontend structure makes more sense, but both will work fine.


问:
IP address changed on Google Compute Engine
The public IP address on my Debian server hosted on Google Compute Engine.  Have not touched configuration for it in the console in a while.  The new IP address is reflected in the Google Compute Engine Console.  How can I find out why this happened and prevent it from happening again.  I am not paying $100/mo for support, so they won't let me open a support ticket unless it is billing related.  I have never had this problem before with any of the other Google Compute Engines.</p>

答: You should reserve a global static ip : https://cloud.google.com/compute/docs/ip-addresses/reserve-static-external-ip-address


问:
Where does Netbeans 7 store FTP passwords
I want to copy all my netbeans ftp details over to my friend's PC. I found th most of what i needed here:
C:\Users\Jason Fonseca\.netbeans\7.0\config\Preferences\org\netbeans\modules\php\project\RemoteConnections

But I can't seem to find any passwords associated with that file.

Any ideas?

Thanks.

答:
Try:

```<code>~\.netbeans\7.0\config\Preferences\org\netbeans\modules\keyring\win32.properties
</code>```

It will most likely be encrypted though.

Edit:

Looking at http://bits.nbextras.org/netbeans/trunk/javadoc/org-netbeans-modules-keyring/org/netbeans/api/keyring/package-summary.html

It seems that the encryption is tied to your user account, so you wont be able to move that file to another computer.

Body:
Try:

~\.netbeans\7.0\config\Preferences\org\netbeans\modules\keyring\win32.properties

It will most likely be encrypted though.

Edit:

Looking at http://bits.nbextras.org/netbeans/trunk/javadoc/org-netbeans-modules-keyring/org/netbeans/api/keyring/package-summary.html

It seems that the encryption is tied to your user account, so you wont be able to move that file to another computer.


问:
How can I upload a picture using Glide from an external folder
I am developing an app for my auntie: the app displays recipes in a card view inside a Recycler view, the data comes from an SQLite DB.

The images at the moment are just static inside @drawable/... I have read the "@drawable" folder is compiled into the apk and not accessible after the fact. Consequently the need to store the images externally.

The DB stores the filenames.

The card displays basic info, when a card is clicked it opens another activity that displays full information.

Everything works perfectly EXCEPT

I obviously want her to be able to upload pictures and add info, the pictures will be stored in: "/sdcard/Pictures/Recipes/"

In am using Glide as recommended, however Glide reports the following error:

```<code>class com.bumptech.glide.load.engine.GlideException: Failed to load resource
    There were 3 causes:
    java.io.FileNotFoundException(/sdcard/Pictures/Recipes/carrot_cake.jpg: open failed: EFAULT (Bad address))
    java.io.FileNotFoundException(open failed: EFAULT (Bad address))
    java.io.FileNotFoundException(open failed: EFAULT (Bad address))...
</code>```

If I use the following code:

```<code>    String image = "/sdcard/Pictures/Recipes/carrot_cake.jpg"; // hard coded for example
    File file = new File( image );
    if( file.exists() && file.canRead() )
    {
        Log.d( TAG, "File exists" );
        Glide.with( context ).load( image ).into( foodImage ); // foodImage = ImageView
    }
</code>```

The log displays the "File Exists", however, Glide won't load and reports the aforementioned error.

答:
Try this</p>

```<code>File directory = Environment.getExternalStorageDirectory();

//Get the text file
File file = new File(directory, "Pictures/Recipes/carrot_cake.jpg");

...
</code>```

Body:
I am developing an app for my auntie: the app displays recipes in a card view inside a Recycler view, the data comes from an SQLite DB.

The images at the moment are just static inside @drawable/... I have read the "@drawable" folder is compiled into the apk and not accessible after the fact. Consequently the need to store the images externally.

The DB stores the filenames.

The card displays basic info, when a card is clicked it opens another activity that displays full information.

Everything works perfectly EXCEPT

I obviously want her to be able to upload pictures and add info, the pictures will be stored in: "/sdcard/Pictures/Recipes/"

In am using Glide as recommended, however Glide reports the following error:

class com.bumptech.glide.load.engine.GlideException: Failed to load resource
    There were 3 causes:
    java.io.FileNotFoundException(/sdcard/Pictures/Recipes/carrot_cake.jpg: open failed: EFAULT (Bad address))
    java.io.FileNotFoundException(open failed: EFAULT (Bad address))
    java.io.FileNotFoundException(open failed: EFAULT (Bad address))...

If I use the following code:

    String image = "/sdcard/Pictures/Recipes/carrot_cake.jpg"; // hard coded for example
    File file = new File( image );
    if( file.exists() && file.canRead() )
    {
        Log.d( TAG, "File exists" );
        Glide.with( context ).load( image ).into( foodImage ); // foodImage = ImageView
    }

The log displays the "File Exists", however, Glide won't load and reports the aforementioned error.

Body:
Try this

File directory = Environment.getExternalStorageDirectory();

//Get the text file
File file = new File(directory, "Pictures/Recipes/carrot_cake.jpg");

...


问:
Access Property of a Nested Record
I'm using React-Admin 3.5.0 with api-platform/admin 2.1.1.

I have a custom list for one of my resources.

The resource has a title and an author. The author has several properties, one of which is username.

Following the documentation, I tried to display the username of the author in my list like this:

```<code>export const MyList = (props) =>
    <List {...props}>
        <Datagrid>
            <TextField source="title" />
            <TextField source="author.username" />
        </Datagrid>
    </List>
</code>```

This does not work. The field for author.username is empty.

I investigated a bit and found that the record only contains the ID of the author:

```<code>record:
    ...
    title: "abcde"
    author: "/users/1"
</code>```

The response from the server however does contain the username property:

```<code>0: {
    ...,
    "title": "abcde",
    "author": {
        "@id": "/users/1",
        "username": "Test"
    }
},
...
</code>```

Is there any nice way to make it work?

答:
I've created the PR to add support for arrays of embeddeds: https://github.com/api-platform/admin/pull/302.

It will be in the next version (a patch one).

Title: Access Property of a Nested Record

Body:
I'm using React-Admin 3.5.0 with api-platform/admin 2.1.1.

I have a custom list for one of my resources.

The resource has a title and an author. The author has several properties, one of which is username.

Following the documentation, I tried to display the username of the author in my list like this:

export const MyList = (props) =>
    <List {...props}>
        <Datagrid>
            <TextField source="title" />
            <TextField source="author.username" />
        </Datagrid>
    </List>

This does not work. The field for author.username is empty.

I investigated a bit and found that the record only contains the ID of the author:

record:
    ...
    title: "abcde"
    author: "/users/1"

The response from the server however does contain the username property:

0: {
    ...,
    "title": "abcde",
    "author": {
        "@id": "/users/1",
        "username": "Test"
    }
},
...

Is there any nice way to make it work?


问:
Unable to auto post on a Facebook Page using its PHP SDK
I have read at many places that Facebook made some changes around 2018 that prevent people from posting as a page with PHP. I researched for a while to see if I can still auto post on a Facebook page if I am its Admin.

My sources: Facebook Graph API v3.1 Access Token Permission Limitations For Developers and https://adamboother.com/blog/automatically-posting-to-a-facebook-page-using-the-facebook-sdk-v5-for-php-facebook-api/

I am the only one who will use this auto-post app and I am the admin of the page on which I will be posting these links.

Here is the code I tried:

```<code>$fb = new Facebook\Facebook([
    'app_id' => 'app_id',
    'app_secret' => 'app_secret',
    'default_graph_version' => 'v2.2',
]);

$pageAccessToken = "page_access_token";

$linkData = [
    'link' => 'some_link',
    'message' => 'some_message'
];
try {
    $response = $fb->post('/me/feed', $linkData, $pageAccessToken);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
    echo 'Graph returned an error: '.$e->getMessage();
    exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
    echo 'Facebook SDK returned an error: '.$e->getMessage();
    exit;
}
$graphNode = $response->getGraphNode();
</code>```

Running the above code, I get the following error:

Graph returned an error: (#200) If posting to a group, requires app
  being installed in the group, and \ either publish_to_groups
  permission with user token, or both manage_pages \ and publish_pages
  permission with page token; If posting to a page, \ requires both
  manage_pages and publish_pages as an admin with \ sufficient
  administrative permission.

Now, I am an admin of the page. I also have selected manage_pages and publish_pages in permissions. So, why am I getting this error?

答:
On May 5, 2020, Facebook released six new Page permissions to replace the manage_pages and publish_pages permissions. Taking advantage of curl, you can use php to  create and update a post or comment, reply to a post or comment, and delete a post or comment, on your Facebook Page Feed as the Page.

Send a POST request to the /{page-id}/feed endpoint:

curl -i -X POST "https://graph.facebook.com/{page-id}/feed
?message=Hello Fans!
&access_token={page-access-token}"

On success, your app receives the following response:

{
"id": "{page-post-id}"
}

source: https://developers.facebook.com/docs/pages/publishing/

Body:
I have read at many places that Facebook made some changes around 2018 that prevent people from posting as a page with PHP. I researched for a while to see if I can still auto post on a Facebook page if I am its Admin.

My sources: Facebook Graph API v3.1 Access Token Permission Limitations For Developers and https://adamboother.com/blog/automatically-posting-to-a-facebook-page-using-the-facebook-sdk-v5-for-php-facebook-api/

I am the only one who will use this auto-post app and I am the admin of the page on which I will be posting these links.

Here is the code I tried:

$fb = new Facebook\Facebook([
    'app_id' => 'app_id',
    'app_secret' => 'app_secret',
    'default_graph_version' => 'v2.2',
]);

$pageAccessToken = "page_access_token";

$linkData = [
    'link' => 'some_link',
    'message' => 'some_message'
];
try {
    $response = $fb->post('/me/feed', $linkData, $pageAccessToken);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
    echo 'Graph returned an error: '.$e->getMessage();
    exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
    echo 'Facebook SDK returned an error: '.$e->getMessage();
    exit;
}
$graphNode = $response->getGraphNode();

Running the above code, I get the following error:

Graph returned an error: (#200) If posting to a group, requires app
  being installed in the group, and \ either publish_to_groups
  permission with user token, or both manage_pages \ and publish_pages
  permission with page token; If posting to a page, \ requires both
  manage_pages and publish_pages as an admin with \ sufficient
  administrative permission.

Now, I am an admin of the page. I also have selected manage_pages and publish_pages in permissions. So, why am I getting this error?