问:
Reduce Observable<T[]> into T[]
If I'm working with an Observable<number[]> and I would like to collect all the emissions into a single number[] .

I have always done something like this:

```<code>const items$ = Rx.Observable.of([10, 20, 30], [20,30,40])
  .reduce((acc, curr) => acc.concat(curr));

let itemsArray = [];

items.subscribe(arr => itemsArray = arr);

console.log(itemsArray); // [10, 20, 30, 20, 30, 40]
</code>```

I was just wondering if there is any way to "collect" items from an Observable - inline in RxJS without calling subscribe on the observable.

This would suggest a synchronous approach which I'm not sure is possible given the async nature of observables.

Something like:

```<code>const itemsArray = Rx.Observable.of([10, 20, 30], [20,30,40])
  .reduce((acc, curr) => acc.concat(curr))
  .collect( /* return a number[]  - not an Observable<number[]> */);

console.log(itemsArray); // [10, 20, 30, 20, 30, 40]
</code>```

答:
You can't do it without subscribing.

It's a stream (cold) and you need to subscribe in order to receive values.

That say, I think what do you want is to not wait until the last value has been emitted, and receive the new concatenated array over time (which is totally possible).

The operator to use for that is : scan.

in fact, you weren't far with reduce ;) !!

```<code>const items$ = Rx
  .Observable
  .of([10, 20, 30], [20,30,40])
  .scan((acc, curr) => acc.concat(curr), []);

items$.subscribe(arr => console.log(arr));
</code>```

https://plnkr.co/edit/2e8eR6RrHrrE1WOuRRdf?p=preview

Title: Reduce Observable<T[]> into T[]

Body:
If I'm working with an Observable<number[]> and I would like to collect all the emissions into a single number[] .

I have always done something like this:

const items$ = Rx.Observable.of([10, 20, 30], [20,30,40])
  .reduce((acc, curr) => acc.concat(curr));

let itemsArray = [];

items.subscribe(arr => itemsArray = arr);

console.log(itemsArray); // [10, 20, 30, 20, 30, 40]

I was just wondering if there is any way to "collect" items from an Observable - inline in RxJS without calling subscribe on the observable.

This would suggest a synchronous approach which I'm not sure is possible given the async nature of observables.

Something like:

const itemsArray = Rx.Observable.of([10, 20, 30], [20,30,40])
  .reduce((acc, curr) => acc.concat(curr))
  .collect( /* return a number[]  - not an Observable<number[]> */);

console.log(itemsArray); // [10, 20, 30, 20, 30, 40]

Body:
You can't do it without subscribing.

It's a stream (cold) and you need to subscribe in order to receive values.

That say, I think what do you want is to not wait until the last value has been emitted, and receive the new concatenated array over time (which is totally possible).

The operator to use for that is : scan.

in fact, you weren't far with reduce ;) !!

const items$ = Rx
  .Observable
  .of([10, 20, 30], [20,30,40])
  .scan((acc, curr) => acc.concat(curr), []);

items$.subscribe(arr => console.log(arr));

https://plnkr.co/edit/2e8eR6RrHrrE1WOuRRdf?p=preview


来源: stackexchange

问:
Composite primary key with Eloquent
We want to implement Composite primary key with Eloquent ORM and Laravel 5 for http://www.mbarendezvous.com/ I understand it is not currently supported by Eloquent .
Please suggest what should be the best alternative for the same.</p>

答:
You can override the save() method on your class that extends Model that has composite keys like the following:

```<code>public function save(array $options = array())
{
  $query = $this->newQueryWithoutScopes();
  // MY MODEL SPECIFIC FIX
  $query->where('OTHER_ID', '=', $this->OTHER_ID);
  // END MY FIX

 // the rest of the standard model->save() code is here but I cut it out for brevity.
 // Use what is in Model.php already.
}
</code>```

I saw this solution here: https://github.com/laravel/framework/issues/5517

ContentLicense: CC BY-SA 3.0

Title: Composite primary key with Eloquent

Body:
You can override the save() method on your class that extends Model that has composite keys like the following:

public function save(array $options = array())
{
  $query = $this->newQueryWithoutScopes();
  // MY MODEL SPECIFIC FIX
  $query->where('OTHER_ID', '=', $this->OTHER_ID);
  // END MY FIX

 // the rest of the standard model->save() code is here but I cut it out for brevity.
 // Use what is in Model.php already.
}

I saw this solution here: https://github.com/laravel/framework/issues/5517


问:
Docker How to connect to MongoDB from Web Service inside Container
Currently I want to setup a Linux Server with MongoDB and a WebServer which saves stuff inside this DB. I need them both to run inside Docker containers.

My problem is that my WebServer doesnt seem to "see" the MongoDB from inside its container.

What ive tried so far is:
run MongoDB with

docker run -p 27017:27017 -v... repoimage

it initializes fine and I can access this DB through the mongoshell without any problems.
Also the Webserver can access the DB if it DOESNT run in a container but just on the host as java application.

When I try now to run the server through a container I get a java exception saying "Connection refused" (which is thrown when he cant open the socket)

(Important: the server accesses the mongodb through "localhost")

I thought that container networks are "linked" together. Does anyone have the same problem?

答:
Localhost will be resolved by the hosts file in the container, hence it won't point outside of the container to the host machines localhost. Run the container with --net="host" to resolve.

Also, I would suggest starting up the two containers with docker-compose to have their own network and refer to each other in their host files through their own hashes.

https://docs.docker.com/compose/networking/#configuring-the-default-network


问:
IBM MobileFirst Platform 8.0 app authenticity not working on iOS
I'm currently testing IBM MobileFirst Platform 8.0 app authenticity feature for both Android and iOS environments, and Android version works fine with all the required setting and procedures but iOS version does not seem to work under the following environment and procedures:

IBM MobileFirst platform v8 running on Bluemix ver 8.0.0.00-20161122-1902

cordova-plugin-MFP 8.0.2016110713

Test app: MFPStarterCordova

The app is archived into ipa file and authenticity_data file is generated using mfp-app-authenticity-tool.jar too for the ipa file. The authenticity file registration and related security check (appAuthenticity) setting are done correctly on Console, and I installed the ipa on a (real) iPhone device. (The app successfully connects to and gets token from the server as expected)

I changed a bit of html code - e.g. simple string value - and reinstalled the changed ipa on the iPhone device, but the server does not seem to check / detect the change, under the setting I did with the original app. - i.e. The changed app connects to and gets token from the server successfully.

Is there anything else to be configured or to change to make the feature work on iOS?

答:
Use new version of Application Authenticity(i.e Dynamic Application Authencity) which is more advanced and easy to use in MobileFirst Platform Foundation 8.0.

Upgrade your Client SDK and Server to the latest iFix level to get the feature.

More details about Dynamic and Static Application Authenticity feature can be found here.


问:
seaborn.boxplot and wide-format dataframe
I have a DataFrame like this:

I tried these two instructions one after another:

```<code>sns.boxplot([dataFrame.mean_qscore_template,dataFrame.mean_qscore_complement,dataFrame.mean_qscore_2d])

sns.boxplot(x = "mean_qscore_template", y= "mean_qscore_complement", hue = "mean_qscore_2d" data = tips)
</code>```

I want to get mean_qscore_template,  mean_qscore_complement and mean_qscore_2d on the x-axis with the measure on y-axis but it doesn't work.

In the documentation they give an example with tips but my dataFrame is not organized f the same way.

答: sns.boxplot(data = dataFrame) will make boxplots for each numeric column of your dataframe.

ContentLicense: CC BY-SA 4.0

Body:
I have a DataFrame like this:

I tried these two instructions one after another:

sns.boxplot([dataFrame.mean_qscore_template,dataFrame.mean_qscore_complement,dataFrame.mean_qscore_2d])

sns.boxplot(x = "mean_qscore_template", y= "mean_qscore_complement", hue = "mean_qscore_2d" data = tips)

I want to get mean_qscore_template,  mean_qscore_complement and mean_qscore_2d on the x-axis with the measure on y-axis but it doesn't work.

In the documentation they give an example with tips but my dataFrame is not organized f the same way.


问:
What is the highest Ruby version supported by Rails v4.1.16?
In other words, can I run Rails 4.1.16 on Ruby 2.4? If not, can I run it on Ruby 2.3?</p>

答:
According to Rubygems, Rails 4.1.16 should work with any  ruby version higher or equal to 1.9.3. I would recommend testing it extensively in a local environment so you can check for any possible deprecations.
 Also, in case you are not, consider using RVM or any other Ruby version manager.

The Rails blog posted recently that the first version of the 4.2 series that officially support Ruby 2.4 is Rails 4.2.8.


问:
How to copy selected item in list box in C#?
How to copy selected item in list box to clipboard, using right click "Copy" menu?</p>

答:
If you want to select an item, and do ctrl + c then use this code:</p>

```<code> private void listBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Control == true && e.KeyCode == Keys.C)
        {
            string s = listBox1.SelectedItem.ToString();
            Clipboard.SetData(DataFormats.StringFormat, s);
        }
    }
</code>```

Body:
If you want to select an item, and do ctrl + c then use this code:

 private void listBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Control == true && e.KeyCode == Keys.C)
        {
            string s = listBox1.SelectedItem.ToString();
            Clipboard.SetData(DataFormats.StringFormat, s);
        }
    }


问:
Tiny mce image edit delete
Is there any tinymce or jquery plugins for edit/delete image in tinymce (Same as wordpress tinymce) ?</p>

答:
There is the plugin called imagemanager, but this one is not a free plugin owned by moxiecode - the creators of tinymce.

But you are free to create your own plugin with that functionality, but that's a lot of work.

ContentLicense: CC BY-SA 2.5

Title: Tiny mce image edit delete


问:
Display the number of additions and deletions per commit for a file
Is there a way to do the following but only by using git commands:</p>

```<code>$ ./git_helper.py index.d.ts
commit  added deleted            commit message
bd1de57 4     4       index.d.ts Error object fix
c3a54db 25    120     index.d.ts Merge branch 'master' into types-2.0
e9a0e98 58    10      index.d.ts Merge commit 'upstream/master~300' into merge_7_25
</code>```

答:
You can see the files with --stat

```<code>git log --stat --decorate --graph --oneline
</code>```

Alternatively, you can use

```<code>gitk your_commit_here
</code>```

Body:
Is there a way to do the following but only by using git commands:

$ ./git_helper.py index.d.ts
commit  added deleted            commit message
bd1de57 4     4       index.d.ts Error object fix
c3a54db 25    120     index.d.ts Merge branch 'master' into types-2.0
e9a0e98 58    10      index.d.ts Merge commit 'upstream/master~300' into merge_7_25

Body:
You can see the files with --stat

git log --stat --decorate --graph --oneline

Alternatively, you can use

gitk your_commit_here


问:
OAuthException using Socialite with facebook - "message": "An active access token must be used to query information about the current user.",
I have been using Socialite for a few days with Facebook without issue. Today, I started getting this error.

```<code>{ "error":
    {
       "message": "An active access token must be used to query information
        about the current user.", "type": "OAuthException",
        "code": 2500, "fbtrace_id": "FTvIz9t1LT+"
   }
}
</code>```

The error seems straight forward but I can't seem to see a solution online. Is there a way to reset my access_token using Socialite.

Please note: I pretty much followed this tutorial

The error is in the callback when I try and get the

```<code>$userProvider try {
    $userProvider = Socialite::driver('facebook')->user();
} catch (Exception $e) {
   Log::info('Callback Error ' . $e->getMessage());
   return Redirect::to('redirect');
}
</code>```

