问:
Resizing WPF Prism Regions
In a WPF Prism app, I have two separate views in two separate regions, say LeftRegion and RightRegion. I would like to be able to drag the edge of LeftRegion (ie. the view in LeftRegion) like a gridsplitter works. Any ideas on how to accomplish this? Thank you.

EDIT:  Here is the ShellView.xaml called by bootstrapper.cs that defines the regions.

```<code><Grid >
 <Grid.RowDefinitions>
 <RowDefinition Height ="*"/>
 </Grid.RowDefinitions>
 <Grid.ColumnDefinitions>
 <ColumnDefinition Width="215"/>
  <ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ContentControl  Grid.Column ="0" Height ="500" prism:RegionManager.RegionName="LeftRegion" />
<GridSplitter Grid.Column ="0" Width="5" HorizontalAlignment="Right" VerticalAlignment="Stretch" ResizeBehavior="CurrentAndNext"/>
<ContentControl Grid.Column="1" Height ="400" prism:RegionManager.RegionName="RightRegion" />
</Grid>
</code>```

答:
Since Prism regions are nothing but UIElements, typically ContentPresenters, you should be able to use a GridSplitter as usual:

```<code><Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp2"
        prism:RegionManager.RegionName="LeftRegion"
        mc:Ignorable="d"
        Title="MainWindow" Height="300" Width="300">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="50" />
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>

        <ContentControl prism:RegionManager.RegionName="LeftRegion" />

        <GridSplitter Grid.Column="1" Width="5" HorizontalAlignment="Stretch" />

        <ContentControl Grid.Column="2" prism:RegionManager.RegionName="RightRegion" />
    </Grid>
</Window>
</code>```

Title: Resizing WPF Prism Regions

Body:
In a WPF Prism app, I have two separate views in two separate regions, say LeftRegion and RightRegion. I would like to be able to drag the edge of LeftRegion (ie. the view in LeftRegion) like a gridsplitter works. Any ideas on how to accomplish this? Thank you.

EDIT:  Here is the ShellView.xaml called by bootstrapper.cs that defines the regions.

<Grid >
 <Grid.RowDefinitions>
 <RowDefinition Height ="*"/>
 </Grid.RowDefinitions>
 <Grid.ColumnDefinitions>
 <ColumnDefinition Width="215"/>
  <ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ContentControl  Grid.Column ="0" Height ="500" prism:RegionManager.RegionName="LeftRegion" />
<GridSplitter Grid.Column ="0" Width="5" HorizontalAlignment="Right" VerticalAlignment="Stretch" ResizeBehavior="CurrentAndNext"/>
<ContentControl Grid.Column="1" Height ="400" prism:RegionManager.RegionName="RightRegion" />
</Grid>

Body:
Since Prism regions are nothing but UIElements, typically ContentPresenters, you should be able to use a GridSplitter as usual:

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp2"
        prism:RegionManager.RegionName="LeftRegion"
        mc:Ignorable="d"
        Title="MainWindow" Height="300" Width="300">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="50" />
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>

        <ContentControl prism:RegionManager.RegionName="LeftRegion" />

        <GridSplitter Grid.Column="1" Width="5" HorizontalAlignment="Stretch" />

        <ContentControl Grid.Column="2" prism:RegionManager.RegionName="RightRegion" />
    </Grid>
</Window>


来源: stackexchange

问:
postman testing on 'response body contains string' does not work
To narrow down the problem, I change the response body into something as simple as one sentence as text/plain.

```<code>this is a test
</code>```

However, the following very basic function still fails:

```<code>tests["Body matches string"] = responseBody.has("this");
</code>```

Ironically this test works:

```<code>tests["Body matches string"] = responseBody.has("t");
</code>```

I am using the latest postman v4.11.1. It looks like a fundamental defect for postman.

答: it turns out that postman does not support unicode. if i change the encoding to utf-8, everything works perfectly. </p>

ContentLicense: CC BY-SA 3.0

Body:
To narrow down the problem, I change the response body into something as simple as one sentence as text/plain.

this is a test

However, the following very basic function still fails:

tests["Body matches string"] = responseBody.has("this");

Ironically this test works:

tests["Body matches string"] = responseBody.has("t");

I am using the latest postman v4.11.1. It looks like a fundamental defect for postman.


问:
Wrong button size
I have DialogFragment layout:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="@color/white"
android:orientation="vertical"
android:paddingTop="21dp"
android:paddingLeft="24dp"
android:paddingRight="8dp"
android:paddingBottom="8dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
    android:text="@string/lbl_why_go_away"
    android:textStyle="bold"
    android:textColor="@color/whyGoAwayCaption"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="@dimen/fontHuge"
    android:layout_marginBottom="5dp"
    android:layout_marginRight="18dp"
    android:layout_weight="0" />
<ListView
    android:layout_weight="1"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_marginRight="18dp"
    android:id="@+id/reasonsList" />
<EditText
    android:inputType="textMultiLine"
    android:layout_width="match_parent"
    android:layout_height="108dp"
    android:layout_marginTop="18dp"
    android:layout_marginRight="18dp"
    android:layout_marginBottom="24dp"
    android:gravity="top|left"
    android:padding="16dp"
    android:background="@drawable/cancel_dialog_your_reason_bg"
    android:hint="@string/ph_your_reason"
    android:layout_weight="0"
    android:id="@+id/otherReasonEditText" />
<LinearLayout
    android:orientation="horizontal"
    android:layout_weight="0"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="right">
    <Button
        android:background="#CCCCCC"
        android:text="@string/btn_return"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/primaryRed"
        android:drawablePadding="0dp"
        android:gravity="center_vertical"
        android:layout_margin="0dp"
        android:paddingLeft="9dp"
        android:paddingRight="9dp"
        android:paddingTop="9dp"
        android:paddingBottom="9dp"
        android:id="@+id/returnButton" />
  <Button
        android:background="#CCCCCC"
        android:text="@string/btn_ready"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="9dp"
        android:paddingRight="9dp"
        android:paddingTop="9dp"
        android:paddingBottom="9dp"
        android:drawablePadding="0dp"
        android:layout_margin="0dp"
        android:textColor="@color/primaryRed"
        android:gravity="center_vertical"
        android:id="@+id/readyButton" />
</LinearLayout>
</code>```

This looks like this (Android 4.2 Galaxy S4):

Problem with buttons size. They should have just padding 8dp around text and nothing else, but they are much bigger then text size. If i set background to @android:color/transparent view is the same. Tell me, what's wrong?

PS: Here's right view (screenshot from preview in VisualStudio)

答:
change your buttons to this pls</p>

```<code><Button
    android:id="@+id/returnButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="0dp"
    android:background="#CCCCCC"
    android:drawablePadding="0dp"
    android:gravity="center"
    android:padding="9dp"
    android:text="text" />

<Button
    android:id="@+id/readyButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="0dp"
    android:background="#CCCCCC"
    android:drawablePadding="0dp"
    android:gravity="center"
    android:padding="9dp"
    android:text="text" />
</code>```

Title: Wrong button size

Body:
I have DialogFragment layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="@color/white"
android:orientation="vertical"
android:paddingTop="21dp"
android:paddingLeft="24dp"
android:paddingRight="8dp"
android:paddingBottom="8dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
    android:text="@string/lbl_why_go_away"
    android:textStyle="bold"
    android:textColor="@color/whyGoAwayCaption"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="@dimen/fontHuge"
    android:layout_marginBottom="5dp"
    android:layout_marginRight="18dp"
    android:layout_weight="0" />
<ListView
    android:layout_weight="1"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_marginRight="18dp"
    android:id="@+id/reasonsList" />
<EditText
    android:inputType="textMultiLine"
    android:layout_width="match_parent"
    android:layout_height="108dp"
    android:layout_marginTop="18dp"
    android:layout_marginRight="18dp"
    android:layout_marginBottom="24dp"
    android:gravity="top|left"
    android:padding="16dp"
    android:background="@drawable/cancel_dialog_your_reason_bg"
    android:hint="@string/ph_your_reason"
    android:layout_weight="0"
    android:id="@+id/otherReasonEditText" />
<LinearLayout
    android:orientation="horizontal"
    android:layout_weight="0"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="right">
    <Button
        android:background="#CCCCCC"
        android:text="@string/btn_return"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/primaryRed"
        android:drawablePadding="0dp"
        android:gravity="center_vertical"
        android:layout_margin="0dp"
        android:paddingLeft="9dp"
        android:paddingRight="9dp"
        android:paddingTop="9dp"
        android:paddingBottom="9dp"
        android:id="@+id/returnButton" />
  <Button
        android:background="#CCCCCC"
        android:text="@string/btn_ready"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="9dp"
        android:paddingRight="9dp"
        android:paddingTop="9dp"
        android:paddingBottom="9dp"
        android:drawablePadding="0dp"
        android:layout_margin="0dp"
        android:textColor="@color/primaryRed"
        android:gravity="center_vertical"
        android:id="@+id/readyButton" />
</LinearLayout>

This looks like this (Android 4.2 Galaxy S4):

Problem with buttons size. They should have just padding 8dp around text and nothing else, but they are much bigger then text size. If i set background to @android:color/transparent view is the same. Tell me, what's wrong?

PS: Here's right view (screenshot from preview in VisualStudio)

Body:
change your buttons to this pls

<Button
    android:id="@+id/returnButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="0dp"
    android:background="#CCCCCC"
    android:drawablePadding="0dp"
    android:gravity="center"
    android:padding="9dp"
    android:text="text" />

<Button
    android:id="@+id/readyButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="0dp"
    android:background="#CCCCCC"
    android:drawablePadding="0dp"
    android:gravity="center"
    android:padding="9dp"
    android:text="text" />


问:
Java: Parsed XML but some things are missing
Somehow the parsed XML file seems to be wrong or am I doing something wrong?

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<root>
    <quests>
       <quest id="test">
           <question>Just a little sentence.</question>
        </quest>
    </quests>
</root>
</code>```

I parse it like that:

```<code>File file = new File("file.xml");

DocumentBuilderFactory dF = DocumentBuilderFactory.newInstance();
dF.setNamespaceAware(true);
DocumentBuilder dB = dF.newDocumentBuilder();

Document XML = dB.parse(file);

// ------------------------------------------
Element doc = XML.getDocumentElement();
System.out.println(doc.getChildNodes());

Element dx = (Element) doc.getElementsByTagName("quest").item(0);
System.out.println(dx.getAttribute("id"));
System.out.println(dx.getAttribute("id").length());
System.out.println(dx.getAttributes().getLength());
</code>```

And this is what I get:

```<code>[root: null]

0
0
</code>```

How could that be? How could I parse attributes of elements/tags/nodes?

答: I think there is a getNodeValue() or getTextContent() missing, to get the actual attribute string.</p>

ContentLicense: CC BY-SA 2.5

Body:
Somehow the parsed XML file seems to be wrong or am I doing something wrong?

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<root>
    <quests>
       <quest id="test">
           <question>Just a little sentence.</question>
        </quest>
    </quests>
</root>

I parse it like that:

File file = new File("file.xml");

DocumentBuilderFactory dF = DocumentBuilderFactory.newInstance();
dF.setNamespaceAware(true);
DocumentBuilder dB = dF.newDocumentBuilder();

Document XML = dB.parse(file);

// ------------------------------------------
Element doc = XML.getDocumentElement();
System.out.println(doc.getChildNodes());

