问:
HPUX shell script: split string, put them in an array then loop them
I have a command output as shown below some examples.

```<code>E.g.1    {quey_result} -------- .2 .5 .74 (3 rows)
E.g.2    {quey_result} -------- .1 (1 row)
E.g.3    {quey_result} -------- .234 .54 (2 rows)
E.g.4    {quey_result} -------- (0 row)
</code>```

I want to capture each of those decimal numbers (like .2, .5, .74) and use them for some other commands.

Please help me how to trim the beginning and end; then store each decimal values in variable and process, then loop.

Br,
--Shafeer

答:
First, I'm assuming that a row looks like:

```<code>{query_result} -------- .2 .5 .74 (3 rows)
</code>```

And doesn't have "E.g.1" <s>or "(3 rows)"</s>.

```<code>#!/bin/sh
command | while read -r line
do
    line=$(echo "$line" | sed 's/.*--- \([^(]*\) (.*/\1/'
    set -- $line
    for arg
    do
        do_something_with "$arg"
    done
done
</code>```

<s>This depends on there being no spaces other than the ones you've shown. You can modify the cut command or use awk to split the line up if needed.</s>

The first two lines inside the while loop could be combined into:

```<code>set -- $(echo "$line" | sed 's/.*--- \([^(]*\) (.*/\1/')
</code>```

Note that either way, if your shell doesn't support $() then you'll need to use backticks:

```<code>`echo "$line" | sed 's/.*--- \([^(]*\) (.*/\1/'`
</code>```

If you have ksh or Bash, there are other ways to do the whole process.

Edit: Changed cut to sed

Body:
I have a command output as shown below some examples.

E.g.1    {quey_result} -------- .2 .5 .74 (3 rows)
E.g.2    {quey_result} -------- .1 (1 row)
E.g.3    {quey_result} -------- .234 .54 (2 rows)
E.g.4    {quey_result} -------- (0 row)

I want to capture each of those decimal numbers (like .2, .5, .74) and use them for some other commands.

Please help me how to trim the beginning and end; then store each decimal values in variable and process, then loop.

Br,
--Shafeer

Body:
First, I'm assuming that a row looks like:

{query_result} -------- .2 .5 .74 (3 rows)

And doesn't have "E.g.1" <s>or "(3 rows)"</s>.

#!/bin/sh
command | while read -r line
do
    line=$(echo "$line" | sed 's/.*--- \([^(]*\) (.*/\1/'
    set -- $line
    for arg
    do
        do_something_with "$arg"
    done
done

<s>This depends on there being no spaces other than the ones you've shown. You can modify the cut command or use awk to split the line up if needed.</s>

The first two lines inside the while loop could be combined into:

set -- $(echo "$line" | sed 's/.*--- \([^(]*\) (.*/\1/')

Note that either way, if your shell doesn't support $() then you'll need to use backticks:

`echo "$line" | sed 's/.*--- \([^(]*\) (.*/\1/'`

If you have ksh or Bash, there are other ways to do the whole process.

Edit: Changed cut to sed


来源: stackexchange

问:
How to update component state on redux state change?
Since I have a component with forms, I need the forms to be connected to the component state. The initial data comes from Redux so try to initialize and update the component by setting the state with the props:

```<code>componentWillMount = () => {
  this.setState({
    language: this.props.language || 'en'
  })
}
</code>```

language is a connected prop and I checked that it is updated in the store.

```<code>const mapStateToProps = state => ({
  language: state.language
})
</code>```

I also tried to use componentWillReceiveProps and componentWillUpdate but it doesn't work. I get the initial state, and even though the store and the connected props change, the component's state doesn't update.

```<code>{this.props.language} // updates
{this.state.language} // doesn't change
</code>```

What is the correct way to manage forms from Redux data?

The render part:

```<code>render () {
  const {classes, theme, web} = this.props

  const language = (
    <CardContent>
      <Typography type="headline">
        Language
      </Typography>
      <Divider/>
      <form className={classes.container} autoComplete="off">
        <FormControl fullWidth margin="normal">
          <InputLabel htmlFor="language">Select Block</InputLabel>
          <Select
            value={this.state.language} // <==================== language
            onChange={this.handleLanguaheChange}
            input={<Input id="language"/>}
          >
            <MenuItem value={'en'}>English</MenuItem>
            <MenuItem value={'he'}>עברית</MenuItem>
          </Select>
        </FormControl>
      </form>
    </CardContent>
  )
  ...

  return (
      <Grid
        container
        spacing={theme.spacing.unit * 3}
        justify={'space-between'}
        className={classes.gridWrap}
      >
        <Grid item xs={6}>
          <Card className={classes.card}>
            {language}
          </Card>
...
</code>```

答:
componentWillReceiveProps will be called only when your component re-rendered.

Initially when component first time mounting, it not going to triggered.

You can not call setState inside componentwillupdate.

In order to initialise the initial state of component from redux store,you should use constructor.

```<code>    constructor(props) {

    super(props);

    this.state = {
        language: this.props.language || 'en'
     }
   }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Since I have a component with forms, I need the forms to be connected to the component state. The initial data comes from Redux so try to initialize and update the component by setting the state with the props:

componentWillMount = () => {
  this.setState({
    language: this.props.language || 'en'
  })
}

language is a connected prop and I checked that it is updated in the store.

const mapStateToProps = state => ({
  language: state.language
})

I also tried to use componentWillReceiveProps and componentWillUpdate but it doesn't work. I get the initial state, and even though the store and the connected props change, the component's state doesn't update.

{this.props.language} // updates
{this.state.language} // doesn't change

What is the correct way to manage forms from Redux data?

The render part:

render () {
  const {classes, theme, web} = this.props

  const language = (
    <CardContent>
      <Typography type="headline">
        Language
      </Typography>
      <Divider/>
      <form className={classes.container} autoComplete="off">
        <FormControl fullWidth margin="normal">
          <InputLabel htmlFor="language">Select Block</InputLabel>
          <Select
            value={this.state.language} // <==================== language
            onChange={this.handleLanguaheChange}
            input={<Input id="language"/>}
          >
            <MenuItem value={'en'}>English</MenuItem>
            <MenuItem value={'he'}>עברית</MenuItem>
          </Select>
        </FormControl>
      </form>
    </CardContent>
  )
  ...

  return (
      <Grid
        container
        spacing={theme.spacing.unit * 3}
        justify={'space-between'}
        className={classes.gridWrap}
      >
        <Grid item xs={6}>
          <Card className={classes.card}>
            {language}
          </Card>
...

Body:
componentWillReceiveProps will be called only when your component re-rendered.

Initially when component first time mounting, it not going to triggered.

You can not call setState inside componentwillupdate.

In order to initialise the initial state of component from redux store,you should use constructor.

    constructor(props) {

    super(props);

    this.state = {
        language: this.props.language || 'en'
     }
   }


问:
REST API - execute multiple actions
Currently trying to work out how to use REST API to execute an action.
I added the ReverseInvoice action from Bills screen on my endpoints. And seems execute fine. Unfortunately, executing an action does not return a result e.g. 204 No Content. I'd wish to extract the RefNbr of the Debit Adj. raised.

Second problem is how do you stack actions or call series of actions ? The raised Debit Adj is not Released. So it seems ReverseInvoice & Release need to be executed at the same time. Plus, I also need them to be allocated against each other automatically.

I've got a feeling the REST API is not the way to go with this one.

Cheers and thanks for responses.

答: Unfortunately, you're correct on both points: Acumatica's Contract-based API (both SOAP and REST flavors) doesn't allow you to get the entity that is a result of an action (you can only get the status of action invocation), and if you want to chain a sequence of action you'll have to do that manually from the client (call one action, check for the status, call the second one, check, raise, rinse, repeat). Or you can write a customization with a custom action that call two actions in sequence, and call that from the API.</p>

Title: REST API - execute multiple actions


问:
Enable all GPIO pins on BeagleBone, including the eMMC pins
I'm running Debian Jessie IOT image on a BeagleBone Green.
I like to use the maximum of GPIOs, which is according to the documentation should give me 65 GPIOs.
GPIOs on BeagleBone Green

All work except the pins that are shared with the eMMC:
P8_3-6, P8_20-25

So this works:

config-pin -a P8_7 in+

This does not work:

config-pin -a P8_22 in+

```<code>bash: /sys/devices/platform/ocp/ocp*P8_22_pinmux/state: No such file or directory
Cannot write pinmux file: /sys/devices/platform/ocp/ocp*P8_22_pinmux/state
</code>```

Some information.....

```<code>root@beaglebone:~# cat /sys/devices/platform/bone_capemgr/slots
0: PF----  -1
1: PF----  -1
2: PF----  -1
3: PF----  -1
4: P-O-L-   0 Override Board Name,00A0,Override Manuf,cape-universala
</code>```

cape-universala should export all pins
in dmesg is....

```<code> [    4.002843] pinctrl-single 44e10800.pinmux: pin 44e10814.0 already requested by 481d8000.mmc; cannot claim for ocp:P8_22_pinmux
 [    4.014528] pinctrl-single 44e10800.pinmux: pin-5 (ocp:P8_22_pinmux) status -22
 [    4.021901] pinctrl-single 44e10800.pinmux: could not request pin 5 (44e10814.0) from group pinmux_P8_22_default_pin  on device pinctrl-single
 [    4.034756] bone-pinmux-helper ocp:P8_22_pinmux: Error applying setting, reverse things back
 [    4.089416] pinctrl-single 44e10800.pinmux: pin 44e10814.0 already requested by 481d8000.mmc; cannot claim for ocp:P8_22_pinmux
 [    4.101069] pinctrl-single 44e10800.pinmux: pin-5 (ocp:P8_22_pinmux) status -22
</code>```

I can't seem to disable the eMMC, this is /boot/uEnv.txt

```<code>  cmdline=coherent_pool=1M net.ifnames=0 quiet cape_enable=bone_capemgr.enable_partno=cape-universala cape_disable=bone_capemgr.disable_partno=BB-BONE-EMMC-2G
</code>```

I am booting the BeagleBone from an sd-card, so the eMMC don't have to be used.

what's wrong?

答:
I turns out I was looking to hard...
This is how to use all of the available GPIO pins:

```<code>  root@beaglebone:~# more /boot/uEnv.txt | grep -v '#'
  uname_r=4.4.91-ti-r133
  dtb=am335x-boneblack-overlay.dtb
  cmdline=coherent_pool=1M net.ifnames=0 quiet
</code>```

that's it!

Body:
I'm running Debian Jessie IOT image on a BeagleBone Green.
I like to use the maximum of GPIOs, which is according to the documentation should give me 65 GPIOs.
GPIOs on BeagleBone Green

All work except the pins that are shared with the eMMC:
P8_3-6, P8_20-25

So this works:

config-pin -a P8_7 in+

This does not work:

config-pin -a P8_22 in+

bash: /sys/devices/platform/ocp/ocp*P8_22_pinmux/state: No such file or directory
Cannot write pinmux file: /sys/devices/platform/ocp/ocp*P8_22_pinmux/state

Some information.....

root@beaglebone:~# cat /sys/devices/platform/bone_capemgr/slots
0: PF----  -1
1: PF----  -1
2: PF----  -1
3: PF----  -1
4: P-O-L-   0 Override Board Name,00A0,Override Manuf,cape-universala

cape-universala should export all pins
in dmesg is....

 [    4.002843] pinctrl-single 44e10800.pinmux: pin 44e10814.0 already requested by 481d8000.mmc; cannot claim for ocp:P8_22_pinmux
 [    4.014528] pinctrl-single 44e10800.pinmux: pin-5 (ocp:P8_22_pinmux) status -22
 [    4.021901] pinctrl-single 44e10800.pinmux: could not request pin 5 (44e10814.0) from group pinmux_P8_22_default_pin  on device pinctrl-single
 [    4.034756] bone-pinmux-helper ocp:P8_22_pinmux: Error applying setting, reverse things back
 [    4.089416] pinctrl-single 44e10800.pinmux: pin 44e10814.0 already requested by 481d8000.mmc; cannot claim for ocp:P8_22_pinmux
 [    4.101069] pinctrl-single 44e10800.pinmux: pin-5 (ocp:P8_22_pinmux) status -22

I can't seem to disable the eMMC, this is /boot/uEnv.txt

  cmdline=coherent_pool=1M net.ifnames=0 quiet cape_enable=bone_capemgr.enable_partno=cape-universala cape_disable=bone_capemgr.disable_partno=BB-BONE-EMMC-2G

I am booting the BeagleBone from an sd-card, so the eMMC don't have to be used.

what's wrong?

Body:
I turns out I was looking to hard...
This is how to use all of the available GPIO pins:

  root@beaglebone:~# more /boot/uEnv.txt | grep -v '#'
  uname_r=4.4.91-ti-r133
  dtb=am335x-boneblack-overlay.dtb
  cmdline=coherent_pool=1M net.ifnames=0 quiet

that's it!


问:
Swift 4 Timer Crashes with NSException
I've been searching for a way to use a Timer in Swift 4 and looked at this article. I test out my code in xcode and when the the timer first ticks (in this case after 10 seconds) the app crashes and I get an error, although the build succeeded.

```<code>2017-11-20 19:54:42.781502-0700 Rock Prodigy[3022:554505] -[_SwiftValue   tick]: unrecognized selector sent to instance 0x608000051520
2017-11-20 19:54:42.791278-0700 Rock Prodigy[3022:554505] ***  Terminating app due to uncaught exception 'NSInvalidArgumentException',   reason: '-[_SwiftValue tick]: unrecognized selector sent to instance  0x608000051520'
*** First throw call stack:
(
0   CoreFoundation                      0x000000010360d1ab __exceptionPreprocess + 171
1   libobjc.A.dylib                     0x0000000102ca2f41 objc_exception_throw + 48
2   CoreFoundation                      0x000000010368da34 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
3   CoreFoundation                      0x00000001035900a8 ___forwarding___ + 1432
4   CoreFoundation                      0x000000010358fa88 _CF_forwarding_prep_0 + 120
5   Foundation                          0x000000010270e1ee __NSFireTimer + 83
6   CoreFoundation                      0x000000010359d2a4 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 20
7   CoreFoundation                      0x000000010359cf62 __CFRunLoopDoTimer + 1026
8   CoreFoundation                      0x000000010359cb1a __CFRunLoopDoTimers + 266
9   CoreFoundation                      0x0000000103594534 __CFRunLoopRun + 2308
10  CoreFoundation                      0x00000001035939b9 CFRunLoopRunSpecific + 409
11  GraphicsServices                    0x00000001090e29c6 GSEventRunModal + 62
12  UIKit                               0x0000000103a885e8 UIApplicationMain + 159
13  Rock Prodigy                        0x000000010238b637 main + 55
14  libdyld.dylib                       0x0000000107aa1d81 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
</code>```

Here is my swift 4 code

```<code>import UIKit

class GeneralFitness: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    var timer: Timer! = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(tick), userInfo: nil, repeats: true)

    @objc func tick() {
        print("tick")
    }

}
</code>```

Let me know if you have any questions.

答:
Try this in swift 4</p>

```<code>import UIKit

