问:
Rspec test for when an I18n key is missing?
How do you simulate a missing I18n key in an Rspec test? I have a helper that looks to use a I18n key if its available. I don't know how to create the test case for when it is not available. Based on console testing I'm pretty sure the helper method is correct, but I don't know how to construct the test against that outcome (when all three possible title types are not set).

```<code># app/helpers/application_helper.rb

def available_page_title
  title = ""
  case
  when content_for?(:page_title)
    title = content_for(:page_title)
  when !@page_title.nil?
    title = @page_title
  when I18n.exists?('page_title.default')
    title = t('page_title.default')
  end
end
</code>```

--

```<code># config/locales/en.yml

en:
  page_title:
    delimiter: ' - '
    default: Default Page Title
    admin_namespace: 'Admin'

# spec/helpers/application_helper.rb
describe 'available_page_title' do
  it '(1) returns the the translation title if no other titles set' do
    allow(I18n).to receive(:t).with('page_title.default').and_return("Test Title from i18n")
    @page_title = nil
    expect(helper.available_page_title).to eq(t('page_title.default'))
  end

  it '(2) returns the the @page_title if it exists and no content_for exists' do
    allow(I18n).to receive(:t).with('page_title.default').and_return("Test Title from i18n")
    translation_title = t('page_title.default')
    @page_title = "Test Title from @page_title"
    expect(helper.available_page_title).to eq(@page_title)
  end

  it '(3) returns the the content_for title if it exists' do
    allow(I18n).to receive(:t).with('page_title.default').and_return("Test Title from i18n")
    translation_title = t('page_title.default')
    @page_title = "Test Title from @page_title"
    helper.content_for(:page_title, 'Test Title from content_for')
    expect(helper.available_page_title).to eq('Test Title from content_for')
  end

  it '(4) returns a blank string if no titles are found' do
    # Things I've tried...
    # I18n.backend.store_translations(:en, { page_title: { default: '' }})
    # I18n.backend.store_translations(:en)
    # I18n.backend.store_translations(:en, { nil })
    # I18n.backend.store_translations()
    # I18n.backend = I18n::Backend::Simple.new
    allow(I18n).to receive(:t).with('page_title.default').and_return(nil)
    @page_title = nil
    expect(helper.available_page_title).to eq('')
  end
end
</code>```

Here's the test results:

```<code>$ bundle exec rspec spec/helpers/application_helper_spec.rb:130
Run options: include {:locations=>{"./spec/helpers/application_helper_spec.rb"=>[130]}}

Randomized with seed 14478

ApplicationHelper
  available_page_title
    (3) returns the the content_for title if it exists
    (1) returns the the translation title if no other titles set
    (2) returns the the @page_title if it exists and no content_for exists
    (4) returns a blank string if no titles are found (FAILED - 1)

Failures:

  1) ApplicationHelper available_page_title should (4) return a blank string if no titles are found
     Failure/Error: expect(helper.available_page_title).to eq('')

       expected: ""
            got: "Default Page Title"

       (compared using ==)
     # ./spec/helpers/application_helper_spec.rb:160:in `block (3 levels) in <top (required)>'

Finished in 0.69197 seconds (files took 4.32 seconds to load)
4 examples, 1 failure

Failed examples:

rspec ./spec/helpers/application_helper_spec.rb:152 # ApplicationHelper available_page_title should (4) return a blank string if no titles are found