Element dx = (Element) doc.getElementsByTagName("quest").item(0);
System.out.println(dx.getAttribute("id"));
System.out.println(dx.getAttribute("id").length());
System.out.println(dx.getAttributes().getLength());

And this is what I get:

[root: null]

0
0

How could that be? How could I parse attributes of elements/tags/nodes?


问:
How can I get a solid segmentation from a probability map?
I trained the network for my data. Once I ran this:
To see the probability map

```<code>plt.imshow(prob[1], cmap='hot', interpolation='nearest')
plt.show()
</code>```

And this is the probability map of Object 1:

How can I get the solid segmentation from the probability map (even considering those points with lower probability belonging to the class)?

Thanks

答: There are several ways to get the solid segmentation.  One is to use one of the clustering algorithms to define the area of interest.  Perhaps a simple threshold cut-off p <= (p > threshold) followed by a density-fill algorithm would suit your needs.

Body:
I trained the network for my data. Once I ran this:
To see the probability map

plt.imshow(prob[1], cmap='hot', interpolation='nearest')
plt.show()

And this is the probability map of Object 1:

How can I get the solid segmentation from the probability map (even considering those points with lower probability belonging to the class)?

Thanks


问:
gwtbootstrap3 tooltip at wrong place for pagination

This is what happens when you hover the very left item of the pagination or the very right one.

What I need to have:

That the tooltip is stick to the corresponding element when I hover it.

My code:

```<code>back = new AnchorListItem();
back.setText("Vorherige Aufgabe");
back.setIcon(IconType.CHEVRON_LEFT);
back.setIconPosition(IconPosition.LEFT);
bback.addClickHandler(new ClickHandler() {  ...some code... }
if (some_Condition){
    Tooltip tooltip = new Tooltip(back, "Diese Aufgabe hat nur eine Teilaufgabe");
    tooltip.setPlacement(Placement.TOP);
}
pagination.add(back);

.
.
.
some code
.
.
.
next = new AnchorListItem();
next.setText("Nächste Aufgabe");
next.setIcon(IconType.CHEVRON_RIGHT);
next.setIconPosition(IconPosition.RIGHT);
next.addClickHandler(new ClickHandler() { ...some code... }
if (some_Condition){
    Tooltip tooltip = new Tooltip(next, "Diese Aufgabe hat nur eine Teilaufgabe");
    tooltip.setPlacement(Placement.TOP);
}
pagination.add(next);
</code>```

Setting the Placement differently changes only in which direction the tooltip it placed, but not the origin.

I would be thankful for any hints :)

答:
Please, don't ask how I found it nor why it works, but the solution is:

Add float: left; style to AnchorListItem's
 element inside Pagination.

You can do it in your stylesheet:

```<code>.pagination li {
    float: left;
}
</code>```

Surprisingly, this is also an answer to this problem: bootstrap tooltip shifted right ;)

Body:
This is what happens when you hover the very left item of the pagination or the very right one.

What I need to have:

That the tooltip is stick to the corresponding element when I hover it.

My code:

back = new AnchorListItem();
back.setText("Vorherige Aufgabe");
back.setIcon(IconType.CHEVRON_LEFT);
back.setIconPosition(IconPosition.LEFT);
bback.addClickHandler(new ClickHandler() {  ...some code... }
if (some_Condition){
    Tooltip tooltip = new Tooltip(back, "Diese Aufgabe hat nur eine Teilaufgabe");
    tooltip.setPlacement(Placement.TOP);
}
pagination.add(back);

.
.
.
some code
.
.
.
next = new AnchorListItem();
next.setText("Nächste Aufgabe");
next.setIcon(IconType.CHEVRON_RIGHT);
next.setIconPosition(IconPosition.RIGHT);
next.addClickHandler(new ClickHandler() { ...some code... }
if (some_Condition){
    Tooltip tooltip = new Tooltip(next, "Diese Aufgabe hat nur eine Teilaufgabe");
    tooltip.setPlacement(Placement.TOP);
}
pagination.add(next);

Setting the Placement differently changes only in which direction the tooltip it placed, but not the origin.

I would be thankful for any hints :)

Body:
Please, don't ask how I found it nor why it works, but the solution is:

Add float: left; style to AnchorListItem's <li> element inside Pagination.

You can do it in your stylesheet:

.pagination li {
    float: left;
}

Surprisingly, this is also an answer to this problem: bootstrap tooltip shifted right ;)


问:
ObjectiveC AVAudioPlayer volume is 0
I've seen quite many posts about AVAudioPlayer but nones helps: I cannot get sound anymore (even though it used to work with Xcode before upgrade to 8.3.2)

Here is my code:

```<code>AVAudioPlayer *audioPlayerObj;
AVAudioSession *session;
[...]
- (IBAction)playSound:(id)sender {
audioPlayerObj.delegate = self;

if(playButton.isSelected){
    playButton.selected=NO;
    (void) [audioPlayerObj stop];
}
else{
    session = nil;
    {NSError * _error;

        session = [AVAudioSession sharedInstance];
        [session setCategory:AVAudioSessionCategoryPlayback
                       error:&_error];
        [session setActive:YES error:&_error];
        if(_error !=nil)
        {   NSLog(@"could not init the audio player session %@ ", _error);
        }

    }

    NSString * tune =[NSString stringWithFormat:@"%@.wav",[pickerViewArray objectAtIndex:[pickerView selectedRowInComponent:0]]];
    NSString *path =[[NSBundle mainBundle] pathForResource:tune ofType:@""];

    NSURL * actualFilePath= [NSURL fileURLWithPath:path];
NSError *error;

(void)[audioPlayerObj initWithContentsOfURL:actualFilePath error:&error];

    [audioPlayerObj prepareToPlay];

    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0"))
    {
    [audioPlayerObj setVolume:0.99 fadeDuration: 1];

    }
    NSLog(@"syst volume : %f", [session outputVolume]);
    NSLog(@"vol : %f\n",[audioPlayerObj volume] );

if(error !=nil)
{   NSLog(@"could not init the audio player %@ ", error);
    audioPlayerObj=nil;

}
else
{
    (void) [audioPlayerObj setNumberOfLoops:-1  ];
    (void) [audioPlayerObj play];
    NSLog(@"playing with vol : %f\n",[audioPlayerObj volume] );
    [audioPlayerObj setVolume:0.99 fadeDuration: 1];
    playButton.selected=YES;
}
}
</code>```

`

The output is

    syst volume : 0.476119
    vol : 0.000000
    playing with vol : 0.000000

Any hint on how to raise that volume would be appreciated. The view also has a MPVolumeView, but any action on it would only change the system  volume.

答:
the mistake was here:

```<code>(void)[audioPlayerObj initWithContentsOfURL:actualFilePath error:&error];
</code>```

should have been:

```<code> audioPlayerObj = [[AVAudioPlayer alloc] initWithContentsOfURL:actualFilePath error:&error];
</code>```

Title: ObjectiveC AVAudioPlayer volume is 0

Body:
I've seen quite many posts about AVAudioPlayer but nones helps: I cannot get sound anymore (even though it used to work with Xcode before upgrade to 8.3.2)

Here is my code:

AVAudioPlayer *audioPlayerObj;
AVAudioSession *session;
[...]
- (IBAction)playSound:(id)sender {
audioPlayerObj.delegate = self;

if(playButton.isSelected){
    playButton.selected=NO;
    (void) [audioPlayerObj stop];
}
else{
    session = nil;
    {NSError * _error;

        session = [AVAudioSession sharedInstance];
        [session setCategory:AVAudioSessionCategoryPlayback
                       error:&_error];
        [session setActive:YES error:&_error];
        if(_error !=nil)
        {   NSLog(@"could not init the audio player session %@ ", _error);
        }

    }

    NSString * tune =[NSString stringWithFormat:@"%@.wav",[pickerViewArray objectAtIndex:[pickerView selectedRowInComponent:0]]];
    NSString *path =[[NSBundle mainBundle] pathForResource:tune ofType:@""];

    NSURL * actualFilePath= [NSURL fileURLWithPath:path];
NSError *error;

(void)[audioPlayerObj initWithContentsOfURL:actualFilePath error:&error];

    [audioPlayerObj prepareToPlay];

    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0"))
    {
    [audioPlayerObj setVolume:0.99 fadeDuration: 1];

    }
    NSLog(@"syst volume : %f", [session outputVolume]);
    NSLog(@"vol : %f\n",[audioPlayerObj volume] );

if(error !=nil)
{   NSLog(@"could not init the audio player %@ ", error);
    audioPlayerObj=nil;

}
else
{
    (void) [audioPlayerObj setNumberOfLoops:-1  ];
    (void) [audioPlayerObj play];
    NSLog(@"playing with vol : %f\n",[audioPlayerObj volume] );
    [audioPlayerObj setVolume:0.99 fadeDuration: 1];
    playButton.selected=YES;
}
}

`

The output is

    syst volume : 0.476119
    vol : 0.000000
    playing with vol : 0.000000

Any hint on how to raise that volume would be appreciated. The view also has a MPVolumeView, but any action on it would only change the system  volume.

Body:
the mistake was here:

(void)[audioPlayerObj initWithContentsOfURL:actualFilePath error:&error];

should have been:

 audioPlayerObj = [[AVAudioPlayer alloc] initWithContentsOfURL:actualFilePath error:&error];


问:
How to fetch data from firebase in the form of ArrayList in Android
In this format i have databse in firebase.I have to display all the departments in the form of array list like Director,sports.

```<code>mAuth=FirebaseAuth.getInstance();
 mdatabase=FirebaseDatabase.getInstance().getReference().child("Department";
mdatabase.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        List<String> Department = (ArrayList<String>) dataSnapshot.getValue();
         DepartmentLIST=Department.toArray(new String[Department.size()]);

    }
   @Override
   public void onCancelled(DatabaseError databaseError) {
       Toast.makeText(CheckUpdate.this,databaseError.getMessage(),Toast.LENGTH_LONG).show();
   }

  });

setListAdapter(new ArrayAdapter(this,
        android.R.layout.simple_list_item_1,DepartmentLIST));
</code>```

}

This is my code i have used for it. But it gives NullValue.

答:
(ArrayList<String>) dataSnapshot.getValue() isn't correct.

I think you are looking for dataSnapshot.getChildren(), and / or dataSnapshot.getValue(String.class).

Note: Firebase-UI library could help you here.

Body:
In this format i have databse in firebase.I have to display all the departments in the form of array list like Director,sports.

mAuth=FirebaseAuth.getInstance();
 mdatabase=FirebaseDatabase.getInstance().getReference().child("Department";
mdatabase.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        List<String> Department = (ArrayList<String>) dataSnapshot.getValue();
         DepartmentLIST=Department.toArray(new String[Department.size()]);

    }
   @Override
   public void onCancelled(DatabaseError databaseError) {
       Toast.makeText(CheckUpdate.this,databaseError.getMessage(),Toast.LENGTH_LONG).show();
   }

  });

setListAdapter(new ArrayAdapter(this,
        android.R.layout.simple_list_item_1,DepartmentLIST));

}

This is my code i have used for it. But it gives NullValue.


问:
Node.js - console.log does not show items in array but instead shows [Object]
I have a problem with logging out the contents of an array inside an object. The actual object looks like this

```<code>   var stuff = { accepted: [ 'item1', 'item2' ],
         rejected: [],
         response: 'Foo',
         envelope: { from: 'The sender', to: ['new item1', 'new item2'] },
         messageId: 'xxxxxxxxxxxxx' } }
</code>```