class ViewController: UIViewController {

    var timer: Timer!

    override func viewDidLoad() {
       super.viewDidLoad()

        self.timer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(self.updateValue), userInfo: nil, repeats: true)
    }

    func updateValue(){

        print("Timer is call")
    }
}
</code>```

Title: Swift 4 Timer Crashes with NSException

Body:
I've been searching for a way to use a Timer in Swift 4 and looked at this article. I test out my code in xcode and when the the timer first ticks (in this case after 10 seconds) the app crashes and I get an error, although the build succeeded.

2017-11-20 19:54:42.781502-0700 Rock Prodigy[3022:554505] -[_SwiftValue   tick]: unrecognized selector sent to instance 0x608000051520
2017-11-20 19:54:42.791278-0700 Rock Prodigy[3022:554505] ***  Terminating app due to uncaught exception 'NSInvalidArgumentException',   reason: '-[_SwiftValue tick]: unrecognized selector sent to instance  0x608000051520'
*** First throw call stack:
(
0   CoreFoundation                      0x000000010360d1ab __exceptionPreprocess + 171
1   libobjc.A.dylib                     0x0000000102ca2f41 objc_exception_throw + 48
2   CoreFoundation                      0x000000010368da34 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
3   CoreFoundation                      0x00000001035900a8 ___forwarding___ + 1432
4   CoreFoundation                      0x000000010358fa88 _CF_forwarding_prep_0 + 120
5   Foundation                          0x000000010270e1ee __NSFireTimer + 83
6   CoreFoundation                      0x000000010359d2a4 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 20
7   CoreFoundation                      0x000000010359cf62 __CFRunLoopDoTimer + 1026
8   CoreFoundation                      0x000000010359cb1a __CFRunLoopDoTimers + 266
9   CoreFoundation                      0x0000000103594534 __CFRunLoopRun + 2308
10  CoreFoundation                      0x00000001035939b9 CFRunLoopRunSpecific + 409
11  GraphicsServices                    0x00000001090e29c6 GSEventRunModal + 62
12  UIKit                               0x0000000103a885e8 UIApplicationMain + 159
13  Rock Prodigy                        0x000000010238b637 main + 55
14  libdyld.dylib                       0x0000000107aa1d81 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

Here is my swift 4 code

import UIKit

class GeneralFitness: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    var timer: Timer! = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(tick), userInfo: nil, repeats: true)

    @objc func tick() {
        print("tick")
    }

}

Let me know if you have any questions.

Body:
Try this in swift 4

import UIKit

class ViewController: UIViewController {

    var timer: Timer!

    override func viewDidLoad() {
       super.viewDidLoad()

        self.timer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(self.updateValue), userInfo: nil, repeats: true)
    }

    func updateValue(){

        print("Timer is call")
    }
}


问:
Jquery Tabs: spinner option not working
I need an ajax animation while the remote page is loaded in tabs.

I am using

```<code>$('#tabs2').tabs({ spinner: ''<img src="../../Content/images/Jquery/spinner.gi'' });
</code>```

Even $('#tabs2').tabs({ spinner: 'Loading..' }); also doesn't works ...

Though the tab functionality is working but the animation is not working ...

I am using JQuery theme roller files. Your help is much appreciated.  Many Thanks

答:
I couldn't figure out what is the answer, so once again, if somebody couldn't figure out as well.

Not the content of the tab is being replaced during load but the tab title.
All you need to do is putting tab title into span tags

before:

```<code><ul >
 <li><a href="link.html" >Users</a></li>
</ul>
</code>```

after

```<code><ul >
 <li><a href="link.html" ><span>Users</span></a></li>
</ul>
</code>```

The tab header must be surrounded with span, as you can see
Users becomes Users

ContentLicense: CC BY-SA 2.5

Title: Jquery Tabs: spinner option not working

Body:
I need an ajax animation while the remote page is loaded in tabs.

I am using

$('#tabs2').tabs({ spinner: ''<img src="../../Content/images/Jquery/spinner.gi'' });

Even $('#tabs2').tabs({ spinner: 'Loading..' }); also doesn't works ...

Though the tab functionality is working but the animation is not working ...

I am using JQuery theme roller files. Your help is much appreciated.  Many Thanks

Body:
I couldn't figure out what is the answer, so once again, if somebody couldn't figure out as well.

Not the content of the tab is being replaced during load but the tab title.
All you need to do is putting tab title into span tags

before:

<ul >
 <li><a href="link.html" >Users</a></li>
</ul>

after

<ul >
 <li><a href="link.html" ><span>Users</span></a></li>
</ul>

The tab header must be surrounded with span, as you can see
Users becomes <span>Users</span>


问:
How do I use extends for interface using typescript?
Below is my origin code

```<code>interface customerInfo {
    Success: boolean;
    Code: string;
    Message: string;
    Result: {
        name: string
        tel: number
    }
}

interface accountInfo {
    Success: boolean;
    Code: string;
    Message: string;
    Result: {
        xxx: number
        vvv: string
    }
}
</code>```

How can I use extends for this code?

```<code>interface outer {
    Success: boolean;
    Code: string;
    Message: string;
    Result: Object;
}

interface customerInfo extends outer.Result {
        name: string
        tel: number
}

interface accountInfo extends outer.Result {
        xxx: number
        vvv: string
}
</code>```

Is code above correct?
The content of interface customerInfo and accountInfo is under result Object.

答:
Simplest thing is just to extend outer with the new Result type:

```<code>interface customerInfo extends outer {
  Result: {
        name: string
        tel: number
      }
}
</code>```

That will complain if you try to assign a different object to Result in a customerInfo.

But, really do you want to do this? Do all of your responses have Code, Message and Result whether they succeed or fail?

Much simpler to define customerInfo and accountInfo up top and then include them inside the outer interface which itself is modified to discriminate between success and failure cases:

```<code>interface customerInfo {
    name: string
    tel: number
}

interface outerSuccess {
    Success: true;
    Result: customerInfo | accountInfo;
}
interface outerFail {
    Success: false;
    Code: string;
    Message: string;
}
type outer = outerSuccess | outerFail;
</code>```

Now when you use it:

```<code>if (response.Success) { ... can access Result here ... }
else { ... can access Code and Message here ... }
</code>```

P.S. tel: number? Should probably be a string as well.

Body:
Below is my origin code

interface customerInfo {
    Success: boolean;
    Code: string;
    Message: string;
    Result: {
        name: string
        tel: number
    }
}

interface accountInfo {
    Success: boolean;
    Code: string;
    Message: string;
    Result: {
        xxx: number
        vvv: string
    }
}

How can I use extends for this code?

interface outer {
    Success: boolean;
    Code: string;
    Message: string;
    Result: Object;
}

interface customerInfo extends outer.Result {
        name: string
        tel: number
}

interface accountInfo extends outer.Result {
        xxx: number
        vvv: string
}

Is code above correct?
The content of interface customerInfo and accountInfo is under result Object.

Body:
Simplest thing is just to extend outer with the new Result type:

interface customerInfo extends outer {
  Result: {
        name: string
        tel: number
      }
}

That will complain if you try to assign a different object to Result in a customerInfo.

But, really do you want to do this? Do all of your responses have Code, Message and Result whether they succeed or fail?

Much simpler to define customerInfo and accountInfo up top and then include them inside the outer interface which itself is modified to discriminate between success and failure cases:

interface customerInfo {
    name: string
    tel: number
}

interface outerSuccess {
    Success: true;
    Result: customerInfo | accountInfo;
}
interface outerFail {
    Success: false;
    Code: string;
    Message: string;
}
type outer = outerSuccess | outerFail;

Now when you use it:

if (response.Success) { ... can access Result here ... }
else { ... can access Code and Message here ... }

P.S. tel: number? Should probably be a string as well.


问:
Updating Apache Felix SCR to OSGi Declarative Services R6 - @Property
I'm updating from Apache Felix SCR Annotations to OSGi DS R6 ones and the one is causing me more problem is the @Property inside the class.

Before I had:

```<code>@Component (immediate = true)
@Service (A.class)
public class AImpl implements A
{
    @Property (intValue = 604800)
    public static final String A = "a";
    ...
}
</code>```

Now I have:

```<code>@Component (service = A.class, immediate = true)
@Designate (ocd = Configuration.class)
public class AImpl implements A
{
    ...
}
</code>```

and

```<code>@ObjectClassDefinition (name = "Bla")
public @interface Configuration
{
    @AttributeDefinition (name = "A", type = AttributeType.INTEGER)
    int A() default 604800;
}
</code>```

The most bizarre thing on all of this is:

Before, I could see my AImpl class as a component.

Now, I couldn't see my AImpl class as a component and everyone who uses it cannot start because of unsatisfied references.

How come changing just configurations like this can cause this behaviour ? Maybe I'm missing something ?

The stranger part on all of this is my xml is inside the .jar and seems ok.
The scr:info is getting me nullpointer exception and I cannot see my component, meaning the scr:list will no help in anything.

XML BELLOW:

```<code><?xml version="1.0" encoding="UTF-8"?>
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.3.0" name="AImpl" immediate="true" activate="init" deactivate="stop">
  <implementation class="AImpl"/>
  <service>
    <provide interface="A"/>
  </service>
  <reference name="Bla1" interface="Bla1Service" bind="bindBla1Service" unbind="unbindBla1Service"/>
  <property name="PROP.EVENT.INTERVAL" type="Long" value="900000"/>
</scr:component>
</code>```

Ps.: The classes are with strange names and so on because it's from a private company.

STACKTRACE:

2017-12-11T16:40:27.689+0100 [Framework Event Dispatcher] ERROR o.o.p.l.l.internal.FrameworkHandler:144 frameworkEvent FrameworkEvent ERROR - org.apache.felix.scr
org.osgi.framework.BundleException: The activator org.apache.felix.scr.impl.Activator for bundle org.apache.felix.scr is invalid
        at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadBundleActivator(AbstractBundle.java:172)
        at org.eclipse.osgi.framework.internal.core.BundleContextImpl.start(BundleContextImpl.java:679)
        at org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:381)
        at org.eclipse.osgi.framework.internal.core.AbstractBundle.updateWorker(AbstractBundle.java:645)
        at org.eclipse.osgi.framework.internal.core.AbstractBundle.update(AbstractBundle.java:592)
        at org.apache.felix.webconsole.internal.core.UpdateHelper.doRun(UpdateHelper.java:60)
        at org.apache.felix.webconsole.internal.core.BaseUpdateInstallHelper.doRun(BaseUpdateInstallHelper.java:93)
        at org.apache.felix.webconsole.internal.core.UpdateHelper.doRun(UpdateHelper.java:70)
        at org.apache.felix.webconsole.internal.core.BaseUpdateInstallHelper.run(BaseUpdateInstallHelper.java:123)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.ClassCastException: org.apache.felix.scr.impl.Activator cannot be cast to org.osgi.framework.BundleActivator
        at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadBundleActivator(AbstractBundle.java:167)
        ... 9 common frames omitted

Part of POM.XML who install on karaf my bundles:

```<code><artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-kar-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <inherited>false</inherited>
                        <configuration>
                            <includeScope>runtime</includeScope>
                            <prependGroupId>true</prependGroupId>
                            <excludeTransitive>true</excludeTransitive>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>org.osgi</groupId>
                                    <artifactId>org.osgi.framework</artifactId>
                                    <version>${org.osgi.framework.version}</version>
                                </artifactItem>
                                <artifactItem>
                                    <groupId>org.osgi</groupId>
                                    <artifactId>org.osgi.core</artifactId>
                                    <version>${org.osgi.core.version}</version>
                                </artifactItem>
                                <artifactItem>
                                    <groupId>org.apache.felix</groupId>
                                    <artifactId>org.apache.felix.scr</artifactId>
                                    <version>${org.apache.felix.scr.version}</version>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
</execution>
</executions>
</code>```

答:
Your AImpl class still being a Component. However, now it's a "Configuration" Component, hence it has a @Designate annotation linking to a @ObjectClassDefinition Property class.

Go to the Configuration tab and you should see your Component and its properties.

Body:
I'm updating from Apache Felix SCR Annotations to OSGi DS R6 ones and the one is causing me more problem is the @Property inside the class.

Before I had:

@Component (immediate = true)
@Service (A.class)
public class AImpl implements A
{
    @Property (intValue = 604800)
    public static final String A = "a";
    ...
}

Now I have:

@Component (service = A.class, immediate = true)
@Designate (ocd = Configuration.class)
public class AImpl implements A
{
    ...
}

and

@ObjectClassDefinition (name = "Bla")
public @interface Configuration
{
    @AttributeDefinition (name = "A", type = AttributeType.INTEGER)
    int A() default 604800;
}

The most bizarre thing on all of this is:

Before, I could see my AImpl class as a component.

Now, I couldn't see my AImpl class as a component and everyone who uses it cannot start because of unsatisfied references.

How come changing just configurations like this can cause this behaviour ? Maybe I'm missing something ?

The stranger part on all of this is my xml is inside the .jar and seems ok.
The scr:info is getting me nullpointer exception and I cannot see my component, meaning the scr:list will no help in anything.

XML BELLOW:

<?xml version="1.0" encoding="UTF-8"?>
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.3.0" name="AImpl" immediate="true" activate="init" deactivate="stop">
  <implementation class="AImpl"/>
  <service>
    <provide interface="A"/>
  </service>
  <reference name="Bla1" interface="Bla1Service" bind="bindBla1Service" unbind="unbindBla1Service"/>
  <property name="PROP.EVENT.INTERVAL" type="Long" value="900000"/>
</scr:component>

Ps.: The classes are with strange names and so on because it's from a private company.

STACKTRACE:

2017-12-11T16:40:27.689+0100 [Framework Event Dispatcher] ERROR o.o.p.l.l.internal.FrameworkHandler:144 frameworkEvent FrameworkEvent ERROR - org.apache.felix.scr
org.osgi.framework.BundleException: The activator org.apache.felix.scr.impl.Activator for bundle org.apache.felix.scr is invalid
        at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadBundleActivator(AbstractBundle.java:172)
        at org.eclipse.osgi.framework.internal.core.BundleContextImpl.start(BundleContextImpl.java:679)
        at org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:381)
        at org.eclipse.osgi.framework.internal.core.AbstractBundle.updateWorker(AbstractBundle.java:645)
        at org.eclipse.osgi.framework.internal.core.AbstractBundle.update(AbstractBundle.java:592)
        at org.apache.felix.webconsole.internal.core.UpdateHelper.doRun(UpdateHelper.java:60)
        at org.apache.felix.webconsole.internal.core.BaseUpdateInstallHelper.doRun(BaseUpdateInstallHelper.java:93)
        at org.apache.felix.webconsole.internal.core.UpdateHelper.doRun(UpdateHelper.java:70)
        at org.apache.felix.webconsole.internal.core.BaseUpdateInstallHelper.run(BaseUpdateInstallHelper.java:123)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.ClassCastException: org.apache.felix.scr.impl.Activator cannot be cast to org.osgi.framework.BundleActivator
        at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadBundleActivator(AbstractBundle.java:167)
        ... 9 common frames omitted

Part of POM.XML who install on karaf my bundles:

<artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-kar-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <inherited>false</inherited>
                        <configuration>
                            <includeScope>runtime</includeScope>
                            <prependGroupId>true</prependGroupId>
                            <excludeTransitive>true</excludeTransitive>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>org.osgi</groupId>
                                    <artifactId>org.osgi.framework</artifactId>
                                    <version>${org.osgi.framework.version}</version>
                                </artifactItem>
                                <artifactItem>
                                    <groupId>org.osgi</groupId>
                                    <artifactId>org.osgi.core</artifactId>
                                    <version>${org.osgi.core.version}</version>
                                </artifactItem>
                                <artifactItem>
                                    <groupId>org.apache.felix</groupId>
                                    <artifactId>org.apache.felix.scr</artifactId>
                                    <version>${org.apache.felix.scr.version}</version>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
</execution>
</executions>


问:
Access Form Bring Text Box in Front of Listbox?
This application is Access 2010, with a SQL backend.

I have a form, which has a tab control, with 2 pages.  1 page has 1 listbox and the other has 2 listboxes.  I use some code, on change of the tab control, to determine the active page, and set the listbox(es) row source(s) for the one(s) on the active page, and clear it out on the inactive page.  This takes a sec and the listboxes look yucky while this is happening.

To prevent the user from seeing this, I made a text box, with a colored background and the control source ="Please Wait One Moment..."
with like 48 font.  On load of the form, this textbox is visible = false.  On click of the tab control, the text box is to be made visible, and it is big enough to cover then entire tab control. It does cover the tab control, but I can still see the listboxes through the text box.  The text box has a back color and is not transparent. I tried right-clicking the listboxes in design view and choosing Position - Send to Back, and right-clicking the textbox and choosing Position - Send to Front.

This doesn't seem to work.  Is anyone familiar with this issue? Figuring someone has tried a trick like this.

The meat of my code is all functioning properly, for this on change of the tab control.  I have this code at the beginning:

```<code>DoCmd.Hourglass True
Me.txtPleaseWait.Visible = True
Me.Repaint
Application.Echo False
Debug.Print Me.txtPleaseWait.Visible
</code>```

and this at the end:

```<code>Application.Echo True
Me.txtPleaseWait.Visible = False
Me.Repaint
Debug.Print Me.txtPleaseWait.Visible
DoCmd.Hourglass False
Debug.Print "got to end of resting form state"
</code>```

Does that make sense?

Should I handle this differently?

Thank you.

Edit

I found that listboxes have a higher zorder than textboxes, so I changed my textbox to a listbox.  I still see the listboxes from the tab control, through the listbox I'm using to cover them up.

Is there a control that would better cover these and could have this "intermission" type message show, while the listboxes are being set and unset?

答:
I researched different aspects of this, and found the listbox has a higher zorder than text boxes, which is position front or back relative to other objects.  I tried just doing this onload of the form, and there wasn't time to hide anything. It just waited to load the form, until the rowsources were set.

Since the find tab is the default one, and quicker to load, I just load that on load.  Then, if someone clicks on the other tab, I will load the add listboxes. I also set an integer variable to 0 on load of the form. When I click on the tab to go to the add page (add page is active), I check that variable, and if it is 0, I set the row source, and then +1 to the variable.  Next time I click on it, I don't re-order it.

This way, I'm not using resources to load and unload the listboxes, and I only load 2 of them, if the user even goes to that tab. Many times, they might just be looking for one in the system, and going to view it.

Here is the full code, in case this method helps someone else.  You could also make the variable boolean, and just set it to true, and then false.

```<code>Option Compare Database
Option Explicit
Dim AddLoaded As Integer

Property Get ActivePage() As Access.Page
    'PROPERTY TO IDENTIFY WHICH TAB WE ARE ON, FOR FILTERING AND IDENTIFYING WHICH ACTIVE LISTBOX TO LOOK AT, FOR VALUES AND ACTIONS
    With Me.tbAddFind
        Set ActivePage = .Pages(.Value)
    End With
End Property

Private Sub Form_Load()
    Dim Listctrl As Control
    Dim cmd As ADODB.Command
    Set cmd = New ADODB.Command
    Dim cSQL As String

    AddLoaded = 0

    For Each Listctrl In Form.Controls
        If (Listctrl.ControlType = acListBox) Then
            With Listctrl
                .RowSource = ""
            End With
        End If
    Next Listctrl

    Me.tbAddFind.Value = 0

    cSQL = "SELECT vw_CMP_Projects.CM_CID, [vw_CMP_Projects]![ProjectName] &" & Chr$(34) & " (" & Chr$(34) & "& [vw_CMP_Projects]![ProjectNo] &" & Chr$(34) & ") " & Chr$(34) & " AS Projects FROM vw_CMP_Projects ORDER BY [vw_CMP_Projects]![ProjectName] &" & Chr$(34) & " (" & Chr$(34) & "& [vw_CMP_Projects]![ProjectNo] &" & Chr$(34) & ")" & Chr$(34)
    Me.lstProjects.RowSource = cSQL
    Me.lstProjects.Requery

End Sub

Private Sub tbAddFind_Change()
    Dim cmd As ADODB.Command
    Set cmd = New ADODB.Command
    Select Case Me.ActivePage.Name
        Case "pgAddProjects"
            If AddLoaded = 0 Then
                cmd.ActiveConnection = GetCatalog()
                cmd.CommandType = adCmdStoredProc
                cmd.CommandText = "sp_RefreshProjectsAdd"
                cmd.Execute

                Me.lstAllProjects.RowSource = "Select * From qryAddProjectsYes"
                Me.lstAllProjects.Requery
                Me.lstAddProjects.RowSource = "Select * From qryAddProjectsNo"
                Me.lstAddProjects.Requery

                AddLoaded = AddLoaded + 1
            End If
    End Select
End Sub
</code>```

Thanks for the discussion. It was helpful, as it gave me things to research.

Body:
This application is Access 2010, with a SQL backend.

I have a form, which has a tab control, with 2 pages.  1 page has 1 listbox and the other has 2 listboxes.  I use some code, on change of the tab control, to determine the active page, and set the listbox(es) row source(s) for the one(s) on the active page, and clear it out on the inactive page.  This takes a sec and the listboxes look yucky while this is happening.

To prevent the user from seeing this, I made a text box, with a colored background and the control source ="Please Wait One Moment..."
with like 48 font.  On load of the form, this textbox is visible = false.  On click of the tab control, the text box is to be made visible, and it is big enough to cover then entire tab control. It does cover the tab control, but I can still see the listboxes through the text box.  The text box has a back color and is not transparent. I tried right-clicking the listboxes in design view and choosing Position - Send to Back, and right-clicking the textbox and choosing Position - Send to Front.

This doesn't seem to work.  Is anyone familiar with this issue? Figuring someone has tried a trick like this.

The meat of my code is all functioning properly, for this on change of the tab control.  I have this code at the beginning:

DoCmd.Hourglass True
Me.txtPleaseWait.Visible = True
Me.Repaint
Application.Echo False
Debug.Print Me.txtPleaseWait.Visible

and this at the end:

Application.Echo True
Me.txtPleaseWait.Visible = False
Me.Repaint
Debug.Print Me.txtPleaseWait.Visible
DoCmd.Hourglass False
Debug.Print "got to end of resting form state"

Does that make sense?

Should I handle this differently?

Thank you.

Edit

I found that listboxes have a higher zorder than textboxes, so I changed my textbox to a listbox.  I still see the listboxes from the tab control, through the listbox I'm using to cover them up.

Is there a control that would better cover these and could have this "intermission" type message show, while the listboxes are being set and unset?

Body:
I researched different aspects of this, and found the listbox has a higher zorder than text boxes, which is position front or back relative to other objects.  I tried just doing this onload of the form, and there wasn't time to hide anything. It just waited to load the form, until the rowsources were set.

Since the find tab is the default one, and quicker to load, I just load that on load.  Then, if someone clicks on the other tab, I will load the add listboxes. I also set an integer variable to 0 on load of the form. When I click on the tab to go to the add page (add page is active), I check that variable, and if it is 0, I set the row source, and then +1 to the variable.  Next time I click on it, I don't re-order it.

This way, I'm not using resources to load and unload the listboxes, and I only load 2 of them, if the user even goes to that tab. Many times, they might just be looking for one in the system, and going to view it.

Here is the full code, in case this method helps someone else.  You could also make the variable boolean, and just set it to true, and then false.

Option Compare Database
Option Explicit
Dim AddLoaded As Integer

Property Get ActivePage() As Access.Page
    'PROPERTY TO IDENTIFY WHICH TAB WE ARE ON, FOR FILTERING AND IDENTIFYING WHICH ACTIVE LISTBOX TO LOOK AT, FOR VALUES AND ACTIONS
    With Me.tbAddFind
        Set ActivePage = .Pages(.Value)
    End With
End Property

Private Sub Form_Load()
    Dim Listctrl As Control
    Dim cmd As ADODB.Command
    Set cmd = New ADODB.Command
    Dim cSQL As String

    AddLoaded = 0

    For Each Listctrl In Form.Controls
        If (Listctrl.ControlType = acListBox) Then
            With Listctrl
                .RowSource = ""
            End With
        End If
    Next Listctrl

    Me.tbAddFind.Value = 0

    cSQL = "SELECT vw_CMP_Projects.CM_CID, [vw_CMP_Projects]![ProjectName] &" & Chr$(34) & " (" & Chr$(34) & "& [vw_CMP_Projects]![ProjectNo] &" & Chr$(34) & ") " & Chr$(34) & " AS Projects FROM vw_CMP_Projects ORDER BY [vw_CMP_Projects]![ProjectName] &" & Chr$(34) & " (" & Chr$(34) & "& [vw_CMP_Projects]![ProjectNo] &" & Chr$(34) & ")" & Chr$(34)
    Me.lstProjects.RowSource = cSQL
    Me.lstProjects.Requery

End Sub

Private Sub tbAddFind_Change()
    Dim cmd As ADODB.Command
    Set cmd = New ADODB.Command
    Select Case Me.ActivePage.Name
        Case "pgAddProjects"
            If AddLoaded = 0 Then
                cmd.ActiveConnection = GetCatalog()
                cmd.CommandType = adCmdStoredProc
                cmd.CommandText = "sp_RefreshProjectsAdd"
                cmd.Execute

                Me.lstAllProjects.RowSource = "Select * From qryAddProjectsYes"
                Me.lstAllProjects.Requery
                Me.lstAddProjects.RowSource = "Select * From qryAddProjectsNo"
                Me.lstAddProjects.Requery

                AddLoaded = AddLoaded + 1
            End If
    End Select
End Sub

Thanks for the discussion. It was helpful, as it gave me things to research.


问:
Modify image href attribute inside an svg element
Inside a function I have an svg object, when I console log it looks like this:

```<code><svg height="100" version="1.1" width="1000" xmlns="http://www.w3.org/2000/svg"
     style="overflow: hidden; position: relative;">

  <desc style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">Created with Raphaël 2.1.0</desc>
  <defs style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></defs>
  <path fill="#000000" stroke="#000000" d="M0,0L12,12L12,-12L0,0" transform="matrix(1,0,0,1,0,50)"
     opacity="0" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); opacity: 0;">
  </path>
  <rect x="0" y="10" width="30" height="80" r="0" rx="0" ry="0"
    fill="#000000" stroke="#000" opacity="0" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); opacity: 0;"></rect>
  <image x="134" y="10" width="30" height="80" preserveAspectRatio="none"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    xlink:href="/static/img/pads/numberline/symbols/leftParen.png"
    style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">
  </image>