Thanks, Rich

答:
i think problem is parsing the token so changing this 2 lines should fix the problem

https://github.com/laravel/socialite/pull/214/files#diff-b221dafd8a91f5753288a2d8603cef25

Body:
I have been using Socialite for a few days with Facebook without issue. Today, I started getting this error.

{ "error":
    {
       "message": "An active access token must be used to query information
        about the current user.", "type": "OAuthException",
        "code": 2500, "fbtrace_id": "FTvIz9t1LT+"
   }
}

The error seems straight forward but I can't seem to see a solution online. Is there a way to reset my access_token using Socialite.

Please note: I pretty much followed this tutorial

The error is in the callback when I try and get the

$userProvider try {
    $userProvider = Socialite::driver('facebook')->user();
} catch (Exception $e) {
   Log::info('Callback Error ' . $e->getMessage());
   return Redirect::to('redirect');
}

Thanks, Rich


问:
Compare-And-Swap not working on many Cores
When I discovered the "CAS" instruction, I remember that I well understood that it could work for threads running on one single CPU but I was surprised that it could for many CPUs

Yesterday, I had my first opportunity to test it on one of my developments. I implemented it and it really worked fine; all my unit-tests was green. Perfect.

But today, I ran my unit-tests on another machine and they are now failing. Less perfect

The main difference on the two machines is that the first one (the one on which the unit-tests are green) is a quit old laptop, with only one core! The second one is more recent i7, and more powerfull...

Now, on my i7, if I force my unit-tests to run on one single core, they become successful. I do this by running

```<code>taskset -c <cpu-id> my-unit-test
</code>```

Legitimately, my original question comes back: is CAS working on many cores? OK, according to what I read, I would be surprised if it didn't...

So what? I hope it comes from a bug in my code. To give you more information, I have a class with a critical section. I added an attribute

```<code>bool m_isBeingModified;
</code>```

It is initialized to false. Moreover, at the beginning of my critical section, I run the function

```<code>inline void waitForClassBeingModified()
{
  while (!__sync_bool_compare_and_swap(&m_isBeingModified, false, true))
  {} /// I concider that I can to such a loop as my critical section is very light/short
}
</code>```

Finally, at the end of my critical section, I reset my boolean variable

```<code> m_isBeingModified = false;
</code>```

I tried to set my attribute as volatile but it did not change anything: my unit-tests are still failing

Last information:

```<code>gcc --version
gcc (Ubuntu 6.2.0-5ubuntu12) 6.2.0 20161005
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
</code>```

Thank you for your help

答:
Also use __sync_bool_compare_and_swap to unset the variable instead of just m_isBeingModified = false;. Also, don't implement your own mutex...

Both the compiler and the CPU can reorder code in unintended ways. The __sync primitives are marked in such a way to prevent this reordering from happining. Thus, with m_isBeingModified = false; it could very well the case that the compiler would first set the variable to false and only then generate the code for whatever you intended to be inside of the critical region.

Body:
When I discovered the "CAS" instruction, I remember that I well understood that it could work for threads running on one single CPU but I was surprised that it could for many CPUs

Yesterday, I had my first opportunity to test it on one of my developments. I implemented it and it really worked fine; all my unit-tests was green. Perfect.

But today, I ran my unit-tests on another machine and they are now failing. Less perfect

The main difference on the two machines is that the first one (the one on which the unit-tests are green) is a quit old laptop, with only one core! The second one is more recent i7, and more powerfull...

Now, on my i7, if I force my unit-tests to run on one single core, they become successful. I do this by running

taskset -c <cpu-id> my-unit-test

Legitimately, my original question comes back: is CAS working on many cores? OK, according to what I read, I would be surprised if it didn't...

So what? I hope it comes from a bug in my code. To give you more information, I have a class with a critical section. I added an attribute

bool m_isBeingModified;

It is initialized to false. Moreover, at the beginning of my critical section, I run the function

inline void waitForClassBeingModified()
{
  while (!__sync_bool_compare_and_swap(&m_isBeingModified, false, true))
  {} /// I concider that I can to such a loop as my critical section is very light/short
}

Finally, at the end of my critical section, I reset my boolean variable

 m_isBeingModified = false;

I tried to set my attribute as volatile but it did not change anything: my unit-tests are still failing

Last information:

gcc --version
gcc (Ubuntu 6.2.0-5ubuntu12) 6.2.0 20161005
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Thank you for your help


问:
How to prevent Tensorflow unpack() method casting to float64
I'm trying to set up a sequential RNN in Tensorflow with seq2seq.rnn_decoder().  The input that rnn_decoder() wants is a list of tensors, so to generate this I've passed in a rank-3 tensor and used tf.unpack() to make it into a list.  The problem arises when the float32 array that I pass in in turned into a float64 tensor by tf.unpack(), making it incompatible with the rest of the model.   Here's the code I put together to convince me that the culprit is tf.unpack():

```<code>inputDat = loader.getSequential(BATCH_SIZE)
print(inputDat.shape)
</code>```

output (BATCH_SIZE is five, sequence length is ten):

```<code>(10, 5, 3)
</code>```

Then I can load this data in a Tensorflow session:

```<code>sess = tf.InteractiveSession()
input_tensor = tf.constant(inputDat.astype('float32'), dtype=tf.float32)
print "Input tensor type: " + str(type(input_tensor.eval()[0,0,0]))
input_tensor = tf.unpack(inputDat)
print "Input tensor shape: " + str(len(input_tensor)) + "x" + str(input_tensor[0].eval().shape)
print "Input tensor type: " + str(type(input_tensor[0].eval()[0,0]))
</code>```

Output:

```<code>Input tensor type: <type 'numpy.float32'>
Input tensor shape: 10x(5, 3)
Input tensor type: <type 'numpy.float64'>
</code>```

What's going on here?   Using a FOR loop to iterate through each of the sequential entries and re-cast it seems like the wrong way to do this, and I can't find a method inside Tensorflow to cast every member of a list.

答:
You don't need a for-loop: you can use tf.cast().

Example:

```<code>input_tensor = tf.unpack(inputDat) # result is 64-bit
input_tensor = tf.cast(input_tensor, tf.float32) # now it's 32-bit
</code>```

Body:
I'm trying to set up a sequential RNN in Tensorflow with seq2seq.rnn_decoder().  The input that rnn_decoder() wants is a list of tensors, so to generate this I've passed in a rank-3 tensor and used tf.unpack() to make it into a list.  The problem arises when the float32 array that I pass in in turned into a float64 tensor by tf.unpack(), making it incompatible with the rest of the model.   Here's the code I put together to convince me that the culprit is tf.unpack():

inputDat = loader.getSequential(BATCH_SIZE)
print(inputDat.shape)

output (BATCH_SIZE is five, sequence length is ten):

(10, 5, 3)

Then I can load this data in a Tensorflow session:

sess = tf.InteractiveSession()
input_tensor = tf.constant(inputDat.astype('float32'), dtype=tf.float32)
print "Input tensor type: " + str(type(input_tensor.eval()[0,0,0]))
input_tensor = tf.unpack(inputDat)
print "Input tensor shape: " + str(len(input_tensor)) + "x" + str(input_tensor[0].eval().shape)
print "Input tensor type: " + str(type(input_tensor[0].eval()[0,0]))

Output:

Input tensor type: <type 'numpy.float32'>
Input tensor shape: 10x(5, 3)
Input tensor type: <type 'numpy.float64'>

What's going on here?   Using a FOR loop to iterate through each of the sequential entries and re-cast it seems like the wrong way to do this, and I can't find a method inside Tensorflow to cast every member of a list.

Body:
You don't need a for-loop: you can use tf.cast().

Example:

input_tensor = tf.unpack(inputDat) # result is 64-bit
input_tensor = tf.cast(input_tensor, tf.float32) # now it's 32-bit


问:
angular 2 pipe getting maximum and minimum value
I try to display maximum and minimum values in my table how can we get with angular 2 built in pipes here i try like this</p>

```<code> <td > {{value.max | MaxMinPipe}} </td>

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'MaxMinPipe'
})
export class MaxMinPipe implements PipeTransform {
  transform(value) {
   return Math.max(value);
  }

}
</code>```

答:
Its pretty easy way to get max amd min using ngx-pipes </p>

```<code> <td > {{rpi.north_h | max}} </td>
 <td > {{rpi.north_h | min}} </td>
</code>```

Body:
I try to display maximum and minimum values in my table how can we get with angular 2 built in pipes here i try like this

  {{value.max | MaxMinPipe}}

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'MaxMinPipe'
})
export class MaxMinPipe implements PipeTransform {
  transform(value) {
   return Math.max(value);
  }

}

Body:
Its pretty easy way to get max amd min using ngx-pipes

 <td > {{rpi.north_h | max}} </td>
 <td > {{rpi.north_h | min}} </td>


问:
RadScheduler - Capturing Appointment Save from the EditAppointmentTemplate - Web
I use telerik radscheduler on the web. I would like to do some validation when a user clicks on the Save Button in the EditAppointmentTemplate window. Is there any event that gets triggered that I will be able to use. I am seeing AppointmentSaving event in WPF, but not for the web.

Really appreciate your help.

答: You can subscribe to the OnAppointmentCommand event as described in Telerik's "Using Templates" Demo.


问:
swift UIImage blue square
I have a project where any image I try to call using .setImage shows a blue square instead of the image.

```<code>sender.setImage(UIImage(named: "o.png"), for: [])
print(sender.tag)
</code>```

any help is greatly appreciated

Edit: I forgot to mention this is setting an image for a button inside of an IBAction

答:
This occurs when the image you are trying to access is not in .png format.
Or else the image does not exist in the bundle at all.

Title: swift UIImage blue square

Body:
I have a project where any image I try to call using .setImage shows a blue square instead of the image.

sender.setImage(UIImage(named: "o.png"), for: [])
print(sender.tag)

any help is greatly appreciated

Edit: I forgot to mention this is setting an image for a button inside of an IBAction


问:
How to set focus on a textbox in Angular
How can I set focus on an element (such as a textbox) in a component's template? I have tried the below code.

Html:

```<code><input #input id="name" type="text" [(ngModel)]="person.Name" class="form-control" />
</code>```

Component:

```<code>import {Component, Input, Output, AfterContentInit, ContentChild,
    AfterViewChecked, AfterViewInit, ViewChild,ViewChildren} from 'angular2/core';

export class AppComponent implements AfterViewInit,AfterViewChecked {
    @ViewChildren('input') vc;

    ngAfterViewInit() {
        this.vc.first.nativeElement.focus();
    }
</code>```

But it's giving an error.

答:
Try using ElementRef, tested and working with Angular 4.0.1:

import { ElementRef } from '@angular/core';

@ViewChild('input') vc: ElementRef;