The console.log shows the items of the first array fine but the second array is being output as [Object].

```<code> { accepted: [ 'item1', 'item2' ],
             rejected: [],
             response: 'Foo',
             envelope: { from: 'The sender', to: [Object] },
             messageId: 'xxxxxxxxxxxxx' } }
</code>```

What is happening here and how can I get the items of the second array to show when I console.log. Thanks for any help!

UPDATE

Sorry, I forgot to add that I am working exclusively in Node.js so it's a server side log that needs to display the object exactly as it's received from a callback with a straight console.log, ie. no further stringify-ing.

I also just tried creating another random object with a similar structure like this.

```<code> var objText = {
      fun: {
        stuff: 'Some stuff',
        list: ['this', 'it', 'takes']
      }
    };
</code>```

The console.log for the above is:

```<code>{ fun: { stuff: 'Some stuff', list: [ 'this', 'it', 'takes' ] } }
</code>```

This appears to be the same structure to me and yet the console.log works fine so it seems to be perfectly possible in Node to log arrays content even when it's embedded inside and an object inside an outer object.

答:
If you like Chrome devtools, that folds your json objects and let you observe a lot of things, you can use the --inspect flag:

```<code>node --inspect index.js
</code>```

The console will then give you an URL and you just have to copy paste in Google Chrome to enjoy Google Chrome console.

More information on this link

Body:
I have a problem with logging out the contents of an array inside an object. The actual object looks like this

   var stuff = { accepted: [ 'item1', 'item2' ],
         rejected: [],
         response: 'Foo',
         envelope: { from: 'The sender', to: ['new item1', 'new item2'] },
         messageId: 'xxxxxxxxxxxxx' } }

The console.log shows the items of the first array fine but the second array is being output as [Object].

 { accepted: [ 'item1', 'item2' ],
             rejected: [],
             response: 'Foo',
             envelope: { from: 'The sender', to: [Object] },
             messageId: 'xxxxxxxxxxxxx' } }

What is happening here and how can I get the items of the second array to show when I console.log. Thanks for any help!

UPDATE

Sorry, I forgot to add that I am working exclusively in Node.js so it's a server side log that needs to display the object exactly as it's received from a callback with a straight console.log, ie. no further stringify-ing.

I also just tried creating another random object with a similar structure like this.

 var objText = {
      fun: {
        stuff: 'Some stuff',
        list: ['this', 'it', 'takes']
      }
    };

The console.log for the above is:

{ fun: { stuff: 'Some stuff', list: [ 'this', 'it', 'takes' ] } }

This appears to be the same structure to me and yet the console.log works fine so it seems to be perfectly possible in Node to log arrays content even when it's embedded inside and an object inside an outer object.

Body:
If you like Chrome devtools, that folds your json objects and let you observe a lot of things, you can use the --inspect flag:

node --inspect index.js

The console will then give you an URL and you just have to copy paste in Google Chrome to enjoy Google Chrome console.

More information on this link


问:
Decoding gzipped http response that is inside json object
I am attemping to get data from an HTTP post using the following snippet:

```<code>import request

# Using @ to signify personal info
url = "@@@@@"

querystring = {"user":"@@@@@yahoo.com"}

headers = {
    'token': 1234,
    'content-type': "application/x-www-form-urlencoded",
    'host': "@@@",
    'connection': "Keep-Alive",
    'accept-encoding': "gzip",
    'content-length': "0",
    'cache-control': "no-cache"
}

response = requests.request("POST", url, headers=headers,     params=querystring)

print(response.text)
</code>```

I get the following result (the ... is the rest of the 'data' string):

```<code>{'data': 'H4sIAAAAAAAAAO...T7R358EQT/u3/8D+8Rtv5/DwIA', 'error_code': 0, 'response_desc': 'SUCCESS'}
</code>```

Unlike all other questions I have found on stackoverflow, the gzipped data of interest lives within a json response. The json object itself is not compressed. I have tried

```<code>zlib.decompress(response.json().get("data"),15 + 32)
</code>```

But get the error

```<code>    TypeError: a bytes-like object is required, not'str'
</code>```

Am I going about handling the decoding correctly? I see plenty of documentation on decoding a gz file but this is just a string that is gz compressed.

Additional attempt: trying

```<code>zlib.decompress(response.json().get("data").encode(), 16 + zlib.MAX_WBITS)
</code>```

Gives me the error:

```<code>incorrect header checkk
</code>```

答:
You need to convert the string into a byte array first. This can be done two ways

```<code>bytes = bytes(your_string)
</code>```

or

```<code>bytes = your_string.encode()
</code>```

Body:
I am attemping to get data from an HTTP post using the following snippet:

import request

# Using @ to signify personal info
url = "@@@@@"

querystring = {"user":"@@@@@yahoo.com"}

headers = {
    'token': 1234,
    'content-type': "application/x-www-form-urlencoded",
    'host': "@@@",
    'connection': "Keep-Alive",
    'accept-encoding': "gzip",
    'content-length': "0",
    'cache-control': "no-cache"
}

response = requests.request("POST", url, headers=headers,     params=querystring)

print(response.text)

I get the following result (the ... is the rest of the 'data' string):

{'data': 'H4sIAAAAAAAAAO...T7R358EQT/u3/8D+8Rtv5/DwIA', 'error_code': 0, 'response_desc': 'SUCCESS'}

Unlike all other questions I have found on stackoverflow, the gzipped data of interest lives within a json response. The json object itself is not compressed. I have tried

zlib.decompress(response.json().get("data"),15 + 32)

But get the error

    TypeError: a bytes-like object is required, not'str'

Am I going about handling the decoding correctly? I see plenty of documentation on decoding a gz file but this is just a string that is gz compressed.

Additional attempt: trying

zlib.decompress(response.json().get("data").encode(), 16 + zlib.MAX_WBITS)

Gives me the error:

incorrect header checkk

Body:
You need to convert the string into a byte array first. This can be done two ways

bytes = bytes(your_string)

or

bytes = your_string.encode()


问:
Call Python functions from TCL script with arguments
I have a Python script, say, sample.py with 2 functions func1() and func2():

```<code>def func1():
    print("Called Function 1")

def func2():
    print("Called Function 2")
</code>```

How do I call this function func2() from the Tcl script and also how to pass the arguments to that function?

答:
python code needs this (I called it junk.py and put it in the same folder with tcl script).

```<code>import sys

def func1():
    print("Called Function 1")

def func2():
    print("Called Function 2")

if __name__ == '__main__':
    eval(sys.argv[1] + '()')
</code>```

Tcl file called test_tcl.tcl:

```<code>set out [exec python junk.py [lindex $argv 0]]
puts $out
</code>```

Execute from command line:

```<code>tclsh test_tcl.tcl func1
</code>```

Output is:

```<code>Called Function 1
</code>```

Body:
I have a Python script, say, sample.py with 2 functions func1() and func2():

def func1():
    print("Called Function 1")

def func2():
    print("Called Function 2")

How do I call this function func2() from the Tcl script and also how to pass the arguments to that function?

Body:
python code needs this (I called it junk.py and put it in the same folder with tcl script).

import sys

def func1():
    print("Called Function 1")

def func2():
    print("Called Function 2")

if __name__ == '__main__':
    eval(sys.argv[1] + '()')

Tcl file called test_tcl.tcl:

set out [exec python junk.py [lindex $argv 0]]
puts $out

Execute from command line:

tclsh test_tcl.tcl func1

Output is:

Called Function 1


问:
UIButton returns nil
So this is my situation: I have a class:

```<code>class upgrade {
    var buttonOutlet: UIButton?
init(buttonOutlet: UIButton?) {
self.buttonOutlet = buttonOutlet }
}
</code>```

Then, I have one upgrade:

```<code>var upgrade1 = upgrade.init(buttonOutlet: nil)`
</code>```

Obviously, I can't set the 'buttonOutlet' at that point.
So I have a function that sets it for me when needed:

```<code>func setBO() {
upgrade1.buttonOutlet?  = buttonOutletForUpgrade1
}
</code>```

This "buttonOutletForUpgrade1" is an outlet from a button I created earlier.
I want to be able to set the button's title after calling 'setBO'. However, it doesn't do anything!
When I run the code, my upgrade1.buttonOutlet returns nil. How can this be? Didn't I set it right? Please explain!
Thanks!

答:
Change your code as follows and it works. Tested before and after and it works. </p>

```<code>func setBO() {
    upgrade1.buttonOutlet = buttonOutletForUpgrade1
}
</code>```

<p>Don't add a question mark at the end. </p>

Title: UIButton returns nil

Body:
So this is my situation: I have a class:

class upgrade {
    var buttonOutlet: UIButton?
init(buttonOutlet: UIButton?) {
self.buttonOutlet = buttonOutlet }
}

Then, I have one upgrade:

var upgrade1 = upgrade.init(buttonOutlet: nil)`

Obviously, I can't set the 'buttonOutlet' at that point.
So I have a function that sets it for me when needed:

func setBO() {
upgrade1.buttonOutlet?  = buttonOutletForUpgrade1
}

This "buttonOutletForUpgrade1" is an outlet from a button I created earlier.
I want to be able to set the button's title after calling 'setBO'. However, it doesn't do anything!
When I run the code, my upgrade1.buttonOutlet returns nil. How can this be? Didn't I set it right? Please explain!
Thanks!

Body:
Change your code as follows and it works. Tested before and after and it works.

func setBO() {
    upgrade1.buttonOutlet = buttonOutletForUpgrade1
}

Don't add a question mark at the end.


问:
How to tell if hex value is negative?
I have just learned how to read hexadecimal values. Until now, I was only reading them as positive numbers. I heard you could also write negative hex values.

My issue is that I can't tell if a value is negative or positive.
I found a few explanations here and there but if I try to verify them by using online hex to decimal converters, they always give me different results.

Sources I found:

https://stackoverflow.com/a/5827491/5016201

https://coderanch.com/t/246080/java-programmer-OCPJP/certification/Negative-Hexadecimal-number

If I understand correctly it means that:
 If a hex value written with all its bits having something > 7 as its first hex digit, it is negative.

All 'F' at the beginning or the first digit means is that the value is negative, it is not calculated.

For exemple if the hex value is written in 32 bits:

FFFFF63C  => negative ( -2500 ?)

844fc0bb  => negative ( -196099909 ?)

F44fc0bb  => negative ( -196099909 ?)

FFFFFFFF  => negative ( -1 ?)

7FFFFFFF  => positive

Am I correct? If not, could you tell me what I am not getting right?

答:
From what I understand, you always need to look at the left-most digit to tell the sign. If in hex, then anything from 0-7 is positive and 8-f is negative. Alternatively, you can convert from hex to binary, and if there's a 1 in the left-most digit, then the number is negative.

HEX <->  BINARY   <->  SIGN

0-7  <-> 0000-0111 <->  pos

8-F <->  1000-1111  <-> neg

ContentLicense: CC BY-SA 4.0

Title: How to tell if hex value is negative?


问:
Understanding docker swarm in terms of high availability
I am currently trying to understand what would be necessary to create a docker swarm to make some service highly available. I read through a lot of the docker swarm documentation, but if my understanding is correct, docker swarm will just execute a service on any host. What would happen if a host fails? Would the swarm manager restart the service(s) running on that host/node on another one? Is there any better explanation of this than in the original documentation found here?</p>