</svg>
</code>```

Now I need to change the href of the image inside the svg element.
What i did it so far is set the width svgObject.setAttribute('width', 1000);

But how can I change and select the image element href attribute?

答:
Try querySelectorAll. It returns a list of elements and then you'll have to pick the first item ([0]) of the list.

```<code>document.querySelectorAll("svg image")[0].setAttribute("xlink:href", "myImage.jpg");
</code>```

Fiddle

Result:

Body:
Inside a function I have an svg object, when I console log it looks like this:

<svg height="100" version="1.1" width="1000" xmlns="http://www.w3.org/2000/svg"
     style="overflow: hidden; position: relative;">

  <desc style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">Created with Raphaël 2.1.0</desc>
  <defs style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></defs>
  <path fill="#000000" stroke="#000000" d="M0,0L12,12L12,-12L0,0" transform="matrix(1,0,0,1,0,50)"
     opacity="0" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); opacity: 0;">
  </path>
  <rect x="0" y="10" width="30" height="80" r="0" rx="0" ry="0"
    fill="#000000" stroke="#000" opacity="0" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); opacity: 0;"></rect>
  <image x="134" y="10" width="30" height="80" preserveAspectRatio="none"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    xlink:href="/static/img/pads/numberline/symbols/leftParen.png"
    style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">
  </image>
</svg>

Now I need to change the href of the image inside the svg element.
What i did it so far is set the width svgObject.setAttribute('width', 1000);

But how can I change and select the image element href attribute?

Body:
Try querySelectorAll. It returns a list of elements and then you'll have to pick the first item ([0]) of the list.

document.querySelectorAll("svg image")[0].setAttribute("xlink:href", "myImage.jpg");

Fiddle

Result:


问:
Is there anyway to access the XML payload in HTTP Trigger of Google Cloud Function or Firebase Cloud Function
Google/Firebase Cloud Functions appear very powerful for quick implementation of APIs. However, unlike Amazon and Azure, it seems that they auto convert to JSON payload and do NOT make the underlying payload available (req.body is empty) if the caller submitted application/xml or text/xml payload.

It is not always  in control to force the caller to submit JSON payload, especially for WebHooks type of operations.

Is there anyway to retrieve raw XML payload from the HTTP Trigger requests which we can then manually parse as xml and perform necessary operations.

thanks for your help.

答:
```<code>request.rawBody.toString();
</code>```

This does not work for now with the emulator, but it does work on Google's servers. I tested it on Firebase.

Note that you can't use request.pipe() (though it works with the emulator...) because the request payload is fully read before being handled to your function.

Discussion about this issue is here:
https://issuetracker.google.com/issues/36252545

Body:
request.rawBody.toString();

This does not work for now with the emulator, but it does work on Google's servers. I tested it on Firebase.

Note that you can't use request.pipe() (though it works with the emulator...) because the request payload is fully read before being handled to your function.

Discussion about this issue is here:
https://issuetracker.google.com/issues/36252545


问:
Unable to use Anypoint MQ in mule flow
I am learning mule ESB and using Anypoint Studio version 6.4.1. I was trying to create a flow containing composite Source. I wanted to add FTP, HTTP and Anypoint MQ connectors to composite source. Whenever i drag Anypoint MQ connector into composite source, it disappears. It doesn't get added. I can add other connectors fine. Not sure why I am not able to add Anypoint MQ to the composite source.

EDIT: Added a picture of what I am trying to do. Flow has a composite source scope and it will need to have HTTP, FTP and AnypointMQ connectors as described in this image

.

答:
Do clean and build your project and restart your Anypoint studio.

Because i have tried adding the AnypointMQ connector in my flow.Please find the attached screen shot.
Added Anypoint MQ in composite source
enter image description here

Title: Unable to use Anypoint MQ in mule flow


问:
How to see if webdriver clicking a button downloaded a file successfully?
I'm trying to click a button with this  </p>

```<code>public void clickDownloadButton() {
        WebDriverWait wait = new WebDriverWait(driver, 15);
        wait.until(ExpectedConditions.elementToBeClickable(downloadTransactionsButton)).click();
        System.out.println("Clicking download transactions button...");
    }