ngAfterViewInit() {
   this.vc.nativeElement.focus();
}
```

DEMO

Body:
How can I set focus on an element (such as a textbox) in a component's template? I have tried the below code.

Html:

<input #input id="name" type="text" [(ngModel)]="person.Name" class="form-control" />

Component:

import {Component, Input, Output, AfterContentInit, ContentChild,
    AfterViewChecked, AfterViewInit, ViewChild,ViewChildren} from 'angular2/core';

export class AppComponent implements AfterViewInit,AfterViewChecked {
    @ViewChildren('input') vc;

    ngAfterViewInit() {
        this.vc.first.nativeElement.focus();
    }

But it's giving an error.

Body:
Try using ElementRef, tested and working with Angular 4.0.1:

import { ElementRef } from '@angular/core';

@ViewChild('input') vc: ElementRef;

ngAfterViewInit() {
   this.vc.nativeElement.focus();
}

DEMO


问:
Silverlight PrtScr some controls
I need to programmatically PrtScr my controls in silverlight.(Save to bitmap)
How can i do this?</p>

答:
In WPF you can use the RenderTagetBitmap class to convert a Visual to an image, however this is not present in Sivlerlight. The following article details a rather long winded approach you can use to (sort of) save visuals in Silverlight. It's not a great solution though.

http://thedatafarm.com/blog/tablet/converting-silverlight-inkpresenter-images-to-a-png-file/

Title: Silverlight PrtScr some controls


问:
html check if input is greater than other input after submit
I have two input fields and want to check if one field is greater than the other.
I want to check this before the submit-Button is clicked.

<input type="text" name = "minValue" pattern="(|-)?[0-9]{0,3}?" id="min_value" value="" required/>

<input type="text" name = "maxValue" pattern="(|-)?[0-9]{0,3}?" id="max_value" value="" required/>

<button type = "submit" name = "submitcheck" id = "submit_check"> Let´s Go </button>```

Do I need jquery? I want to do this check before checking the submt button.

答:
You can try like his also

HTML

```<code><input type="text" name = "minValue" pattern="(|-)?[0-9]{0,3}?" id="min_value" value="" required/>

<input type="text" name = "maxValue" pattern="(|-)?[0-9]{0,3}?" id="max_value" value="" required/>

<button type = "submit" name = "submitcheck" id = "submit_check" onclick="return validate();"> Let´s Go </button>
</code>```

Script

```<code>function validate(){
     var max = parseInt(document.getElementById('max_value').value);
     var min = parseInt(document.getElementById('min_value').value);
     if(min > max){
         alert('Minvalue is greter than Maxvalue');
          return false;
     }else{
           alert('Maxvalue is greter than Minvalue');
          return false;
     }

}
</code>```

Thanks,

Body:
I have two input fields and want to check if one field is greater than the other.
I want to check this before the submit-Button is clicked.

<input type="text" name = "minValue" pattern="(|-)?[0-9]{0,3}?" id="min_value" value="" required/>

<input type="text" name = "maxValue" pattern="(|-)?[0-9]{0,3}?" id="max_value" value="" required/>

<button type = "submit" name = "submitcheck" id = "submit_check"> Let´s Go </button>

Do I need jquery? I want to do this check before checking the submt button.

Body:
You can try like his also

HTML

<input type="text" name = "minValue" pattern="(|-)?[0-9]{0,3}?" id="min_value" value="" required/>

<input type="text" name = "maxValue" pattern="(|-)?[0-9]{0,3}?" id="max_value" value="" required/>

<button type = "submit" name = "submitcheck" id = "submit_check" onclick="return validate();"> Let´s Go </button>

Script

function validate(){
     var max = parseInt(document.getElementById('max_value').value);
     var min = parseInt(document.getElementById('min_value').value);
     if(min > max){
         alert('Minvalue is greter than Maxvalue');
          return false;
     }else{
           alert('Maxvalue is greter than Minvalue');
          return false;
     }

}

Thanks,


答:
Use setBackgroundImage property instead of setImage property. It will work:

```<code>sender.setBackgroundImage(UIImage(named: "o.png"), for: .normal)
</code>```

Title: swift UIImage blue square

Body:
Use setBackgroundImage property instead of setImage property. It will work:

sender.setBackgroundImage(UIImage(named: "o.png"), for: .normal)


问:
allocating memory using calloc and freeing
gcc 4.4.4 c89

I have a program that I am testing. I create a struct object called devname and allocate memory so that I can fill the elements. I display them and then free the memory that was allocated.

However, I am getting the following error:

```<code>invalid operands to binary != (have ‘struct Devices_names’ and ‘void *’)
</code>```

That is in my for loop for displaying the structure elements. However, I feel I am testing for a NULL pointer.

Just a further question, is there an problem with the free?

Many thanks for any advice,

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

static struct Devices_names {
#define MAX_NAME_LEN 80
    int id;
    char name[MAX_NAME_LEN];
} *devname;

static void g_create_device_names(size_t devices);
static void g_get_device_names();
static void destroy_devices();

int main(void)
{
#define DEVICES 5
    g_create_device_names(DEVICES);

    g_get_device_names();

    destroy_devices();

    return 0;
}

static void g_create_device_names(size_t devices)
{
    size_t i = 0;
    devname = calloc(devices, sizeof *devname);
    if(devname == NULL) {
        exit(0);
    }

    for(i = 0; i < devices; i++) {
        devname[i].id = i;
        sprintf(devname[i].name, "device: %d", i);
    }
}

static void g_get_device_names()
{
    size_t i = 0;

    for(i = 0; devname[i] != NULL; i++) { <-- ERROR HERE
        printf("Device id --- [ %d ]\n", devname[i].id);
        printf("Device name - [ %s ]\n", devname[i].name);
    }
}

static void destroy_devices()
{
    while(devname != NULL) {
        free(devname++);
    }
}
</code>```

答:
Where you write:

```<code>for(i = 0; devname[i] != NULL; i++) { <-- ERROR HERE
</code>```

you are testing against NULL an instance of Device_names, not a pointer. It would be fine if you had an array of pointers to Device_names.

The other problem is that you are allocating only one Device_names, so you have not an array of them.

Body:
gcc 4.4.4 c89

I have a program that I am testing. I create a struct object called devname and allocate memory so that I can fill the elements. I display them and then free the memory that was allocated.

However, I am getting the following error:

invalid operands to binary != (have ‘struct Devices_names’ and ‘void *’)

That is in my for loop for displaying the structure elements. However, I feel I am testing for a NULL pointer.

Just a further question, is there an problem with the free?

Many thanks for any advice,

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

static struct Devices_names {
#define MAX_NAME_LEN 80
    int id;
    char name[MAX_NAME_LEN];
} *devname;

static void g_create_device_names(size_t devices);
static void g_get_device_names();
static void destroy_devices();

int main(void)
{
#define DEVICES 5
    g_create_device_names(DEVICES);

    g_get_device_names();

    destroy_devices();

    return 0;
}

static void g_create_device_names(size_t devices)
{
    size_t i = 0;
    devname = calloc(devices, sizeof *devname);
    if(devname == NULL) {
        exit(0);
    }

    for(i = 0; i < devices; i++) {
        devname[i].id = i;
        sprintf(devname[i].name, "device: %d", i);
    }
}

static void g_get_device_names()
{
    size_t i = 0;

    for(i = 0; devname[i] != NULL; i++) { <-- ERROR HERE
        printf("Device id --- [ %d ]\n", devname[i].id);
        printf("Device name - [ %s ]\n", devname[i].name);
    }
}

static void destroy_devices()
{
    while(devname != NULL) {
        free(devname++);
    }
}

Body:
Where you write:

for(i = 0; devname[i] != NULL; i++) { <-- ERROR HERE

you are testing against NULL an instance of Device_names, not a pointer. It would be fine if you had an array of pointers to Device_names.

The other problem is that you are allocating only one Device_names, so you have not an array of them.


问:
Print value after certain word and upto mentioned word
So I have a file.txt that goes like this

```<code>abc, def, class="my_name", this is good
def, hij, this is getting bad, and bad, class="my_class"
trying to achive my goal class="still_looking"
</code>```

So I need a value of class, ie:

```<code>my_name
my_class
still_looking
</code>```

I tried sed and grep but no success.

```<code>sed "s/[^class=]*,\([^\"]*\),^C/\1/" file.txt

grep -oP '(?<=class)[0-9][a-z][A-Z]+' file.txt
</code>```

答:
To capture and output all non " characters after class=" string:

```<code>sed 's/.*class="\([^"]*\)".*/\1/' file.txt
</code>```

or if multiple class per line, with grep, :

```<code>grep -oP '(?<=class=")[^"]*' file.txt
</code>```

Body:
So I have a file.txt that goes like this

abc, def, class="my_name", this is good
def, hij, this is getting bad, and bad, class="my_class"
trying to achive my goal class="still_looking"

So I need a value of class, ie:

my_name
my_class
still_looking

I tried sed and grep but no success.

sed "s/[^class=]*,\([^\"]*\),^C/\1/" file.txt

grep -oP '(?<=class)[0-9][a-z][A-Z]+' file.txt

Body:
To capture and output all non " characters after class=" string:

sed 's/.*class="\([^"]*\)".*/\1/' file.txt

or if multiple class per line, with grep, :

grep -oP '(?<=class=")[^"]*' file.txt


问:
Loop thru values code
This is what I’m trying to do:
When an order is created, click view link and and get redirected to the show page which contains the invoice.  I'm using the below code to loop thru values in the invoice. But its not working correctly, all invoices are showing up instead of only the selected one.
I already tried deleting the <% @orders.each do |order| %> but without any luck.

What am I missing here? Any idea?

```<code><% @orders.each do |order| %>
<% order.line_items.each do |line_item| %>
Order #<%= line_item.order_id %>
<%= order.first_name %> <%= order.last_name %>
<%= line_item.product.title %>
<%= number_to_currency line_item.product.price %>
<%= line_item.quantity %>
<%= number_to_currency line_item.total_price %>
<% end %>
<% end %>
</code>```

Update 1

route.rb: resources :orders, only: [:index, :new, :create, :show]

I don't have an invoice controller, everything is going thru the orders controller.

```<code>  def show
    @orders = Order.all
  end

 def new
    @cart = current_cart
    if @cart.line_items.empty?
    redirect_to root_url, notice: "Your cart is empty"
    return
    end

   @order = Order.new
    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @order }
   end
  end

  def create
    @order = Order.new(order_params)
    @order.add_line_items_from_cart(current_cart)
    @order.user_id = current_user.id

      if @order.save
      if @order.process
      redirect_to root_path, notice: "Successfully charged."
      and
      return
      end
    end
    render 'new'
  end
</code>```

答:
The Show method needs to look like this

```<code>def show
  @order = Order.find(params[:id])
end
</code>```

Make sure the route has the id in it, it should look like this where ":id" is a number (most likely)

```<code>/orders/:id
</code>```

If the route doe snot look like that change the route in the link to that,
probably something like the params[:id] bit is grabbing that id from the route and that is how it finds that specific order.

In your view you will not need to do the each loop.  You will be able to use the @order variable you create, so your view would look like this

```<code><%= @order.first_name %> <%= @order.last_name %>
</code>```

Title: Loop thru values code

Body:
This is what I’m trying to do:
When an order is created, click view link and and get redirected to the show page which contains the invoice.  I'm using the below code to loop thru values in the invoice. But its not working correctly, all invoices are showing up instead of only the selected one.
I already tried deleting the <% @orders.each do |order| %> but without any luck.

What am I missing here? Any idea?

<% @orders.each do |order| %>
<% order.line_items.each do |line_item| %>
Order #<%= line_item.order_id %>
<%= order.first_name %> <%= order.last_name %>
<%= line_item.product.title %>
<%= number_to_currency line_item.product.price %>
<%= line_item.quantity %>
<%= number_to_currency line_item.total_price %>
<% end %>
<% end %>

Update 1

route.rb: resources :orders, only: [:index, :new, :create, :show]

I don't have an invoice controller, everything is going thru the orders controller.

  def show
    @orders = Order.all
  end

 def new
    @cart = current_cart
    if @cart.line_items.empty?
    redirect_to root_url, notice: "Your cart is empty"
    return
    end

   @order = Order.new
    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @order }
   end
  end

  def create
    @order = Order.new(order_params)
    @order.add_line_items_from_cart(current_cart)
    @order.user_id = current_user.id

      if @order.save
      if @order.process
      redirect_to root_path, notice: "Successfully charged."
      and
      return
      end
    end
    render 'new'
  end

Body:
The Show method needs to look like this

def show
  @order = Order.find(params[:id])
end

Make sure the route has the id in it, it should look like this where ":id" is a number (most likely)

/orders/:id

If the route doe snot look like that change the route in the link to that,
probably something like the params[:id] bit is grabbing that id from the route and that is how it finds that specific order.

In your view you will not need to do the each loop.  You will be able to use the @order variable you create, so your view would look like this

<%= @order.first_name %> <%= @order.last_name %>


问:
QSettings how to save QMap<QString,int> into configuration file
After reading Save QList<int> to QSettings, I'm tring to do the same with QMap<QString,int>. I would like the configuration file to look like this:

```<code>1111=1
2222=3
4444=0
</code>```

But I'm getting a compilation error:

```<code>Q_DECLARE_METATYPE(QMap<QString,int>)