Randomized with seed 14478
</code>```

Update 2017-05-31

@gwcodes's answer helped a little but still didn't get the test set up properly.

```<code>allow(I18n).to receive(:translate).with('page_title.default').and_return(nil)
</code>```

Using that line, the test is set up so that there actually is still a key page_title.default, but its value is nil. That's not useful.

What my helper method checks for is the existence of the key. Here's the pry output of the current test situation:

```<code>[5] pry(#<RSpec::ExampleGroups::ApplicationHelper::AvailablePageTitle>)> I18n.translate('page_title.default')
=> nil
[6] pry(#<RSpec::ExampleGroups::ApplicationHelper::AvailablePageTitle>)> I18n.exists?('page_title.default')
=> true
[7] pry(#<RSpec::ExampleGroups::ApplicationHelper::AvailablePageTitle>)> I18n.t('page_title.default').empty?
=> false
</code>```

So the question still remains. How do you set the test environment so that a check for the existence of an I18n key returns false?

答:
I am thinking to use your first solution into a shared context.

```<code># spec/support/i18n_stubs.rb

RSpec.shared_context 'i18n stubs' do
  def stub_i18n_value_with_nil(key)
    allow(I18n).to receive(:t).with(key).and_return(nil)
    allow(I18n).to receive(:exists?).with(key).and_return(false)
  end
end
</code>```

Then add require support/i18n_stubs on your spec helper file. Inside wherever your spec file needs it, you can just simply put include_context 'i18n stubs' and call stub_i18n_value_with_nil('some.i18n.key') before doing assertions.

For example in spec file:

```<code>require 'spec_helper'

RSpec.describe 'some_file_or_class' do
  include_context 'i18n stubs'

  describe 'available_page_title' do
    context 'when i18n key is not present' do
      before(:each) do
        stub_i18n_value_with_nil('some.i18n.key')
      end

      it 'returns blank string' do
        # do assertion here
      end
    end
  end
end
</code>```

Body:
How do you simulate a missing I18n key in an Rspec test? I have a helper that looks to use a I18n key if its available. I don't know how to create the test case for when it is not available. Based on console testing I'm pretty sure the helper method is correct, but I don't know how to construct the test against that outcome (when all three possible title types are not set).

# app/helpers/application_helper.rb

def available_page_title
  title = ""
  case
  when content_for?(:page_title)
    title = content_for(:page_title)
  when !@page_title.nil?
    title = @page_title
  when I18n.exists?('page_title.default')
    title = t('page_title.default')
  end
end

--

# config/locales/en.yml

en:
  page_title:
    delimiter: ' - '
    default: Default Page Title
    admin_namespace: 'Admin'

# spec/helpers/application_helper.rb
describe 'available_page_title' do
  it '(1) returns the the translation title if no other titles set' do
    allow(I18n).to receive(:t).with('page_title.default').and_return("Test Title from i18n")
    @page_title = nil
    expect(helper.available_page_title).to eq(t('page_title.default'))
  end

  it '(2) returns the the @page_title if it exists and no content_for exists' do
    allow(I18n).to receive(:t).with('page_title.default').and_return("Test Title from i18n")
    translation_title = t('page_title.default')
    @page_title = "Test Title from @page_title"
    expect(helper.available_page_title).to eq(@page_title)
  end

  it '(3) returns the the content_for title if it exists' do
    allow(I18n).to receive(:t).with('page_title.default').and_return("Test Title from i18n")
    translation_title = t('page_title.default')
    @page_title = "Test Title from @page_title"
    helper.content_for(:page_title, 'Test Title from content_for')
    expect(helper.available_page_title).to eq('Test Title from content_for')
  end

  it '(4) returns a blank string if no titles are found' do
    # Things I've tried...
    # I18n.backend.store_translations(:en, { page_title: { default: '' }})
    # I18n.backend.store_translations(:en)
    # I18n.backend.store_translations(:en, { nil })
    # I18n.backend.store_translations()
    # I18n.backend = I18n::Backend::Simple.new
    allow(I18n).to receive(:t).with('page_title.default').and_return(nil)
    @page_title = nil
    expect(helper.available_page_title).to eq('')
  end
end

Here's the test results:

$ bundle exec rspec spec/helpers/application_helper_spec.rb:130
Run options: include {:locations=>{"./spec/helpers/application_helper_spec.rb"=>[130]}}

Randomized with seed 14478

ApplicationHelper
  available_page_title
    (3) returns the the content_for title if it exists
    (1) returns the the translation title if no other titles set
    (2) returns the the @page_title if it exists and no content_for exists
    (4) returns a blank string if no titles are found (FAILED - 1)

Failures:

  1) ApplicationHelper available_page_title should (4) return a blank string if no titles are found
     Failure/Error: expect(helper.available_page_title).to eq('')

       expected: ""
            got: "Default Page Title"

       (compared using ==)
     # ./spec/helpers/application_helper_spec.rb:160:in `block (3 levels) in <top (required)>'

Finished in 0.69197 seconds (files took 4.32 seconds to load)
4 examples, 1 failure

Failed examples:

rspec ./spec/helpers/application_helper_spec.rb:152 # ApplicationHelper available_page_title should (4) return a blank string if no titles are found

Randomized with seed 14478

Update 2017-05-31

@gwcodes's answer helped a little but still didn't get the test set up properly.

allow(I18n).to receive(:translate).with('page_title.default').and_return(nil)

Using that line, the test is set up so that there actually is still a key page_title.default, but its value is nil. That's not useful.

What my helper method checks for is the existence of the key. Here's the pry output of the current test situation:

[5] pry(#<RSpec::ExampleGroups::ApplicationHelper::AvailablePageTitle>)> I18n.translate('page_title.default')
=> nil
[6] pry(#<RSpec::ExampleGroups::ApplicationHelper::AvailablePageTitle>)> I18n.exists?('page_title.default')
=> true
[7] pry(#<RSpec::ExampleGroups::ApplicationHelper::AvailablePageTitle>)> I18n.t('page_title.default').empty?
=> false

So the question still remains. How do you set the test environment so that a check for the existence of an I18n key returns false?

Body:
I am thinking to use your first solution into a shared context.

# spec/support/i18n_stubs.rb

RSpec.shared_context 'i18n stubs' do
  def stub_i18n_value_with_nil(key)
    allow(I18n).to receive(:t).with(key).and_return(nil)
    allow(I18n).to receive(:exists?).with(key).and_return(false)
  end
end

Then add require support/i18n_stubs on your spec helper file. Inside wherever your spec file needs it, you can just simply put include_context 'i18n stubs' and call stub_i18n_value_with_nil('some.i18n.key') before doing assertions.

For example in spec file:

require 'spec_helper'

RSpec.describe 'some_file_or_class' do
  include_context 'i18n stubs'

  describe 'available_page_title' do
    context 'when i18n key is not present' do
      before(:each) do
        stub_i18n_value_with_nil('some.i18n.key')
      end

      it 'returns blank string' do
        # do assertion here
      end
    end
  end
end


来源: stackexchange

问:
How to convert a string to a string property
I'm trying to write a function using Typescript that takes 2 arguments in which the second argument is always of type string. The function should apply the second argument on the first argument as its property

Example:

```<code>let x = measure('Hello', 'length'); // should return 'Hello'.length
// => x = 5
</code>```

How can I convert the string 'length' to be a property of 'Hello' to return 'Hello'.length?

答:
If I understood you:

```<code>function measure(obj: any, property: string): any {
    return obj[property];
}

let x = measure('Hello', 'length');
console.log(x); // 5
</code>```

(code in playground)

Edit

Or even better:

```<code>function measure<T, K extends keyof T>(obj: T, property: K): T[K] {
    return obj[property];
}
</code>```

In this version the compiler can infer the type of the returned value, and will also enforce that only existing property names are used, for example:

```<code>let x = measure('Hello', 'lengthy'); // error
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to write a function using Typescript that takes 2 arguments in which the second argument is always of type string. The function should apply the second argument on the first argument as its property

Example:

let x = measure('Hello', 'length'); // should return 'Hello'.length
// => x = 5

How can I convert the string 'length' to be a property of 'Hello' to return 'Hello'.length?

Body:
If I understood you:

function measure(obj: any, property: string): any {
    return obj[property];
}

let x = measure('Hello', 'length');
console.log(x); // 5

(code in playground)

Edit

Or even better:

function measure<T, K extends keyof T>(obj: T, property: K): T[K] {
    return obj[property];
}

In this version the compiler can infer the type of the returned value, and will also enforce that only existing property names are used, for example:

let x = measure('Hello', 'lengthy'); // error


问:
How to implement interface from a different package in golang?
I am beginner in golang and was trying interfaces. I want to keep interfaces in a separate packages so that I can use it to implement this in various other packages, also provide it to other teams (.a file) so that they can implement custom plugins. Please see example below on what I would like to achieve.

```<code>--- Folder structure ---
gitlab.com/myproject/
                  interfaces/
                            shaper.go
                  shapes/
                        rectangle.go
                        circle.go

---- shaper.go ---
package interfaces

type Shaper interface{

    Area() int

}
</code>```

How do I ensure that the rectangle.go implements shaper interface?
I understand that go implements interfaces implicitly, does this mean rectangle.go automatically implements shaper.go even though it is in a different package?

I tried it like below, but when I run gofmt tool, it removes the import because it is unused.

```<code>--- rectangle.go ---
package shapes

import "gitlab.com/myproject/interfaces"

type rectangle struct{

  length int
  width int
}

func (r rectangle) Area() int {
 return r.length * r.width
}
</code>```

Thanks in advance.

答:
There is an excellent section in the go wiki about interfaces:

Go interfaces generally belong in the package that uses values of the interface type, not the package that implements those values. The implementing package should return concrete (usually pointer or struct) types: that way, new methods can be added to implementations without requiring extensive refactoring.

This also has the advantage that it reduces coupling between packages (by not forcing anybody to import your package just for the interface) and it generally leads to smaller interfaces (by allowing people to consume only a subset of the interface that you would have built).

If you are new to go I highly recommend reading the "Go Code Review Comments" wiki article I linked and if you have some more time also Effective Go. Happy hacking!

Body:
I am beginner in golang and was trying interfaces. I want to keep interfaces in a separate packages so that I can use it to implement this in various other packages, also provide it to other teams (.a file) so that they can implement custom plugins. Please see example below on what I would like to achieve.

--- Folder structure ---
gitlab.com/myproject/
                  interfaces/
                            shaper.go
                  shapes/
                        rectangle.go
                        circle.go

---- shaper.go ---
package interfaces

type Shaper interface{

    Area() int

}

How do I ensure that the rectangle.go implements shaper interface?
I understand that go implements interfaces implicitly, does this mean rectangle.go automatically implements shaper.go even though it is in a different package?

I tried it like below, but when I run gofmt tool, it removes the import because it is unused.

--- rectangle.go ---
package shapes

import "gitlab.com/myproject/interfaces"

type rectangle struct{

  length int
  width int
}

func (r rectangle) Area() int {
 return r.length * r.width
}

Thanks in advance.


问:
List if items displayed in scroll pane
I have objects stored in HasMap with keys as Strings, where registration number of the car is the key in a map.

Map cars = new HashMap<>();

Now I want to display all keys from the map in a Scroll Pane where user can select registration number of the Car. The question is how to display the keys of Car from the map in a Scroll Pane box?
Should I add jList to Scroll Pane and then loop through the Map keys adding each String from the Key to jList?

答:
you can get the the keys from the hashmap like below.once you have got the key you can get the particular value Associated with the key.</p>

```<code>Map cars = new HashMap<>();
Set<String> keys=cars.keySet();
for(String key:keys){
    System.out.println(cars.get(key));
}
</code>```

Title: List if items displayed in scroll pane

Body:
you can get the the keys from the hashmap like below.once you have got the key you can get the particular value Associated with the key.

Map cars = new HashMap<>();
Set<String> keys=cars.keySet();
for(String key:keys){
    System.out.println(cars.get(key));
}


问:
how to assign a method pointer to block variable in objectivec

I typedef a block like below

```<code>typedef void(^cbGeneric)();
</code>```

I define a property using block in a class

```<code>@property(nonatomic, strong)cbGeneric batchLoadStartedEvent;
</code>```

I need to bind a member method address of class to this property.

How to get pointer of member method of class and assign it to block property? thanks

答:
You can get the member method address with class_getMethodImplementation() for example. But this does not help, because you cannot assign a method implementation (basically a function) to a block var. This is, because blocks are not simply function vars, but closures. And closures have a creational context, methods have an object context. That's not the same.

However, there are options to get,what you probably want to get:

Instead of having a block var, use a method implementation var of type IMP. If you execute the method, remember to pass a self pointer and a selector as expected by methods.

You can have a selector var, which stores the selector of the method to be executed. It's type is SEL. Then you can send a message using one method of the -performSelector: family.

You can assign a block to your current ivar, that does nothing else than sending a message with the method's selector. (Which "calls" the desired method.)

If you give more information about your situation, I can add a more detailed solution fitting to your problem.

Body:
I typedef a block like below

typedef void(^cbGeneric)();

I define a property using block in a class

@property(nonatomic, strong)cbGeneric batchLoadStartedEvent;

I need to bind a member method address of class to this property.

How to get pointer of member method of class and assign it to block property? thanks


问:
How do I undo the most recent local commits in Git?
I accidentally committed the wrong files to Git, but didn't push the commit to the server yet.

How do I undo those commits from the local repository?

答:
Find the last commit hash code by seeing the log by:

```<code>git log
</code>```

Then

```<code>git reset <the previous co>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Find the last commit hash code by seeing the log by:

git log

Then

git reset <the previous co>


问:
Replacing character string with another character string
I have a data frame for which I am attempting to replace certain values with others. So, as a small example, I have a dummy data frame of:

```<code>dummy<-c("1","2","3","4")
dummy<-data.frame(dummy)
dummy$dummy<-as.character(dummy$dummy)

odd<-c("1","3")

replace(dummy$dummy, dummy$dummy==odd, "odd")

#> [1] "odd" "2"   "3"   "4"
</code>```

Why would this only replace "1" with "odd" and not "3"?

My actual dataset has more information in it (it is restaurant cuisine types and I need to replace the types of cuisine by a more general category. For example, I have the cuisine types "Italian" and "French" in my dataset that need to be replaced with "European", and cuisine types "Southwestern" and "Pacific Northwestern" that need to be replaced with "American".

Is the above idea the most efficient way to do this?

答:
Like epi99 suggested, you can use stringr::str_replace() for this. You might also want to look over their guide to using Regular Expressions as well.

library(dplyr)
library(stringr)

df <- data_frame(dummy = c("1","2","3","4"))

df %>% mutate(dummy = str_replace(dummy, "1|3", "odd"))

#> # A tibble: 4 x 1
#>   dummy
#>   <chr>
#> 1   odd
#> 2     2
#> 3   odd
#> 4     4
```

Body:
I have a data frame for which I am attempting to replace certain values with others. So, as a small example, I have a dummy data frame of:

dummy<-c("1","2","3","4")
dummy<-data.frame(dummy)
dummy$dummy<-as.character(dummy$dummy)

odd<-c("1","3")

replace(dummy$dummy, dummy$dummy==odd, "odd")

#> [1] "odd" "2"   "3"   "4"

Why would this only replace "1" with "odd" and not "3"?

My actual dataset has more information in it (it is restaurant cuisine types and I need to replace the types of cuisine by a more general category. For example, I have the cuisine types "Italian" and "French" in my dataset that need to be replaced with "European", and cuisine types "Southwestern" and "Pacific Northwestern" that need to be replaced with "American".

Is the above idea the most efficient way to do this?


问:
Is there a way to render only after only a complete input? Delaying render() - ReactJS
I have some Controlled Component text inputs for a form:

```<code><input type="text" onChange={(e) => this.props.changeBusiness(e)}/>
</code>```

I also want to render the (above) text input in a separate component - however! It would be nice if I could render it with the COMPLETED text input to give (in my opinion), what would be a better feel.

How might this be implemented? I assume I could have an onBlur
handler that is triggered.

Is there any way to delay the render() till only after the complete text input?

Danke

答:
Yes if you want to delay a render you just need to return null in the render based on a flag. Lets say you have a state variable inputBlurred that you pass around as a prop to something else.

```<code>render() {
    if (!this.props.inputBlurred) return null;
    ... more here
}
</code>```

You would use it like so.

```<code>class ParentComponent extends Component {
    constructor() {
        super();
        this.state = {inputBlurred: false}
    }
    handleBlur = (e) => {
        if(e.target.value){
            this.setState({inputBlurred: true});
        }
    }
    render() {
        return(
            <div>
                <input onBlur={this.handleBlur} />
                <ChildComponent inputBlurred={this.state.inputBlurred} />
            </div>
        )
    }
}
</code>```

Body:
I have some Controlled Component text inputs for a form:

<input type="text" onChange={(e) => this.props.changeBusiness(e)}/>

I also want to render the (above) text input in a separate component - however! It would be nice if I could render it with the COMPLETED text input to give (in my opinion), what would be a better feel.

How might this be implemented? I assume I could have an onBlur
handler that is triggered.

Is there any way to delay the render() till only after the complete text input?

Danke

Body:
Yes if you want to delay a render you just need to return null in the render based on a flag. Lets say you have a state variable inputBlurred that you pass around as a prop to something else.

render() {
    if (!this.props.inputBlurred) return null;
    ... more here
}

You would use it like so.

class ParentComponent extends Component {
    constructor() {
        super();
        this.state = {inputBlurred: false}
    }
    handleBlur = (e) => {
        if(e.target.value){
            this.setState({inputBlurred: true});
        }
    }
    render() {
        return(
            <div>
                <input onBlur={this.handleBlur} />
                <ChildComponent inputBlurred={this.state.inputBlurred} />
            </div>
        )
    }
}


问:
is there a way to translate data from SSAS OLAP cube into JSON format?
We have an SSAS OLAP cube built for a typical MS BI purposes.
Recently, we have discovered a great visualization power of d3.
Now, we are interested in presenting the cube data with d3, dc, crossfilter.
Is there a way to query SSAS cube in a background, and translate the results into an array of JSON objects, which could be served to d3/dc.js</p>

答:
You can expose your SSAS cube as an HTTP endpoint in IIS.

Once you've configured that, you can use Tedious to connect to your SSAS instance, pass queries, and return results. And then you'll have to wrap those results in some sort of JSON parser to make it play nice with d3.


问:
Stack question: pop out in a pattern
At run time I want to input two types of datatype, double and string.
One of the condition is that String should pop in the order I input, and double will pop as the usual stack behaviour, LIFO. Another condition is that the stack is limited to max size 10

E.g. one runtime example

Input Hello 1 World 2 blah blah 3 4 5

Output Hello 5 World 4 blah blah 3 2 1

My first question is how many ways is there to solve this problem?
I have solved this problem using 3 stacks, one which stores double, one which store strings, and one which is used to reverse the string order.

I need to save the pattern so the program know which order the doubles comes, thus I save the pattern to the string stack. Since the stack is limited to size 10, I will need to save the pattern in another way.

So this is how my string stack will look like after the push

Hello*

World*

blah

blah***

So when at the first read I need to make specific read in that Stack position and just extract Hello out of it. Asterisk * is left for later use when I tell the program next pop is an double.

My second question is that I wonder if there is some other more elegant solution to this problem. Since my solution will involve some string manipulation to solve this problem. And as for now I'm not actually using the pop function in the string case as it is supposed to be used. I made the solution in C++ btw.

答:
I'll ignore the stack size constraint since I think it's meaning is unclear. In addition, if you can use multiple stacks all limited to size 10, then you can simulate larger stacks by using multiple actual stacks.

So, this can be done with 2 stacks using only push/pop.

push everything onto stack A.

pop everything from A onto B.

if B.empty return

if B.top is a double goto 7

output B.top and pop it off of B

goto 3

pop all of B onto A

while A.top is not a double pop A onto B

output A.top and pop it off of A

goto 2.

ContentLicense: CC BY-SA 2.5

Title: Stack question: pop out in a pattern


问:
how to modify a small script to run without jquery
The following script(enables 2 parallel scrollbars) have few lines but require jquery library, how can i make it standalone javascript, thanks in advance...

http://jsfiddle.net/TBnqw/1/

HTML:

```<code><div class="wrapper1">
    <div class="div1">
    </div>
</div>
<div class="wrapper2">
    <div class="div2">
    aaaa bbbb cccc dddd aaaa bbbb cccc dddd aaaa bbbb cccc dddd aaaa bbbb cccc dddd aaaa bbbb cccc dddd aaaa bbbb cccc dddd aaaa bbbb cccc dddd
    </div>
</div>
</code>```

JAVASCRIPT:

```<code>$(function(){
    $(".wrapper1").scroll(function(){
        $(".wrapper2")
            .scrollLeft($(".wrapper1").scrollLeft());
    });
    $(".wrapper2").scroll(function(){
        $(".wrapper1")
            .scrollLeft($(".wrapper2").scrollLeft());
    });
});
</code>```

CSS:

```<code>.wrapper1, .wrapper2{width: 300px; border: none 0px RED;
overflow-x: scroll; overflow-y:hidden;}
.wrapper1{height: 20px; }
.wrapper2{height: 200px; }
.div1 {width:1000px; height: 20px; }
.div2 {width:1000px; height: 200px; background-color: #88FF88;
overflow: auto;}
</code>```

答:
This is the Angular 2 / Angular way of doing it. i.e. wihout Jquery

oddly you can't just set the variables but have to do it directly to the document

https://plnkr.co/edit/eYz2c8?p=preview

```<code>import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  encapsulation: ViewEncapsulation.Emulated
 })
export class AppComponent {

onWindowsScrollTop() {
  document.querySelector('.table-wrapper-bottom').scrollLeft = document.querySelector('.table-wrapper-top').scrollLeft;
}
onWindowsScrollBottom() {
  document.querySelector('.table-wrapper-top').scrollLeft = document.querySelector('.table-wrapper-bottom').scrollLeft;
}

reportTopScrollLeft() {
  alert('the scrollLeft for top = ' + document.querySelector('.table-wrapper-top').scrollLeft)
}

reportBottomScrollLeft() {
  alert('the scrollLeft for top = ' + document.querySelector('.table-wrapper-bottom').scrollLeft)
}

 }
</code>```

Body:
The following script(enables 2 parallel scrollbars) have few lines but require jquery library, how can i make it standalone javascript, thanks in advance...

http://jsfiddle.net/TBnqw/1/

HTML:

    aaaa bbbb cccc dddd aaaa bbbb cccc dddd aaaa bbbb cccc dddd aaaa bbbb cccc dddd aaaa bbbb cccc dddd aaaa bbbb cccc dddd aaaa bbbb cccc dddd

JAVASCRIPT:

$(function(){
    $(".wrapper1").scroll(function(){
        $(".wrapper2")
            .scrollLeft($(".wrapper1").scrollLeft());
    });
    $(".wrapper2").scroll(function(){
        $(".wrapper1")
            .scrollLeft($(".wrapper2").scrollLeft());
    });
});

CSS:

.wrapper1, .wrapper2{width: 300px; border: none 0px RED;
overflow-x: scroll; overflow-y:hidden;}
.wrapper1{height: 20px; }
.wrapper2{height: 200px; }
.div1 {width:1000px; height: 20px; }
.div2 {width:1000px; height: 200px; background-color: #88FF88;
overflow: auto;}

Body:
This is the Angular 2 / Angular way of doing it. i.e. wihout Jquery

oddly you can't just set the variables but have to do it directly to the document

https://plnkr.co/edit/eYz2c8?p=preview

import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  encapsulation: ViewEncapsulation.Emulated
 })
export class AppComponent {

onWindowsScrollTop() {
  document.querySelector('.table-wrapper-bottom').scrollLeft = document.querySelector('.table-wrapper-top').scrollLeft;
}
onWindowsScrollBottom() {
  document.querySelector('.table-wrapper-top').scrollLeft = document.querySelector('.table-wrapper-bottom').scrollLeft;
}

reportTopScrollLeft() {
  alert('the scrollLeft for top = ' + document.querySelector('.table-wrapper-top').scrollLeft)
}

reportBottomScrollLeft() {
  alert('the scrollLeft for top = ' + document.querySelector('.table-wrapper-bottom').scrollLeft)
}

 }


问:
Socket.IO acknowledgement vs event emitting
I'm trying to build application (to be more accurate a library for my personal projects) which will be based on room management (lobby, matchmaking, rooms, etc).

I managed to do it with socket.io.

Now, my question is, I don't know what kind of design pattern should I use.

I noticed that socket.io has ack callbacks, which surprised me and think it's good, but I'm not sure what's the difference between sending back ack with parameters or emitting an event with parameters.

So, question is, what's the pros and cons using acks over emitting an event and vice-versa?

Let's say, what's the pros and cons using following codes:

assuming handler callback is fn(err, res);

acknowledgement style:

socket.on('join', function (data, ack) {
  // do the joining stuff here.
  return ack(null, { response: 'goes_here' });
});
```

<p>versus</p>

<p><strong>event emitting style:</strong></p>

<pre class="lang-js prettyprint-override"><code>socket.on('join', function (data, ack) {
  // do the joining stuff here.
  io.to(client_sid).emit('join_response', null, { response: 'goes_here' });
});
</code>```

答:
As you noted, there is not a real difference if you only think about the ping-pong thing. I would the notable changes is that it allows you to validate a specific event has been acknowledged (although you could argue that you can also do that with a _response event by passing an event id), and provides a more convenient way to handle responses, by using a simple callback style notation: the first example looks way cleaner and simple.

Besides, it allows you to avoid creating two event keys for just one type of event which is kinda repeating. Acknowledgement has been made for this purpose, so there is no real reason not to use it in favor or creating another event.

Body:
I'm trying to build application (to be more accurate a library for my personal projects) which will be based on room management (lobby, matchmaking, rooms, etc).

I managed to do it with socket.io.

Now, my question is, I don't know what kind of design pattern should I use.

I noticed that socket.io has ack callbacks, which surprised me and think it's good, but I'm not sure what's the difference between sending back ack with parameters or emitting an event with parameters.

So, question is, what's the pros and cons using acks over emitting an event and vice-versa?

Let's say, what's the pros and cons using following codes:

assuming handler callback is fn(err, res);

acknowledgement style:

socket.on('join', function (data, ack) {
  // do the joining stuff here.
  return ack(null, { response: 'goes_here' });
});

versus

event emitting style:

socket.on('join', function (data, ack) {
  // do the joining stuff here.
  io.to(client_sid).emit('join_response', null, { response: 'goes_here' });
});


问:
How do Monitored Training Sessions work?
I'm trying to understand the difference between using tf.Session and tf.train.MonitoredTrainingSession, and where I might prefer one over the other. It seems that when I use the latter, I can avoid many "chores" such as initializing variables, starting queue runners, or setting up file writers for summary operations. On the other hand, with a monitored training session, I cannot specify the computation graph I want to use explicitly. All of this seems rather mysterious to me. Is there some underlying philosophy behind how these classes were created that I'm not understanding?

答:
I can't give some insights on how these classes were created, but here are a few things which I think are relevants on how you could use them.

The tf.Session is a low level object in the python TensorFlow API while,
as you said, the tf.train.MonitoredTrainingSession comes with a lot of  handy features, especially useful in most of the common cases.

Before describing some of the benefits of tf.train.MonitoredTrainingSession, let me answer the question about the graph used by the session. You can specify the tf.Graph used by the MonitoredTrainingSession by using a context manager with your_graph.as_default():

```<code>from __future__ import print_function
import tensorflow as tf

def example():
    g1 = tf.Graph()
    with g1.as_default():
        # Define operations and tensors in `g`.
        c1 = tf.constant(42)
        assert c1.graph is g1

    g2 = tf.Graph()
    with g2.as_default():
        # Define operations and tensors in `g`.
        c2 = tf.constant(3.14)
        assert c2.graph is g2

    # MonitoredTrainingSession example
    with g1.as_default():
        with tf.train.MonitoredTrainingSession() as sess:
            print(c1.eval(session=sess))
            # Next line raises
            # ValueError: Cannot use the given session to evaluate tensor:
            # the tensor's graph is different from the session's graph.
            try:
                print(c2.eval(session=sess))
            except ValueError as e:
                print(e)

    # Session example
    with tf.Session(graph=g2) as sess:
        print(c2.eval(session=sess))
        # Next line raises
        # ValueError: Cannot use the given session to evaluate tensor:
        # the tensor's graph is different from the session's graph.
        try:
            print(c1.eval(session=sess))
        except ValueError as e:
            print(e)

if __name__ == '__main__':
    example()
</code>```

So, as you said, the benefits of using MonitoredTrainingSession are that, this object takes care of

initialising variables,

starting queue runner as well as

setting up the file writers,

but it has also the benefit of making your code easy to distribute as it also works differently depending if you specified the running process as a master or not.

For example you could run something like:

```<code>def run_my_model(train_op, session_args):
    with tf.train.MonitoredTrainingSession(**session_args) as sess:
        sess.run(train_op)
</code>```

that you would call in a non-distributed way:

```<code>run_my_model(train_op, {})`
</code>```

or in a distributed way (see the distributed doc for more information on the inputs):

```<code>run_my_model(train_op, {"master": server.target,
                        "is_chief": (FLAGS.task_index == 0)})
</code>```

On the other hand, the benefit of using the raw tf.Session object is that, you don't have the extra benefits of tf.train.MonitoredTrainingSession, which can be useful if you don't plan to use them or if you want to get more control (for example on how the queues are started).

EDIT (as per comment):
For the op initialisation, you would have to do something like (cf. official doc:

```<code># Define your graph and your ops
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init_p)
    sess.run(your_graph_ops,...)
</code>```

For the QueueRunner, I would refer you to the official doc where you will find more complete examples.

EDIT2:

The main concept to understand to get a sense on how tf.train.MonitoredTrainingSession works is the _WrappedSession class:

This wrapper is used as a base class for various session wrappers
    that provide additional functionality such as monitoring, coordination,
    and recovery.

The tf.train.MonitoredTrainingSession works (as of version 1.1) this way:

It first checks if it is a chief or a worker (cf. the distributed doc for lexical question).

It begins the hooks which have been provided (for example, StopAtStepHook would just retrieve the global_step tensor at this stage.

It creates a session which is a Chief (or Worker session) wrapped into a _HookedSession wrapped into a _CoordinatedSession wrapped into a _RecoverableSession.

The Chief/Worker sessions are in charge of running initialising ops provided by the Scaffold.

```<code>  scaffold: A `Scaffold` used for gathering or building supportive ops. If
not specified a default one is created. It's used to finalize the graph.
</code>```

The chief session also takes care of all the checkpoint parts: e.g. restoring from checkpoints using the Saver from the Scaffold.

The _HookedSession is basically there to decorate the run method: it calls the _call_hook_before_run and after_run methods when relevant.

At creation the _CoordinatedSession builds a Coordinator which starts the queue runners and will be responsible of closing them.

The _RecoverableSession will insures that there is retry in case of tf.errors.AbortedError.

In conclusion, the tf.train.MonitoredTrainingSession avoids a lot of boiler plate code while being easily extendable with the hooks mechanism.

Body:
I can't give some insights on how these classes were created, but here are a few things which I think are relevants on how you could use them.

The tf.Session is a low level object in the python TensorFlow API while,
as you said, the tf.train.MonitoredTrainingSession comes with a lot of  handy features, especially useful in most of the common cases.

Before describing some of the benefits of tf.train.MonitoredTrainingSession, let me answer the question about the graph used by the session. You can specify the tf.Graph used by the MonitoredTrainingSession by using a context manager with your_graph.as_default():

from __future__ import print_function
import tensorflow as tf

def example():
    g1 = tf.Graph()
    with g1.as_default():
        # Define operations and tensors in `g`.
        c1 = tf.constant(42)
        assert c1.graph is g1

    g2 = tf.Graph()
    with g2.as_default():
        # Define operations and tensors in `g`.
        c2 = tf.constant(3.14)
        assert c2.graph is g2

    # MonitoredTrainingSession example
    with g1.as_default():
        with tf.train.MonitoredTrainingSession() as sess:
            print(c1.eval(session=sess))
            # Next line raises
            # ValueError: Cannot use the given session to evaluate tensor:
            # the tensor's graph is different from the session's graph.
            try:
                print(c2.eval(session=sess))
            except ValueError as e:
                print(e)

    # Session example
    with tf.Session(graph=g2) as sess:
        print(c2.eval(session=sess))
        # Next line raises
        # ValueError: Cannot use the given session to evaluate tensor:
        # the tensor's graph is different from the session's graph.
        try:
            print(c1.eval(session=sess))
        except ValueError as e:
            print(e)

if __name__ == '__main__':
    example()

So, as you said, the benefits of using MonitoredTrainingSession are that, this object takes care of

initialising variables,

starting queue runner as well as

setting up the file writers,

but it has also the benefit of making your code easy to distribute as it also works differently depending if you specified the running process as a master or not.

For example you could run something like:

def run_my_model(train_op, session_args):
    with tf.train.MonitoredTrainingSession(**session_args) as sess:
        sess.run(train_op)

that you would call in a non-distributed way:

run_my_model(train_op, {})`

or in a distributed way (see the distributed doc for more information on the inputs):

run_my_model(train_op, {"master": server.target,
                        "is_chief": (FLAGS.task_index == 0)})

On the other hand, the benefit of using the raw tf.Session object is that, you don't have the extra benefits of tf.train.MonitoredTrainingSession, which can be useful if you don't plan to use them or if you want to get more control (for example on how the queues are started).

EDIT (as per comment):
For the op initialisation, you would have to do something like (cf. official doc:

# Define your graph and your ops
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init_p)
    sess.run(your_graph_ops,...)

For the QueueRunner, I would refer you to the official doc where you will find more complete examples.

EDIT2:

The main concept to understand to get a sense on how tf.train.MonitoredTrainingSession works is the _WrappedSession class:

This wrapper is used as a base class for various session wrappers
    that provide additional functionality such as monitoring, coordination,
    and recovery.

The tf.train.MonitoredTrainingSession works (as of version 1.1) this way:

It first checks if it is a chief or a worker (cf. the distributed doc for lexical question).

It begins the hooks which have been provided (for example, StopAtStepHook would just retrieve the global_step tensor at this stage.

It creates a session which is a Chief (or Worker session) wrapped into a _HookedSession wrapped into a _CoordinatedSession wrapped into a _RecoverableSession.

The Chief/Worker sessions are in charge of running initialising ops provided by the Scaffold.

  scaffold: A `Scaffold` used for gathering or building supportive ops. If
not specified a default one is created. It's used to finalize the graph.

The chief session also takes care of all the checkpoint parts: e.g. restoring from checkpoints using the Saver from the Scaffold.

The _HookedSession is basically there to decorate the run method: it calls the _call_hook_before_run and after_run methods when relevant.

At creation the _CoordinatedSession builds a Coordinator which starts the queue runners and will be responsible of closing them.

The _RecoverableSession will insures that there is retry in case of tf.errors.AbortedError.

In conclusion, the tf.train.MonitoredTrainingSession avoids a lot of boiler plate code while being easily extendable with the hooks mechanism.


问:
How to kill a ping on a webshell?
I am using a web shell to test ping on my router and then I cannot kill the process...since control + c doesn't work via web shell. I tried kill ping and it didn't work...

答:
you can use this command,</p>

```<code>$ ps aux | grep ping
$ kill -9 (ping_pid)
</code>```

Title: How to kill a ping on a webshell?

Body:
you can use this command,

$ ps aux | grep ping
$ kill -9 (ping_pid)


问:
Error with datetime insertion
I'm trying to insert a datetime in my table, but I can't figure why it isn't working. I'm running the following query:

```<code>DROP TABLE IF EXISTS dynamic_pricing ;
CREATE TABLE dynamic_pricing(
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    time_start  TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    time_stop TIMESTAMP NOT NULL,
    change_ratio REAL NOT NULL
    -- day_of_week INT(1)
);

INSERT INTO  dynamic_pricing(id,time_start,time_stop,change_ratio)
VALUES(1,DATETIME('2000-01-01 00:00:00'),DATETIME('2000-01-01 00:00:02'),2);
</code>```

I tried using this, only to get

```<code>ERROR 1064 (42000): You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near '('2000-01-01 00:00:00'),DATETIME('2000-01-01
00:00:02'),2)' at line 2
</code>```

What's wrong with this query?

答:
The problem is that your value is defined as DATETIME() but you could use
INSERT INTO dynamic_pricing VALUES ('2017-06-03 21:30:03' )
instead.

Title: Error with datetime insertion

Body:
I'm trying to insert a datetime in my table, but I can't figure why it isn't working. I'm running the following query:

DROP TABLE IF EXISTS dynamic_pricing ;
CREATE TABLE dynamic_pricing(
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    time_start  TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    time_stop TIMESTAMP NOT NULL,
    change_ratio REAL NOT NULL
    -- day_of_week INT(1)
);

INSERT INTO  dynamic_pricing(id,time_start,time_stop,change_ratio)
VALUES(1,DATETIME('2000-01-01 00:00:00'),DATETIME('2000-01-01 00:00:02'),2);

I tried using this, only to get

ERROR 1064 (42000): You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near '('2000-01-01 00:00:00'),DATETIME('2000-01-01
00:00:02'),2)' at line 2

What's wrong with this query?


问:
PHP Time: get next minute/hour what's divisible by five
I need a code what detect the current time and give me the following time what is divisible by five.

For example: It's: 06 03, 2017 21:22:23 , give me 06 03, 2017 21:25:00 in php.
I have no any idea to starting. Is there any code or solution to do this?

答:
```<code>$now = time();
// Add five minutes in seconds, round it down to the nearest five:
$next = ceil($now/300)*300;
echo date('H:i', $next);
</code>```


问:
How can i parse only the numbers from the string?
I want that in Rect.rectangles under the transform property instead to have the string "matrix(0.87142591,0.49052715,-0.49052715,0.87142591,0,0)" to have 2 properties like transform and transform1 and each one will have a number for example: transform "0.12345678"
         transform1 "1.12345678"

```<code>private void Parse()
    {
        XDocument document = XDocument.Load(@"C:\Users\mysvg\Documents\my.svg");

        Rect.rectangles = document.Descendants().Where(x => x.Name.LocalName == "rect").Select(x => new Rect()
        {
            style = Rect.GetStyle((string)x.Attribute("style")),
            id = (string)x.Attribute("id"),
            width = (double)x.Attribute("width"),
            height = (double)x.Attribute("width"),
            x = (double?)x.Attribute("width"),
            y = (double?)x.Attribute("width"),
            transform = x.Attribute("transform".Substring(18, 43)) == null ? "" : (string)x.Attribute("transform".Substring(18, 43))
        }).ToList();
    }
</code>```

And the Rect class:

```<code>public class Rect
    {
        public static List<Rect> rectangles { get; set; }
        public Dictionary<string, string> style { get; set; }
        public string id { get; set; }
        public double width { get; set; }
        public double height { get; set; }
        public double? x { get; set; }
        public double? y { get; set; }
        public string transform { get; set; }

        public static Dictionary<string, string> GetStyle(string styles)
        {
            string pattern = @"(?'name'[^:]+):(?'value'.*)";
            string[] splitArray = styles.Split(new char[] { ';' });
            Dictionary<string, string> style = splitArray.Select(x => Regex.Match(x, pattern))
                .GroupBy(x => x.Groups["name"].Value, y => y.Groups["value"].Value)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
            return style;
        }
    }
</code>```

I'm trying to use substring but getting out of range exception.

ArgumentOutOfRangeException: Cannot exceed length of string

On the line:

```<code>transform = x.Attribute("transform".Substring(18, 43)) == null ? "" : (string)x.Attribute("transform".Substring(18, 43))
</code>```

The string is:

transform="matrix(0.40438612,-0.91458836,0.92071162,0.39024365,0,0)"

And i want to get only the first two numbers: 0.40438612,-0.91458836

Update:

I found also a way to do it using foreach:

```<code>private void Parse()
    {
        XDocument document = XDocument.Load(@"C:\Users\mysvg\Documents\my.svg");

        Rect.rectangles = document.Descendants().Where(x => x.Name.LocalName == "rect").Select(x => new Rect()
        {
            style = Rect.GetStyle((string)x.Attribute("style")),
            id = (string)x.Attribute("id"),
            width = (double)x.Attribute("width"),
            height = (double)x.Attribute("width"),
            x = (double?)x.Attribute("width"),
            y = (double?)x.Attribute("width"),
            transform = x.Attribute("transform") == null ? "" : (string)x.Attribute("transform")
        }).ToList();
        string t = null;
        foreach(Rect rect in Rect.rectangles)
        {
            if (rect.transform != null && rect.transform != "")
            {
                t = rect.transform.Substring(7, 21);
            }
        }
    }
</code>```

But i don't want to do it after the new Rect() {
I want to do the first two numbers extraction on the line:

```<code>transform = x.Attribute("transform") == null ? "" : (string)x.Attribute("transform")
</code>```

The reason is that i have in the bottom of the code a class:

```<code>public class Rect
    {
        public static List<Rect> rectangles { get; set; }
        public Dictionary<string, string> style { get; set; }
        public string id { get; set; }
        public double width { get; set; }
        public double height { get; set; }
        public double? x { get; set; }
        public double? y { get; set; }
        public string transform { get; set; }

        public static Dictionary<string, string> GetStyle(string styles)
        {
            string pattern = @"(?'name'[^:]+):(?'value'.*)";
            string[] splitArray = styles.Split(new char[] { ';' });
            Dictionary<string, string> style = splitArray.Select(x => Regex.Match(x, pattern))
                .GroupBy(x => x.Groups["name"].Value, y => y.Groups["value"].Value)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
            return style;
        }
    }
</code>```

And i want that the property transform to hold/contain the two numbers already.

And another small problem how can i extract the first two numbers if for example one of the numbers have -(minus) in the start for example if transform contain the string: "matrix(0.40438612,-0.91458836,0.92071162,0.39024365,0,0)"

If one of the two numbers have minus in the start or both of them have minus in the start the Substring(7, 21) will not work. I need somehow to get in any case the first two numbers. But the main issue is how to extract the numbers directly from the attribute already.

答:
Are you looking for regular expressions?

```<code> using System.Globalization;
 using System.Linq;
 using System.Text.RegularExpressions;

 ...

 string transform = "matrix(0.40438612,-0.91458836,0.92071162,0.39024365,0,0)";

 double[] result = Regex
   .Matches(transform, @"-?[0-9]*\.?[0-9]+")
   .OfType<Match>()
   .Take(2)
   .Select(match => double.Parse(match.Value, CultureInfo.InvariantCulture))
   .ToArray();
</code>```

Body:
I want that in Rect.rectangles under the transform property instead to have the string "matrix(0.87142591,0.49052715,-0.49052715,0.87142591,0,0)" to have 2 properties like transform and transform1 and each one will have a number for example: transform "0.12345678"
         transform1 "1.12345678"

private void Parse()
    {
        XDocument document = XDocument.Load(@"C:\Users\mysvg\Documents\my.svg");

        Rect.rectangles = document.Descendants().Where(x => x.Name.LocalName == "rect").Select(x => new Rect()
        {
            style = Rect.GetStyle((string)x.Attribute("style")),
            id = (string)x.Attribute("id"),
            width = (double)x.Attribute("width"),
            height = (double)x.Attribute("width"),
            x = (double?)x.Attribute("width"),
            y = (double?)x.Attribute("width"),
            transform = x.Attribute("transform".Substring(18, 43)) == null ? "" : (string)x.Attribute("transform".Substring(18, 43))
        }).ToList();
    }

And the Rect class:

public class Rect
    {
        public static List<Rect> rectangles { get; set; }
        public Dictionary<string, string> style { get; set; }
        public string id { get; set; }
        public double width { get; set; }
        public double height { get; set; }
        public double? x { get; set; }
        public double? y { get; set; }
        public string transform { get; set; }

        public static Dictionary<string, string> GetStyle(string styles)
        {
            string pattern = @"(?'name'[^:]+):(?'value'.*)";
            string[] splitArray = styles.Split(new char[] { ';' });
            Dictionary<string, string> style = splitArray.Select(x => Regex.Match(x, pattern))
                .GroupBy(x => x.Groups["name"].Value, y => y.Groups["value"].Value)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
            return style;
        }
    }

I'm trying to use substring but getting out of range exception.

ArgumentOutOfRangeException: Cannot exceed length of string

On the line:

transform = x.Attribute("transform".Substring(18, 43)) == null ? "" : (string)x.Attribute("transform".Substring(18, 43))

The string is:

transform="matrix(0.40438612,-0.91458836,0.92071162,0.39024365,0,0)"

And i want to get only the first two numbers: 0.40438612,-0.91458836

Update:

I found also a way to do it using foreach:

private void Parse()
    {
        XDocument document = XDocument.Load(@"C:\Users\mysvg\Documents\my.svg");

        Rect.rectangles = document.Descendants().Where(x => x.Name.LocalName == "rect").Select(x => new Rect()
        {
            style = Rect.GetStyle((string)x.Attribute("style")),
            id = (string)x.Attribute("id"),
            width = (double)x.Attribute("width"),
            height = (double)x.Attribute("width"),
            x = (double?)x.Attribute("width"),
            y = (double?)x.Attribute("width"),
            transform = x.Attribute("transform") == null ? "" : (string)x.Attribute("transform")
        }).ToList();
        string t = null;
        foreach(Rect rect in Rect.rectangles)
        {
            if (rect.transform != null && rect.transform != "")
            {
                t = rect.transform.Substring(7, 21);
            }
        }
    }

But i don't want to do it after the new Rect() {
I want to do the first two numbers extraction on the line:

transform = x.Attribute("transform") == null ? "" : (string)x.Attribute("transform")

The reason is that i have in the bottom of the code a class:

public class Rect
    {
        public static List<Rect> rectangles { get; set; }
        public Dictionary<string, string> style { get; set; }
        public string id { get; set; }
        public double width { get; set; }
        public double height { get; set; }
        public double? x { get; set; }
        public double? y { get; set; }
        public string transform { get; set; }

        public static Dictionary<string, string> GetStyle(string styles)
        {
            string pattern = @"(?'name'[^:]+):(?'value'.*)";
            string[] splitArray = styles.Split(new char[] { ';' });
            Dictionary<string, string> style = splitArray.Select(x => Regex.Match(x, pattern))
                .GroupBy(x => x.Groups["name"].Value, y => y.Groups["value"].Value)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
            return style;
        }
    }

And i want that the property transform to hold/contain the two numbers already.

And another small problem how can i extract the first two numbers if for example one of the numbers have -(minus) in the start for example if transform contain the string: "matrix(0.40438612,-0.91458836,0.92071162,0.39024365,0,0)"

If one of the two numbers have minus in the start or both of them have minus in the start the Substring(7, 21) will not work. I need somehow to get in any case the first two numbers. But the main issue is how to extract the numbers directly from the attribute already.

Body:
Are you looking for regular expressions?

 using System.Globalization;
 using System.Linq;
 using System.Text.RegularExpressions;

 ...

 string transform = "matrix(0.40438612,-0.91458836,0.92071162,0.39024365,0,0)";

 double[] result = Regex
   .Matches(transform, @"-?[0-9]*\.?[0-9]+")
   .OfType<Match>()
   .Take(2)
   .Select(match => double.Parse(match.Value, CultureInfo.InvariantCulture))
   .ToArray();


问:
include sqlite3 lib in c makfile
my makefile can't find my sqlite3 library, I want to link it with a -lsqlite3 flag in the gcc commandline. Can someone tell me want I am doing wrong here.
The error message is the following:

```<code>/usr/bin/ld: cannot find -lsqlite3
</code>```

tom

答: You forgot to pass -L followed by the directory containing the SQLite library. You can also use pkg-config sqlite3 --libs to get the appropriate linker flags.

Title: include sqlite3 lib in c makfile

Body:
my makefile can't find my sqlite3 library, I want to link it with a -lsqlite3 flag in the gcc commandline. Can someone tell me want I am doing wrong here.
The error message is the following:

/usr/bin/ld: cannot find -lsqlite3

tom


问:
Editing a line tag inside svg tag using javascript
I am trying to create a line to draw from one side of the window to the other. Using javascript I want it to be at a certain point. I want to detect window size and the nav bar height. The problem I had was that the line is not being displayed.

Here is my javascript and html code:

```<code>      <script>
        function createLineScreenWidth() {

          var elem = getElementsByTagName("svg")[0];
          var line = getElementsByTagName("line")[0];
          var y_pos = getElementByID("navbar").height;

          elem.style.height = "10";
          elem.style.width =  screen.width;

          line.style.stroke = rgb(188, 204, 229);
          line.x2 = screen.width;
          line.y1 = line.y2 = y_pos;
        }
      </script>
        <div class="navbar" id="navbar">
            <nav>
                <a href="/contact/"><div class="pageIcon">CONTACT</div></a>
                <a href="/products/"><div class="pageIcon">PRODUCTS</div></a>
                <a><div class="pageIcon onpageIconChange">ABOUT</div></a>
            </nav>
        </div>
        <svg onload="createLineScreenWidth()">
          <line x1="0" style="stroke-width: 2;" />
        </svg>
</code>```

答:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>ds</title>

CONTACT

PRODUCTS

ABOUT

  <svg onload="createLineScreenWidth()">
    <line x1="0" style="stroke-width: 2;" />
  </svg>

```

Actually there were lot of errors

missing document.get

it was clientHeight not height

there is no rgb function instead you have to wrap that value in double quotes

last but not least instead of line. I'm using .setAttribute which is more clear what we are doing IMO

Body:
I am trying to create a line to draw from one side of the window to the other. Using javascript I want it to be at a certain point. I want to detect window size and the nav bar height. The problem I had was that the line is not being displayed.

Here is my javascript and html code:

CONTACT

PRODUCTS

ABOUT

        <svg onload="createLineScreenWidth()">
          <line x1="0" style="stroke-width: 2;" />
        </svg>

Body:
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>ds</title>
  <style>
    #navbar{
      position: relative;

    }
  </style>
</head>
<body>
  <script>
    function createLineScreenWidth() {

      var elem = document.getElementsByTagName("svg")[0];
      var line = document.getElementsByTagName("line")[0];

      var y_pos = document.getElementById("navbar").clientHeight;

      elem.style.height = "100";
      elem.style.width =  screen.width;

      // line.style.stroke = "red";
      // line.x2 = screen.width;
      // line.y1 = line.y2 = y_pos;

      line.setAttribute('x1','0');
      line.setAttribute('y1',y_pos);
      line.setAttribute('x2',screen.width);
      line.setAttribute('y2',y_pos);
      line.setAttribute("stroke", "rgb(188, 204, 229)")
      elem.appendChild(line);
    }
  </script>
  <div class="navbar" id="navbar">
    <nav>
      <a href="/contact/"><div class="pageIcon">CONTACT</div></a>
      <a href="/products/"><div class="pageIcon">PRODUCTS</div></a>
      <a><div class="pageIcon onpageIconChange">ABOUT</div></a>
    </nav>
  </div>
  <svg onload="createLineScreenWidth()">
    <line x1="0" style="stroke-width: 2;" />
  </svg>
</body>
</html>

Actually there were lot of errors

missing document.get

it was clientHeight not height

there is no rgb function instead you have to wrap that value in double quotes

last but not least instead of line. I'm using .setAttribute which is more clear what we are doing IMO


问:
Ruby on Rails Integration With Wordpress
I have a client who has requested for me to build them a website with a very user friendly way to update content. They have expressed familiarity with wordpress, and expressed interest in being able to use the wordpress front-end to update their content.

I had originally intended to build them a simple admin page, where they can create posts, or add other types of content.. but it seems like wordpress has most of the functionality already in place.

The main problem is that i am a RoR developer. I prefer to use haml for every thing I do, and have 100% full control over how the site works.

So i was hoping someone out there would have an idea of a way i could still build the site using rails and haml, but still allow my client to update using wordpress. I thought maybe i could access the wordpress api, and just pull the content and display it the way i want? or maybe i should go with another CMS.. like Refinery?

Honestly, I just really dont want to have to touch PHP, and preferably use haml, rather than html. O_o

答:
The older answers are not relevant anymore. WordPress now provides a Rest API which can be accessed here:
https://developer.wordpress.org/rest-api/

1) You will probably want to integrate all routing (by taking the "slug" from the articles) in your rails app to serve the articles correctly and present them with a nice "show" view.

2) If you want to store data in the rails system (e.g. for routing and to increase speed) you could create a database table called wp_articles, simply read the full article list or update relevant articles, then present them similar to your normal code.

I've looked at the non-maintained MOMA gem (not required anymore, not maintained), checked the above answer with direct database access (huge effort, slower, outdated) and read about a slighlty complex direct javascript based solution here (http://marydickson.com/how-to-use-the-wordpress-rest-api-in-rails/), but I think that simply copying the relevant info into your system and then presenting them with the normal MVC process is the easiest way.

Disadvantages: Some additional WP-Plugins provide more database fields and other information and its not clear whether you can always access those via the API. So you might have slightly limited functionality.


问:
C++ ADT Set implementation on HashTable (resolving colisions with independent lists)
As the title says I am trying to implement Set ADT on a Hashtable with independent lists. The thing is I don't know where I'm wrong.

The code I am about to post is taken from a bigger project and I took just the esential parts of it to show you.

SetADT.h:

```<code>    #pragma once
#pragma once
#include <stdio.h>

#define CAPACITY 10

using namespace std;

template <typename TElement>
class IteratorSet;

template<typename TElement>
class Set {

    class Nod {
    public:
        TElement element;
        Nod* next;

    };

public:

    Set();

    void add(TElement element);

    int size();

    void sterge(TElement element);

    bool cauta(TElement element);

    friend class IteratorSet<TElement>;
    IteratorSet<TElement> iterator() { return IteratorSet<TElement>(this); }

private:

    int dimensiune;

    typename Set<TElement>::Nod* prim;

    int max;

    Nod** table;

    int hashFunction(TElement element) { return element.hashCode() % max; }

    Nod* set;
};

template<typename TElement>
Set<TElement>::Set()

{
    max = CAPACITATE;
    table = new Nod*[max];
    for (int i = 0; i < max; i++)
        table[i] = NULL;
}

template <typename TElement>
void Set<TElement>::add(TElement element)

{
    int pozitie = hashFunction(element);
    Nod* curent = table[pozitie];
    while (curent != NULL && !(element == curent->element))
        curent = curent->next;
    if (curent != NULL)
        return;
    else
    {
        Nod* n = new Nod;
        n->element = element;
        n->next = table[pozitie];
        table[pozitie] = n;
    }
    dimensiune++;
}

template <typename TElement>
int Set<TElement>::size()

{
    return dimensiune;
}

template <typename TElement>
void Set<TElement>::sterge(TElement element)

{
    int pozitie = hashFunction(element);
    Nod* curent = table[pozitie];

    if (table[pozitie] == NULL)
        return;

    if (table[pozitie]->element == element)
    {
        Nod* deSters = table[pozitie];
        table[pozitie] = table[pozitie]->next;
        delete deSters;
        dimensiune--;
        return;
    }

    Nod* elem = table[pozitie];
    while (elem->next != NULL && (elem->next->element) == element)
        elem = elem->next;

    if (elem->next != NULL)
    {
        Nod* deSters = elem->next;
        elem->next = elem->next->next;
        delete deSters;
        dimensiune--;
    }

}

template <typename TElement>
bool Set<TElement>::cauta(TElement element)

{
    int pozitie = hashFunction(element);
    Nod* curent = table[pozitie];
    while (curent != NULL && !(element == curent->element))
        curent = curent->next;
    if (curent != NULL)
    {
        return true;
    }
    return false;
}

template<typename TElement>
class IteratorSet {
public:
    IteratorSet(Set<TElement>* m);
    void next();
    bool valid();
    TElement element();
private:
    Set<TElement>* Set;
    typename Set<TElement>::Nod* crt;
};

template<typename TElement>
IteratorSet<TElement>::IteratorSet(Set<TElement>* mul) {
    Set = mul;
    crt = mul->prim;
}

template<typename TElement>
bool IteratorSet<TElement>::valid() {
    return crt != NULL;
}

template<typename TElement>
TElement IteratorSet<TElement>::element() {
    return crt->element;
}

template<typename TElement>
void IteratorSet<TElement>::next() {
    crt = crt->next;
}
</code>```

=======================================================
domain.h (names of Pizzas)

```<code>#include <string>
using namespace std;

class Pizza {
public:
    Pizza(string namePizza) : namePizza(namePizza) {}
    Pizza() : namePizza("") {}

    string getName() const {
        return namePizza;
    }
    int hashCode()
    {
        int sum = 0;
        for (unsigned i = 0; i < str.length(); i++)
            sum += str[i];
        return sum;
    }
    bool operator == (Pizza& other) {
        return namePizza == other.getName();
    }

private:
    string namePizza;
    string str;
};
</code>```

====================================================
main.cpp:

```<code>#include "SetADT.h"
#include <string>
#include <iostream>
#include "domain.h"

void show(Set<Pizza>* set) {
    IteratorSet<string> it = set->iterator();
    while (it.valid()) {
        cout << "\t" << it.element().getName() << endl;
        it.next();
    }
}

int main()
{
    Set<Pizza> set;

    Pizza pizza1{ "diavola" };
    Pizza pizza2{ "prosciuto" };

    set.add(pizza1);
    set.add(pizza2);

    show(set);

    return 0;
}
</code>```

When I try to print the objects added to the Set it pops and error and the program stops.

I don't know anywhere else to look to find the problem.

Anyway, if the code sample isn't enough, here the complete project ( has parts of romanian in it )

http://www20.zippyshare.com/v/qKpEcZhr/file.html

答: The reason might be, for example, prim variable that you use in the iterator, that is initialized to an undefined value. However, code you posted is not compilable, i.e. there are other problems why your code is not working. Did not download your zip file.

Body:
As the title says I am trying to implement Set ADT on a Hashtable with independent lists. The thing is I don't know where I'm wrong.

The code I am about to post is taken from a bigger project and I took just the esential parts of it to show you.

SetADT.h:

    #pragma once
#pragma once
#include <stdio.h>

#define CAPACITY 10

using namespace std;

template <typename TElement>
class IteratorSet;

template<typename TElement>
class Set {

    class Nod {
    public:
        TElement element;
        Nod* next;

    };

public:

    Set();

    void add(TElement element);

    int size();

    void sterge(TElement element);

    bool cauta(TElement element);

    friend class IteratorSet<TElement>;
    IteratorSet<TElement> iterator() { return IteratorSet<TElement>(this); }

private:

    int dimensiune;

    typename Set<TElement>::Nod* prim;

    int max;

    Nod** table;

    int hashFunction(TElement element) { return element.hashCode() % max; }

    Nod* set;
};

template<typename TElement>
Set<TElement>::Set()

{
    max = CAPACITATE;
    table = new Nod*[max];
    for (int i = 0; i < max; i++)
        table[i] = NULL;
}

template <typename TElement>
void Set<TElement>::add(TElement element)

{
    int pozitie = hashFunction(element);
    Nod* curent = table[pozitie];
    while (curent != NULL && !(element == curent->element))
        curent = curent->next;
    if (curent != NULL)
        return;
    else
    {
        Nod* n = new Nod;
        n->element = element;
        n->next = table[pozitie];
        table[pozitie] = n;
    }
    dimensiune++;
}

template <typename TElement>
int Set<TElement>::size()

{
    return dimensiune;
}

template <typename TElement>
void Set<TElement>::sterge(TElement element)

{
    int pozitie = hashFunction(element);
    Nod* curent = table[pozitie];

    if (table[pozitie] == NULL)
        return;

    if (table[pozitie]->element == element)
    {
        Nod* deSters = table[pozitie];
        table[pozitie] = table[pozitie]->next;
        delete deSters;
        dimensiune--;
        return;
    }

    Nod* elem = table[pozitie];
    while (elem->next != NULL && (elem->next->element) == element)
        elem = elem->next;

    if (elem->next != NULL)
    {
        Nod* deSters = elem->next;
        elem->next = elem->next->next;
        delete deSters;
        dimensiune--;
    }

}

template <typename TElement>
bool Set<TElement>::cauta(TElement element)

{
    int pozitie = hashFunction(element);
    Nod* curent = table[pozitie];
    while (curent != NULL && !(element == curent->element))
        curent = curent->next;
    if (curent != NULL)
    {
        return true;
    }
    return false;
}

template<typename TElement>
class IteratorSet {
public:
    IteratorSet(Set<TElement>* m);
    void next();
    bool valid();
    TElement element();
private:
    Set<TElement>* Set;
    typename Set<TElement>::Nod* crt;
};

template<typename TElement>
IteratorSet<TElement>::IteratorSet(Set<TElement>* mul) {
    Set = mul;
    crt = mul->prim;
}

template<typename TElement>
bool IteratorSet<TElement>::valid() {
    return crt != NULL;
}

template<typename TElement>
TElement IteratorSet<TElement>::element() {
    return crt->element;
}

template<typename TElement>
void IteratorSet<TElement>::next() {
    crt = crt->next;
}

=======================================================
domain.h (names of Pizzas)

#include <string>
using namespace std;

class Pizza {
public:
    Pizza(string namePizza) : namePizza(namePizza) {}
    Pizza() : namePizza("") {}

    string getName() const {
        return namePizza;
    }
    int hashCode()
    {
        int sum = 0;
        for (unsigned i = 0; i < str.length(); i++)
            sum += str[i];
        return sum;
    }
    bool operator == (Pizza& other) {
        return namePizza == other.getName();
    }

private:
    string namePizza;
    string str;
};

====================================================
main.cpp:

#include "SetADT.h"
#include <string>
#include <iostream>
#include "domain.h"

void show(Set<Pizza>* set) {
    IteratorSet<string> it = set->iterator();
    while (it.valid()) {
        cout << "\t" << it.element().getName() << endl;
        it.next();
    }
}

int main()
{
    Set<Pizza> set;

    Pizza pizza1{ "diavola" };
    Pizza pizza2{ "prosciuto" };

    set.add(pizza1);
    set.add(pizza2);

    show(set);

    return 0;
}

When I try to print the objects added to the Set it pops and error and the program stops.

I don't know anywhere else to look to find the problem.

Anyway, if the code sample isn't enough, here the complete project ( has parts of romanian in it )

http://www20.zippyshare.com/v/qKpEcZhr/file.html


问:
traitlets.traitlets.TraitError in Pycharm
I am a beginner in python. I am facing the following problem.

Whenever I start pycharm Community edition (version 5.0.3), the Python console fails to starts and shows the following error:

```<code>usr/bin/python2.7 /usr/lib/pycharm-community/helpers/pydev/pydevconsole.py 53192 49994
Traceback (most recent call last):
  File "/usr/lib/pycharm-community/helpers/pydev/pydevconsole.py", line 488, in <module>
    pydevconsole.StartServer(pydev_localhost.get_localhost(), int(port), int(client_port))
  File "/usr/lib/pycharm-community/helpers/pydev/pydevconsole.py", line 330, in StartServer
    interpreter = InterpreterInterface(host, client_port, threading.currentThread())
  File "/usr/lib/pycharm-community/helpers/pydev/pydev_ipython_console.py", line 26, in __init__
    self.interpreter = get_pydev_frontend(host, client_port)
  File "/usr/lib/pycharm-community/helpers/pydev/pydev_ipython_console_011.py", line 472, in get_pydev_frontend
    _PyDevFrontEndContainer._instance = _PyDevFrontEnd()
  File "/usr/lib/pycharm-community/helpers/pydev/pydev_ipython_console_011.py", line 303, in __init__
    self.ipython = PyDevTerminalInteractiveShell.instance()
  File "/usr/lib/python2.7/dist-packages/IPython/config/configurable.py", line 354, in instance
    inst = cls(*args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/IPython/terminal/interactiveshell.py", line 328, in __init__
    **kwargs
  File "/usr/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 483, in __init__
    self.init_readline()
  File "/usr/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 1816, in init_readline
    if self.readline_use:
  File "/home/vivekruhela/.local/lib/python2.7/site-packages/traitlets/traitlets.py", line 529, in __get__
    return self.get(obj, cls)
  File "/home/vivekruhela/.local/lib/python2.7/site-packages/traitlets/traitlets.py", line 507, in get
    % (self.name, obj))
  traitlets.traitlets.TraitError: No default value found for None trait of <pydev_ipython_console_011.PyDevTerminalInteractiveShell object at 0x7f7b0e682cd0>

Process finished with exit code 1
Couldn't connect to console process.
</code>```

How can I connect to the pycharm console? I have already installed IPython in my system.

答: In my case, this was due to a conflicting installation of IPython through pip and apt. Removing the apt-installed version using sudo apt remove ipython fixed the problem.

Body:
I am a beginner in python. I am facing the following problem.

Whenever I start pycharm Community edition (version 5.0.3), the Python console fails to starts and shows the following error:

usr/bin/python2.7 /usr/lib/pycharm-community/helpers/pydev/pydevconsole.py 53192 49994
Traceback (most recent call last):
  File "/usr/lib/pycharm-community/helpers/pydev/pydevconsole.py", line 488, in <module>
    pydevconsole.StartServer(pydev_localhost.get_localhost(), int(port), int(client_port))
  File "/usr/lib/pycharm-community/helpers/pydev/pydevconsole.py", line 330, in StartServer
    interpreter = InterpreterInterface(host, client_port, threading.currentThread())
  File "/usr/lib/pycharm-community/helpers/pydev/pydev_ipython_console.py", line 26, in __init__
    self.interpreter = get_pydev_frontend(host, client_port)
  File "/usr/lib/pycharm-community/helpers/pydev/pydev_ipython_console_011.py", line 472, in get_pydev_frontend
    _PyDevFrontEndContainer._instance = _PyDevFrontEnd()
  File "/usr/lib/pycharm-community/helpers/pydev/pydev_ipython_console_011.py", line 303, in __init__
    self.ipython = PyDevTerminalInteractiveShell.instance()
  File "/usr/lib/python2.7/dist-packages/IPython/config/configurable.py", line 354, in instance
    inst = cls(*args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/IPython/terminal/interactiveshell.py", line 328, in __init__
    **kwargs
  File "/usr/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 483, in __init__
    self.init_readline()
  File "/usr/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 1816, in init_readline
    if self.readline_use:
  File "/home/vivekruhela/.local/lib/python2.7/site-packages/traitlets/traitlets.py", line 529, in __get__
    return self.get(obj, cls)
  File "/home/vivekruhela/.local/lib/python2.7/site-packages/traitlets/traitlets.py", line 507, in get
    % (self.name, obj))
  traitlets.traitlets.TraitError: No default value found for None trait of <pydev_ipython_console_011.PyDevTerminalInteractiveShell object at 0x7f7b0e682cd0>

Process finished with exit code 1
Couldn't connect to console process.

How can I connect to the pycharm console? I have already installed IPython in my system.


问:
Any function to perform on rdd as a whole
I am new on spark. I need a function that will do a work on an RDD as a whole. Not on each element on RDD that map() do.
Example:
JavaRDD<String> str= sc.parallelize(list);
 str.map(func);
now I want to perfrom func on str as whole not on each element of str.
Is there anything that serves my purpose.

答:
I would like to suggest lets transform it to a DataFrame!

```<code>from pyspark.sql import toDF
df = rdd.toDF(['column', 'value'])
</code>```

It solves your problem i think, or please tell me why you do not want to use the DataFrame object

Body:
I would like to suggest lets transform it to a DataFrame!

from pyspark.sql import toDF
df = rdd.toDF(['column', 'value'])

It solves your problem i think, or please tell me why you do not want to use the DataFrame object


问:
REACT: Unhandled Rejection (TypeError): this.props.flights.forEach is not a function
I am trying to learn React, and I stumbled upon the error from the title in my program. Here is my code:

```<code>class FlightRow extends React.Component{

handleClicke=(event)=>{
    console.log('delete button pentru '+this.props.flight.flightId);
    this.props.deleteFunc(this.props.flight.flightId);
}

render() {
    return (
        <tr>
            <td>{this.props.flight.flightId}</td>
            <td>{this.props.flight.destination}</td>
            <td>{this.props.flight.airport}</td>
            <td>{this.props.flight.freeseats}</td>
            <td>{this.props.flight.datehour}</td>
            <td><button  onClick={this.handleClicke}>Delete</button></td>
        </tr>
    );
}
}

class FlightTable extends React.Component {
render() {
    var rows = [];
    var functieStergere=this.props.deleteFunc;
    this.props.flights.forEach(function(flight) {

        rows.push(<FlightRow flight={flight} key={flight.flightId} deleteFunc={functieStergere} />);
    });
    return (<div className="FlightTable">

        <table className="center">
            <thead>
            <tr>
                <th>FlightId</th>
                <th>Destination</th>
                <th>Airport</th>
                <th>Freeseats</th>
                <th>Datehour</th>
                <th></th>
            </tr>
            </thead>
            <tbody>{rows}</tbody>
        </table>

        </div>
    );
}
}

export default FlightTable;
</code>```

I am getting the error in the first lines of the FlightTable class, when I am trying to fill it. Immediately after I start the app, I see for like one second the table filled exactly how it should be, then I receive the error.

Here is where I declare my "flights" array.

```<code>class FlightApp extends React.Component{
constructor(props){
    super(props);
    this.state={flights:[{"flightId":12,"destination":"CCCCC","airport":"AAAAA","freeseats":100,"datehour":"2017-02-02"},{"flightId":13,"destination":"CCCCC","airport":"AAAAA","freeseats":100,"datehour":"2017-02-02"}],
        deleteFunc:this.deleteFunc.bind(this),
        addFunc:this.addFunc.bind(this),
    }
    console.log('FlightApp constructor')
}

addFunc(flight){
    console.log('inside add Func '+flight);
    AddFlight(flight)
        .then(res=> GetFlights())
        .then(flights=>this.setState({flights}))
        .catch(erorr=>console.log('eroare add ',erorr));
}

deleteFunc(flight){
    console.log('inside deleteFunc '+flight);
    DeleteFlight(flight)
        .then(res=> GetFlights())
        .then(flights=>this.setState({flights}))
        .catch(error=>console.log('eroare delete', error));
}

componentDidMount(){
    console.log('inside componentDidMount')
    GetFlights().then(flights=>this.setState({flights}));
}

render(){
    return(
        <div className="FlightApp">
            <h1>Flight Management</h1>
            <FlightForm addFunc={this.state.addFunc}/>
            <br/>
            <br/>
             <FlightTable flights={this.state.flights} deleteFunc={this.state.deleteFunc}/>
        </div>
    );
}
}

export default FlightApp;
</code>```

The "GetFlights()" method looks like this, and it calls a method from a Java REST Spring Server that return a List

```<code>export function GetFlights(){
var headers = new Headers();
headers.append('Accept', 'application/json');
var myInit = { method: 'GET',
    headers: headers,
    mode: 'cors'};
var request = new Request(CHAT_USERS_BASE_URL, myInit);
console.log('Inainte de fetch pentru '+CHAT_USERS_BASE_URL)
return fetch(request)
    .then(status)
    .then(json)
    .then(data=> {
         console.log('Request succeeded with JSON response', data);
         return data;
     }).catch(error=>{
            console.log('Request failed', error);
            return error;
      });

}
</code>```

How could I fix this error? Thank you.

答: Did you check the response you receive from the server? I believe it's not an array which is leading to this error. Post the response received from the server.</p>

Body:
I am trying to learn React, and I stumbled upon the error from the title in my program. Here is my code:

class FlightRow extends React.Component{

handleClicke=(event)=>{
    console.log('delete button pentru '+this.props.flight.flightId);
    this.props.deleteFunc(this.props.flight.flightId);
}

render() {
    return (

            {this.props.flight.flightId}
            {this.props.flight.destination}
            {this.props.flight.airport}
            {this.props.flight.freeseats}
            {this.props.flight.datehour}
            <button  onClick={this.handleClicke}>Delete</button>

    );
}
}

class FlightTable extends React.Component {
render() {
    var rows = [];
    var functieStergere=this.props.deleteFunc;
    this.props.flights.forEach(function(flight) {

        rows.push(<FlightRow flight={flight} key={flight.flightId} deleteFunc={functieStergere} />);
    });
    return (

                FlightId
                Destination
                Airport
                Freeseats
                Datehour

{rows}

    );
}
}

export default FlightTable;

I am getting the error in the first lines of the FlightTable class, when I am trying to fill it. Immediately after I start the app, I see for like one second the table filled exactly how it should be, then I receive the error.

Here is where I declare my "flights" array.

class FlightApp extends React.Component{
constructor(props){
    super(props);
    this.state={flights:[{"flightId":12,"destination":"CCCCC","airport":"AAAAA","freeseats":100,"datehour":"2017-02-02"},{"flightId":13,"destination":"CCCCC","airport":"AAAAA","freeseats":100,"datehour":"2017-02-02"}],
        deleteFunc:this.deleteFunc.bind(this),
        addFunc:this.addFunc.bind(this),
    }
    console.log('FlightApp constructor')
}

addFunc(flight){
    console.log('inside add Func '+flight);
    AddFlight(flight)
        .then(res=> GetFlights())
        .then(flights=>this.setState({flights}))
        .catch(erorr=>console.log('eroare add ',erorr));
}

deleteFunc(flight){
    console.log('inside deleteFunc '+flight);
    DeleteFlight(flight)
        .then(res=> GetFlights())
        .then(flights=>this.setState({flights}))
        .catch(error=>console.log('eroare delete', error));
}

componentDidMount(){
    console.log('inside componentDidMount')
    GetFlights().then(flights=>this.setState({flights}));
}

render(){
    return(

Flight Management

            <FlightForm addFunc={this.state.addFunc}/>

             <FlightTable flights={this.state.flights} deleteFunc={this.state.deleteFunc}/>

    );
}
}

export default FlightApp;

The "GetFlights()" method looks like this, and it calls a method from a Java REST Spring Server that return a List

export function GetFlights(){
var headers = new Headers();
headers.append('Accept', 'application/json');
var myInit = { method: 'GET',
    headers: headers,
    mode: 'cors'};
var request = new Request(CHAT_USERS_BASE_URL, myInit);
console.log('Inainte de fetch pentru '+CHAT_USERS_BASE_URL)
return fetch(request)
    .then(status)
    .then(json)
    .then(data=> {
         console.log('Request succeeded with JSON response', data);
         return data;
     }).catch(error=>{
            console.log('Request failed', error);
            return error;
      });

}

How could I fix this error? Thank you.


问:
C# LINQ accessing another property within a LINQ SELECT statement (method)
I have a question which refers to whether it's possible to access another property in LINQ in order to set another property's value in LINQ:

```<code>  var v = ctx.myTableItems
          .Where(x => x.id== anotherid)
          .Select(e => new MyViewModel
          {
            Title = e.Title,
            CurrentPrice = e.CurrenctPrice.Value,

            ItemID =  e.ItemID.ToString(),
            Transactions= e.Transactions,
            Sales =
            })
            .Where(x=>x.Sales>0);
</code>```

So check this out guys, when I was setting my Transactions property I set the transactions collection in my previous line, and now I'd like to set my sales propert with the Transactions property that was assigned in a previous line:

```<code>  Transactions= e.Transactions,
  Sales = e.Transactions.Sum(x=>x.Quantity) // Normaly I'd do it like this
</code>```

But I wanted to try out something like this:

```<code> Sales = Transactions.Sum(x=>x.Quantity) // is this doable ?
</code>```

So my question here is, is it possible to set another property within the select statement with a previously property's value? In my case it's Transactions collection ?

Is this doable, if so , how?

P.S. I'm trying to figure if this is doable because if I could use this previously set property's value , then I would avoid performing 2 unnecesary queries on my Transactions table in DB?

答:
You cannot use the previous value because you dont want to call e.Transactions.Sum() for every item.

Just add a method to MyViewModel

```<code>public double GetSales()
{
 return Transactions.Sum(x=>x.Quantity);
}

//at the end of your code use:
.Where(x=>x.GetSales()>0);
</code>```

Body:
I have a question which refers to whether it's possible to access another property in LINQ in order to set another property's value in LINQ:

  var v = ctx.myTableItems
          .Where(x => x.id== anotherid)
          .Select(e => new MyViewModel
          {
            Title = e.Title,
            CurrentPrice = e.CurrenctPrice.Value,

            ItemID =  e.ItemID.ToString(),
            Transactions= e.Transactions,
            Sales =
            })
            .Where(x=>x.Sales>0);

So check this out guys, when I was setting my Transactions property I set the transactions collection in my previous line, and now I'd like to set my sales propert with the Transactions property that was assigned in a previous line:

  Transactions= e.Transactions,
  Sales = e.Transactions.Sum(x=>x.Quantity) // Normaly I'd do it like this

But I wanted to try out something like this:

 Sales = Transactions.Sum(x=>x.Quantity) // is this doable ?

So my question here is, is it possible to set another property within the select statement with a previously property's value? In my case it's Transactions collection ?

Is this doable, if so , how?

P.S. I'm trying to figure if this is doable because if I could use this previously set property's value , then I would avoid performing 2 unnecesary queries on my Transactions table in DB?

Body:
You cannot use the previous value because you dont want to call e.Transactions.Sum() for every item.

Just add a method to MyViewModel

public double GetSales()
{
 return Transactions.Sum(x=>x.Quantity);
}

//at the end of your code use:
.Where(x=>x.GetSales()>0);