</code>```

<p>Once the button is clicked, a new window is opened and the file is downloaded. How do I ensure that the file downloaded successfully? </p>

答:
I think this will help.</p>

```<code> String user = System.getProperty("user.name");
        //Assuming your download location is the default location
        File f = new File("C:/users/" + user + "/Downloads/NameOfYourDownloadedFile.fileType");
        if (f.exists() && !f.isDirectory()) {
            System.out.println("File downloaded successfully...");
            /*If you have to run the test multiple times,
            you may want to delete the file once it's downloaded so*/
            if (f.delete()) {
                System.out.println("File Removed...");
            } else {
                System.out.println("Failed to delete the file...");
            }
        } else {
            System.out.println("The file was not downloaded...");

        }
</code>```

Body:
I'm trying to click a button with this

public void clickDownloadButton() {
        WebDriverWait wait = new WebDriverWait(driver, 15);
        wait.until(ExpectedConditions.elementToBeClickable(downloadTransactionsButton)).click();
        System.out.println("Clicking download transactions button...");
    }

Once the button is clicked, a new window is opened and the file is downloaded. How do I ensure that the file downloaded successfully?

Body:
I think this will help.

 String user = System.getProperty("user.name");
        //Assuming your download location is the default location
        File f = new File("C:/users/" + user + "/Downloads/NameOfYourDownloadedFile.fileType");
        if (f.exists() && !f.isDirectory()) {
            System.out.println("File downloaded successfully...");
            /*If you have to run the test multiple times,
            you may want to delete the file once it's downloaded so*/
            if (f.delete()) {
                System.out.println("File Removed...");
            } else {
                System.out.println("Failed to delete the file...");
            }
        } else {
            System.out.println("The file was not downloaded...");

        }


问:
Official C++ language and base class library documentations?
I'm newbie on C++. And I have multiple years of C# background.
In C#, official language standard and basic class library documentations can be found on MSDN.
What's the equivalent for C++?

And what's the most basic library of C++? There are many libraries. Boost, STL, ATL, and etc... What's the most basic and I should start from?

答:
The equivalent is The ISO C++ Standard.  The last revision was published in 2003 (the link is to where you can purchase the PDF of that document).  The next revision, what is called C++0x, is slated to be finished sometime around the end of this year (the latest draft can be downloaded freely from the C++ committee website; a very large PDF can be found here).

The most basic library for C++ is just called the C++ Standard Library.  It should be supported by every C++ compiler.


问:
Extract strings from HTML
I have following  element:

```<code><div class="column4">
        Unlimited Subscription<br/> Discount for Monthly <br/> Total Amount
    </div>