答:
Nothing more complex than that really. Like it says, Swarm (and kubernetes, and most other tooling in this space) is declarative, which means that you tell it the state that you want (i.e. 'I want 4 instances of redis') and Swarm will converge the system to that state. If you have 3 nodes, then it will schedule 1 redis on Node 1, 1 on Node 2, and 2 on Node 3. If Node 2 dies, then the system is now not 'compliant' with your declared state, and Swarm will schedule another redis on Node 1 or 3 (depending on strategy, etc...).

Now this dynamism of container / task / instance scheduling brings another problem, discovery. Swarm deals with this by maintaining an internal DNS registry and by creating VIP (virtual IPs) for each service. Instead of having to address / keep track of each redis instance, I can instead point to a service alias and Swarm will automatically route traffic to where it needs to go.

Of course there are also other considerations:

Can your service support multiple backend instances? Is it stateless? Sessions? Cache? Etc...

What is 'HA'? Multi-node? Multi-AZ? Multi-region? Etc...


问:
using wildcards in batch files in windows
Well, simple batch file question :

```<code>md "03 Explore\Music\Explore\"
move  * "03 Explore\Music\Explore"
</code>```

works but moves also the bat !

```<code>move  *.mp3 "03 Explore\Music\Explore"
</code>```

does not work.

答:
SOLVED :</p>

```<code>move  *.mp3 "03 Explore\Music\Explore\"
</code>```

Body:
Well, simple batch file question :

md "03 Explore\Music\Explore\"
move  * "03 Explore\Music\Explore"

works but moves also the bat !

move  *.mp3 "03 Explore\Music\Explore"

does not work.

Body:
SOLVED :

move  *.mp3 "03 Explore\Music\Explore\"


问:
Overwriting the default case class constructor (Scala)
If I have a case class:

```<code>case class NonNegativeInt(i: Int)
</code>```

where the field i to be set to 0 if the parameter is negative. So I cannot just use the default constructor provided by the case class. If I define an apply() method in the companion object (or wherever):

```<code>def apply(n: Int) = new NonNegativeInt(Math.max(0, n))
</code>```

Apparently they have the same signature. Is there a practical way/pattern to process the constraints on the fields?

答:
```<code>case class NonNegativeInt(i: Int)
</code>```

If you can't use apply just name it something else.

```<code>object NonNegativeInt {
  def fromInt(i: Int): NonNegativeInt = NonNegativeInt(Math.max(0, i)
}
</code>```

You can get fancier if you like, typecheck literal constants with compile time restrictions on positive ints with Refined or shapeless, hide the primary constructor by sealing the case class or other such means, but it feels a bit overkill under the circumstances.

Body:
If I have a case class:

case class NonNegativeInt(i: Int)

where the field i to be set to 0 if the parameter is negative. So I cannot just use the default constructor provided by the case class. If I define an apply() method in the companion object (or wherever):

def apply(n: Int) = new NonNegativeInt(Math.max(0, n))

Apparently they have the same signature. Is there a practical way/pattern to process the constraints on the fields?

Body:
case class NonNegativeInt(i: Int)

If you can't use apply just name it something else.

object NonNegativeInt {
  def fromInt(i: Int): NonNegativeInt = NonNegativeInt(Math.max(0, i)
}

You can get fancier if you like, typecheck literal constants with compile time restrictions on positive ints with Refined or shapeless, hide the primary constructor by sealing the case class or other such means, but it feels a bit overkill under the circumstances.


问:
Return two pointers from a function in c
I know that you can return a pointer to the first element of an array in c by doing:

```<code>#include <stdlib.h>
#include <stdio.h>

int *my_func(void);

int main(void)
{
    int *a;
    int i;

    a = my_func();

    for(i = 0; i < 3; i++)
    {
        printf("a[%d] = %d\n", i, a[i]);
    }

    free(a);

    return 0;
}

int *my_func(void)
{
    int *array;
    int i;

    array = calloc(3, sizeof(int));

    for(i = 0; i < 3; i++)
    {
        array[i] = i;
    }

    return array;
}
</code>```

But if I wanted to return two pointers instead of just one, I tried:

```<code>#include <stdlib.h>
#include <stdio.h>

int *my_func(int *);

int main(void)
{
    int *a;
    int *b;
    int i;

    a = my_func(b);

    for(i = 0; i < 3; i++)
    {
        printf("a[%d] = %d\n", i, a[i]);
        printf("b[%d] = %d\n", i, b[i]);
    }

    free(a);
    free(b);

    return 0;
}

int *my_func(int *array2)
{
    int *array;
    int i;

    array = calloc(3, sizeof(int));
    array2 = calloc(3, sizeof(int));

    for(i = 0; i < 3; i++)
    {
        array[i] = i;
        array2[i] = i;
    }

    return array;
}
</code>```

But this seg faults on the printf for b. I ran it through valgrind and it says that there is an invalid read of size 4 at the printf for b, which means I'm doing something screwy with the b pointer. I was just wondering what the best way to "return" a second pointer to an array was in c? I'm asking because I would like to do it this way rather than use a global variable (I'm not opposed to them, as they are useful at times, I just prefer not to use them if possible). The other questions I've seen on this site used statically allocated arrays, but I haven't yet stumbled across a question that was using dynamic allocation. Thanks in advance!

答:
```<code>#include <stdlib.h>
#include <stdio.h>

int *my_func(int **);

int main(void)
{
    int *a;
    int *b;
    int i;

    b=(int *)malloc(sizeof(int));

    a = my_func(&b);

    for(i = 0; i < 3; i++)
    {
        printf("a[%d] = %d\n", i, a[i]);
        printf("b[%d] = %d\n", i, b[i]);
    }

    free(a);
    free(b);

    return 0;
}

int *my_func(int **array2)
{
    int *array;
    int i;

    array = calloc(3, sizeof(int));
    *array2 =calloc(3,sizeof(int));

    for(i = 0; i < 3; i++)
    {
        array[i] = i;
        *((*array2)+i)=i;//or (*array2)[i]

    }

    return array;
}
</code>```

Pass the pointer by reference. Because its the same logic as, to manipulate an integer block you need to pass a pointer to it. Similarly, to manipulate a pointer, you will have to pass a pointer to it(i.e. pointer to pointer).

Body:
I know that you can return a pointer to the first element of an array in c by doing:

#include <stdlib.h>
#include <stdio.h>

int *my_func(void);

int main(void)
{
    int *a;
    int i;

    a = my_func();

    for(i = 0; i < 3; i++)
    {
        printf("a[%d] = %d\n", i, a[i]);
    }

    free(a);

    return 0;
}

int *my_func(void)
{
    int *array;
    int i;

    array = calloc(3, sizeof(int));

    for(i = 0; i < 3; i++)
    {
        array[i] = i;
    }

    return array;
}

But if I wanted to return two pointers instead of just one, I tried:

#include <stdlib.h>
#include <stdio.h>

int *my_func(int *);

int main(void)
{
    int *a;
    int *b;
    int i;

    a = my_func(b);

    for(i = 0; i < 3; i++)
    {
        printf("a[%d] = %d\n", i, a[i]);
        printf("b[%d] = %d\n", i, b[i]);
    }

    free(a);
    free(b);

    return 0;
}

int *my_func(int *array2)
{
    int *array;
    int i;

    array = calloc(3, sizeof(int));
    array2 = calloc(3, sizeof(int));

    for(i = 0; i < 3; i++)
    {
        array[i] = i;
        array2[i] = i;
    }

    return array;
}

But this seg faults on the printf for b. I ran it through valgrind and it says that there is an invalid read of size 4 at the printf for b, which means I'm doing something screwy with the b pointer. I was just wondering what the best way to "return" a second pointer to an array was in c? I'm asking because I would like to do it this way rather than use a global variable (I'm not opposed to them, as they are useful at times, I just prefer not to use them if possible). The other questions I've seen on this site used statically allocated arrays, but I haven't yet stumbled across a question that was using dynamic allocation. Thanks in advance!

Body:
#include <stdlib.h>
#include <stdio.h>

int *my_func(int **);

int main(void)
{
    int *a;
    int *b;
    int i;

    b=(int *)malloc(sizeof(int));

    a = my_func(&b);

    for(i = 0; i < 3; i++)
    {
        printf("a[%d] = %d\n", i, a[i]);
        printf("b[%d] = %d\n", i, b[i]);
    }

    free(a);
    free(b);

    return 0;
}

int *my_func(int **array2)
{
    int *array;
    int i;

    array = calloc(3, sizeof(int));
    *array2 =calloc(3,sizeof(int));

    for(i = 0; i < 3; i++)
    {
        array[i] = i;
        *((*array2)+i)=i;//or (*array2)[i]

    }

    return array;
}

Pass the pointer by reference. Because its the same logic as, to manipulate an integer block you need to pass a pointer to it. Similarly, to manipulate a pointer, you will have to pass a pointer to it(i.e. pointer to pointer).


问:
How to properly export string data with quotes from MySQL to Big Query via csv?
I'm having problems with Big Query when trying to import CSV files from MySQL. These files have been exported with the following options:

```<code>SELECT <some collunms>
FROM <my table>
INTO OUTFILE 'export-20160411.csv'
CHARACTER SET 'utf8'
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '\"'
ESCAPED BY '\\';
</code>```

The problem is how to escape a " (double quote) for BQ, here is a CSV example:

```<code>field01, field02, field03, field04
"xxx \" xxx \\", \N, "xxx", "xxx"
</code>```

which are causing issues. So BQ gives errors like this:

```<code>BigQuery error in load operation: Error processing job
'<project>:bqjob_r7269aea2ac9eae3c_0000015c88a9049d_1': Too many
errors encountered.
Failure details:
- file-00000000: Too many values in row starting at position:
2052615.
</code>```

and this:

```<code>- mediaupload-snapshot: Error detected while parsing row starting at
position: 561497. Error: Missing close double quote (") character.
</code>```

Finally, my question is: what is the best way to export a CSV so BQ can import it without problems?

Thanks in advance.

UPDATE

The format:

```<code>field01, field02, field03, field04
"xxx "" xxx \\", \N, "xxx", "xxx"
</code>```

Works, with "" instead of \" inside the string. But I don't know how to export in this way from MySQL.

答:
one of the approach is to load your original csv file as if it had just one column (the whole row is just one column)   and than - to do parsing on BigQuery side

In Example below - assume that CSVtable is a table that you loaded with that CSV file as with one column as below:

oneField
"xxx "" xxx \\", \N, "xxx", "xxx"
```

<p>So "parsing" can look like below  :   </p>

<pre class="lang-sql prettyprint-override"><code>#standardSQL
WITH CSVtable AS (
  SELECT '''"xxx "" xxx \\\\", \\N, "xxx", "xxx"''' AS oneField
)
SELECT
  SPLIT(oneField)[OFFSET(0)] AS field01,
  SPLIT(oneField)[OFFSET(1)] AS field02,
  SPLIT(oneField)[OFFSET(2)] AS field03,
  SPLIT(oneField)[OFFSET(3)] AS field04
FROM CSVtable
</code>```

The output of such query is

field01             field02     field03     field04
"xxx "" xxx \\"     \N          "xxx"       "xxx"
```

Body:
I'm having problems with Big Query when trying to import CSV files from MySQL. These files have been exported with the following options:

SELECT <some collunms>
FROM <my table>
INTO OUTFILE 'export-20160411.csv'
CHARACTER SET 'utf8'
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '\"'
ESCAPED BY '\\';

The problem is how to escape a " (double quote) for BQ, here is a CSV example:

field01, field02, field03, field04
"xxx \" xxx \\", \N, "xxx", "xxx"

which are causing issues. So BQ gives errors like this:

BigQuery error in load operation: Error processing job
'<project>:bqjob_r7269aea2ac9eae3c_0000015c88a9049d_1': Too many
errors encountered.
Failure details:
- file-00000000: Too many values in row starting at position:
2052615.

and this:

- mediaupload-snapshot: Error detected while parsing row starting at
position: 561497. Error: Missing close double quote (") character.

Finally, my question is: what is the best way to export a CSV so BQ can import it without problems?

Thanks in advance.

UPDATE

The format:

field01, field02, field03, field04
"xxx "" xxx \\", \N, "xxx", "xxx"

Works, with "" instead of \" inside the string. But I don't know how to export in this way from MySQL.

Body:
one of the approach is to load your original csv file as if it had just one column (the whole row is just one column)   and than - to do parsing on BigQuery side

In Example below - assume that CSVtable is a table that you loaded with that CSV file as with one column as below:

oneField
"xxx "" xxx \\", \N, "xxx", "xxx"

So "parsing" can look like below  :

#standardSQL
WITH CSVtable AS (
  SELECT '''"xxx "" xxx \\\\", \\N, "xxx", "xxx"''' AS oneField
)
SELECT
  SPLIT(oneField)[OFFSET(0)] AS field01,
  SPLIT(oneField)[OFFSET(1)] AS field02,
  SPLIT(oneField)[OFFSET(2)] AS field03,
  SPLIT(oneField)[OFFSET(3)] AS field04
FROM CSVtable

The output of such query is

field01             field02     field03     field04
"xxx "" xxx \\"     \N          "xxx"       "xxx"


问:
Powershell bulk rename file name including ()
Files are named like 20160825().xlsx

Have tried both of this without any changes to the file names

```<code>Get-ChildItem "C:\Users\..." -Filter “*()*” -Recurse | Rename-Item NewName {$_.name -replace ‘()’,’’ }

Get-ChildItem "C:\Users\..." -Filter “*()*” -Recurse | Rename-Item -LiteralPath -NewName {$_.name -replace ‘()’,’’ }
</code>```

答:
-replace uses regular expressions (regex), which is a different language with different rules, and parentheses are special characters for grouping, and they need to be escaped to match literally. Try:

```<code>$_.name -replace '\(\)'
</code>```

Body:
Files are named like 20160825().xlsx

Have tried both of this without any changes to the file names

Get-ChildItem "C:\Users\..." -Filter “*()*” -Recurse | Rename-Item NewName {$_.name -replace ‘()’,’’ }

Get-ChildItem "C:\Users\..." -Filter “*()*” -Recurse | Rename-Item -LiteralPath -NewName {$_.name -replace ‘()’,’’ }

Body:
-replace uses regular expressions (regex), which is a different language with different rules, and parentheses are special characters for grouping, and they need to be escaped to match literally. Try:

$_.name -replace '\(\)'


问:
How to fetch data of a node in Firebase in the form of Array in Android
In this format I have a database in Firebase. I have to display all the departments in the form of array list like Director,sports.

Code:

```<code> mAuth=FirebaseAuth.getInstance();
    mdatabase= FirebaseDatabase.getInstance().getReference().child("Department");
   mdatabase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            List<String> Department = (ArrayList<String>) dataSnapshot.getValue();
             DepartmentLIST=Department.toArray(new String[Department.size()]);

        }
       @Override
       public void onCancelled(DatabaseError databaseError) {
           Toast.makeText(CheckUpdate.this,databaseError.getMessage(),Toast.LENGTH_LONG).show();
       }

      });

    setListAdapter(new ArrayAdapter(this,
            android.R.layout.simple_list_item_1,DepartmentLIST));
}
</code>```

This is my code I have used for it. But it gives NullValue.

答:
Please use this code:

```<code>mdatabase = FirebaseDatabase.getInstance().getReference().child("Department");
mdatabase.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
         List<String> departmentList = new ArrayList<>();
         for(DataSnapshot ds : dataSnapshot.getChildren()) {
             String departmentName = (String) ds.getValue();
             departmentList.add(departmentName);
         }
         setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, departmentList));
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
});
</code>```

Hope it helps.

Body:
In this format I have a database in Firebase. I have to display all the departments in the form of array list like Director,sports.

Code:

 mAuth=FirebaseAuth.getInstance();
    mdatabase= FirebaseDatabase.getInstance().getReference().child("Department");
   mdatabase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            List<String> Department = (ArrayList<String>) dataSnapshot.getValue();
             DepartmentLIST=Department.toArray(new String[Department.size()]);

        }
       @Override
       public void onCancelled(DatabaseError databaseError) {
           Toast.makeText(CheckUpdate.this,databaseError.getMessage(),Toast.LENGTH_LONG).show();
       }

      });

    setListAdapter(new ArrayAdapter(this,
            android.R.layout.simple_list_item_1,DepartmentLIST));
}

This is my code I have used for it. But it gives NullValue.

Body:
Please use this code:

mdatabase = FirebaseDatabase.getInstance().getReference().child("Department");
mdatabase.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
         List<String> departmentList = new ArrayList<>();
         for(DataSnapshot ds : dataSnapshot.getChildren()) {
             String departmentName = (String) ds.getValue();
             departmentList.add(departmentName);
         }
         setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, departmentList));
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
});

Hope it helps.


问:
Where can I find a comprehensive list of new features for C# 4.0?
I've heard bits and pieces here and there, but I have yet find a comprehensive list of new features for C# 4.0? Does anyone know what they are or where I can find them?

Duplicate of:

New Cool Features of C# 4.0

and/or:

C# 4.0 Specification Beta?

答:
The best way to get familiar with them is to view Anders' Future of C# presentation

http://channel9.msdn.com/pdc2008/TL16/

Charlie Calvert also has a blog entry listing a bunch of different resources for C# 4.0 features.  Including a link to Mad's paper which will contain more than enough detail for you.  There are also several comprehensive sample links on the page.

http://blogs.msdn.com/charlie/archive/2008/11/04/new-features-in-c-4-0-paper-plus-feedback-and-samples.aspx

OwnerDisplayName: Micah

LastEditorDisplayName: Gortok

OwnerDisplayName: JaredPar


问:
How to adjust the distance between two plots in R shiny?
I have generated two plots in R shiny but currently the two plots are overlaid on one another. How can i adjust the distance between them? Here is my ui.R and server.R code along with the picture generated from the same

ui.R

```<code>library(shiny)
library(leaflet)