Warning C4002: too many actual parameters for macro 'Q_DECLARE_METATYPE'
ConfigSettings.h(5) : error C2976: 'QMap' : too few template arguments
</code>```

答:
QSetting accept QVariant type to pass into setValue method, so it means that you can store QMap<QString, QVarint> map directly to settings

```<code>// Store
QMap<QString, QVariant> storeMap;
QMapIterator it(myMap);
// iterate through the map to save the values in your chosen format
while(it.hasNext())
{
    storeMap[it.key()] = QVariant(it.value());
    it.next();
}
settings.setValue("myKey", storeMap);

..
// Read
QMap<QString, QVariant> readMap = settings.value("myKey").toMap();
QMapIterator it(readMap);
while(it.hasNext())
{
    myMap[it.key()] = it.value().toInt();
    it.next();
}
</code>```

Body:
After reading Save QList<int> to QSettings, I'm tring to do the same with QMap<QString,int>. I would like the configuration file to look like this:

1111=1
2222=3
4444=0

But I'm getting a compilation error:

Q_DECLARE_METATYPE(QMap<QString,int>)

Warning C4002: too many actual parameters for macro 'Q_DECLARE_METATYPE'
ConfigSettings.h(5) : error C2976: 'QMap' : too few template arguments

Body:
QSetting accept QVariant type to pass into setValue method, so it means that you can store QMap<QString, QVarint> map directly to settings

// Store
QMap<QString, QVariant> storeMap;
QMapIterator it(myMap);
// iterate through the map to save the values in your chosen format
while(it.hasNext())
{
    storeMap[it.key()] = QVariant(it.value());
    it.next();
}
settings.setValue("myKey", storeMap);

..
// Read
QMap<QString, QVariant> readMap = settings.value("myKey").toMap();
QMapIterator it(readMap);
while(it.hasNext())
{
    myMap[it.key()] = it.value().toInt();
    it.next();
}


问:
mysqldump table selected row cron job
I am using cron job to dump a table in my database. This code works fine and dumps me a sql file.

```<code>mysqldump pabu1v2_pabu tbl_students > /home/pabu1v2/autobackup/backups1.sql
</code>```

I don't know how to dump only specific rows from this table. But do I wrote this

```<code>mysqldump pabu1v2_pabu tbl_students where="schoolid = '113'" > /home/pabu1v2/autobackup/backups1.sql
</code>```

It gives me a blank sql.

Please, help. I am writing this directly in cron jobs not in php.

答:
Try:

$ mysqldump pabu1v2_pabu tbl_students --where="schoolid = 113" > /home/pabu1v2/autobackup/backups1.sql
```

See 5.5.4 mysqldump — A Database Backup Program :: where.

Title: mysqldump table selected row cron job

Body:
I am using cron job to dump a table in my database. This code works fine and dumps me a sql file.

mysqldump pabu1v2_pabu tbl_students > /home/pabu1v2/autobackup/backups1.sql

I don't know how to dump only specific rows from this table. But do I wrote this

mysqldump pabu1v2_pabu tbl_students where="schoolid = '113'" > /home/pabu1v2/autobackup/backups1.sql

It gives me a blank sql.

Please, help. I am writing this directly in cron jobs not in php.

Body:
Try:

$ mysqldump pabu1v2_pabu tbl_students --where="schoolid = 113" > /home/pabu1v2/autobackup/backups1.sql

See 5.5.4 mysqldump — A Database Backup Program :: where.


问:
Object Spread and Rest Operators in Typescript 2.1 - error at usage attempt
Typescript 2.1.6

I have the foolowing:

registrant.reducers.ts

```<code>const registration_reducers = {
languageData: languageDataReducer,
  languageUi: languageUiReducer}
</code>```

app.reducers.ts

```<code>import { registration_reducers } from '../registration/+registrant/registrant.reducers'

const reducers = {...registration_reducers}
</code>```

Webstorm displays no errors. However, compilation fails with the following message:

```<code>ERROR in ./src/app/store/app.reducer.ts
Module build failed: TypeError: Cannot read property 'kind' of undefined
    at _getContentOfKeyLiteral (J:\workspace\angular2\ts\epimss\node_modules\@ngtools\webpack\src\loader.js:9:13)
    at node.properties.some.prop (J:\workspace\angular2\ts\epimss\node_modules\@ngtools\webpack\src\loader.js:205:56)
    at Array.some (native)
    at refactor.findAstNodes.filter (J:\workspace\angular2\ts\epimss\node_modules\@ngtools\webpack\src\loader.js:205:43)
    at Array.filter (native)
    at _removeModuleId (J:\workspace\angular2\ts\epimss\node_modules\@ngtools\webpack\src\loader.js:205:10)
    at Promise.resolve.then.then (J:\workspace\angular2\ts\epimss\node_modules\@ngtools\webpack\src\loader.js:301:33)
 @ ./src/app/app.module.ts 21:0-46
 @ ./src/main.ts
 @ multi webpack-dev-server/client?http://localhost:4200/ ./src/main.ts
</code>```

Reading the docs https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html>Object Spread and Rest suggest that this should work.

What am I doing wrong.
Cheers

答:
If this is in fact related to the Spread operator:

Angular 2.4.2 added support for TypeScript 2.1, in which case you need to make sure that you are running that first (check your package.json).

I would also suggest doing a fresh/clean install of your node_modules.

Body:
Typescript 2.1.6

I have the foolowing:

registrant.reducers.ts

const registration_reducers = {
languageData: languageDataReducer,
  languageUi: languageUiReducer}

app.reducers.ts

import { registration_reducers } from '../registration/+registrant/registrant.reducers'

const reducers = {...registration_reducers}

Webstorm displays no errors. However, compilation fails with the following message:

ERROR in ./src/app/store/app.reducer.ts
Module build failed: TypeError: Cannot read property 'kind' of undefined
    at _getContentOfKeyLiteral (J:\workspace\angular2\ts\epimss\node_modules\@ngtools\webpack\src\loader.js:9:13)
    at node.properties.some.prop (J:\workspace\angular2\ts\epimss\node_modules\@ngtools\webpack\src\loader.js:205:56)
    at Array.some (native)
    at refactor.findAstNodes.filter (J:\workspace\angular2\ts\epimss\node_modules\@ngtools\webpack\src\loader.js:205:43)
    at Array.filter (native)
    at _removeModuleId (J:\workspace\angular2\ts\epimss\node_modules\@ngtools\webpack\src\loader.js:205:10)
    at Promise.resolve.then.then (J:\workspace\angular2\ts\epimss\node_modules\@ngtools\webpack\src\loader.js:301:33)
 @ ./src/app/app.module.ts 21:0-46
 @ ./src/main.ts
 @ multi webpack-dev-server/client?http://localhost:4200/ ./src/main.ts

Reading the docs https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html>Object Spread and Rest suggest that this should work.

What am I doing wrong.
Cheers


答:
After clicking the sender state changed as selected.

So kindly clear the tint color of sender

otherwise

```<code>sender.setImage(UIImage(named: "o.png"), for: .normal)
</code>```

Title: swift UIImage blue square

Body:
I have a project where any image I try to call using .setImage shows a blue square instead of the image.

sender.setImage(UIImage(named: "o.png"), for: [])
print(sender.tag)

any help is greatly appreciated

Edit: I forgot to mention this is setting an image for a button inside of an IBAction

Body:
After clicking the sender state changed as selected.

So kindly clear the tint color of sender

otherwise

sender.setImage(UIImage(named: "o.png"), for: .normal)


问:
Position a dialog box in center of viewable region of a browser window using javascript/DOM
I need to position a dialog box(read div) in the center of viewable region of a browser window. I need to use javascript DOM for doing this - making use of scrollHeight, scrollTop, clientHeight, etc. is permissible.
The dialog box needs to appear upon clicking a link, it remains invisible otherwise.

CAN'T USE JQUERY TO CREATE A MODAL DIALOG.

Can somebody help me with the centering part of this problem

Regards

答:
```<code>(function () {
  var getVieportWidth,
      getViewportHeight;

  if (window.innerWidth) {
    // All browsers except IE
    getViewportWidth = function() { return window.innerWidth; };
    getViewportHeight = function() { return window.innerHeight; };
  }
  else if (document.documentElement && document.documentElement.clientWidth) {
    // IE6 with DOCTYPE
    getViewportWidth = function() { return document.documentElement.clientWidth; };
    getViewportHeight = function() { return document.documentElement.clientHeight; };
  }
  else if (document.body.clientWidth) {
    // IE4, IE5, IE6 without DOCTYPE
    getViewportWidth = function() { return document.body.clientWidth; };
    getViewportHeight = function() { return document.body.clientHeight; };
  }

  var dialogDIVNode = document.getElementById('someID'),
      dialogDIVNodeWidth = dialogDIVNode.offsetWidth,
      dialogDIVNodeHeight = dialogDIVNode.offsetHeight;

  document.getElementById('someLinkID').addEventListener('click', function (e) {
    e.preventDefault();

    dialogDIVNode.style.left = ( getViewportWidth() / 2 - dialogDIVNodeWidth / 2 ) + 'px';
    dialogDIVNode.style.top = ( getViewportHeight() / 2 - dialogDIVNodeHeight / 2) + 'px';
    dialogDIVNode.style.display = 'block';
  }, false);
}());
</code>```


问:
ASP .NET MVC multiple models in one view
I have this two classes:

```<code>public class Kolobezka : IEntity1
{
    public virtual int Id { get; set; }
    public virtual int VelikostKola { get; set; }
    public virtual string Znacka { get; set; }
    public virtual string Stav { get; set; }
    public virtual string Description { get; set; }
    public virtual Kategorie_kolobezek Kategorie { get; set; }
    public virtual int Dostupnost { get; set; }

}
public class Rezervace : IEntity1
    {
        public virtual int Id { get; set; }
        public virtual Kolobezka Rez_kolobezky { get; set; }
        [Required(ErrorMessage = "Jméno je požadováno!")]
        public virtual string Jmeno { get; set; }
        [Required(ErrorMessage = "Příjmení je požadováno!")]
        public virtual string Prijmeni { get; set; }
        [Required(ErrorMessage = "Datum začátku rezervace je požadováno!")]
        public virtual DateTime Datum_od { get; set; }
        [Required(ErrorMessage = "Datum konce rezervace je požadováno!")]
        public virtual DateTime Datum_do { get; set; }
        public virtual string Popis { get; set; }
    }
</code>```