</code>```

How can I extract three strings as three different elements with using Beautiful Soup only. String conversion and regexps can not be used:

Expected output:

```<code>Unlimited Subscription
Discount for Monthly
Total Amount
</code>```

答:
If you want to get the output exactly the way you have shown above, then you can comply something like this:

```<code>from bs4 import BeautifulSoup

html_elem ="""
<div class="column4">
    Unlimited Subscription<br/> Discount for Monthly <br/> Total Amount
</div>
"""
soup = BeautifulSoup(html_elem, 'lxml')
for item in soup.select(".column4"):
    for data in item.select("br"):data.replace_with("\n")
    print(item.text.strip())
</code>```

Output:

```<code>Unlimited Subscription
Discount for Monthly
Total Amount
</code>```

Title: Extract strings from HTML

Body:
I have following  element:

        Unlimited Subscription
 Discount for Monthly
 Total Amount

How can I extract three strings as three different elements with using Beautiful Soup only. String conversion and regexps can not be used:

Expected output:

Unlimited Subscription
Discount for Monthly
Total Amount

Body:
If you want to get the output exactly the way you have shown above, then you can comply something like this:

from bs4 import BeautifulSoup

html_elem ="""
<div class="column4">
    Unlimited Subscription<br/> Discount for Monthly <br/> Total Amount
</div>
"""
soup = BeautifulSoup(html_elem, 'lxml')
for item in soup.select(".column4"):
    for data in item.select("br"):data.replace_with("\n")
    print(item.text.strip())

Output:

Unlimited Subscription
Discount for Monthly
Total Amount


问:
WriteableBitmap set pixels
I am using WPF and i would like to manipulate some pixels of my image. I am using WritableBitmap because i can use it indirect from source. When i try to set some pixels RGB values (in order), the result is not that i expected.
I use this extension method to read source:

```<code>        public static PixelColor[,] CopyPixels(this BitmapSource source,out int stride)
        {
            if (source.Format != PixelFormats.Bgra32)
                source = new FormatConvertedBitmap(source, PixelFormats.Bgra32, null, 0);
                PixelColor[,] pixels = new PixelColor[source.PixelWidth, source.PixelHeight];
                stride = source.PixelWidth * ((source.Format.BitsPerPixel + 7) / 8);
                GCHandle pinnedPixels = GCHandle.Alloc(pixels, GCHandleType.Pinned);
                source.CopyPixels(
                  new Int32Rect(0, 0, source.PixelWidth, source.PixelHeight),
                  pinnedPixels.AddrOfPinnedObject(),
                  pixels.GetLength(0) * pixels.GetLength(1) * 4, stride);

            pinnedPixels.Free();
            return pixels;
        }
</code>```

The output struct is

```<code>[StructLayout(LayoutKind.Sequential)]
public struct PixelColor
{
    public byte Blue;
    public byte Green;
    public byte Red;
    public byte Alpha;
}
</code>```

this is the simple example code to modify pixels (between 200x200 and 300x300) to black:

```<code>        int stride = 0;
        PixelColor[,] PixelData = wBitmap.CopyPixels(out stride);

        for (int i = 0; i < PixelData.GetLength(0); i++)
        {
            for (int j = 0; j < PixelData.GetLength(1); j++)
            {

                if ((200 < i && 300 > i) && (200 < j && 300 > j))
                {
                    PixelData[i, j].Blue = 0;
                    PixelData[i, j].Red = 0;
                    PixelData[i, j].Green = 0;

                }

            }
        }

        wBitmap.WritePixels(new Int32Rect(0, 0, wBitmap.PixelWidth, wBitmap.PixelHeight), PixelData, stride,0);