shinyUI(fluidPage(

  # Application title
  titlePanel("Old Faithful Geyser Data"),

  # Sidebar with a slider input for number of bins
  sidebarLayout(
    sidebarPanel(
      selectInput("n", label = "Select K for display", choices = c("2", "3", "4")),
      checkboxInput("show", "Flood_path")
  ),

    # Show a plot of the generated distribution
    mainPanel(
      plotOutput("preImage"),
      leafletOutput("map")
    )
  )
))
</code>```

server.R

```<code>library(shiny)

shinyServer(function(input, output, session) {

  output$preImage <- renderImage({
    # When input$n is 3, filename is ./images/image3.jpeg
    filename <- normalizePath(file.path('./images', paste('image', input$n, '.jpeg', sep='')))

    # Return a list containing the filename and alt text
    list(src = filename, alt = paste("Image number", input$n))

  }, deleteFile = FALSE)

  # Switch for Structure
  dt <- reactive(
    switch(input$n,
           "2" = data_K2$Structure.2,
           "3" = data_K2$Structure.3,
           "4" = data_K2$Structure.4))

  # Map
  output$map <- renderLeaflet(
    leaflet(data = data_K2) %>% addTiles() %>% setView(lng = mean(data_K2$Long), lat = mean(data_K2$Lat), zoom = 4) %>%
      addCircleMarkers(lat = ~Lat, lng = ~Long, popup = ~Location_discription, radius=2, color = ~dt(), fill = TRUE) %>%
      addPolylines(group="markers", lng = data_fp$Long, lat = data_fp$Lat, col = "red", weight = 2, opacity = 0.5)
  )
</code>```

答:
I would use fluidrow:

```<code>library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(

   # Application title
   titlePanel("Old Faithful Geyser Data"),

   # Sidebar with a slider input for number of bins
   fluidRow(column(12,
                   fluidRow(
                     column(2,
         sliderInput("bins", "Number of bins:", min = 1, max = 50, value = 30)
      ),
      column(10,  plotOutput("distPlot"))
   ),
   fluidRow(column(2),
            column(10, plotOutput("distPlot2")))
)
)
)

# Define server logic required to draw a histogram
server <- function(input, output) {

   output$distPlot <- renderPlot({
      # generate bins based on input$bins from ui.R
      x    <- faithful[, 2]
      bins <- seq(min(x), max(x), length.out = input$bins + 1)

      # draw the histogram with the specified number of bins
      hist(x, breaks = bins, col = 'darkgray', border = 'white')
   })

   output$distPlot2 <- renderPlot({
     # generate bins based on input$bins from ui.R
     x    <- faithful[, 2]
     bins <- seq(min(x), max(x), length.out = input$bins + 1)

     # draw the histogram with the specified number of bins
     hist(x, breaks = bins, col = 'darkgray', border = 'white')
   })
}

# Run the application
shinyApp(ui = ui, server = server)
</code>```

I just realized how old this post was.

Body:
I have generated two plots in R shiny but currently the two plots are overlaid on one another. How can i adjust the distance between them? Here is my ui.R and server.R code along with the picture generated from the same

ui.R

library(shiny)
library(leaflet)

shinyUI(fluidPage(

  # Application title
  titlePanel("Old Faithful Geyser Data"),

  # Sidebar with a slider input for number of bins
  sidebarLayout(
    sidebarPanel(
      selectInput("n", label = "Select K for display", choices = c("2", "3", "4")),
      checkboxInput("show", "Flood_path")
  ),

    # Show a plot of the generated distribution
    mainPanel(
      plotOutput("preImage"),
      leafletOutput("map")
    )
  )
))

server.R

library(shiny)

shinyServer(function(input, output, session) {

  output$preImage <- renderImage({
    # When input$n is 3, filename is ./images/image3.jpeg
    filename <- normalizePath(file.path('./images', paste('image', input$n, '.jpeg', sep='')))

    # Return a list containing the filename and alt text
    list(src = filename, alt = paste("Image number", input$n))

  }, deleteFile = FALSE)

  # Switch for Structure
  dt <- reactive(
    switch(input$n,
           "2" = data_K2$Structure.2,
           "3" = data_K2$Structure.3,
           "4" = data_K2$Structure.4))

  # Map
  output$map <- renderLeaflet(
    leaflet(data = data_K2) %>% addTiles() %>% setView(lng = mean(data_K2$Long), lat = mean(data_K2$Lat), zoom = 4) %>%
      addCircleMarkers(lat = ~Lat, lng = ~Long, popup = ~Location_discription, radius=2, color = ~dt(), fill = TRUE) %>%
      addPolylines(group="markers", lng = data_fp$Long, lat = data_fp$Lat, col = "red", weight = 2, opacity = 0.5)
  )

Body:
I would use fluidrow:

library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(

   # Application title
   titlePanel("Old Faithful Geyser Data"),

   # Sidebar with a slider input for number of bins
   fluidRow(column(12,
                   fluidRow(
                     column(2,
         sliderInput("bins", "Number of bins:", min = 1, max = 50, value = 30)
      ),
      column(10,  plotOutput("distPlot"))
   ),
   fluidRow(column(2),
            column(10, plotOutput("distPlot2")))
)
)
)

# Define server logic required to draw a histogram
server <- function(input, output) {

   output$distPlot <- renderPlot({
      # generate bins based on input$bins from ui.R
      x    <- faithful[, 2]
      bins <- seq(min(x), max(x), length.out = input$bins + 1)

      # draw the histogram with the specified number of bins
      hist(x, breaks = bins, col = 'darkgray', border = 'white')
   })

   output$distPlot2 <- renderPlot({
     # generate bins based on input$bins from ui.R
     x    <- faithful[, 2]
     bins <- seq(min(x), max(x), length.out = input$bins + 1)

     # draw the histogram with the specified number of bins
     hist(x, breaks = bins, col = 'darkgray', border = 'white')
   })
}

# Run the application
shinyApp(ui = ui, server = server)

I just realized how old this post was.


问:
How can I select all posts which have specific tags?
Here is my table structure:

```<code>// posts
+----+-----------+---------------------+-------------+
| id |   title   |        body         |   keywords  |
+----+-----------+---------------------+-------------+
| 1  | title1    | Something here      | php,oop     |
| 2  | title2    | Something else      | html,css,js |
+----+-----------+---------------------+-------------+

// tags
+----+----------+
| id |   name   |
+----+----------+
| 1  | php      |
| 2  | oop      |
| 3  | html     |
| 4  | css      |
| 5  | js       |
+----+----------+

// pivot
+---------+--------+
| post_id | tag_id |
+---------+--------+
| 1       | 1      |
| 1       | 2      |
| 2       | 3      |
| 2       | 4      |
| 2       | 5      |
+---------+--------+
</code>```

Ok well, I have two tags (php and html) and I need to select all posts tagged with them. How can I do that?

Currently I use REGEXP and simply select what I want like this:

```<code>SELECT * FROM posts WHERE keywords REGEXP 'php|html';
</code>```

See? I don't use even 1 join. These days my dataset is grown up and my query takes a while to be executed. I guess I have to use a relational feature like join.  However I'm not sure it would be better than my current query.

Anyway, does anybody know, how can I get the expected result faster?

答:
Regular expressions can be slow to process. Using LIKE will probably give better response times:

```<code>SELECT *
FROM   posts
WHERE  (keywords LIKE '%php%' OR keywords LIKE '%html%')
</code>```

The query based on the normalised tables would be:

```<code>SELECT     posts.id, posts.title, posts.body, posts.keywords
FROM       posts
INNER JOIN pivot ON pivot.post_id = posts.id
INNER JOIN tags ON tags.id = pivot.tag_id
WHERE      tags.name IN ('html', 'php')
GROUP BY   posts.id
</code>```

For optimal speed you must ensure that the id fields are declared as primary keys, and that you have indexes on:

```<code>tags(name)
pivot(tag_id)
</code>```

Still, this will not be faster than your current solution if a significant part of all the posts fulfil the condition: it could well be slower. But if for example less than 1% of the posts would satisfy the condition, then this will likely perform better, as in principle the execution plan does not need to include a scan of the whole posts table.

Body:
Here is my table structure:

// posts
+----+-----------+---------------------+-------------+
| id |   title   |        body         |   keywords  |
+----+-----------+---------------------+-------------+
| 1  | title1    | Something here      | php,oop     |
| 2  | title2    | Something else      | html,css,js |
+----+-----------+---------------------+-------------+

// tags
+----+----------+
| id |   name   |
+----+----------+
| 1  | php      |
| 2  | oop      |
| 3  | html     |
| 4  | css      |
| 5  | js       |
+----+----------+

// pivot
+---------+--------+
| post_id | tag_id |
+---------+--------+
| 1       | 1      |
| 1       | 2      |
| 2       | 3      |
| 2       | 4      |
| 2       | 5      |
+---------+--------+

Ok well, I have two tags (php and html) and I need to select all posts tagged with them. How can I do that?

Currently I use REGEXP and simply select what I want like this:

SELECT * FROM posts WHERE keywords REGEXP 'php|html';

See? I don't use even 1 join. These days my dataset is grown up and my query takes a while to be executed. I guess I have to use a relational feature like join.  However I'm not sure it would be better than my current query.

Anyway, does anybody know, how can I get the expected result faster?

Body:
Regular expressions can be slow to process. Using LIKE will probably give better response times:

SELECT *
FROM   posts
WHERE  (keywords LIKE '%php%' OR keywords LIKE '%html%')

The query based on the normalised tables would be:

SELECT     posts.id, posts.title, posts.body, posts.keywords
FROM       posts
INNER JOIN pivot ON pivot.post_id = posts.id
INNER JOIN tags ON tags.id = pivot.tag_id
WHERE      tags.name IN ('html', 'php')
GROUP BY   posts.id

For optimal speed you must ensure that the id fields are declared as primary keys, and that you have indexes on:

tags(name)
pivot(tag_id)

Still, this will not be faster than your current solution if a significant part of all the posts fulfil the condition: it could well be slower. But if for example less than 1% of the posts would satisfy the condition, then this will likely perform better, as in principle the execution plan does not need to include a scan of the whole posts table.


问:
Coldfusion member function name matches jSoup function name. How can I force the use of jSoup function
The following code which is used in Coldfusion 10 with jSoup works correctly:

```<code>var jsoup = application.jsoup;
var newBody = jsoup.parseBodyFragment(FileRead(expandPath("\default\includes\display_objects\custom\routesmapping\routePageTemplate.cfm")));
var routeBadge = newBody.select(".routeBadge");
routeBadge.append("<img src=""#$.content('decalFileName')#"" />");
</code>```

On Coldfusion 2016 it errors on line 4, java.lang.String cannot be cast to org.jsoup.nodes.Element.

java.lang.ClassCastException: java.lang.String cannot be cast to
  org.jsoup.nodes.Element at
  org.jsoup.select.Elements.add(Elements.java:15) at
  coldfusion.runtime.ArrayUtil.ArrayAppend(ArrayUtil.java:208) at
  coldfusion.runtime.CFPage._arrayAppend(CFPage.java:578) at
  coldfusion.runtime.CfJspPage.invokeMethodHandle(CfJspPage.java:3198)
  at coldfusion.runtime.CfJspPage._invoke(CfJspPage.java:3155) at
  coldfusion.runtime.CfJspPage._invoke(CfJspPage.java:3072) at

It appears that it is using the ColdFusion member function, append(), added in CF11, instead of the jSoup append() function.

How can I force the use of the jSoup append() function over the CF append() member function in this situation?

答:
At the end of the day, I was never able to get the jSoup append() method to work on any versions of CF11 or CF2016. I ended up having to switch to using the html() method and then concatenating my new string to the existing content.

So instead of:

```<code>descList.append("<dt>Booking Status:</dt><dd class = """ & statusClass &
    """><em>#status#</em></dd>");
</code>```

I had to use:

```<code> descList.html(descList.html() & "<dt>Booking Status:</dt><dd class = """ &
    statusClass & """><em>#status#</em></dd>");
</code>```

Body:
The following code which is used in Coldfusion 10 with jSoup works correctly:

var jsoup = application.jsoup;
var newBody = jsoup.parseBodyFragment(FileRead(expandPath("\default\includes\display_objects\custom\routesmapping\routePageTemplate.cfm")));
var routeBadge = newBody.select(".routeBadge");
routeBadge.append("");

On Coldfusion 2016 it errors on line 4, java.lang.String cannot be cast to org.jsoup.nodes.Element.

java.lang.ClassCastException: java.lang.String cannot be cast to
  org.jsoup.nodes.Element at
  org.jsoup.select.Elements.add(Elements.java:15) at
  coldfusion.runtime.ArrayUtil.ArrayAppend(ArrayUtil.java:208) at
  coldfusion.runtime.CFPage._arrayAppend(CFPage.java:578) at
  coldfusion.runtime.CfJspPage.invokeMethodHandle(CfJspPage.java:3198)
  at coldfusion.runtime.CfJspPage._invoke(CfJspPage.java:3155) at
  coldfusion.runtime.CfJspPage._invoke(CfJspPage.java:3072) at

It appears that it is using the ColdFusion member function, append(), added in CF11, instead of the jSoup append() function.

How can I force the use of the jSoup append() function over the CF append() member function in this situation?

Body:
At the end of the day, I was never able to get the jSoup append() method to work on any versions of CF11 or CF2016. I ended up having to switch to using the html() method and then concatenating my new string to the existing content.

So instead of:

descList.append("<dt>Booking Status:</dt><dd class = """ & statusClass &
    """><em>#status#</em></dd>");

I had to use:

 descList.html(descList.html() & "<dt>Booking Status:</dt><dd class = """ &
    statusClass & """><em>#status#</em></dd>");


问:
how to get value of dynamic checkbox?
In android phonegap application ,I created div with questions and options(chechbox) dynamically(each question have three or four checkbox).I have one submit button.

Now I want to get value of question and selected option while clicking the button.

How to do that?

Please help me.Thanks in advance.

答:
I was looking for the exact same thing. I tried the answer by Yorgo, but it was not working. It just required a small tweaking

```<code>var selected_values = new Array();
$('#myform :checkbox').each(function(){
    if($(this).is(":checked"))
        selected_values.push($(this).attr("value"));
});
</code>```

using

```<code>$(this).attr("value") instead of $(this).val();
</code>```

worked for me.

Title: how to get value of dynamic checkbox?

Body:
I was looking for the exact same thing. I tried the answer by Yorgo, but it was not working. It just required a small tweaking

var selected_values = new Array();
$('#myform :checkbox').each(function(){
    if($(this).is(":checked"))
        selected_values.push($(this).attr("value"));
});

using

$(this).attr("value") instead of $(this).val();

worked for me.


问:
How to handle Connect/ Authentication errors when using imap-idle-channel-adapter
I am able to handle and report connection/ authentication related errors for imap and pop adapter by using error-channel on the poller.

I have one for imap-idle too but its not getting these error on that channel but a warning in the logs only.

what is the way out to handle and report similar errors for email idle adapter?

答:
I guess you mean this peace of code:

```<code>catch (Exception e) { //run again after a delay
        logger.warn("Failed to execute IDLE task. Will attempt to resubmit in " + ImapIdleChannelAdapter.this.reconnectDelay + " milliseconds.", e);
        ImapIdleChannelAdapter.this.receivingTaskTrigger.delayNextExecution();
        ImapIdleChannelAdapter.this.publishException(e);
        }
</code>```

And you see that WARN in your logs.

Pay attention, please, to the latest line about publishException(). It is this code:

```<code>private void publishException(Exception e) {
    if (this.applicationEventPublisher != null) {
        this.applicationEventPublisher.publishEvent(new ImapIdleExceptionEvent(e));
    }
</code>```

So, what you need is to add an EventListener for that ImapIdleExceptionEvent. For example you can use ApplicationEventListeningMessageProducer.

Body:
I guess you mean this peace of code:

catch (Exception e) { //run again after a delay
        logger.warn("Failed to execute IDLE task. Will attempt to resubmit in " + ImapIdleChannelAdapter.this.reconnectDelay + " milliseconds.", e);
        ImapIdleChannelAdapter.this.receivingTaskTrigger.delayNextExecution();
        ImapIdleChannelAdapter.this.publishException(e);
        }

And you see that WARN in your logs.

Pay attention, please, to the latest line about publishException(). It is this code:

private void publishException(Exception e) {
    if (this.applicationEventPublisher != null) {
        this.applicationEventPublisher.publishEvent(new ImapIdleExceptionEvent(e));
    }

So, what you need is to add an EventListener for that ImapIdleExceptionEvent. For example you can use ApplicationEventListeningMessageProducer.


问:
XSLT transformation to xml, grouping by key
I have problem with write xsl to transform my xml to raport version.
It looks like that:

```<code><library>
    <authors>
        <author id="1001">John</author>
        <author id="1002">Tom</author>
    </authors>
    <articles>
        <article>
            <authorId>1001</authorId>
            <title>Article1</title>
        </article>
        <article>
            <authorId>1002</authorId>
            <title>Article2</title>
        </article>
        <article>
            <authorId>1001</authorId>
            <title>Article3</title>
        </article>
    </articles>
</library>
</code>```

I want to tranform it to:

```<code><raport>
    <authorArticles>
        <author>John</author>
        <articles>
            <article>Article1</article>
            <article>Article3</article>
        </articles>
    </authorArticles>
    <authorArticles>
        <author>Tom</author>
        <articles>
            <article>Article2</article>
        </articles>
    </authorArticles>
</raport>
</code>```

I have idea to use for each, on for ids in authors and neasted for articles, but I dont know how to do it. Anyone know how to make this transformation ?

答:
This transformation:

```<code><xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:key name="kArticleById" match="article"
  use="authorId"/>

 <xsl:template match="node()|@*" name="identity">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="/*">
  <raport>
        <xsl:apply-templates select="authors/author"/>
  </raport>
 </xsl:template>

 <xsl:template match="author">
  <authorArticles>
  <xsl:call-template name="identity"/>
    <articles>
      <xsl:apply-templates select="key('kArticleById',@id)"/>
    </articles>
  </authorArticles>
 </xsl:template>

 <xsl:template match="title">
  <xsl:apply-templates/>
 </xsl:template>
 <xsl:template match="author/@id|articles|authorId"/>
</xsl:stylesheet>
</code>```

when applied on the provided XML document:

```<code><library>
    <authors>
        <author id="1001">John</author>
        <author id="1002">Tom</author>
    </authors>
    <articles>
        <article>
            <authorId>1001</authorId>
            <title>Article1</title>
        </article>
        <article>
            <authorId>1002</authorId>
            <title>Article2</title>
        </article>
        <article>
            <authorId>1001</authorId>
            <title>Article3</title>
        </article>
    </articles>
</library>
</code>```

produces the wanted, correct result:

```<code><raport>
   <authorArticles>
      <author>John</author>
      <articles>
         <article>Article1</article>
         <article>Article3</article>
      </articles>
   </authorArticles>
   <authorArticles>
      <author>Tom</author>
      <articles>
         <article>Article2</article>
      </articles>
   </authorArticles>
</raport>
</code>```

Notes:

Use/overriding of the identity rule.

All articles with the same authorId are selected using keys. This is significantly more efficient in case of many authors with many articles.

Body:
I have problem with write xsl to transform my xml to raport version.
It looks like that:

<library>
    <authors>
        <author id="1001">John</author>
        <author id="1002">Tom</author>
    </authors>
    <articles>

            <authorId>1001</authorId>
            <title>Article1</title>

            <authorId>1002</authorId>
            <title>Article2</title>

            <authorId>1001</authorId>
            <title>Article3</title>

    </articles>
</library>

I want to tranform it to:

<raport>
    <authorArticles>
        <author>John</author>
        <articles>

Article1

Article3

        </articles>
    </authorArticles>
    <authorArticles>
        <author>Tom</author>
        <articles>

Article2

        </articles>
    </authorArticles>
</raport>

I have idea to use for each, on for ids in authors and neasted for articles, but I dont know how to do it. Anyone know how to make this transformation ?

Body:
This transformation:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:key name="kArticleById" match="article"
  use="authorId"/>

 <xsl:template match="node()|@*" name="identity">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="/*">
  <raport>
        <xsl:apply-templates select="authors/author"/>
  </raport>
 </xsl:template>

 <xsl:template match="author">
  <authorArticles>
  <xsl:call-template name="identity"/>
    <articles>
      <xsl:apply-templates select="key('kArticleById',@id)"/>
    </articles>
  </authorArticles>
 </xsl:template>

 <xsl:template match="title">
  <xsl:apply-templates/>
 </xsl:template>
 <xsl:template match="author/@id|articles|authorId"/>
</xsl:stylesheet>

when applied on the provided XML document:

<library>
    <authors>
        <author id="1001">John</author>
        <author id="1002">Tom</author>
    </authors>
    <articles>
        <article>
            <authorId>1001</authorId>
            <title>Article1</title>
        </article>
        <article>
            <authorId>1002</authorId>
            <title>Article2</title>
        </article>
        <article>
            <authorId>1001</authorId>
            <title>Article3</title>
        </article>
    </articles>
</library>

produces the wanted, correct result:

<raport>
   <authorArticles>
      <author>John</author>
      <articles>
         <article>Article1</article>
         <article>Article3</article>
      </articles>
   </authorArticles>
   <authorArticles>
      <author>Tom</author>
      <articles>
         <article>Article2</article>
      </articles>
   </authorArticles>
</raport>

Notes:

Use/overriding of the identity rule.

All articles with the same authorId are selected using keys. This is significantly more efficient in case of many authors with many articles.


答:
I can think of three (and a half) simple ways to return multiple items of any kind from a C-function. The ways are described below. It looks like a lot of text, but this answer is mostly code, so read on:

Pass in an output argument as you have done, but do it correctly. You have to allocate space for an int * in main() and then pass the pointer to that to my_func.

In main():

```<code>a = my_func(&b);
</code>```

my_func() becomes:

```<code>int *my_func(int **array2)
{
    int *array;
    int i;

    array = calloc(3, sizeof(int));
    *array2 = calloc(3, sizeof(int));

    for(i = 0; i < 3; i++)
    {
        array[i] = i;
        (*array2)[i] = i;
    }

    return array;
}
</code>```

Make your function allocate array of two pointers to the int arrays you are trying to allocate. This will require an additional allocation of two int pointers, but may be worth the trouble.

main() then becomes:

```<code>int main(void)
{
    int **ab;
    int i;

    ab = my_func(b);

    for(i = 0; i < 3; i++)
    {
        printf("a[%d] = %d\n", i, ab[0][i]);
        printf("b[%d] = %d\n", i, ab[1][i]);
    }

    free(ab[0]);
    free(ab[1]);
    free(ab);

    return 0;
}
</code>```

my_func() then becomes:

```<code>int **my_func(void)
{
    int **arrays;
    int i, j;

    arrays = calloc(2, sizeof(int *));
    arrays[0] = calloc(3, sizeof(int));
    arrays[1] = calloc(3, sizeof(int));

    for(j = 0; j < 2; j++)
    {
        for(i = 0; i < 3; i++)
        {
            arrays[j][i] = i;
        }
    }

    return arrays;
}
</code>```

Return a structure or structure pointer. You will need to define the structure, and decide whether you want to return the structure itself, a newly allocated pointer to it, or pass it in as a pointer and have my_func() fill it in for you.

The structure definition would look something like this:

```<code>struct x
{
    int *a;
    int *b;
}
</code>```

You would then rephrase your current functions as one of the following three options:

Direct passing of structure (not recommended for general use):

```<code>int main(void)
{
    struct x ab;
    int i;

    ab = my_func();

    for(i = 0; i < 3; i++)
    {
        printf("a[%d] = %d\n", i, ab.a[i]);
        printf("b[%d] = %d\n", i, ab.b[i]);
    }

    free(ab.a);
    free(ab.b);

    return 0;
}

struct x my_func(void)
{
    struct x ab;
    int i;

    ab.a = calloc(3, sizeof(int));
    ab.b = calloc(3, sizeof(int));

    for(i = 0; i < 3; i++)
    {
        ab.a[i] = i;
        ab.b[i] = i;
    }

    return ab;
}
</code>```

Return a pointer to a dynamically allocated structure (this is a pretty good option in general):

```<code>int main(void)
{
    struct x *ab;
    int i;

    ab = my_func();

    for(i = 0; i < 3; i++)
    {
        printf("a[%d] = %d\n", i, ab->a[i]);
        printf("b[%d] = %d\n", i, ab->b[i]);
    }

    free(ab->a);
    free(ab->b);
    free(ab);

    return 0;
}

struct x *my_func(void)
{
    struct x *ab;
    int i;

    ab = malloc(sizeof(struct x));
    ab->a = calloc(3, sizeof(int));
    ab->b = calloc(3, sizeof(int));

    for(i = 0; i < 3; i++)
    {
        ab->a[i] = i;
        ab->b[i] = i;
    }

    return ab;
}
</code>```

Allocate the structure in main() and fill it in in my_func via a passed-in pointer. This option is often used in a way where my_func would allocate the structure if you pass in a NULL pointer, otherwise it would return whatever you passed in. The version of my_func shown here has no return value for simplicity:

```<code>int main(void)
{
    struct x ab;
    int i;

    my_func(&ab);

    for(i = 0; i < 3; i++)
    {
        printf("a[%d] = %d\n", i, ab.a[i]);
        printf("b[%d] = %d\n", i, ab.b[i]);
    }

    free(ab.a);
    free(ab.b);

    return 0;
}

void my_func(struct x *ab)
{
    int i;

    ab->a = calloc(3, sizeof(int));
    ab->b = calloc(3, sizeof(int));

    for(i = 0; i < 3; i++)
    {
        ab->a[i] = i;
        ab->b[i] = i;
    }

    return;
}
</code>```

For all the examples shown here, don't forget to update the declaration of my_func at the top of the file, although I am sure any reasonable compiler will remind you if you forget.

Keep in mind also that these are just three options I pulled out of my brain at a moments notice. While they are likely to cover 99% of any use cases you may come up against any time soon, there are (probably lots of) other options out there.

Title: Return two pointers from a function in c

Body:
I know that you can return a pointer to the first element of an array in c by doing:

#include <stdlib.h>
#include <stdio.h>

int *my_func(void);

int main(void)
{
    int *a;
    int i;

    a = my_func();

    for(i = 0; i < 3; i++)
    {
        printf("a[%d] = %d\n", i, a[i]);
    }

    free(a);

    return 0;
}

int *my_func(void)
{
    int *array;
    int i;

    array = calloc(3, sizeof(int));

    for(i = 0; i < 3; i++)
    {
        array[i] = i;
    }

    return array;
}

But if I wanted to return two pointers instead of just one, I tried:

#include <stdlib.h>
#include <stdio.h>

int *my_func(int *);

int main(void)
{
    int *a;
    int *b;
    int i;

    a = my_func(b);

    for(i = 0; i < 3; i++)
    {
        printf("a[%d] = %d\n", i, a[i]);
        printf("b[%d] = %d\n", i, b[i]);
    }

    free(a);
    free(b);

    return 0;
}

int *my_func(int *array2)
{
    int *array;
    int i;

    array = calloc(3, sizeof(int));
    array2 = calloc(3, sizeof(int));

    for(i = 0; i < 3; i++)
    {
        array[i] = i;
        array2[i] = i;
    }

    return array;
}

But this seg faults on the printf for b. I ran it through valgrind and it says that there is an invalid read of size 4 at the printf for b, which means I'm doing something screwy with the b pointer. I was just wondering what the best way to "return" a second pointer to an array was in c? I'm asking because I would like to do it this way rather than use a global variable (I'm not opposed to them, as they are useful at times, I just prefer not to use them if possible). The other questions I've seen on this site used statically allocated arrays, but I haven't yet stumbled across a question that was using dynamic allocation. Thanks in advance!

Body:
I can think of three (and a half) simple ways to return multiple items of any kind from a C-function. The ways are described below. It looks like a lot of text, but this answer is mostly code, so read on:

Pass in an output argument as you have done, but do it correctly. You have to allocate space for an int * in main() and then pass the pointer to that to my_func.

In main():

a = my_func(&b);

my_func() becomes:

int *my_func(int **array2)
{
    int *array;
    int i;

    array = calloc(3, sizeof(int));
    *array2 = calloc(3, sizeof(int));

    for(i = 0; i < 3; i++)
    {
        array[i] = i;
        (*array2)[i] = i;
    }

    return array;
}

Make your function allocate array of two pointers to the int arrays you are trying to allocate. This will require an additional allocation of two int pointers, but may be worth the trouble.

main() then becomes:

int main(void)
{
    int **ab;
    int i;

    ab = my_func(b);

    for(i = 0; i < 3; i++)
    {
        printf("a[%d] = %d\n", i, ab[0][i]);
        printf("b[%d] = %d\n", i, ab[1][i]);
    }

    free(ab[0]);
    free(ab[1]);
    free(ab);

    return 0;
}

my_func() then becomes:

int **my_func(void)
{
    int **arrays;
    int i, j;

    arrays = calloc(2, sizeof(int *));
    arrays[0] = calloc(3, sizeof(int));
    arrays[1] = calloc(3, sizeof(int));

    for(j = 0; j < 2; j++)
    {
        for(i = 0; i < 3; i++)
        {
            arrays[j][i] = i;
        }
    }

    return arrays;
}

Return a structure or structure pointer. You will need to define the structure, and decide whether you want to return the structure itself, a newly allocated pointer to it, or pass it in as a pointer and have my_func() fill it in for you.

The structure definition would look something like this:

struct x
{
    int *a;
    int *b;
}

You would then rephrase your current functions as one of the following three options:

Direct passing of structure (not recommended for general use):

int main(void)
{
    struct x ab;
    int i;

    ab = my_func();

    for(i = 0; i < 3; i++)
    {
        printf("a[%d] = %d\n", i, ab.a[i]);
        printf("b[%d] = %d\n", i, ab.b[i]);
    }

    free(ab.a);
    free(ab.b);

    return 0;
}

struct x my_func(void)
{
    struct x ab;
    int i;

    ab.a = calloc(3, sizeof(int));
    ab.b = calloc(3, sizeof(int));

    for(i = 0; i < 3; i++)
    {
        ab.a[i] = i;
        ab.b[i] = i;
    }

    return ab;
}

Return a pointer to a dynamically allocated structure (this is a pretty good option in general):

int main(void)
{
    struct x *ab;
    int i;

    ab = my_func();

    for(i = 0; i < 3; i++)
    {
        printf("a[%d] = %d\n", i, ab->a[i]);
        printf("b[%d] = %d\n", i, ab->b[i]);
    }

    free(ab->a);
    free(ab->b);
    free(ab);

    return 0;
}

struct x *my_func(void)
{
    struct x *ab;
    int i;

    ab = malloc(sizeof(struct x));
    ab->a = calloc(3, sizeof(int));
    ab->b = calloc(3, sizeof(int));

    for(i = 0; i < 3; i++)
    {
        ab->a[i] = i;
        ab->b[i] = i;
    }

    return ab;
}

Allocate the structure in main() and fill it in in my_func via a passed-in pointer. This option is often used in a way where my_func would allocate the structure if you pass in a NULL pointer, otherwise it would return whatever you passed in. The version of my_func shown here has no return value for simplicity:

int main(void)
{
    struct x ab;
    int i;

    my_func(&ab);

    for(i = 0; i < 3; i++)
    {
        printf("a[%d] = %d\n", i, ab.a[i]);
        printf("b[%d] = %d\n", i, ab.b[i]);
    }

    free(ab.a);
    free(ab.b);

    return 0;
}

void my_func(struct x *ab)
{
    int i;

    ab->a = calloc(3, sizeof(int));
    ab->b = calloc(3, sizeof(int));

    for(i = 0; i < 3; i++)
    {
        ab->a[i] = i;
        ab->b[i] = i;
    }

    return;
}

For all the examples shown here, don't forget to update the declaration of my_func at the top of the file, although I am sure any reasonable compiler will remind you if you forget.

Keep in mind also that these are just three options I pulled out of my brain at a moments notice. While they are likely to cover 99% of any use cases you may come up against any time soon, there are (probably lots of) other options out there.


问:
Add friend error in django
I can log in from one user, when i try logging in with other user accounts, i get the following error

```<code>Friend matching query does not exist.
</code>```

below is my views.py. i get an error on the line 7

```<code>class HomeView(TemplateView):
    template_name = 'home/home.html'
    def get(self, request):
        form = HomeForm()
        posts = Post.objects.all().order_by('-created')
        users = User.objects.exclude(id=request.user.id)
        friend = Friend.objects.get(current_user=request.user) ...
        friends = friend.users.all()
        args = {
            'form': form, 'posts': posts, 'users': users, 'friends': friends
        }
    return render(request, self.template_name, args)
</code>```

答: also make shure that you makemigrations and migrate after adding your Friend model </p>

Title: Add friend error in django

Body:
I can log in from one user, when i try logging in with other user accounts, i get the following error

Friend matching query does not exist.

below is my views.py. i get an error on the line 7

class HomeView(TemplateView):
    template_name = 'home/home.html'
    def get(self, request):
        form = HomeForm()
        posts = Post.objects.all().order_by('-created')
        users = User.objects.exclude(id=request.user.id)
        friend = Friend.objects.get(current_user=request.user) ...
        friends = friend.users.all()
        args = {
            'form': form, 'posts': posts, 'users': users, 'friends': friends
        }
    return render(request, self.template_name, args)


问:
How can I automatically setup and configure the Windows Subsystem for Linux under Windows 10?
When I set up WSL on Windows 10 it wants me to manually configure it:

https://msdn.microsoft.com/en-us/commandline/wsl/install_guide

That does not work well for automation. Is there a way that I can install and configure it such that it does not require manual setup?

答:
Although the MSDN documentation refers to an interactive process, there are a handful of cmdlets and commands you can execute to get you into a workable state without manual intervention.

The following information assumes you are running from a modern instance of PowerShell, and will be executing in that environment as an Administrator.

Enable Developer Mode. This provides you the option and availability to install the Windows Subsystem for Linux (feature).

```<code>reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock"/t REG_DWORD /f /v "AllowDevelopmentWithoutDevLicense" /d "1"
</code>```

Once this has been completed you can observe that in the "For developers" section of "Update & security" settings that Developer mode is now toggled ON.

Install the Windows Subsystem for Linux (Beta) feature, and suppress the reboot prompt.

```<code>Enable-WindowsOptionalFeature `
    -Online `
    -NoRestart `
    -FeatureName Microsoft-Windows-Subsystem-Linux
</code>```

Optionally observe that within the Windows features that Windows Subsystem for Linux (Beta) is now available.

Unfortunately, it does not appear possible to use the environment without a reboot. The binaries we call into are not even present in system32 yet.

Reboot the machine

```<code>Restart-Computer -Force
</code>```

Be aware that -Force does not wait for programs to finish up and kill gracefully. I have placed this here to prevent scenarios where unruly processes can hang the reboot procedure.

Extract and prep the WSL environment

```<code>& lxrun /install /y
</code>```

& executes a command via cmd.exe, as lxrun is not a PowerShell cmdlet but rather a executable. lxrun /install extracts out your new Linux filesystem, and /y suppresses the need to create a user or password, which leaves you with password-less root.

Condensed:

```<code>reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock"/t REG_DWORD /f /v "AllowDevelopmentWithoutDevLicense" /d "1"

Enable-WindowsOptionalFeature `
    -Online `
    -NoRestart `
    -FeatureName Microsoft-Windows-Subsystem-Linux

Restart-Computer -Force

# once your machine is back up... execute:

& lxrun /install /y
</code>```

Additional resource material:

https://learn.microsoft.com/en-us/windows/uwp/get-started/enable-your-device-for-development

https://github.com/Microsoft/BashOnWindows/issues/1445

https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.management/restart-computer

https://gallery.technet.microsoft.com/scriptcenter/Enable-developer-mode-27008e86

Body:
Although the MSDN documentation refers to an interactive process, there are a handful of cmdlets and commands you can execute to get you into a workable state without manual intervention.

The following information assumes you are running from a modern instance of PowerShell, and will be executing in that environment as an Administrator.

Enable Developer Mode. This provides you the option and availability to install the Windows Subsystem for Linux (feature).

reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock"/t REG_DWORD /f /v "AllowDevelopmentWithoutDevLicense" /d "1"

Once this has been completed you can observe that in the "For developers" section of "Update & security" settings that Developer mode is now toggled ON.

Install the Windows Subsystem for Linux (Beta) feature, and suppress the reboot prompt.

Enable-WindowsOptionalFeature `
    -Online `
    -NoRestart `
    -FeatureName Microsoft-Windows-Subsystem-Linux

Optionally observe that within the Windows features that Windows Subsystem for Linux (Beta) is now available.

Unfortunately, it does not appear possible to use the environment without a reboot. The binaries we call into are not even present in system32 yet.

Reboot the machine

Restart-Computer -Force

Be aware that -Force does not wait for programs to finish up and kill gracefully. I have placed this here to prevent scenarios where unruly processes can hang the reboot procedure.

Extract and prep the WSL environment

& lxrun /install /y

& executes a command via cmd.exe, as lxrun is not a PowerShell cmdlet but rather a executable. lxrun /install extracts out your new Linux filesystem, and /y suppresses the need to create a user or password, which leaves you with password-less root.

Condensed:

reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock"/t REG_DWORD /f /v "AllowDevelopmentWithoutDevLicense" /d "1"

Enable-WindowsOptionalFeature `
    -Online `
    -NoRestart `
    -FeatureName Microsoft-Windows-Subsystem-Linux

Restart-Computer -Force

# once your machine is back up... execute:

& lxrun /install /y

Additional resource material:

https://learn.microsoft.com/en-us/windows/uwp/get-started/enable-your-device-for-development

https://github.com/Microsoft/BashOnWindows/issues/1445

https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.management/restart-computer

https://gallery.technet.microsoft.com/scriptcenter/Enable-developer-mode-27008e86


问:
Including angular 2 with java actions and jsp
I am new to the angular 2 framework, recently I decided to work with this framework, after looking at this, many questions arose, my first attempt was to create an angular project with the angular cli, which worked, but when I decided to see How to include jsp files instead of html files I did not know how to do it, and I'm coming to you to find out if anyone has done it.
Since I use Spring and actions to send the information to jsp and display it, if someone could help me I would appreciate it.</p>

答: Angular2 is a single page framework that does not need server side page rendering. Using JPS along with Angular2 does not provide any benefits. You best bet is to use HTML with Angular2 Javascript and make REST calls back to your Spring based server side code.</p>