So I need in one view called Index use two Ilists from those two clases because of this:

```<code>@foreach (Kolobezka k in Model)
        {

            foreach (Rezervace r1 in r)
            {
                if(k.Id == r1.Rez_kolobezky.Id && r1.Datum_od < DateTime.Now && r1.Datum_do > DateTime.Now)
                {
                    k.Dostupnost = 1;
                }
            }

            if (k.Dostupnost == 0)
            {
                <tr class="bg-danger">
                    <td>
                        @Ajax.ActionLink(k.Id.ToString(), "Detail", new { id = k.Id },
                       new AjaxOptions() { UpdateTargetId = "modalContent",
                           InsertionMode = InsertionMode.Replace, OnBegin = "openModalWindow" })
                    </td>
                    <td>@k.VelikostKola</td>
                    <td>@k.Znacka</td>
                    <td>@k.Kategorie.Nazev</td>
                    <td>@k.Stav</td>
                </tr>
            }
</code>```

Whot should I write instead r in the second foreach.
The beginning of index view looks like this:

```<code>@using ClassLibrary1.Model
@model IList<Kolobezka>

@{
    ViewBag.Title = "Index";
}
</code>```

Thank you a lot.

答:
To be able to use both models, viz. Kolobezka and Rezervace, it is suggested to create a ViewModel for this, which will have properties for both these classes. Something like this for example -

```<code>public class KolobezkaRezervaceViewModel
{
    public IEnumerable<Kolobezka> Kolobezkas { get; set; }
    public IEnumerable<Rezervace> Rezervaces { get; set; }
}
</code>```

You can then, bind you View with this ViewModel, that we have created just now, like -

```<code>@model MyWebApplication.Models.KolobezkaRezervaceViewModel
</code>```

Now you can simply use them in your view like this -

```<code>@foreach (Kolobezka k in Model.Kolobezkas)
</code>```

...and

```<code>foreach (Rezervace r1 in Model.Rezervaces)
</code>```

Make sure you are correctly populating the values for you model from your controller.

Body:
I have this two classes:

public class Kolobezka : IEntity1
{
    public virtual int Id { get; set; }
    public virtual int VelikostKola { get; set; }
    public virtual string Znacka { get; set; }
    public virtual string Stav { get; set; }
    public virtual string Description { get; set; }
    public virtual Kategorie_kolobezek Kategorie { get; set; }
    public virtual int Dostupnost { get; set; }

}
public class Rezervace : IEntity1
    {
        public virtual int Id { get; set; }
        public virtual Kolobezka Rez_kolobezky { get; set; }
        [Required(ErrorMessage = "Jméno je požadováno!")]
        public virtual string Jmeno { get; set; }
        [Required(ErrorMessage = "Příjmení je požadováno!")]
        public virtual string Prijmeni { get; set; }
        [Required(ErrorMessage = "Datum začátku rezervace je požadováno!")]
        public virtual DateTime Datum_od { get; set; }
        [Required(ErrorMessage = "Datum konce rezervace je požadováno!")]
        public virtual DateTime Datum_do { get; set; }
        public virtual string Popis { get; set; }
    }

So I need in one view called Index use two Ilists from those two clases because of this:

@foreach (Kolobezka k in Model)
        {

            foreach (Rezervace r1 in r)
            {
                if(k.Id == r1.Rez_kolobezky.Id && r1.Datum_od < DateTime.Now && r1.Datum_do > DateTime.Now)
                {
                    k.Dostupnost = 1;
                }
            }

            if (k.Dostupnost == 0)
            {

                        @Ajax.ActionLink(k.Id.ToString(), "Detail", new { id = k.Id },
                       new AjaxOptions() { UpdateTargetId = "modalContent",
                           InsertionMode = InsertionMode.Replace, OnBegin = "openModalWindow" })

                    @k.VelikostKola
                    @k.Znacka
                    @k.Kategorie.Nazev
                    @k.Stav

            }

Whot should I write instead r in the second foreach.
The beginning of index view looks like this:

@using ClassLibrary1.Model
@model IList<Kolobezka>

@{
    ViewBag.Title = "Index";
}

Thank you a lot.

Body:
To be able to use both models, viz. Kolobezka and Rezervace, it is suggested to create a ViewModel for this, which will have properties for both these classes. Something like this for example -

public class KolobezkaRezervaceViewModel
{
    public IEnumerable<Kolobezka> Kolobezkas { get; set; }
    public IEnumerable<Rezervace> Rezervaces { get; set; }
}

You can then, bind you View with this ViewModel, that we have created just now, like -

@model MyWebApplication.Models.KolobezkaRezervaceViewModel

Now you can simply use them in your view like this -

@foreach (Kolobezka k in Model.Kolobezkas)

...and

foreach (Rezervace r1 in Model.Rezervaces)

Make sure you are correctly populating the values for you model from your controller.


问:
Component not rendering in simple React.js app
I'm trying to get a simple "Hello, World"-type React.js app from the book React and React Native running under Node/webpack-dev-server. I'm not seeing any errors, but the page is blank when I visit it in my browser.

Here's how I tried—and failed—to run the book's very first example:

Install node and npm using these steps (adapted from this gist):

```<code>$ mkdir ~/.local/node-latest-install
$ cd ~/.local/node-latest-install
$ curl http://nodejs.org/dist/node-latest.tar.gz | tar xz --strip-components=1
$ ./configure --prefix=~/.local
$ make -j install
$ curl https://www.npmjs.com/install.sh | sh
$ node -v; npm -v
v7.7.4
4.1.2
</code>```

Clone the examples repo from the book:

```<code>$ git clone https://github.com/PacktPublishing/React-and-React-Native.git
</code>```

Run npm install from the top-level examples folder:

```<code>$ cd React-and-React-Native
$ npm install
</code>```

Attempt to compile/run hello-jsx example:

```<code>$ cd Chapter02/hello-jsx
$ node ../../node_modules/webpack-dev-server/bin/webpack-dev-server.js
...
ERROR in ./main.js
Module build failed: Error: React Hot Loader: The Webpack loader is now exported separately. If you use Babel, we recommend that you remove "react-hot-loader" from the "loaders" section of your Webpack configuration altogether, and instead add "react-hot-loader/babel" to the "plugins" section of your .babelrc file. If you prefer not to use Babel, replace "react-hot-loader" or "react-hot" with "react-hot-loader/webpack" in the "loaders" section of your Webpack configuration.
at Object.warnAboutIncorrectUsage (/home/evadeflow/.local/React-and-React-Native/node_modules/react-hot-loader/lib/index.js:7:11)
@ multi main
webpack: Failed to compile.
</code>```

Edit hello-jsx/webpack.config.js to work around the above error:

```<code>diff --git a/Chapter02/hello-jsx/webpack.config.js b/Chapter02/hello-jsx/webpack.config.js
index 312f152..592e767 100644
--- a/Chapter02/hello-jsx/webpack.config.js
+++ b/Chapter02/hello-jsx/webpack.config.js
@@ -13,7 +13,7 @@ module.exports = {
       {
         test: /\.jsx?$/,
         exclude: /node_modules/,
-        loaders: ['react-hot', 'babel?presets[]=es2015'],
+        loaders: ['react-hot-loader/webpack', 'babel?presets[]=es2015'],
       },
     ],
   },
</code>```

Recompile/re-run:

```<code>$ node ../../node_modules/webpack-dev-server/bin/webpack-dev-server.js
http://localhost:8080/webpack-dev-server/
webpack result is served from /
content is served from /home/evadeflow/.local/React-and-React-Native/Chapter02/hello-jsx
Hash: 590282c761dccbb5710a
Version: webpack 1.14.0
Time: 1260ms
         Asset    Size  Chunks             Chunk Names
main-bundle.js  978 kB       0  [emitted]  main
chunk    {0} main-bundle.js (main) 923 kB [rendered]
    [0] multi main 52 bytes {0} [built]
    [1] (webpack)-dev-server/client?http://0.0.0.0:8080 3.97 kB {0} [built]
    [2] /home/evadeflow/.local/React-and-React-Native/~/url/url.js 23.3 kB {0} [built]
    [3] /home/evadeflow/.local/React-and-React-Native/~/url/~/punycode/punycode.js 14.6 kB {0} [built]

  <... lots of similar output omitted ...>

  [251] /home/evadeflow/.local/React-and-React-Native/~/react-dom/lib/ReactDOMUnknownPropertyHook.js 4.32 kB {0} [built]
  [252] /home/evadeflow/.local/React-and-React-Native/~/react-dom/lib/ReactDOMNullInputValuePropHook.js 1.37 kB {0} [built]
  [253] /home/evadeflow/.local/React-and-React-Native/~/react-dom/lib/ReactDOMInvalidARIAHook.js 3.14 kB {0} [built]
webpack: Compiled successfully.
</code>```

After the last step, node is running. However, I see a blank page when I hit localhost:8080 in my browser:

Am I doing something wrong?

答:
I've resolved a lot of these issues. Try pulling the latest.

The two major things I've fixed are:

Using Webpack 2 as a dependency and adding instructions for installing webpack/webpack-dev-server globally as part of the initial setup.

Simplified webpack configuration for each example. We only need babel-loader and one entry point.

Give it a try, let me know if it's any easier to get going.

Body:
I'm trying to get a simple "Hello, World"-type React.js app from the book React and React Native running under Node/webpack-dev-server. I'm not seeing any errors, but the page is blank when I visit it in my browser.

Here's how I tried—and failed—to run the book's very first example:

Install node and npm using these steps (adapted from this gist):

$ mkdir ~/.local/node-latest-install
$ cd ~/.local/node-latest-install
$ curl http://nodejs.org/dist/node-latest.tar.gz | tar xz --strip-components=1
$ ./configure --prefix=~/.local
$ make -j install
$ curl https://www.npmjs.com/install.sh | sh
$ node -v; npm -v
v7.7.4
4.1.2

Clone the examples repo from the book:

$ git clone https://github.com/PacktPublishing/React-and-React-Native.git

Run npm install from the top-level examples folder:

$ cd React-and-React-Native
$ npm install

Attempt to compile/run hello-jsx example:

$ cd Chapter02/hello-jsx
$ node ../../node_modules/webpack-dev-server/bin/webpack-dev-server.js
...
ERROR in ./main.js
Module build failed: Error: React Hot Loader: The Webpack loader is now exported separately. If you use Babel, we recommend that you remove "react-hot-loader" from the "loaders" section of your Webpack configuration altogether, and instead add "react-hot-loader/babel" to the "plugins" section of your .babelrc file. If you prefer not to use Babel, replace "react-hot-loader" or "react-hot" with "react-hot-loader/webpack" in the "loaders" section of your Webpack configuration.
at Object.warnAboutIncorrectUsage (/home/evadeflow/.local/React-and-React-Native/node_modules/react-hot-loader/lib/index.js:7:11)
@ multi main
webpack: Failed to compile.

Edit hello-jsx/webpack.config.js to work around the above error:

diff --git a/Chapter02/hello-jsx/webpack.config.js b/Chapter02/hello-jsx/webpack.config.js
index 312f152..592e767 100644
--- a/Chapter02/hello-jsx/webpack.config.js
+++ b/Chapter02/hello-jsx/webpack.config.js
@@ -13,7 +13,7 @@ module.exports = {
       {
         test: /\.jsx?$/,
         exclude: /node_modules/,
-        loaders: ['react-hot', 'babel?presets[]=es2015'],
+        loaders: ['react-hot-loader/webpack', 'babel?presets[]=es2015'],
       },
     ],
   },

Recompile/re-run:

$ node ../../node_modules/webpack-dev-server/bin/webpack-dev-server.js
http://localhost:8080/webpack-dev-server/
webpack result is served from /
content is served from /home/evadeflow/.local/React-and-React-Native/Chapter02/hello-jsx
Hash: 590282c761dccbb5710a
Version: webpack 1.14.0
Time: 1260ms
         Asset    Size  Chunks             Chunk Names
main-bundle.js  978 kB       0  [emitted]  main
chunk    {0} main-bundle.js (main) 923 kB [rendered]
    [0] multi main 52 bytes {0} [built]
    [1] (webpack)-dev-server/client?http://0.0.0.0:8080 3.97 kB {0} [built]
    [2] /home/evadeflow/.local/React-and-React-Native/~/url/url.js 23.3 kB {0} [built]
    [3] /home/evadeflow/.local/React-and-React-Native/~/url/~/punycode/punycode.js 14.6 kB {0} [built]

  <... lots of similar output omitted ...>

  [251] /home/evadeflow/.local/React-and-React-Native/~/react-dom/lib/ReactDOMUnknownPropertyHook.js 4.32 kB {0} [built]
  [252] /home/evadeflow/.local/React-and-React-Native/~/react-dom/lib/ReactDOMNullInputValuePropHook.js 1.37 kB {0} [built]
  [253] /home/evadeflow/.local/React-and-React-Native/~/react-dom/lib/ReactDOMInvalidARIAHook.js 3.14 kB {0} [built]
webpack: Compiled successfully.

After the last step, node is running. However, I see a blank page when I hit localhost:8080 in my browser:

Am I doing something wrong?


问:
Scrolling in calabash-android
I am trying to scroll down in calabash-android but couldn't.
Here is the code that I using for the scrolling part

In feature file:

```<code>Then I scrolldown until I see "Engine Light On"
</code>```

In calabash_steps.rb:

Then /^I scroll until I see the "([^\"]*)" text$/ do |text|
  q = query("TextView text:'#{text}'")
  while q.empty?
    scroll_down
    q = query("TextView text:'#{text}'")
  end
end

the error that I am getting:

答:
We can use the following code in the calasbash_steps.rb file.

```<code>Then(/^I scroll view "([^"]*)" "([^"]*)"$/) do |view,direction|
   scroll("#{view}",:"#{direction}")
end
</code>```

In the .feature file, we can pass the view and directions in the manner you want to scroll.Here is a sample:

```<code>Then I scroll view "ExpandableListView" "down"
Then I scroll view "ExpandableListView" "up"
</code>```

Title: Scrolling in calabash-android

Body:
I am trying to scroll down in calabash-android but couldn't.
Here is the code that I using for the scrolling part

In feature file:

Then I scrolldown until I see "Engine Light On"

In calabash_steps.rb:

Then /^I scroll until I see the "([^\"]*)" text$/ do |text|
  q = query("TextView text:'#{text}'")
  while q.empty?
    scroll_down
    q = query("TextView text:'#{text}'")
  end
end

the error that I am getting:

Body:
We can use the following code in the calasbash_steps.rb file.