</code>```

The surprising result is

This is an image with 500x500 parameters. I expected that the result will be an black filled square in the middle of the image instead of black vertical lines. What is the problem with my example code? (The colorful dots behind the lines are part of the original image.)

答:
Just change the order of the dimensions in the 2-dimensional array declaration in your CopyPixels methods:</p>

```<code>var pixels = new PixelColor[source.PixelHeight, source.PixelWidth];
</code>```

Title: WriteableBitmap set pixels

Body:
I am using WPF and i would like to manipulate some pixels of my image. I am using WritableBitmap because i can use it indirect from source. When i try to set some pixels RGB values (in order), the result is not that i expected.
I use this extension method to read source:

        public static PixelColor[,] CopyPixels(this BitmapSource source,out int stride)
        {
            if (source.Format != PixelFormats.Bgra32)
                source = new FormatConvertedBitmap(source, PixelFormats.Bgra32, null, 0);
                PixelColor[,] pixels = new PixelColor[source.PixelWidth, source.PixelHeight];
                stride = source.PixelWidth * ((source.Format.BitsPerPixel + 7) / 8);
                GCHandle pinnedPixels = GCHandle.Alloc(pixels, GCHandleType.Pinned);
                source.CopyPixels(
                  new Int32Rect(0, 0, source.PixelWidth, source.PixelHeight),
                  pinnedPixels.AddrOfPinnedObject(),
                  pixels.GetLength(0) * pixels.GetLength(1) * 4, stride);

            pinnedPixels.Free();
            return pixels;
        }

The output struct is

[StructLayout(LayoutKind.Sequential)]
public struct PixelColor
{
    public byte Blue;
    public byte Green;
    public byte Red;
    public byte Alpha;
}

this is the simple example code to modify pixels (between 200x200 and 300x300) to black:

        int stride = 0;
        PixelColor[,] PixelData = wBitmap.CopyPixels(out stride);

        for (int i = 0; i < PixelData.GetLength(0); i++)
        {
            for (int j = 0; j < PixelData.GetLength(1); j++)
            {

                if ((200  i) && (200 < j && 300 > j))
                {
                    PixelData[i, j].Blue = 0;
                    PixelData[i, j].Red = 0;
                    PixelData[i, j].Green = 0;

                }

            }
        }

        wBitmap.WritePixels(new Int32Rect(0, 0, wBitmap.PixelWidth, wBitmap.PixelHeight), PixelData, stride,0);

The surprising result is

This is an image with 500x500 parameters. I expected that the result will be an black filled square in the middle of the image instead of black vertical lines. What is the problem with my example code? (The colorful dots behind the lines are part of the original image.)

Body:
Just change the order of the dimensions in the 2-dimensional array declaration in your CopyPixels methods:

var pixels = new PixelColor[source.PixelHeight, source.PixelWidth];


问:
Azure VM - linking the *.cloudapp.azure.com URL to godaddy?
I am trying to figure out how to link my *.cloudapp.azure.com VM's DNS info to a GoDaddy subdomain off my company's site. I am not able to wrap my head around the directions on Azure.

The second part is we have a purchased wildcard SSL cert for our main domain on GoDaddy that we need to install. I can see you can purchase certs from Azure, however we have our own.

Thanks for any assistance anyone can provide in this matter.

答:
A DNS zone is used to host the DNS records for a particular domain. To start hosting your domain in Azure DNS, you need to create a DNS zone for that domain name. Each DNS record for your domain is then created inside this DNS zone. Finally, to publish your DNS zone to the Internet, you need to configure the name servers for the domain.

Each of these steps is described in the following steps:

Step1: First create the Azure Virtual Machines.

Step2: To get DNS addresses, you need create DNS zones with your domain name.

Go to Azure Portal => New => search DNS zones => Create DNS zones

Name= azurewala.com, Subscription, Resource Group, and Location

Step3: Once Azure DNS zones created you can see four Name Servers.

Step4: Go to GoDaddy control panel and click on the DNS.

Step5: Change the Nameservers by choose your new nameserver type as: Custom

Note: Copy and paste the Name Servers from Azure DNS to GoDaddy

And make sure you have to remove the extra dot before you save.

Step6: Open Created DNS Zones and add a record set

Name: www
Type: A
TTL: 1 Hours

IP ADDRESS: 52.176.102.178

Note: Give IP Address of the VM.

You may refer detailed workaround steps here: https://stackoverflow.com/questions/45449401/configuring-a-custom-domain-name-for-an-azure-vm-and-godaddy/45453110#45453110


问:
asymmetric hybrid mapping with SLURM
I want to do an asymmetric hybrid mapping with slurm.

My code need to have 3 mpi tasks. But, only the task 1 and 2 need to have more than one cpu. The mpi task 0 need to have only one cpu.

I use currently this slurm configuration:

```<code>#SBATCH --nodes 3
#SBATCH --ntasks 3
#SBATCH --cpus-per-task 32
</code>```

In this configuration, I allocated 32 cpus for each mpi task. But 31 cpus in the node 0 are not used because the mpi task 0 use only one.

Do you know how I can configure the slurm job to do an asymmetric allocation ?

One cpu for the mpi task 0, 31 cpus for the mpi task 1 and 31 cpus for the mpi task 2. In this way, I could maximize the use of 2 nodes, without use a 3rd node for just one cpu.

I cannot find in the slurm documentation ...

答:
The  17.11 version introduced Packed jobs so you can specify something like this:

```<code>#SBATCH --nodes 1 --ntasks 1 --cpus-per-task 1
#SBATCH packjob
#SBATCH --nodes 2 --ntasks 2 --cpus-per-task 32
</code>```

to have one MPI rank with one CPU and two ranks with 32 CPUs.

Title: asymmetric hybrid mapping with SLURM

Body:
I want to do an asymmetric hybrid mapping with slurm.

My code need to have 3 mpi tasks. But, only the task 1 and 2 need to have more than one cpu. The mpi task 0 need to have only one cpu.

I use currently this slurm configuration:

#SBATCH --nodes 3
#SBATCH --ntasks 3
#SBATCH --cpus-per-task 32

In this configuration, I allocated 32 cpus for each mpi task. But 31 cpus in the node 0 are not used because the mpi task 0 use only one.

Do you know how I can configure the slurm job to do an asymmetric allocation ?

One cpu for the mpi task 0, 31 cpus for the mpi task 1 and 31 cpus for the mpi task 2. In this way, I could maximize the use of 2 nodes, without use a 3rd node for just one cpu.

I cannot find in the slurm documentation ...

Body:
The  17.11 version introduced Packed jobs so you can specify something like this:

#SBATCH --nodes 1 --ntasks 1 --cpus-per-task 1
#SBATCH packjob
#SBATCH --nodes 2 --ntasks 2 --cpus-per-task 32

to have one MPI rank with one CPU and two ranks with 32 CPUs.


问:
NullPointer Exception Volley android studio
I am working in a Page2 activity in Android Studio and I am using php file pause_in, below is java code using Volley class.It gives me the error:
java.lang.NullPointerException:
Attempt to invoke virtual method 'com.android.volley.Request com.android.volley.RequestQueue.add(com.android.volley.Request)' on a null object reference.
But after I have added the line for initializing the request,it gives me that:(I have to mention that I used getExtra method to get the variables of email and password from the first screen).

```<code>12-08 12:49:03.446 1346-1370/? W/audio_hw_generic: Not supplying enough
data to HAL, expected position 455229 , only wrote 455040
12-08 12:49:03.446 2245-2245/? D/key: valuee
12-08 12:49:03.514 2245-2245/? W/System.err: org.json.JSONException:
End of input at character 1 of
12-08 12:49:03.514 2245-2245/? W/System.err:     at
org.json.JSONTokener.syntaxError(JSONTokener.java:449)
12-08 12:49:03.514 2245-2245/? W/System.err:     at
org.json.JSONTokener.nextValue(JSONTokener.java:97)
12-08 12:49:03.514 2245-2245/? W/System.err:     at
org.json.JSONObject.<init>(JSONObject.java:156)
12-08 12:49:03.514 2245-2245/? W/System.err:     at
org.json.JSONObject.<init>(JSONObject.java:173)
12-08 12:49:03.514 2245-2245/? W/System.err:     at
com.example.a.mysql_php_register_login.Page2$1$1.
onResponse(Page2.java:96)
12-08 12:49:03.514 2245-2245/? W/System.err:     at
com.example.a.mysql_php_register_login.Page2$1$1.
onResponse(Page2.java:89)
12-08 12:49:03.514 2245-2245/? W/System.err:     at
com.android.volley.toolbox.StringRequest.
deliverResponse(StringRequest.java:67)
12-08 12:49:03.514 2245-2245/? W/System.err:     at

com.android.volley.toolbox.StringRequest.
deliverResponse(StringRequest.java:30)
12-08 12:49:03.514 2245-2245/? W/System.err:     at

   com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable
  .run(ExecutorDelivery.java:99)
  12-08 12:49:03.514 2245-2245/? W/System.err:     at
  android.os.Handler.handleCallback(Handler.java:751)
  12-08 12:49:03.514 2245-2245/? W/System.err:     at
  android.os.Handler.dispatchMessage(Handler.java:95)
  12-08 12:49:03.514 2245-2245/? W/System.err:     at
  android.os.Looper.loop(Looper.java:154)
  12-08 12:49:03.514 2245-2245/? W/System.err:     at
 android.app.ActivityThread.main(ActivityThread.java:6077)
 12-08 12:49:03.514 2245-2245/? W/System.err:     at
 java.lang.reflect.Method.invoke(Native Method)
  12-08 12:49:03.514 2245-2245/? W/System.err:     at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.
  run(ZygoteInit.java:866)
  12-08 12:49:03.514 2245-2245/? W/System.err:     at
  com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
 12-08 12:49:06.079 1586-1596/? I/ActivityManager: Killing
 3211:com.android.gallery3d/u0a49 (adj 906): empty #17

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class Page2 extends AppCompatActivity {

private EditText emailI,passwordI;

DrawerLayout drawerLayout;
Toolbar toolbar;
ActionBarDrawerToggle actionBarDrawerToggle;
FragmentTransaction fragmentTransaction;
NavigationView navigationView;

Button pauseIn;
EditText pause;

private RequestQueue requestQueue;
private static final String URL = "http://10.31.16.22/pause_in.php";
private StringRequest request;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.page2_activity);

    emailI=(EditText)findViewById(R.id.emailiImprovizum);
    passwordI=(EditText)findViewById(R.id.passImprovizum);

    pauseIn = (Button) findViewById(R.id.btnPauseIn);
    pauseIn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            request = new StringRequest(Request.Method.POST, URL, new
    Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                         JSONObject jsonObject = new
     JSONObject(response);
                        if
     (jsonObject.names().get(0).equals("success1")) {
                          //  Log.d("dfr","a po bon");
                            Toast.makeText(getApplicationContext(),
      "SUCCESS " + jsonObject.getString("success1"),
      Toast.LENGTH_SHORT).show();

                            Intent intent = getIntent();
                            String e = intent.getStringExtra("Email");
                            String p =
       intent.getStringExtra("Password");

                            emailI.setText(e);
                            passwordI.setText(p);

                            startActivity(new
        Intent(getApplicationContext(), about.class));

                        } else if
       (jsonObject.names().get(0).equals("fail1")) {
                            Toast.makeText(getApplicationContext(),
     "Error" + jsonObject.getString("fail1"),
     Toast.LENGTH_SHORT).show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }){
                @Override
                protected Map<String, String> getParams() throws
         AuthFailureError {
                    HashMap<String,String> hashMap = new
          HashMap<String, String>();
                    hashMap.put("pause_in","pauseIn");

                    hashMap.put("emailI",emailI.getText().ToString());

               hashMap.put("passwordI",password.getText().ToString());

                    return hashMap;
                }
            };

            requestQueue.add(request);
            Log.d("key","valuee");
        }
    });

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    drawerLayout = (DrawerLayout) findViewById(R.id.drawableT);
    actionBarDrawerToggle = new ActionBarDrawerToggle(this,
    drawerLayout, toolbar,
            R.string.drawer_open, R.string.drawer_close);