Then(/^I scroll view "([^"]*)" "([^"]*)"$/) do |view,direction|
   scroll("#{view}",:"#{direction}")
end

In the .feature file, we can pass the view and directions in the manner you want to scroll.Here is a sample:

Then I scroll view "ExpandableListView" "down"
Then I scroll view "ExpandableListView" "up"


问:
Lumen: Enable CORS
I built an API with Lumen and want to access it with JavaScript and the XMLHttpRequest object. But every time my PUT, GET, POST, and DELETE requests are transformed into OPTIONS - Request. I read a lot of websites with information of CORS. I build middleware with the following content:

```<code>class CORSMiddleware
{
    public function handle($request, \Closure $next)
    {
      $response = null;
      /* Preflight handle */
      if ($request->isMethod('OPTIONS')) {
         $response = new Response();
      } else {
         $response = $next($request);
      }

      $response->header('Access-Control-Allow-Methods', 'OPTIONS, HEAD, GET, POST, PUT, DELETE');
      $response->header('Access-Control-Allow-Headers', $request->header('Access-Control-Request-Headers'));
      $response->header('Access-Control-Allow-Origin', '*');
      return $response;
    }
}
</code>```

My client code:

```<code>var url = "http://localhost:8000/api/user";
var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open('PUT', url, false);
xmlHttpRequest.send('{"username": "ABC", "password": "ABC","email": "mail@cool.xyz" }');
if (xmlHttpRequest.status == 200) {
  console.log(xmlHttpRequest.responseText);
}
</code>```

My request-information of GET request:

```<code>Host: localhost:8000
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: de,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Origin: null
Connection: keep-alive
Cache-Control: max-age=0
</code>```

My response-information of a GET request:

```<code>Access-Control-Allow-Methods: OPTIONS, HEAD, GET, POST, PUT, DELETE
Access-Control-Allow-Origin: *
Cache-Control: no-cache
Connection: close
Content-Type: text/html; charset=UTF-8
Date: Sun, 27 Dec 2015 10:36:51 GMT
Host: localhost:8000
x-powered-by: PHP/7.0.0
</code>```

My request-information of a PUT request:

```<code>Host: localhost:8000
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: de,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: PUT
Origin: null
Connection: keep-alive
Cache-Control: max-age=0
</code>```

My response information of a PUT request:

```<code>Cache-Control: no-cache
Connection: close
Content-Type: text/html; charset=UTF-8
Date: Sun, 27 Dec 2015 10:36:51 GMT
Host: localhost:8000
x-powered-by: PHP/7.0.0
</code>```

In the preflight there are no "Access-Control-Allow-*"-Headers. I don't know why; I enabled it with my lumen-cors-middleware.

答:
Add following headers into public/.htaccess file.

```<code>Header set Access-Control-Allow-Origin "*"
Header set  Access-Control-Allow-Methods "GET,POST,PUT,DELETE,OPTIONS"
Header set Access-Control-Allow-Credentials "true"
</code>```

this is working fine for to resolve Cross Origin Issue.

Title: Lumen: Enable CORS

Body:
I built an API with Lumen and want to access it with JavaScript and the XMLHttpRequest object. But every time my PUT, GET, POST, and DELETE requests are transformed into OPTIONS - Request. I read a lot of websites with information of CORS. I build middleware with the following content:

class CORSMiddleware
{
    public function handle($request, \Closure $next)
    {
      $response = null;
      /* Preflight handle */
      if ($request->isMethod('OPTIONS')) {
         $response = new Response();
      } else {
         $response = $next($request);
      }

      $response->header('Access-Control-Allow-Methods', 'OPTIONS, HEAD, GET, POST, PUT, DELETE');
      $response->header('Access-Control-Allow-Headers', $request->header('Access-Control-Request-Headers'));
      $response->header('Access-Control-Allow-Origin', '*');
      return $response;
    }
}

My client code:

var url = "http://localhost:8000/api/user";
var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open('PUT', url, false);
xmlHttpRequest.send('{"username": "ABC", "password": "ABC","email": "mail@cool.xyz" }');
if (xmlHttpRequest.status == 200) {
  console.log(xmlHttpRequest.responseText);
}

My request-information of GET request:

Host: localhost:8000
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: de,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Origin: null
Connection: keep-alive
Cache-Control: max-age=0

My response-information of a GET request:

Access-Control-Allow-Methods: OPTIONS, HEAD, GET, POST, PUT, DELETE
Access-Control-Allow-Origin: *
Cache-Control: no-cache
Connection: close
Content-Type: text/html; charset=UTF-8
Date: Sun, 27 Dec 2015 10:36:51 GMT
Host: localhost:8000
x-powered-by: PHP/7.0.0

My request-information of a PUT request:

Host: localhost:8000
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: de,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: PUT
Origin: null
Connection: keep-alive
Cache-Control: max-age=0

My response information of a PUT request:

Cache-Control: no-cache
Connection: close
Content-Type: text/html; charset=UTF-8
Date: Sun, 27 Dec 2015 10:36:51 GMT
Host: localhost:8000
x-powered-by: PHP/7.0.0

In the preflight there are no "Access-Control-Allow-*"-Headers. I don't know why; I enabled it with my lumen-cors-middleware.

Body:
Add following headers into public/.htaccess file.

Header set Access-Control-Allow-Origin "*"
Header set  Access-Control-Allow-Methods "GET,POST,PUT,DELETE,OPTIONS"
Header set Access-Control-Allow-Credentials "true"

this is working fine for to resolve Cross Origin Issue.


问:
Create a stacked bar using a frequency table
Actually I'm working with two frequency tables who have got the name: identified_modification_table and unidentified_modifications_table

The structure of these files are something like that:

identified_modification_table

```<code>Modifications   | Frequency
MOD:42123       | 12
MOD:1234        | 7
MOD:7618        | 36
MOD:411232      | 51
</code>```

unidentified_modifications_table

```<code>Modifications   | Frequency
MOD:42123       | 12
MOD:12          | 20
MOD:7618        | 36
MOD:411232      | 51
</code>```

I would like to merge these files and create this output in order to create a stacked barplot like this example.

```<code>Modifications   | Frequency.1 | Frequency.2
MOD:42123       | 12          | 12
MOD:1234        | 7           | NA
MOD:12          | NA          | 20
MOD:7618        | 36          | 36
MOD:411232      | 51          | 51
</code>```

I was trying to use this code to merge tables and add NA where the value doesn't exist.

```<code>df_final <- cbind.data.frame(df1, df2[match(df1$modifications, df2$modifications), ]);
</code>```

But this doesn't work properly and I don't know why.

After this I think I should just use melt and ggplot2 stacked bar:

```<code>df_barplot <- melt(df,measure.vars = names(df))

ggplot((df_barplot), aes(x = value, fill = variable)) +
    geom_bar(stat = "count", position = "dodge") +
    theme(axis.text.x = element_text(angle = 20, hjust = 0.5, vjust = -0.1)) +
    guides(fill=FALSE)+
    labs("Barplot") +
    xlab("Values")+
    ylab("Frequency")+
    theme(text = element_text(size=18), axis.text.x = element_text(angle = 90, hjust = 1, size = 15), axis.text.y=element_text(size = 15))
</code>```

Does anyone know how I could do this?

Here you are and a reproducible example:

```<code>df1 <- data.frame(modifications=c("MOD:214", "MOD:3","MOD:24","MOD:44","MOD:123", "MOD:123", "MOD:212"), Frequency=c(1,41,616,727,828,8993,383))

  df2 <- data.frame(modifications=c("MOD:214", "MOD:3","MOD:24","MOD:445","MOD:12", "MOD:123", "MOD:212"), Frequency=c(1,43,64,77,88,893,38))
</code>```

Thank you

答:
Here's the tidyverse way:

```<code>library(tidyverse)
merged_df <- full_join(df1, df2, by = "modifications")
merged_df <- gather(merged_df, key = Category, value = Frequency, -modifications)
</code>```

And the chart:

```<code>ggplot(merged_df, aes(x = modifications, y = Frequency, fill = Category)) +
geom_col(position = "dodge")
</code>```

Body:
Actually I'm working with two frequency tables who have got the name: identified_modification_table and unidentified_modifications_table

The structure of these files are something like that:

identified_modification_table

Modifications   | Frequency
MOD:42123       | 12
MOD:1234        | 7
MOD:7618        | 36
MOD:411232      | 51

unidentified_modifications_table

Modifications   | Frequency
MOD:42123       | 12
MOD:12          | 20
MOD:7618        | 36
MOD:411232      | 51

I would like to merge these files and create this output in order to create a stacked barplot like this example.

Modifications   | Frequency.1 | Frequency.2
MOD:42123       | 12          | 12
MOD:1234        | 7           | NA
MOD:12          | NA          | 20
MOD:7618        | 36          | 36
MOD:411232      | 51          | 51

I was trying to use this code to merge tables and add NA where the value doesn't exist.

df_final <- cbind.data.frame(df1, df2[match(df1$modifications, df2$modifications), ]);

But this doesn't work properly and I don't know why.

After this I think I should just use melt and ggplot2 stacked bar:

df_barplot <- melt(df,measure.vars = names(df))

ggplot((df_barplot), aes(x = value, fill = variable)) +
    geom_bar(stat = "count", position = "dodge") +
    theme(axis.text.x = element_text(angle = 20, hjust = 0.5, vjust = -0.1)) +
    guides(fill=FALSE)+
    labs("Barplot") +
    xlab("Values")+
    ylab("Frequency")+
    theme(text = element_text(size=18), axis.text.x = element_text(angle = 90, hjust = 1, size = 15), axis.text.y=element_text(size = 15))

Does anyone know how I could do this?

Here you are and a reproducible example:

df1 <- data.frame(modifications=c("MOD:214", "MOD:3","MOD:24","MOD:44","MOD:123", "MOD:123", "MOD:212"), Frequency=c(1,41,616,727,828,8993,383))

  df2 <- data.frame(modifications=c("MOD:214", "MOD:3","MOD:24","MOD:445","MOD:12", "MOD:123", "MOD:212"), Frequency=c(1,43,64,77,88,893,38))

Thank you

Body:
Here's the tidyverse way:

library(tidyverse)
merged_df <- full_join(df1, df2, by = "modifications")
merged_df <- gather(merged_df, key = Category, value = Frequency, -modifications)

And the chart:

ggplot(merged_df, aes(x = modifications, y = Frequency, fill = Category)) +
geom_col(position = "dodge")


问:
bash's strange behavior on a function named "@"
Today I found a strange behavior in bash.

When you define function named "@" in an interactive shell using this syntax:

```<code>$ function @() { echo foo; }
</code>```

it (of course) defines a function named "@".

However, in specific situations, e.g. in tmux session or in virtual console (Ctrl+Alt+F1), this defines a function named "@()".
I couldn't find any difference in these environments (output of echo $- was himBH). Besides, function @ { echo bar; } doesn't have this trap and defines "@" in both situations. I couldn't find any document that says @ is a special symbol in bash.

Does anyone know anything about this?
I confirmed these on vanilla Ubuntu 16.04.2.

答:
In bash there are two scenarios (that I'm aware of) where the "@" symbol is used. The first is when dealing with parameters:

```<code>function mytest() {
    echo $@
}
mytest "param1" "param2" "param3"
</code>```

The second is when dealing with arrays:

```<code>declare myarray=("item1" "item2")
printf "${myarray[@]}\n"
</code>```

While function @() {} may work as a function name, it should be considered bad practice. Give functions a practical name. Something that tells the user what it's purpose is.

Body:
Today I found a strange behavior in bash.

When you define function named "@" in an interactive shell using this syntax:

$ function @() { echo foo; }

it (of course) defines a function named "@".

However, in specific situations, e.g. in tmux session or in virtual console (Ctrl+Alt+F1), this defines a function named "@()".
I couldn't find any difference in these environments (output of echo $- was himBH). Besides, function @ { echo bar; } doesn't have this trap and defines "@" in both situations. I couldn't find any document that says @ is a special symbol in bash.

Does anyone know anything about this?
I confirmed these on vanilla Ubuntu 16.04.2.

Body:
In bash there are two scenarios (that I'm aware of) where the "@" symbol is used. The first is when dealing with parameters:

function mytest() {
    echo $@
}
mytest "param1" "param2" "param3"

The second is when dealing with arrays:

declare myarray=("item1" "item2")
printf "${myarray[@]}\n"

While function @() {} may work as a function name, it should be considered bad practice. Give functions a practical name. Something that tells the user what it's purpose is.


问:
Get referrer of Google Analytics current pageview
in Google Analytics i have to set-up two Google Anlaytics instances (of two different Properties):

the first one is instantiated as usual in whole website (ES: www.example.com/ )

the second one in a folder of the main domain ( ES: www.example.com/blog/ )

What i have to do is rewriting the referrer of the second instance of Google Analytics reading it from the original referrer of the first instance of Google Analytics.

In this way i can get the original traffic source also in the report of the second property.

Rewriting the referrer of the second instance of Google Analytics is OK , but how can i get the original referrer of the first instance?

Is there some method similar to ga.getReferrer() or ga('get_referrer') ?

Thanks in advance.

答:
While the tracker has a get method:

```<code>ga(function(tracker) {
  // Logs the URL of the referring site (if available).
  console.log(tracker.get('referrer'));
});
</code>```

it would return the referrer of the current pageview on a landingpage, and "undefined" on a follow up page, not the referrer for the session on the original landingpage. Universal Analytics processes data on the server, so there is no way to get session based data on the client side. Your best chance would probably be to store document.referrer in a cookie and go with that.

(You are asking for the referrer of the current pageview, but since this would be simply document.referrer I do not think this is what you really want. Correct me if I am wrong).

Body:
While the tracker has a get method:

ga(function(tracker) {
  // Logs the URL of the referring site (if available).
  console.log(tracker.get('referrer'));
});

it would return the referrer of the current pageview on a landingpage, and "undefined" on a follow up page, not the referrer for the session on the original landingpage. Universal Analytics processes data on the server, so there is no way to get session based data on the client side. Your best chance would probably be to store document.referrer in a cookie and go with that.

(You are asking for the referrer of the current pageview, but since this would be simply document.referrer I do not think this is what you really want. Correct me if I am wrong).


问:
Retrieving String from JAX-RS Response
In short terms, I simplified the problem a lot. I am calling this code, and the response is received with status 200 (OK):

Receiver.java:

```<code>Response response = componentInstanceService.getResource(componentResourceType);
</code>```

However, I don't know how can I retrieve the String contained in the body from this method:

Sender.java:

```<code>  @Override
    public Response getResource(ComponentResourceType resourceType) {
        String path = getPath();
        return Response.ok(this.getClass().getResourceAsStream(path)).build();
    }
</code>```

Please note that the communication between classes is working fine, as long as the Response is OK, however, how can I retrieve the String that Response contains?

This is what I would like to do roughly:

Receiver:

```<code>String result = componentInstanceService.getResource(componentResourceType);
</code>```

答:
The documentation for Response makes this pretty clear:

static Response.ResponseBuilder ok(java.lang.Object entity)

Create a new ResponseBuilder that contains a representation.

And:

abstract java.lang.Object getEntity()

Return the response entity.

In other words, the object you passed to Response.ok is the entity.  You can retrieve it with the Response’s getEntity() method.

Obviously, you will need to cast it:

```<code>Response response = componentInstanceService.getResource(componentResourceType);
InputStream dataSource = (InputStream) response.getEntity();
</code>```

Then you can read the stream as text.  You haven’t mentioned the charset of your text files, so I’ll assume it’s UTF-8:

```<code>String result;
try (Scanner scanner = new Scanner(dataSource, StandardCharsets.UTF_8)) {
    result = scanner.useDelimiter("\\z").next();
}
</code>```

Update:

I suspected this might happen.  You are returning a raw InputStream, which has no information about what type of data it is.

Change Sender.java to return a DataSource:

```<code>@Override
public DataSource getResource(ComponentResourceType resourceType) {
    String path = getPath();
    return new URLDataSource(this.getClass().getResource(path));
}
</code>```

This way, the JAX-RS service will not only return HTTP 200 OK, but will also return a Content-Type header corresponding to the intuited type of your file.

You should then be able to invoke the method with:

```<code>DataSource dataSource = componentInstanceService.getResource(componentResourceType);

String result;
try (Scanner scanner = new Scanner(dataSource.getInputStream(), StandardCharsets.UTF_8)) {
    result = scanner.useDelimiter("\\z").next();
}
</code>```

There actually is a more robust way to read a DataSource.  You can wrap it in a DataHandler:

```<code>DataSource dataSource = componentInstanceService.getResource(componentResourceType);
DataHandler handler = new DataHandler(dataSource);

DataFlavor flavor = DataFlavor.selectBestTextFlavor(
    handler.getTransferDataFlavors());

if (flavor == null) {
    // This should never happen with text files.
    throw new IllegalArgumentException(
        "Data has no flavors capable of supplying text.");
}

String result;
try (Reader reader = flavor.getReaderForText(handler)) {
    StringBuilder s = new StringBuilder();
    int c;
    while ((c = reader.read()) >= 0) {
        s.append((char) c);
    }
    result = s.toString();
} catch (UnsupportedFlavorException e) {
    // Since we started with a flavor provided by the DataHandler,
    // we should never get here.
    throw new RuntimeException(e);
}
</code>```

Title: Retrieving String from JAX-RS Response

Body:
In short terms, I simplified the problem a lot. I am calling this code, and the response is received with status 200 (OK):

Receiver.java:

Response response = componentInstanceService.getResource(componentResourceType);

However, I don't know how can I retrieve the String contained in the body from this method:

Sender.java:

  @Override
    public Response getResource(ComponentResourceType resourceType) {
        String path = getPath();
        return Response.ok(this.getClass().getResourceAsStream(path)).build();
    }

Please note that the communication between classes is working fine, as long as the Response is OK, however, how can I retrieve the String that Response contains?

This is what I would like to do roughly:

Receiver:

String result = componentInstanceService.getResource(componentResourceType);

Body:
The documentation for Response makes this pretty clear:

static Response.ResponseBuilder ok(java.lang.Object entity)

Create a new ResponseBuilder that contains a representation.

And:

abstract java.lang.Object getEntity()

Return the response entity.

In other words, the object you passed to Response.ok is the entity.  You can retrieve it with the Response’s getEntity() method.

Obviously, you will need to cast it:

Response response = componentInstanceService.getResource(componentResourceType);
InputStream dataSource = (InputStream) response.getEntity();

Then you can read the stream as text.  You haven’t mentioned the charset of your text files, so I’ll assume it’s UTF-8:

String result;
try (Scanner scanner = new Scanner(dataSource, StandardCharsets.UTF_8)) {
    result = scanner.useDelimiter("\\z").next();
}

Update:

I suspected this might happen.  You are returning a raw InputStream, which has no information about what type of data it is.

Change Sender.java to return a DataSource:

@Override
public DataSource getResource(ComponentResourceType resourceType) {
    String path = getPath();
    return new URLDataSource(this.getClass().getResource(path));
}

This way, the JAX-RS service will not only return HTTP 200 OK, but will also return a Content-Type header corresponding to the intuited type of your file.

You should then be able to invoke the method with:

DataSource dataSource = componentInstanceService.getResource(componentResourceType);

String result;
try (Scanner scanner = new Scanner(dataSource.getInputStream(), StandardCharsets.UTF_8)) {
    result = scanner.useDelimiter("\\z").next();
}

There actually is a more robust way to read a DataSource.  You can wrap it in a DataHandler:

DataSource dataSource = componentInstanceService.getResource(componentResourceType);
DataHandler handler = new DataHandler(dataSource);

DataFlavor flavor = DataFlavor.selectBestTextFlavor(
    handler.getTransferDataFlavors());

if (flavor == null) {
    // This should never happen with text files.
    throw new IllegalArgumentException(
        "Data has no flavors capable of supplying text.");
}

String result;
try (Reader reader = flavor.getReaderForText(handler)) {
    StringBuilder s = new StringBuilder();
    int c;
    while ((c = reader.read()) >= 0) {
        s.append((char) c);
    }
    result = s.toString();
} catch (UnsupportedFlavorException e) {
    // Since we started with a flavor provided by the DataHandler,
    // we should never get here.
    throw new RuntimeException(e);
}


问:
Replace only text content inside DIV using JavaScript
I want to change only text content inside an h1 tag. Here's my code:

Change only this text and keep the rest

```
</div>
</div>
</p>
<p>I've tried this code :</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>document.getElementById("DeltaPlaceHolderPageTitleInTitleArea").innerHTML = "text changed";</code>```

But it doesn't work, here's the result:

  text changed

```

Any help would be appreciated

答:
You have to use querySelector() method, in order to change text content of hyperlink.

document.querySelector("#pageTitle a").innerHTML = "text changed";```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1 id="pageTitle" class="ms-core-pageTitle">
  <span id="DeltaPlaceHolderPageTitleInTitleArea">

  <span>
<span>
Change only this text and keep the rest
</span>
</span>
  </span>
</h1></code>```

Body:
I want to change only text content inside an h1 tag. Here's my code:

Change only this text and keep the rest

I've tried this code :

document.getElementById("DeltaPlaceHolderPageTitleInTitleArea").innerHTML = "text changed";

But it doesn't work, here's the result:

  text changed

Any help would be appreciated

Body:
You have to use querySelector() method, in order to change text content of hyperlink.

document.querySelector("#pageTitle a").innerHTML = "text changed";

<h1 id="pageTitle" class="ms-core-pageTitle">
  <span id="DeltaPlaceHolderPageTitleInTitleArea">

  <span>
<span>
<a title="some title" href="/link/page.aspx">Change only this text and keep the rest</a>
</span>
</span>
  </span>
</h1>


问:
jquery ajax submit form+extra data, retrieve results in php
I have a pretty complex html form that consist of 10+ normal input fields and also a dynamic row entry that creates an array of things. Imagine having a form with Personal details and the user can also add extra rows with family member details.
I need to be able to send both 'blocks' of data to a php. A simple $('#myForm').serialize(); wont do, because the 2nd block has to be sent as an array of things.
The problem that i am facing is this...

When i send the form values this way:

```<code>var frm_data = $('#myForm').serialize();
$.ajax({
    "url": "request.php?action=save",
    "data": frm_data,
    "type": "POST",
    "success": function(data) {
            var response = JSON.parse(data);
        if(response.data == "error"){
            //
        }else{
            //
        }
    }
});
</code>```

I get each input field from the form as an associate php array. Because the 2nd block with the dynamic rows has no unique name= values...(the only distinction is their
), i get only the last row's data.

```<code>Array
(
    [name] => George Blah
    [address] => Str. 25
    [zip] => 35510
    ...
    [extra_name] => Maria
    [extra_Tele] => 21214454
    [extra_Mobil] => 111111
    [extra_Email] =>
)
</code>```

But i managed to create a js array of all the 'extra' rows, before i send the form, and i have it stored in a variable, which i have available.
The problem is, when i am sending BOTH (the form data and the 2nd block array) to the php file, the form's data is not an associated array anymore.

```<code>var extra = [];
//After a pretty complex function,
//i have all the extra dynamic rows stored in this array

var frm_data = $('#myForm').serialize();
$.ajax({
    "url": "request.php?action=save",
    "data": {"form": frm_data, "extras": JSON.stringify(extra)} ,
    "type": "POST",
    "success": function(data) {
            var response = JSON.parse(data);
        if(response.data == "error"){
                //
        }else{
            //
        }
    }
});
</code>```

And the result is like this:

```<code>Array
(
    [form] => name=George+Blah&address=Str+25&zip=35510&=email=&extra_name=Maria&extra_Tele=21214454&extra_Mobil=111111&extra_Email=
    [extras] => [{"extra_name":"Maria","extra_Tele":"21214454","extra_Mobil":"111111","extra_Email":""}]
)
</code>```

I need the 'form' value to look like the 'extras' value, before it reaches the php file. I dont want to break the string sent to the php based on the '&' sign in case the user adds something like: 'George & Marry' for name, and all hell breaks lose after that.

So basically i want this:

```<code>[form] => name=George+Blah&address=Str+25&zip=35510&=email=&extra_name=Maria&extra_Tele=21214454&extra_Mobil=111111&extra_Email=
</code>```

to be like this:

```<code>[form] => [{"name":"George Blah","address":"Str 25","zip":"35510","email":"".....}]
</code>```

I hope i am understood. :/

Thanks

答:
Nevermind, i am an idiot.

In the php file, all i had to do is:

```<code>parse_str($post["form"], $data);
</code>```

Now $data holds all the $_POST results in the format i want.

Body:
I have a pretty complex html form that consist of 10+ normal input fields and also a dynamic row entry that creates an array of things. Imagine having a form with Personal details and the user can also add extra rows with family member details.
I need to be able to send both 'blocks' of data to a php. A simple $('#myForm').serialize(); wont do, because the 2nd block has to be sent as an array of things.
The problem that i am facing is this...

When i send the form values this way:

var frm_data = $('#myForm').serialize();
$.ajax({
    "url": "request.php?action=save",
    "data": frm_data,
    "type": "POST",
    "success": function(data) {
            var response = JSON.parse(data);
        if(response.data == "error"){
            //
        }else{
            //
        }
    }
});

I get each input field from the form as an associate php array. Because the 2nd block with the dynamic rows has no unique name= values...(the only distinction is their
), i get only the last row's data.

Array
(
    [name] => George Blah
    [address] => Str. 25
    [zip] => 35510
    ...
    [extra_name] => Maria
    [extra_Tele] => 21214454
    [extra_Mobil] => 111111
    [extra_Email] =>
)

But i managed to create a js array of all the 'extra' rows, before i send the form, and i have it stored in a variable, which i have available.
The problem is, when i am sending BOTH (the form data and the 2nd block array) to the php file, the form's data is not an associated array anymore.

var extra = [];
//After a pretty complex function,
//i have all the extra dynamic rows stored in this array

var frm_data = $('#myForm').serialize();
$.ajax({
    "url": "request.php?action=save",
    "data": {"form": frm_data, "extras": JSON.stringify(extra)} ,
    "type": "POST",
    "success": function(data) {
            var response = JSON.parse(data);
        if(response.data == "error"){
                //
        }else{
            //
        }
    }
});

And the result is like this:

Array
(
    [form] => name=George+Blah&address=Str+25&zip=35510&=email=&extra_name=Maria&extra_Tele=21214454&extra_Mobil=111111&extra_Email=
    [extras] => [{"extra_name":"Maria","extra_Tele":"21214454","extra_Mobil":"111111","extra_Email":""}]
)

I need the 'form' value to look like the 'extras' value, before it reaches the php file. I dont want to break the string sent to the php based on the '&' sign in case the user adds something like: 'George & Marry' for name, and all hell breaks lose after that.

So basically i want this:

[form] => name=George+Blah&address=Str+25&zip=35510&=email=&extra_name=Maria&extra_Tele=21214454&extra_Mobil=111111&extra_Email=

to be like this:

[form] => [{"name":"George Blah","address":"Str 25","zip":"35510","email":"".....}]

I hope i am understood. :/

Thanks

Body:
Nevermind, i am an idiot.

In the php file, all i had to do is:

parse_str($post["form"], $data);

Now $data holds all the $_POST results in the format i want.


问:
Make elasticsearch only return certain fields?
I'm using elasticsearch to index my documents.

Is it possible to instruct it to only return particular fields instead of the entire json document it has stored?

答:
In java you can use setFetchSource like this : </p>

```<code>client.prepareSearch(index).setTypes(type)
            .setFetchSource(new String[] { "field1", "field2" }, null)
</code>```

Body:
In java you can use setFetchSource like this :

client.prepareSearch(index).setTypes(type)
            .setFetchSource(new String[] { "field1", "field2" }, null)


问:
How to fire a button's click event from another controller angular
I am new to angular. Am having two controller. One controller have a button. That button's click event wrote in another controller's script. How to make fire the click event. Please help. Thank in advance.

```<code>controller==> A
<button ng-click="click()"></button>

<script>
controller ==> B
$scope.click = function()
{
alert("hai");
}
<script>
</code>```

My doubt explains above sample code.

答:
You can do it by using angular events that is $emit and $broadcast.

First we call a function from one controller.

```<code>var myApp = angular.module('sample', []);
myApp.controller('firstCtrl', function($scope) {
    $scope.sum = function() {
        $scope.$emit('sumTwoNumber', [1, 2]);
    };
});
myApp.controller('secondCtrl', function($scope) {
    $scope.$on('sumTwoNumber', function(e, data) {
        var sum = 0;
        for (var a = 0; a < data.length; a++) {
            sum = sum + data[a];
        }
        console.log('event working', sum);

    });
});
</code>```

You can also use $rootScope in place of $scope. Use your controller accordingly.

Body:
I am new to angular. Am having two controller. One controller have a button. That button's click event wrote in another controller's script. How to make fire the click event. Please help. Thank in advance.

controller==> A
<button ng-click="click()"></button>

Body:
You can do it by using angular events that is $emit and $broadcast.

First we call a function from one controller.

var myApp = angular.module('sample', []);
myApp.controller('firstCtrl', function($scope) {
    $scope.sum = function() {
        $scope.$emit('sumTwoNumber', [1, 2]);
    };
});
myApp.controller('secondCtrl', function($scope) {
    $scope.$on('sumTwoNumber', function(e, data) {
        var sum = 0;
        for (var a = 0; a < data.length; a++) {
            sum = sum + data[a];
        }
        console.log('event working', sum);

    });
});

You can also use $rootScope in place of $scope. Use your controller accordingly.


问:
True merge statement in Entity Framework
Is there a true equivalent of the T-SQL MERGE statement in EF? I know they added AddOrUpdate in a previous version which obviously handles the add or update aspect. It's missing the when not matched from source then delete from the target table.

This particular process is literally just syncing down a third party json structure wholesale. I haven't found anything on a wrapped add / update / delete function in Entity Framework. Thought I would ask on here or for any creative thoughts on wrapping this versus enumerating over the entity, checking for existence, and deleting where the key exists in the DB but not in the source entity.

Thanks.

答:
After pouring thru a series of 3rd party solutions for this, I finally found one that does a perfect job. http://www.zzzprojects.com/entity-framework/library/bulk-merge

It's blazing fast and required a nuget install, a using, and one line of code.

```<code>context.BulkMerge(list);
</code>```

(I also found bulk update useful.)

```<code>context.BulkUpdate(list);
</code>```

The functions take in a list of entities.

My full context is something like:

```<code>public void Merge(MyDataBaseEntity[] array)
{
     using (var ctx = new Entities())
     {
         var list = array.ToList();
         ctx.BulkMerge(list);
     }
}
</code>```

Body:
After pouring thru a series of 3rd party solutions for this, I finally found one that does a perfect job. http://www.zzzprojects.com/entity-framework/library/bulk-merge

It's blazing fast and required a nuget install, a using, and one line of code.

context.BulkMerge(list);

(I also found bulk update useful.)

context.BulkUpdate(list);

The functions take in a list of entities.

My full context is something like:

public void Merge(MyDataBaseEntity[] array)
{
     using (var ctx = new Entities())
     {
         var list = array.ToList();
         ctx.BulkMerge(list);
     }
}