actionBarDrawerToggle.getDrawerArrowDrawable().setColor(getResources()
.getColor(R.color.white));

    drawerLayout.addDrawerListener(actionBarDrawerToggle);

    fragmentTransaction =
 getSupportFragmentManager().beginTransaction();

    fragmentTransaction.commit();

    navigationView = (NavigationView)
findViewById(R.id.navigation_view);
    navigationView.setNavigationItemSelectedListener(new
 NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item)
  {

            switch (item.getItemId()) {

                case R.id.about_id:
                    Intent i = new Intent(Page2.this, about.class);
                    startActivity(i);

                    break;

                case R.id.id_instructions:

                    Intent i3 = new Intent(Page2.this, about.class);
                    startActivity(i3);

                    break;
            }

            return false;
        }
    });

}

@Override
protected void onPostCreate(@Nullable Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    actionBarDrawerToggle.syncState();
    }
}

<?php
include_once 'connection.php';

class User1{

private $db;
private $connection;

function __construct() {
        $this -> db = new DB_Connection();
        $this -> connection = $this->db->getConnection();
    }

public function pause($email,$password)
    {
        $pauseIn=time();
        $query = "Select * from users where email='$email' and password
     ='$password'";

        $result = mysqli_query($this->connection, $query);
        if(mysqli_num_rows($result)>0){
        $query2="update users set pause_in='$pauseIn' where
      email='$email' ";
        $inserted = mysqli_query($this -> connection, $query2);
        if($inserted ==1 )
        {
            $json['success1'] = 'welcome';
            echo json_encode($json);
            mysqli_close($this -> connection);
        }
        else{

                $json['fail1'] = ': Email or password is wrong';

            echo json_encode($json);

        }

             }

        }
   }
   $user = new User1();

   if(isset($_POST['email'],$_POST['password'])) {
    $email=$_POST['email'];
    $password=$_POST['password'];

    $user-> pause($email,$password);

        }
        else{

        }
    ?>
</code>```

答:
you are forget to initialize private StringRequest request; in onCreate();
like below code

```<code> RequestQueue mRequestQueue;

// Instantiate the cache
Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap

// Set up the network to use HttpURLConnection as the HTTP client.
Network network = new BasicNetwork(new HurlStack());

// Instantiate the RequestQueue with the cache and network.
mRequestQueue = new RequestQueue(cache, network);

// Start the queue
mRequestQueue.start();
</code>```

for more info check this link.

Body:
I am working in a Page2 activity in Android Studio and I am using php file pause_in, below is java code using Volley class.It gives me the error:
java.lang.NullPointerException:
Attempt to invoke virtual method 'com.android.volley.Request com.android.volley.RequestQueue.add(com.android.volley.Request)' on a null object reference.
But after I have added the line for initializing the request,it gives me that:(I have to mention that I used getExtra method to get the variables of email and password from the first screen).

12-08 12:49:03.446 1346-1370/? W/audio_hw_generic: Not supplying enough
data to HAL, expected position 455229 , only wrote 455040
12-08 12:49:03.446 2245-2245/? D/key: valuee
12-08 12:49:03.514 2245-2245/? W/System.err: org.json.JSONException:
End of input at character 1 of
12-08 12:49:03.514 2245-2245/? W/System.err:     at
org.json.JSONTokener.syntaxError(JSONTokener.java:449)
12-08 12:49:03.514 2245-2245/? W/System.err:     at
org.json.JSONTokener.nextValue(JSONTokener.java:97)
12-08 12:49:03.514 2245-2245/? W/System.err:     at
org.json.JSONObject.<init>(JSONObject.java:156)
12-08 12:49:03.514 2245-2245/? W/System.err:     at
org.json.JSONObject.<init>(JSONObject.java:173)
12-08 12:49:03.514 2245-2245/? W/System.err:     at
com.example.a.mysql_php_register_login.Page2$1$1.
onResponse(Page2.java:96)
12-08 12:49:03.514 2245-2245/? W/System.err:     at
com.example.a.mysql_php_register_login.Page2$1$1.
onResponse(Page2.java:89)
12-08 12:49:03.514 2245-2245/? W/System.err:     at
com.android.volley.toolbox.StringRequest.
deliverResponse(StringRequest.java:67)
12-08 12:49:03.514 2245-2245/? W/System.err:     at

com.android.volley.toolbox.StringRequest.
deliverResponse(StringRequest.java:30)
12-08 12:49:03.514 2245-2245/? W/System.err:     at

   com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable
  .run(ExecutorDelivery.java:99)
  12-08 12:49:03.514 2245-2245/? W/System.err:     at
  android.os.Handler.handleCallback(Handler.java:751)
  12-08 12:49:03.514 2245-2245/? W/System.err:     at
  android.os.Handler.dispatchMessage(Handler.java:95)
  12-08 12:49:03.514 2245-2245/? W/System.err:     at
  android.os.Looper.loop(Looper.java:154)
  12-08 12:49:03.514 2245-2245/? W/System.err:     at
 android.app.ActivityThread.main(ActivityThread.java:6077)
 12-08 12:49:03.514 2245-2245/? W/System.err:     at
 java.lang.reflect.Method.invoke(Native Method)
  12-08 12:49:03.514 2245-2245/? W/System.err:     at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.
  run(ZygoteInit.java:866)
  12-08 12:49:03.514 2245-2245/? W/System.err:     at
  com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
 12-08 12:49:06.079 1586-1596/? I/ActivityManager: Killing
 3211:com.android.gallery3d/u0a49 (adj 906): empty #17

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class Page2 extends AppCompatActivity {

private EditText emailI,passwordI;

DrawerLayout drawerLayout;
Toolbar toolbar;
ActionBarDrawerToggle actionBarDrawerToggle;
FragmentTransaction fragmentTransaction;
NavigationView navigationView;

Button pauseIn;
EditText pause;

private RequestQueue requestQueue;
private static final String URL = "http://10.31.16.22/pause_in.php";
private StringRequest request;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.page2_activity);

    emailI=(EditText)findViewById(R.id.emailiImprovizum);
    passwordI=(EditText)findViewById(R.id.passImprovizum);

    pauseIn = (Button) findViewById(R.id.btnPauseIn);
    pauseIn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            request = new StringRequest(Request.Method.POST, URL, new
    Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                         JSONObject jsonObject = new
     JSONObject(response);
                        if
     (jsonObject.names().get(0).equals("success1")) {
                          //  Log.d("dfr","a po bon");
                            Toast.makeText(getApplicationContext(),
      "SUCCESS " + jsonObject.getString("success1"),
      Toast.LENGTH_SHORT).show();

                            Intent intent = getIntent();
                            String e = intent.getStringExtra("Email");
                            String p =
       intent.getStringExtra("Password");

                            emailI.setText(e);
                            passwordI.setText(p);

                            startActivity(new
        Intent(getApplicationContext(), about.class));

                        } else if
       (jsonObject.names().get(0).equals("fail1")) {
                            Toast.makeText(getApplicationContext(),
     "Error" + jsonObject.getString("fail1"),
     Toast.LENGTH_SHORT).show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }){
                @Override
                protected Map<String, String> getParams() throws
         AuthFailureError {
                    HashMap<String,String> hashMap = new
          HashMap<String, String>();
                    hashMap.put("pause_in","pauseIn");

                    hashMap.put("emailI",emailI.getText().ToString());

               hashMap.put("passwordI",password.getText().ToString());

                    return hashMap;
                }
            };

            requestQueue.add(request);
            Log.d("key","valuee");
        }
    });

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    drawerLayout = (DrawerLayout) findViewById(R.id.drawableT);
    actionBarDrawerToggle = new ActionBarDrawerToggle(this,
    drawerLayout, toolbar,
            R.string.drawer_open, R.string.drawer_close);

actionBarDrawerToggle.getDrawerArrowDrawable().setColor(getResources()
.getColor(R.color.white));

    drawerLayout.addDrawerListener(actionBarDrawerToggle);

    fragmentTransaction =
 getSupportFragmentManager().beginTransaction();

    fragmentTransaction.commit();

    navigationView = (NavigationView)
findViewById(R.id.navigation_view);
    navigationView.setNavigationItemSelectedListener(new
 NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item)
  {

            switch (item.getItemId()) {

                case R.id.about_id:
                    Intent i = new Intent(Page2.this, about.class);
                    startActivity(i);

                    break;

                case R.id.id_instructions:

                    Intent i3 = new Intent(Page2.this, about.class);
                    startActivity(i3);

                    break;
            }

            return false;
        }
    });

}

@Override
protected void onPostCreate(@Nullable Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    actionBarDrawerToggle.syncState();
    }
}

<?php
include_once 'connection.php';

class User1{

private $db;
private $connection;

function __construct() {
        $this -> db = new DB_Connection();
        $this -> connection = $this->db->getConnection();
    }

public function pause($email,$password)
    {
        $pauseIn=time();
        $query = "Select * from users where email='$email' and password
     ='$password'";

        $result = mysqli_query($this->connection, $query);
        if(mysqli_num_rows($result)>0){
        $query2="update users set pause_in='$pauseIn' where
      email='$email' ";
        $inserted = mysqli_query($this -> connection, $query2);
        if($inserted ==1 )
        {
            $json['success1'] = 'welcome';
            echo json_encode($json);
            mysqli_close($this -> connection);
        }
        else{

                $json['fail1'] = ': Email or password is wrong';

            echo json_encode($json);

        }

             }

        }
   }
   $user = new User1();

   if(isset($_POST['email'],$_POST['password'])) {
    $email=$_POST['email'];
    $password=$_POST['password'];

    $user-> pause($email,$password);

        }
        else{

        }
    ?>

Body:
you are forget to initialize private StringRequest request; in onCreate();
like below code

 RequestQueue mRequestQueue;

// Instantiate the cache
Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap

// Set up the network to use HttpURLConnection as the HTTP client.
Network network = new BasicNetwork(new HurlStack());

// Instantiate the RequestQueue with the cache and network.
mRequestQueue = new RequestQueue(cache, network);

// Start the queue
mRequestQueue.start();

for more info check this link.


问:
how to let jacoco know sources/classes are outside the module
Module A is a separate module having all the integration tests. Maven-Jacoco-Sonar works fine, if sources and tests are located at one module.

Since module A is a different module altogether, we couldn't be able to generate the jacoco reports easily. Because, jacoco is unable to find the sources within module A to measure the coverage for report. Source files are all residing at different modules. jacoco needs to have the class files and source files available in order to generate a report. We need to link up them to module A accordingly while generating the jacoco report so that, jacoco-it.exec can be easily pulled to Sonar to display the coverage analysis.

Currently in this case,
Classes triggered according to the jacoco agent but no source/class files available

Please help me if anyone has as solution how to achieve the above functionality. It would be so helpful to me.

答:
try adding the following as your main src

```<code> def debugTree = [fileTree(dir: "${buildDir}/intermediates/classes/debug", excludes: fileFilter),
                 fileTree(dir: "${project(":your_module_name").projectDir}/build/intermediates/classes/debug", excludes: fileFilter)]
 def mainsrc = [fileTree(dir:"${project(":your_module_name").projectDir}/src/main/java"),
                     fileTree(dir:"${project.projectDir}/src/main/java")]
 sourceDirectories = files(mainsrc)
 classDirectories = files(debugTree)
</code>```

This will include your external sub module files to be used while creating the jacoco report.

Body:
try adding the following as your main src

 def debugTree = [fileTree(dir: "${buildDir}/intermediates/classes/debug", excludes: fileFilter),
                 fileTree(dir: "${project(":your_module_name").projectDir}/build/intermediates/classes/debug", excludes: fileFilter)]
 def mainsrc = [fileTree(dir:"${project(":your_module_name").projectDir}/src/main/java"),
                     fileTree(dir:"${project.projectDir}/src/main/java")]
 sourceDirectories = files(mainsrc)
 classDirectories = files(debugTree)

This will include your external sub module files to be used while creating the jacoco report.


问:
How to load logistic regression model?
I want to train the logistic regression model using Apache Spark in Java. As first step I would like to train the model just once and save the model parameters (intercept and Coefficient). Subsequently use the saved model parameters to score at a later point in time. I am able to save the model in parquet file, using the following code

```<code>LogisticRegressionModel trainedLRModel = logReg.fit(data);
trainedLRModel.write().overwrite().save("mypath");
</code>```

When I load the model to score, I get the following error.

```<code>LogisticRegression lr = new LogisticRegression();
lr.load("//saved_model_path");

Exception in thread "main" java.lang.NoSuchMethodException: org.apache.spark.ml.classification.LogisticRegressionModel.<init>(java.lang.String)
    at java.lang.Class.getConstructor0(Class.java:3082)
    at java.lang.Class.getConstructor(Class.java:1825)
    at org.apache.spark.ml.util.DefaultParamsReader.load(ReadWrite.scala:325)
    at org.apache.spark.ml.util.MLReadable$class.load(ReadWrite.scala:215)
    at org.apache.spark.ml.classification.LogisticRegression$.load(LogisticRegression.scala:672)
    at org.apache.spark.ml.classification.LogisticRegression.load(LogisticRegression.scala)
</code>```

Is there a way to train and save model and then evaluate(score) later? I am using Spark ML 2.1.0 in Java.

答:
TL;DR Use LogisticRegressionModel.load.

load(path: String): LogisticRegressionModel Reads an ML instance from the input path, a shortcut of read.load(path).

As a matter of fact, as of Spark 2.0.0, the recommended approach to use Spark MLlib, incl. LogisticRegression estimator, is using the brand new and shiny Pipeline API.

```<code>import org.apache.spark.ml.classification._
val lr = new LogisticRegression()

import org.apache.spark.ml.feature._
val tok = new Tokenizer().setInputCol("body")
val hashTF = new HashingTF().setInputCol(tok.getOutputCol).setOutputCol("features")

import org.apache.spark.ml._
val pipeline = new Pipeline().setStages(Array(tok, hashTF, lr))

// training dataset
val emails = Seq(("hello world", 1)).toDF("body", "label")

val model = pipeline.fit(emails)

model.write.overwrite.save("mypath")
val loadedModel = PipelineModel.load("mypath")
</code>```

Title: How to load logistic regression model?

Body:
I want to train the logistic regression model using Apache Spark in Java. As first step I would like to train the model just once and save the model parameters (intercept and Coefficient). Subsequently use the saved model parameters to score at a later point in time. I am able to save the model in parquet file, using the following code

LogisticRegressionModel trainedLRModel = logReg.fit(data);
trainedLRModel.write().overwrite().save("mypath");

When I load the model to score, I get the following error.

LogisticRegression lr = new LogisticRegression();
lr.load("//saved_model_path");

Exception in thread "main" java.lang.NoSuchMethodException: org.apache.spark.ml.classification.LogisticRegressionModel.<init>(java.lang.String)
    at java.lang.Class.getConstructor0(Class.java:3082)
    at java.lang.Class.getConstructor(Class.java:1825)
    at org.apache.spark.ml.util.DefaultParamsReader.load(ReadWrite.scala:325)
    at org.apache.spark.ml.util.MLReadable$class.load(ReadWrite.scala:215)
    at org.apache.spark.ml.classification.LogisticRegression$.load(LogisticRegression.scala:672)
    at org.apache.spark.ml.classification.LogisticRegression.load(LogisticRegression.scala)

Is there a way to train and save model and then evaluate(score) later? I am using Spark ML 2.1.0 in Java.

Body:
TL;DR Use LogisticRegressionModel.load.

load(path: String): LogisticRegressionModel Reads an ML instance from the input path, a shortcut of read.load(path).

As a matter of fact, as of Spark 2.0.0, the recommended approach to use Spark MLlib, incl. LogisticRegression estimator, is using the brand new and shiny Pipeline API.

import org.apache.spark.ml.classification._
val lr = new LogisticRegression()

import org.apache.spark.ml.feature._
val tok = new Tokenizer().setInputCol("body")
val hashTF = new HashingTF().setInputCol(tok.getOutputCol).setOutputCol("features")

import org.apache.spark.ml._
val pipeline = new Pipeline().setStages(Array(tok, hashTF, lr))

// training dataset
val emails = Seq(("hello world", 1)).toDF("body", "label")

val model = pipeline.fit(emails)

model.write.overwrite.save("mypath")
val loadedModel = PipelineModel.load("mypath")


问:
Trying to get an XML file with attached styles on an XSL file with Angular does not seem to work

Im trying to fetch the data of an XML file that is stored under assets folder.
i have included in the assets folder an XSL file with all the styles that i want to apply on the XML file. and in fact when i preview it directly on the browser it works.
but what i want is to fetch the data with http.get from the assets folder, and then it only gives me the data without the styles.

What's happening?

答: If you're using an <?xml-stylesheet?> processing instruction in the XML instances, then browsers will use that as a signal to transform the XML using the specified stylesheet, but server-side software generally will return the XML document "as is" unless you somehow instruct it to do otherwise. It's easy enough to set things up on the server to do the transformation, but the exact way of doing it depends on what technology you are using server-side.


问:
Using software from a c++ program
I downloaded a c++ program for a software that i want to use, with the following directories :
CHANGELOG  LICENSE  README.md  build  doc  include  src

The code is a bit old , and i want to compile it from a linux terminal , i know that i have to use gcc and make for that( that's all the install details says) but the src directories containing cpp files doesnt have a 'main.cpp' file , the build contains one file : Makefile
What are the steps to follow to use this software , and how can i compile this with no main.cpp
I'm using gcc version 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04.3) and GNU Make 3.81 ; but the program is a bit old ( 2011)

答:
Without testing, could you try something like:</p>

```<code>$ apt install cmake make gcc g++
$ cd build
$ cmake .
$ make .
$ make install
</code>```

Title: Using software from a c++ program

Body:
Without testing, could you try something like:

$ apt install cmake make gcc g++
$ cd build
$ cmake .
$ make .
$ make install


问:
@MappedSuperclass and @OneToMany
I need association @OneToMany from Country to superclass Place (@MappedSuperclass). It could be bidirectional. I would need something like @OneToAny.

```<code>@MappedSuperclass
public class Place {

    private String name;
    private Country country;

    @Column
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @ManyToOne
    @JoinColumn(name="country_id")
    public Country getCountry() {
        return country;
    }

    public void setCountry(Country country) {
        this.country = country;
    }
}
</code>```

Country:

```<code>@Entity
   public class Country {
   private long id;
   private String name;
   private List<Place> places;

   @Any(metaColumn = @Column(name = "place_type"), fetch = FetchType.EAGER)
   @AnyMetaDef(idType = "integer", metaType = "string", metaValues = {
         @MetaValue(value = "C", targetEntity = City.class),
         @MetaValue(value = "R", targetEntity = Region.class) })
   @Cascade({ org.hibernate.annotations.CascadeType.ALL })
   //@JoinColumn(name="unnecessary")
   //@OneToMany(mappedBy="country")  // if this, NullPointerException...
   public List<Place> getPlaces() {
      return places;
   }
//and rest of class
</code>```

Without @JoinColunm there is an exception:

Caused by: org.hibernate.AnnotationException: @Any requires an explicit @JoinColumn(s): tour.spring.bc.model.vo.Country.places

In table City and Region is foreign key to table Country (Region.country_id, City.country_id) which is ok.
But I do NOT need foreign key in table Country to tables Region and City so I don't need @JoinColum.

What can I do?

答:
@Any doesn't make sense here since foreign key is at the Places side and therefore it doesn't need additional meta column.

I'm not sure if it's possible to create a polymorphic relationship to @MappedSuperclass. However, you can try to declare Place as @Entity @Inheritance(InheritanceType.TABLE_PER_CLASS), it should produce the same database schema and allow polymorpic relationship.

ContentLicense: CC BY-SA 4.0

Title: @MappedSuperclass and @OneToMany

Body:
I need association @OneToMany from Country to superclass Place (@MappedSuperclass). It could be bidirectional. I would need something like @OneToAny.

@MappedSuperclass
public class Place {

    private String name;
    private Country country;

    @Column
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @ManyToOne
    @JoinColumn(name="country_id")
    public Country getCountry() {
        return country;
    }

    public void setCountry(Country country) {
        this.country = country;
    }
}

Country:

@Entity
   public class Country {
   private long id;
   private String name;
   private List<Place> places;

   @Any(metaColumn = @Column(name = "place_type"), fetch = FetchType.EAGER)
   @AnyMetaDef(idType = "integer", metaType = "string", metaValues = {
         @MetaValue(value = "C", targetEntity = City.class),
         @MetaValue(value = "R", targetEntity = Region.class) })
   @Cascade({ org.hibernate.annotations.CascadeType.ALL })
   //@JoinColumn(name="unnecessary")
   //@OneToMany(mappedBy="country")  // if this, NullPointerException...
   public List<Place> getPlaces() {
      return places;
   }
//and rest of class

Without @JoinColunm there is an exception:

Caused by: org.hibernate.AnnotationException: @Any requires an explicit @JoinColumn(s): tour.spring.bc.model.vo.Country.places

In table City and Region is foreign key to table Country (Region.country_id, City.country_id) which is ok.
But I do NOT need foreign key in table Country to tables Region and City so I don't need @JoinColum.

What can I do?