问:
Why does the compiler not give an ambiguous reference error?
With reference to the following code

```<code>#include <iostream>
#include <tuple>
#include <string>
#include <type_traits>

using std::cout;
using std::endl;
using std::string;

template <typename... Args>
void bar(Args&&...) {}

int change(const string&) { return 1; }
double change(int) { return 1.0; }

int main() {
    // bar(1, 2.0, static_cast<int(*)(const string&)>(&change));
    bar(1, 2.0, &change);
    return 0;
}
</code>```

I understand that the error in the above code is that the reference to the change function is ambiguous (which is why the commented line works), but then why does the compiler give this error message?

```<code>test.cpp:17:5: error: no matching function for call to 'bar'
    bar(1, 2.0, &change);
    ^~~
test.cpp:11:6: note: candidate function not viable: requires 2 arguments, but 3 were
      provided
void bar(Args&&...) {}
     ^
1 error generated.
</code>```

This happens both on gcc (>5) as well as clang (Apple LLVM version 8.0.0 (clang-800.0.42.1))

I am just curious as to why both the compilers do not just say that the reference is ambiguous.  I feel like it has something to do with how template instantiations work in C++ but I am not sure of the exact reason.

答:
Justin is correct. Running GCC through a debugger leads to these lines of code:

```<code>cp_parser_lookup_name(cp_parser*, tree_node*, tag_types, bool, bool, bool, tree_node**, unsigned int) () at ../../gcc/cp/parser.c:24665
24665   {
(gdb)
24667     tree object_type = parser->context->object_type;
(gdb)
24670     if (ambiguous_decls)
(gdb)
24665   {
(gdb)
24667     tree object_type = parser->context->object_type;
(gdb)
24670     if (ambiguous_decls)
(gdb)
24676     parser->context->object_type = NULL_TREE;

...

(gdb) list 24670
24665   {
24666     tree decl;
24667     tree object_type = parser->context->object_type;
24668
24669     /* Assume that the lookup will be unambiguous.  */
24670     if (ambiguous_decls)
24671       *ambiguous_decls = NULL_TREE;
24672
24673     /* Now that we have looked up the name, the OBJECT_TYPE (if any) is
24674        no longer valid.  Note that if we are parsing tentatively, and
</code>```

And this is the actual code that emits the diagnostic:

```<code>6914                        complain);
(gdb)

test.cpp:9:24: error: too many arguments to function ‘void bar(Args&& ...) [with Args = {}]’
     bar(1, 2.0, &change);
                        ^
test.cpp:2:6: note: declared here
 void bar(Args&&...) {}

...

(gdb) list 6914
6909              /* All other function calls.  */
6910              postfix_expression
6911            = finish_call_expr (postfix_expression, &args,
6912                        /*disallow_virtual=*/false,
6913                        koenig_p,
6914                        complain);
6915
6916            if (close_paren_loc != UNKNOWN_LOCATION)
6917              {
6918            location_t combined_loc = make_location (token->location,
</code>```

Skipping through a bunch of stuff (as it would make this answer unnecessarily long), the actual error occurs during overload resolution:

```<code>(gdb)
add_candidates (fns=0x7fffeffb0940, first_arg=first_arg@entry=0x0, args=args@entry=0x7fffeff9baf0, return_type=return_type@entry=0x0, explicit_targs=0x0,
    template_only=false, conversion_path=0x0, access_path=0x0, flags=1, candidates=0x7fffffffd320, complain=3) at ../../gcc/cp/call.c:5302
5302      for (; fns; fns = OVL_NEXT (fns))
(gdb)
5365    }
(gdb)
perform_overload_resolution (complain=3, any_viable_p=<synthetic pointer>, candidates=0x7fffffffd320, args=0x7fffeff9baf0, fn=<optimized out>)
    at ../../gcc/cp/call.c:4036
4036      *candidates = splice_viable (*candidates, false, any_viable_p);
(gdb)
build_new_function_call(tree_node*, vec<tree_node*, va_gc, vl_embed>**, bool, int) () at ../../gcc/cp/call.c:4111
4111                          complain);
(gdb)
4115          if (complain & tf_error)
(gdb)
4119          if (!any_viable_p && candidates && ! candidates->next
(gdb)
4120              && (TREE_CODE (candidates->fn) == FUNCTION_DECL))
(gdb)
4121            return cp_build_function_call_vec (candidates->fn, args, complain);
</code>```

The error occurs in convert_arguments:

```<code>(gdb) list 3611
3606          allocated = make_tree_vector ();
3607          params = &allocated;
3608        }
3609
3610        nargs = convert_arguments (parm_types, params, fndecl, LOOKUP_NORMAL,
3611                       complain);
3612      if (nargs < 0)
3613        return error_mark_node;
3614
3615      argarray = (*params)->address ();
</code>```

Finally, the diagnostic is emitted in error_num_args because if (TREE_CODE (TREE_TYPE (fndecl)) == METHOD_TYPE) is false.

Body:
With reference to the following code

#include <iostream>
#include <tuple>
#include <string>
#include <type_traits>

using std::cout;
using std::endl;
using std::string;

template <typename... Args>
void bar(Args&&...) {}

int change(const string&) { return 1; }
double change(int) { return 1.0; }

int main() {
    // bar(1, 2.0, static_cast<int(*)(const string&)>(&change));
    bar(1, 2.0, &change);
    return 0;
}

I understand that the error in the above code is that the reference to the change function is ambiguous (which is why the commented line works), but then why does the compiler give this error message?

test.cpp:17:5: error: no matching function for call to 'bar'
    bar(1, 2.0, &change);
    ^~~
test.cpp:11:6: note: candidate function not viable: requires 2 arguments, but 3 were
      provided
void bar(Args&&...) {}
     ^
1 error generated.

This happens both on gcc (>5) as well as clang (Apple LLVM version 8.0.0 (clang-800.0.42.1))

I am just curious as to why both the compilers do not just say that the reference is ambiguous.  I feel like it has something to do with how template instantiations work in C++ but I am not sure of the exact reason.

Body:
Justin is correct. Running GCC through a debugger leads to these lines of code:

cp_parser_lookup_name(cp_parser*, tree_node*, tag_types, bool, bool, bool, tree_node**, unsigned int) () at ../../gcc/cp/parser.c:24665
24665   {
(gdb)
24667     tree object_type = parser->context->object_type;
(gdb)
24670     if (ambiguous_decls)
(gdb)
24665   {
(gdb)
24667     tree object_type = parser->context->object_type;
(gdb)
24670     if (ambiguous_decls)
(gdb)
24676     parser->context->object_type = NULL_TREE;

...

(gdb) list 24670
24665   {
24666     tree decl;
24667     tree object_type = parser->context->object_type;
24668
24669     /* Assume that the lookup will be unambiguous.  */
24670     if (ambiguous_decls)
24671       *ambiguous_decls = NULL_TREE;
24672
24673     /* Now that we have looked up the name, the OBJECT_TYPE (if any) is
24674        no longer valid.  Note that if we are parsing tentatively, and

And this is the actual code that emits the diagnostic:

6914                        complain);
(gdb)

test.cpp:9:24: error: too many arguments to function ‘void bar(Args&& ...) [with Args = {}]’
     bar(1, 2.0, &change);
                        ^
test.cpp:2:6: note: declared here
 void bar(Args&&...) {}

...

(gdb) list 6914
6909              /* All other function calls.  */
6910              postfix_expression
6911            = finish_call_expr (postfix_expression, &args,
6912                        /*disallow_virtual=*/false,
6913                        koenig_p,
6914                        complain);
6915
6916            if (close_paren_loc != UNKNOWN_LOCATION)
6917              {
6918            location_t combined_loc = make_location (token->location,

Skipping through a bunch of stuff (as it would make this answer unnecessarily long), the actual error occurs during overload resolution:

(gdb)
add_candidates (fns=0x7fffeffb0940, first_arg=first_arg@entry=0x0, args=args@entry=0x7fffeff9baf0, return_type=return_type@entry=0x0, explicit_targs=0x0,
    template_only=false, conversion_path=0x0, access_path=0x0, flags=1, candidates=0x7fffffffd320, complain=3) at ../../gcc/cp/call.c:5302
5302      for (; fns; fns = OVL_NEXT (fns))
(gdb)
5365    }
(gdb)
perform_overload_resolution (complain=3, any_viable_p=<synthetic pointer>, candidates=0x7fffffffd320, args=0x7fffeff9baf0, fn=<optimized out>)
    at ../../gcc/cp/call.c:4036
4036      *candidates = splice_viable (*candidates, false, any_viable_p);
(gdb)
build_new_function_call(tree_node*, vec<tree_node*, va_gc, vl_embed>**, bool, int) () at ../../gcc/cp/call.c:4111
4111                          complain);
(gdb)
4115          if (complain & tf_error)
(gdb)
4119          if (!any_viable_p && candidates && ! candidates->next
(gdb)
4120              && (TREE_CODE (candidates->fn) == FUNCTION_DECL))
(gdb)
4121            return cp_build_function_call_vec (candidates->fn, args, complain);

The error occurs in convert_arguments:

(gdb) list 3611
3606          allocated = make_tree_vector ();
3607          params = &allocated;
3608        }
3609
3610        nargs = convert_arguments (parm_types, params, fndecl, LOOKUP_NORMAL,
3611                       complain);
3612      if (nargs < 0)
3613        return error_mark_node;
3614
3615      argarray = (*params)->address ();

Finally, the diagnostic is emitted in error_num_args because if (TREE_CODE (TREE_TYPE (fndecl)) == METHOD_TYPE) is false.


来源: stackexchange

问:
Pass function inside string literal to other component
I want to pass a function defined in my actions to an element.

Reducer

```<code>case 'UPDATE_HEADER':
    return Object.assign({}, state, {
        headerChildren: state.headerChildren.concat([action.child])
    });
</code>```

Action.js

```<code>export const deleteHeader = () => {
    return {
        type: 'DELETE_HEADER',
    };
}
</code>```

I am passing this action to my sidebar

```<code>onAddHeader () {
    this.props.addHeader();
    this.props.updateHeader(
        `<Header key='${this.props.childKey}'
             deleteHeader='${this.props.deleteHeader}'/>`,
    );
}
</code>```

The deleteHeader function is being passed to the Header component but the problem is that it is being passed as a string and not as a function.

I am rendering it as this

```<code>`{this.props.headerChildren.map((value, index) => (
    <JsxParser
        key={index}
        components={[Header]}
        jsx={value}
    />
))}`
</code>```

Can someone please guide me through the solution. I have searched a lot and couldn't find a way to do it. If this is not the correct approach to do so, kindly let me know the proper way to do it. I am new to React + Redux so finding it a bit difficult.

Thanks in advance

答:
I am going to take a stab at guessing what I think you want to achieve here - it is a bit unclear so if I am wrong please feel free to comment and I can try and fix.

You don't need to use a string template if you are not trying to pass a string. You can simply pass the component and props themselves. Something like this...

```<code>// I'm assuming you're doing something like this
import Header from './wheverYourHeaderIs';

...

onAddHeader () {
    this.props.addHeader();
    this.props.updateHeader(Header,
       { key: this.props.childKey,
         deleteHeader: this.props.deleteHeader
       }
    );
}
</code>```

I turned your props into 1 keyed object so it is flexible to add more/less props without having to modify the number of arguments your updateHeader function has to take.

Then your updateHeader would do something like :

```<code> function updateHeader(Component, props) {

  // do whatever you were going to do with your component
     <Component {...props} />
  // becasue we combined props into one object
  // this is the same as <Header key={this.props.childKey} deleteHeader={this.props.deleteHeader}/>
 }
</code>```

Not sure if this is what you were trying to achieve please feel free to comment if not.

ContentLicense: CC BY-SA 3.0

Body:
I want to pass a function defined in my actions to an element.

Reducer

case 'UPDATE_HEADER':
    return Object.assign({}, state, {
        headerChildren: state.headerChildren.concat([action.child])
    });

Action.js

export const deleteHeader = () => {
    return {
        type: 'DELETE_HEADER',
    };
}

I am passing this action to my sidebar

onAddHeader () {
    this.props.addHeader();
    this.props.updateHeader(
        ``,
    );
}

The deleteHeader function is being passed to the Header component but the problem is that it is being passed as a string and not as a function.

I am rendering it as this

`{this.props.headerChildren.map((value, index) => (
    <JsxParser
        key={index}
        components={[Header]}
        jsx={value}
    />
))}`

Can someone please guide me through the solution. I have searched a lot and couldn't find a way to do it. If this is not the correct approach to do so, kindly let me know the proper way to do it. I am new to React + Redux so finding it a bit difficult.

Thanks in advance

Body:
I am going to take a stab at guessing what I think you want to achieve here - it is a bit unclear so if I am wrong please feel free to comment and I can try and fix.

You don't need to use a string template if you are not trying to pass a string. You can simply pass the component and props themselves. Something like this...

// I'm assuming you're doing something like this
import Header from './wheverYourHeaderIs';

...

onAddHeader () {
    this.props.addHeader();
    this.props.updateHeader(Header,
       { key: this.props.childKey,
         deleteHeader: this.props.deleteHeader
       }
    );
}

I turned your props into 1 keyed object so it is flexible to add more/less props without having to modify the number of arguments your updateHeader function has to take.

Then your updateHeader would do something like :

 function updateHeader(Component, props) {

  // do whatever you were going to do with your component
     <Component {...props} />
  // becasue we combined props into one object
  // this is the same as <Header key={this.props.childKey} deleteHeader={this.props.deleteHeader}/>
 }

Not sure if this is what you were trying to achieve please feel free to comment if not.


问:
In angular 2+ ui-router 1+, how do I pass parameters to child view?
Parent template

```<code><ui-view [inputValue]="something"></ui-view>
</code>```

Example child component

```<code>@Component({
  selector: 'child',
  template: '...'
})
export class ChildComponent {
  @Input() inputValue;
}
</code>```

The UIView directive doesn't allow input parameters it doesn't know about (e.g. inputValue), so how could I get the "something" variable down to the child inputValue?

答:
Remove the property binding syntax and declare the inputValue as an attribute for the child selector block you used in Parent HTML block

Parent template

```<code> <ui-view>
         <child inputValue="something"></child>
    </ui-view>
</code>```

Example child component

```<code>@Component({
  selector: 'child',
  template: '...'
})
export class ChildComponent {
  @Input() inputValue;
}
</code>```

Now you can use the inputValue in your child template

Body:
Parent template

<ui-view [inputValue]="something"></ui-view>

Example child component

@Component({
  selector: 'child',
  template: '...'
})
export class ChildComponent {
  @Input() inputValue;
}

The UIView directive doesn't allow input parameters it doesn't know about (e.g. inputValue), so how could I get the "something" variable down to the child inputValue?

Body:
Remove the property binding syntax and declare the inputValue as an attribute for the child selector block you used in Parent HTML block

Parent template

 <ui-view>
         <child inputValue="something"></child>
    </ui-view>

Example child component

@Component({
  selector: 'child',
  template: '...'
})
export class ChildComponent {
  @Input() inputValue;
}

Now you can use the inputValue in your child template


问:
How to create a loop using values from a different file?
I have a file containing following numbers
file1.txt

```<code>1
5
6
8
14
</code>```

I have another file named rmsd.txt which contains values like the following

```<code>1 2.12
2 3.1243
3 4.156
4 3.22
5 3.882
6 8.638
7 8.838
8 7.5373
9 10.7373
10 8.3527
11 3.822
12 5.672
13 7.23
14 5.9292
</code>```

I want to get the values of column 2 from rmsd.txt for the numbers present in file.txt. I want to get something like the following

```<code>1 2.12
5 3.882
6 8.638
8 7.5373
14 5.9292
</code>```

I can do that by do like that grep 1 rmsd.txt and so on but it will take a long time. I was trying a for loop something like

```<code>for a in awk '{print $1}' file.txt; do
grep $a rmsd.txt >result.txt
done
</code>```

But it didn't work. Maybe it is very simple and I am thinking in a wrong direction. Any help will be highly appreciated.

答:
```<code>for WORD in `cat FILE`
do
   echo $WORD
   command $WORD > $WORD
done
</code>```

Origina source

EDIT: Here is your code with few fixes:

```<code>for a in `awk '{print $1}' file.txt`
do
    grep $a rmsd.txt >>result.txt
done
</code>```

Body:
I have a file containing following numbers
file1.txt

1
5
6
8
14

I have another file named rmsd.txt which contains values like the following

1 2.12
2 3.1243
3 4.156
4 3.22
5 3.882
6 8.638
7 8.838
8 7.5373
9 10.7373
10 8.3527
11 3.822
12 5.672
13 7.23
14 5.9292

I want to get the values of column 2 from rmsd.txt for the numbers present in file.txt. I want to get something like the following

1 2.12
5 3.882
6 8.638
8 7.5373
14 5.9292

I can do that by do like that grep 1 rmsd.txt and so on but it will take a long time. I was trying a for loop something like

for a in awk '{print $1}' file.txt; do
grep $a rmsd.txt >result.txt
done

But it didn't work. Maybe it is very simple and I am thinking in a wrong direction. Any help will be highly appreciated.

Body:
for WORD in `cat FILE`
do
   echo $WORD
   command $WORD > $WORD
done

Origina source

EDIT: Here is your code with few fixes:

for a in `awk '{print $1}' file.txt`
do
    grep $a rmsd.txt >>result.txt
done


问:
JQuery parameter injection on bind/click vs. embedded click handlers with parameters
So the old JavaScript aficionado and the young jQuery wizard in me are having a little disagreement. Sorry for the long setup, but the heart of the issue is whether to embed onClick code directly in my HTML or to go jQuery-style and and use bind() or click().  I find myself & myself disagreeing on this topic quite often, so I thought I would try generate some discussion on the issue. To explain the issue, the pattern below seems to bring this to the forefront most often.

Typical Example

I'm writing a search for a member directory.  On my interface I have various filter criteria like  "gender", "member since", and "has profile photo".  A criteria looks like this ...

A user can select an option by clicking on the text (e.g. "Female") or choosing the radio button.

When a selection is made the appropriate radio button is selected  the text is bold-ed

My html ends up looking something like ...

```<code>    <div id="FilterContainer_GenderDIV">
        <span id="FilterLabel_Gender">Gender:</span>
        <span id="FilterSelection_Gender">Any</span>
        <span id="FilterChicklet_Gender" class="sprite_MediumArrowDown inline" ></span>
    <div id="FilterOptions_GenderDIV">
        <input type="radio" id="GenderID" name="GenderID" value="1"/> <a href="" id="FilterOptionLink_CoupleGender_1" >Male</a><br />
        <input type="radio" id="GenderID" name="GenderID" value="2"/> <a href="" id="FilterOptionLink_CoupleGender_2" >Female</a><br />
        <input type="radio" id="GenderID" name="GenderID" value="0" checked="checked"/> <a href="" id="FilterOptionLink_CoupleGender_0" class="SearchSelectedChoice" >Any</a><br />
    </div>
</code>```

The issue really arises when a user clicks on the text link.  At that point I need to know which radio set to change,which link text to bold, and take the newly selected text and change my header label.  I see a few options for making this type of scenario work.

Options for making it work

jQuery Injection with Clever element names

I can use jQuery to bind to my elements in a generic fashion. $('#FinderBodyDIV input:radio').click(SearchOption_Click);  Then sort out the appropriate ID & text with clever dom inspection.    For example, name my hyperlink could be named  GenderID_Link_1 where 1 is the ID I should select and GenderID tells me which radio set to change.  I could use a combination of '.parents().find()and.siblings()` to find the radio next door and set it with the ID.

This is good because my binding code is simple and my jQuery is separated from my HTML

It's bad because my code functioning now really depends on a brittle HTML structure & naming.

Bind elements individually with eventData

An alternate option is to gather up my set of elements and for each individual element do a 'bind()' passing eventData.

```<code>var elements = $('#FinderBodyDIV input:radio');
elements.each (   FunctionWithLogicToBindPassingEventData );
</code>```

This is satisfying because I've separate the logic for binding event data from a brittle HTML structure.

It's bad because I've simply moved the brittle piece to a new function

It's also bad because I've introduced slowed down (relatively) the binding (more DOM traversal).

Embed onClick code in the HTML

This is where my old JavaScript inclinations keep taking me.  Instead of using jQuery to inject bindings, I change my link/radio button HTML to include click handlers.  Something like ...

```<code><input type="radio" id="GenderID" name="GenderID" value="1" onClick="SetGender(1,'Male')"/> <a href="" id="FilterOptionLink_Gender" onClick="SetGender(1,'Male')">Male</a><br />
</code>```

This is satisfying because i know the values when I'm generating the HTML, so I've simplified my life.

I've removed a lot of dependency on my HTML structure (although not all).

On the down side, I've co-mingled my JS and HTML.

It feels dirty.

So what's a boy to do?

This seems like a fairly common scenario.  I find it pops up in quite a few situations besides the one I've described above.  I've searched tubes on the interweb, blogumentation, and technical articles on twitter.  Yet, I don't see anyone talking about this issue.  Maybe I just don't know how to phrase the issue.   Whatever the reason, I don't feel good about any of the solutions I've come up with.

It really comes down to how do I associate a clicked element with it's related data--JSON, embedded in HTML names, or otherwise. So what's your take?

答:
The pat answer is that embedding the onClick call in the input element goes against the unobtrusive javascript concept. However, I'm the kind of developer that'll go ahead and use it anyway if it gets the jorb done and the audience is not likely to have javascript disabled.

If I'm understanding the problem correctly, you need a way to do things jQuery-style without relying on html structure and such. Give your radio buttons a class name, for example, the "Male" radio button can have class="Male", and you can select it via jQuery easier.

Bonus: There are some instances where you may need to assign some element more than one class, for example, you are filtering by language and by country. So you can assign some element multiple classes like this:

```<code>$('#someElement').addClass('French').addClass('fr-FR');
</code>```

And select it using either class later.

Body:
So the old JavaScript aficionado and the young jQuery wizard in me are having a little disagreement. Sorry for the long setup, but the heart of the issue is whether to embed onClick code directly in my HTML or to go jQuery-style and and use bind() or click().  I find myself & myself disagreeing on this topic quite often, so I thought I would try generate some discussion on the issue. To explain the issue, the pattern below seems to bring this to the forefront most often.

Typical Example

I'm writing a search for a member directory.  On my interface I have various filter criteria like  "gender", "member since", and "has profile photo".  A criteria looks like this ...

A user can select an option by clicking on the text (e.g. "Female") or choosing the radio button.

When a selection is made the appropriate radio button is selected  the text is bold-ed

My html ends up looking something like ...

        Gender:
        Any

        <input type="radio" id="GenderID" name="GenderID" value="1"/> Male

        <input type="radio" id="GenderID" name="GenderID" value="2"/> Female

        <input type="radio" id="GenderID" name="GenderID" value="0" checked="checked"/> Any

The issue really arises when a user clicks on the text link.  At that point I need to know which radio set to change,which link text to bold, and take the newly selected text and change my header label.  I see a few options for making this type of scenario work.

Options for making it work

jQuery Injection with Clever element names

I can use jQuery to bind to my elements in a generic fashion. $('#FinderBodyDIV input:radio').click(SearchOption_Click);  Then sort out the appropriate ID & text with clever dom inspection.    For example, name my hyperlink could be named  GenderID_Link_1 where 1 is the ID I should select and GenderID tells me which radio set to change.  I could use a combination of '.parents().find()and.siblings()` to find the radio next door and set it with the ID.

This is good because my binding code is simple and my jQuery is separated from my HTML

It's bad because my code functioning now really depends on a brittle HTML structure & naming.

Bind elements individually with eventData

An alternate option is to gather up my set of elements and for each individual element do a 'bind()' passing eventData.

var elements = $('#FinderBodyDIV input:radio');
elements.each (   FunctionWithLogicToBindPassingEventData );

This is satisfying because I've separate the logic for binding event data from a brittle HTML structure.

It's bad because I've simply moved the brittle piece to a new function

It's also bad because I've introduced slowed down (relatively) the binding (more DOM traversal).

Embed onClick code in the HTML

This is where my old JavaScript inclinations keep taking me.  Instead of using jQuery to inject bindings, I change my link/radio button HTML to include click handlers.  Something like ...

<input type="radio" id="GenderID" name="GenderID" value="1" onClick="SetGender(1,'Male')"/> Male

This is satisfying because i know the values when I'm generating the HTML, so I've simplified my life.

I've removed a lot of dependency on my HTML structure (although not all).

On the down side, I've co-mingled my JS and HTML.

It feels dirty.

So what's a boy to do?

This seems like a fairly common scenario.  I find it pops up in quite a few situations besides the one I've described above.  I've searched tubes on the interweb, blogumentation, and technical articles on twitter.  Yet, I don't see anyone talking about this issue.  Maybe I just don't know how to phrase the issue.   Whatever the reason, I don't feel good about any of the solutions I've come up with.

It really comes down to how do I associate a clicked element with it's related data--JSON, embedded in HTML names, or otherwise. So what's your take?

Body:
The pat answer is that embedding the onClick call in the input element goes against the unobtrusive javascript concept. However, I'm the kind of developer that'll go ahead and use it anyway if it gets the jorb done and the audience is not likely to have javascript disabled.

If I'm understanding the problem correctly, you need a way to do things jQuery-style without relying on html structure and such. Give your radio buttons a class name, for example, the "Male" radio button can have class="Male", and you can select it via jQuery easier.

Bonus: There are some instances where you may need to assign some element more than one class, for example, you are filtering by language and by country. So you can assign some element multiple classes like this:

$('#someElement').addClass('French').addClass('fr-FR');

And select it using either class later.

ContentLicense: CC BY-SA 2.5


问:
identical email bootstrap validation
Can't seem to get this to work. Trying to do a confirm email bootstrap validator. The original email validator works but not the second. Not sure what I'm missing.</p>

```<code>   <div class="form-group">
      <div class="col-md-11">
         <label for="inputEmail" class="sr-only">Enter Email</label>
         <input type="email" class="form-control" placeholder="Enter Email" id="email" name="email" size="35" required/>
         <div class="help-block with-errors"></div>
         <span class="glyphicon form-control-feedback" id="email1"></span>
     </div>
     </div>
     <div class="form-group">
         <div class="col-md-11">
            <input type="email" class="form-control" name="emailConfirmed" placeholder="Confirm Email" id="emailConfirmed" size="35" />
     </div>
 </div>

$('#form').validate({
    fields: {
        email: {
            minlength: 3,
            required: true,
            validators: {
                notEmpty: {
                    message: 'The confirm email is required and cannot be empty'
                },
                identical: {
                    field: 'emailConfirmed',
                    message: 'The email and its confirm are not the same'
                }
            }
        },
        emailConfirmed: {
            validators: {
                notEmpty: {
                    message: 'The confirm email is required and cannot be empty'
                },
                identical: {
                    field: 'email',
                    message: 'The email and its confirm are not the same'
                }
            }
        }
    }
 });
</code>```

答:
You could use the equalTo method:</p>

```<code>$('#myform').validate({
    rules: {
        email: 'required',
        emailConfirm: {
            equalTo: '#email'
        }
    }
});
</code>```

Title: identical email bootstrap validation

Body:
Can't seem to get this to work. Trying to do a confirm email bootstrap validator. The original email validator works but not the second. Not sure what I'm missing.

         Enter Email
         <input type="email" class="form-control" placeholder="Enter Email" id="email" name="email" size="35" required/>

            <input type="email" class="form-control" name="emailConfirmed" placeholder="Confirm Email" id="emailConfirmed" size="35" />

$('#form').validate({
    fields: {
        email: {
            minlength: 3,
            required: true,
            validators: {
                notEmpty: {
                    message: 'The confirm email is required and cannot be empty'
                },
                identical: {
                    field: 'emailConfirmed',
                    message: 'The email and its confirm are not the same'
                }
            }
        },
        emailConfirmed: {
            validators: {
                notEmpty: {
                    message: 'The confirm email is required and cannot be empty'
                },
                identical: {
                    field: 'email',
                    message: 'The email and its confirm are not the same'
                }
            }
        }
    }
 });

Body:
You could use the equalTo method:

$('#myform').validate({
    rules: {
        email: 'required',
        emailConfirm: {
            equalTo: '#email'
        }
    }
});


问:
Excel Macro: I would like to add one column to a range and call a function to fill it
Below is a macro we use to build a worksheet with a subset of a larger worksheet.
When the loop finds a match in our array of server names, it copies it over to the new worksheet.
I would like to add a new column to the new worksheet during the copy process. And after getting that working, I would like to fill this field by calling a function. We are trying to have a column that shows whether a server is a "critical" server. Simple y/n returns from a function that would look in an array of critical servers. I don't need the function, just how to add a column and fill it during the loop.

I will paste the big loop farther down, but here is the individual line of code that would copy over a range if found to a new worksheet. It is here I would like to add or copy one more column filled by a function:

```<code> Rcount = Rcount + 1
 Source.Range("A" & Rng.Row & ":R" & Rng.Row).Copy NewSh.Range("A" & Rcount & ":R" & Rcount)
</code>```

Here is the big loop for inquiring minds. It might be useful or at least prove this code is being used:

```<code>With Source.Range("A1:R9000")

    'Find where the actual data we need starts
    Set Rng = .Find(What:="Client", _
                        After:=.Cells(.Cells.Count), _
                        LookIn:=xlFormulas, _
                        LookAt:=xlPart, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlNext, _
                        MatchCase:=False)

    intColorMatch = 0

    If Not Rng Is Nothing Then
        FirstAddress = Rng.Address
        Do
            Set Rng = .FindNext(Rng)
            If (Rng.Interior.Color = 13421772) Then
                intColorMatch = intColorMatch + 1
            End If

            If (intColorMatch < 2) = False Then
                StartRow = Rng.Row
                Exit Do
            End If

        Loop While Not Rng Is Nothing And Rng.Address <> FirstAddress
    End If

    Source.Range("A" & StartRow & ":R" & StartRow + 1).Copy NewSh.Range("A1:R2")

    Rcount = 2
    FirstAddress = 0

    For I = LBound(MyArr) To UBound(MyArr)

        'If you use LookIn:=xlValues it will also work with a
        'formula cell that evaluates to "@"
        'Note : I use xlPart in this example and not xlWhole
        Set Rng = .Find(What:=MyArr(I), _
                        After:=.Cells(.Cells.Count), _
                        LookIn:=xlFormulas, _
                        LookAt:=xlPart, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlNext, _
                        MatchCase:=False)
        If Not Rng Is Nothing Then
            FirstAddress = Rng.Address
            Do
                If Rng.Row >= StartRow Then
                    Rcount = Rcount + 1
                    Source.Range("A" & Rng.Row & ":R" & Rng.Row).Copy NewSh.Range("A" & Rcount & ":R" & Rcount)

              ' Use this if you only want to copy the value
                    ' NewSh.Range("A" & Rcount).Value = Rng.Value
                End If

                Set Rng = .FindNext(Rng)
            Loop While Not Rng Is Nothing And Rng.Address <> FirstAddress
        End If
    Next I
End With
</code>```

答:
If the "new" column that you are wanting to populate is after the end of your copied data, you aren't really adding a column - you are just populating an existing empty column.

If so, you can just say something like

```<code>NewSh.Cells(Rcount, "Q").Formula = "=whatever_formula_you_want"
</code>```

(or use FormulaR1C1 if that is easier).

Or, if you only want to insert a value there (which you are calculating in your VBA code), it is just

```<code>NewSh.Cells(Rcount, "Q").Value = the_value_I_want
</code>```

Body:
Below is a macro we use to build a worksheet with a subset of a larger worksheet.
When the loop finds a match in our array of server names, it copies it over to the new worksheet.
I would like to add a new column to the new worksheet during the copy process. And after getting that working, I would like to fill this field by calling a function. We are trying to have a column that shows whether a server is a "critical" server. Simple y/n returns from a function that would look in an array of critical servers. I don't need the function, just how to add a column and fill it during the loop.

I will paste the big loop farther down, but here is the individual line of code that would copy over a range if found to a new worksheet. It is here I would like to add or copy one more column filled by a function:

 Rcount = Rcount + 1
 Source.Range("A" & Rng.Row & ":R" & Rng.Row).Copy NewSh.Range("A" & Rcount & ":R" & Rcount)

Here is the big loop for inquiring minds. It might be useful or at least prove this code is being used:

With Source.Range("A1:R9000")

    'Find where the actual data we need starts
    Set Rng = .Find(What:="Client", _
                        After:=.Cells(.Cells.Count), _
                        LookIn:=xlFormulas, _
                        LookAt:=xlPart, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlNext, _
                        MatchCase:=False)

    intColorMatch = 0

    If Not Rng Is Nothing Then
        FirstAddress = Rng.Address
        Do
            Set Rng = .FindNext(Rng)
            If (Rng.Interior.Color = 13421772) Then
                intColorMatch = intColorMatch + 1
            End If

            If (intColorMatch < 2) = False Then
                StartRow = Rng.Row
                Exit Do
            End If

        Loop While Not Rng Is Nothing And Rng.Address <> FirstAddress
    End If

    Source.Range("A" & StartRow & ":R" & StartRow + 1).Copy NewSh.Range("A1:R2")

    Rcount = 2
    FirstAddress = 0

    For I = LBound(MyArr) To UBound(MyArr)

        'If you use LookIn:=xlValues it will also work with a
        'formula cell that evaluates to "@"
        'Note : I use xlPart in this example and not xlWhole
        Set Rng = .Find(What:=MyArr(I), _
                        After:=.Cells(.Cells.Count), _
                        LookIn:=xlFormulas, _
                        LookAt:=xlPart, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlNext, _
                        MatchCase:=False)
        If Not Rng Is Nothing Then
            FirstAddress = Rng.Address
            Do
                If Rng.Row >= StartRow Then
                    Rcount = Rcount + 1
                    Source.Range("A" & Rng.Row & ":R" & Rng.Row).Copy NewSh.Range("A" & Rcount & ":R" & Rcount)

              ' Use this if you only want to copy the value
                    ' NewSh.Range("A" & Rcount).Value = Rng.Value
                End If

                Set Rng = .FindNext(Rng)
            Loop While Not Rng Is Nothing And Rng.Address <> FirstAddress
        End If
    Next I
End With

Body:
If the "new" column that you are wanting to populate is after the end of your copied data, you aren't really adding a column - you are just populating an existing empty column.

If so, you can just say something like

NewSh.Cells(Rcount, "Q").Formula = "=whatever_formula_you_want"

(or use FormulaR1C1 if that is easier).

Or, if you only want to insert a value there (which you are calculating in your VBA code), it is just

NewSh.Cells(Rcount, "Q").Value = the_value_I_want


问:
Edit only a selection in Javascript editor
I am working on an very specialized editor. In short, I drafted an example of the code (below) which runs in firefox. The iText function will fill in example content.

The user should select a part of the example content an hit "Letters", then the iLetter function should take only the selected part of the sentence and invert capital letters to small letter and small letters ot capital letters only in the selection (the inversion itself is not the issue).

I searched for hours on how to get the position of the selection within the displayed text/string or how to get the start and end position. It would be great if I could extract the selection, modify it as a string (I managed that) and replace the selection with the modified string (I failed). Is it possible at all? Any hints or suggestions are very welcome.

Edit Test

<form action="parse_file.php" name="form" id="form" method="post">

  <input type="button" onClick="iText()" value="Text">
  <input type="button" onClick="iLetters()" value="Letters">

<textarea style="display:none;" name="myTextArea" id="myTextArea" cols="100" rows="14"></textarea>

</form>

```

答:
I figured out... A great help was:
replace selected text in contenteditable div

The function only sets it to lowercase, but that is a trivial modification made to keep the example compact.

Edit Test

<form action="parse_file.php" name="form" id="form" method="post">

  <input type="button" onClick="iText()" value="Text">
  <input type="button" onClick="iLetters()" value="Letters">

<textarea style="display:none;" name="myTextArea" id="myTextArea" cols="100" rows="14"></textarea>

</form>

```

Body:
I figured out... A great help was:
replace selected text in contenteditable div

The function only sets it to lowercase, but that is a trivial modification made to keep the example compact.

<html>
<head>
<script>
function iFrameOn(){
 richTextField.document.designMode = 'On';
}

function iText(){
 window.frames['richTextField'].document.body.innerHTML = "HELLO WORLD READY FOR A SIMPLE TEXT TRIAL?";
}

function iLetters(){
    var sel, range;
    if (window.frames['richTextField'].getSelection) {
        sel = window.frames['richTextField'].getSelection();
  var theSelection = sel.toString();
  var replacementText = theSelection.toLowerCase();
        if (sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();
            range.insertNode(window.frames['richTextField'].document.createTextNode(replacementText));
        }
    }
}
</script>
</head>
<body onLoad="iFrameOn();">
<h2>Edit Test</h2>
<form action="parse_file.php" name="form" id="form" method="post">
<p>
<div id="wysiwyg_cp" style="padding:8px; width:700px;">
  <input type="button" onClick="iText()" value="Text">
  <input type="button" onClick="iLetters()" value="Letters">
</div>
<textarea style="display:none;" name="myTextArea" id="myTextArea" cols="100" rows="14"></textarea>
<iframe name="richTextField" id="richTextField" style="border:#000000 1px solid; width:700px; height:300px;"></iframe>
<!-- End replacing your normal textarea -->
</p>
</form>
</body>
</html>


问:
Why is rand() giving me numbers outside of my defined interval? (It worked fine yesterday)
I am generating random integers between 1000, and 11000. However they must have a mean of 6000. I used this snip of code in my program yesterday and it worked just fine, but now it gives me huge numbers as if my interval doesn't matter.

Edit: Stripped the code down a bit for easier reading.

```<code>srand(time(NULL));
int k = 5;
int cTotal = 0;
int cAverage = 0;

  struct process {
    int pid; // process id
    int cycles; // number of cycles required to complete the process
    int mSize; // size of the memory footprint
};

    for (int i = 0; i < k; i++) {

        processes[i].pid = i; // set the unique identifier of the process.

        // If statements for determining the number cycles in each process
        if (k == 0) {
            processes[i].cycles = 6000; // if the user decides to try only one process, the average must be 6000, so assign 6000 as its value.
            cTotal += processes[i].cycles; //update the total number of cycles, and the average.
            cAverage = cTotal / (i + 1);

        } else if (cAverage == 0) { // if we have more than 1 process and  it happens to be the first one, go ahead and randomize it since we can adjust the average after the first iteration.
            processes[i].cycles = rand() % 11000 + 1000; //update the total number of cycles, and the average.
            cTotal += processes[i].cycles;
            cAverage = cTotal / (i + 1);

        } else if (cAverage == 6000 && i != k - 1) { // if the average is already at 6000, it's safe to choose any random number so do that unless this is the last iteration of the loop.
            processes[i].cycles = rand() % 11000 + 1000; //update the total number of cycles, and the average.
            cTotal += processes[i].cycles;
            cAverage = cTotal / (i + 1);

        } else {
            processes[i].cycles = (6000 * (i + 1)) - cTotal; // set the number of cycles such that the average will be 6000
            cTotal = cTotal + processes[i].cycles; //update the total number of cycles, and the average.
            cAverage = cTotal / (i + 1);
        }
    } //for
</code>```

Edit2: Here is some of the output from my program (includes this plus another identical if statement for memory size)

```<code>    How many processes would you like to simulate? - >5
  5
Simulating 5 Processes...
***********************
PID: 0
Cycles: 63
Mem Size: 1877994624
***********************
PID: 1
Cycles: -23
Mem Size: 1877936645
***********************
PID: 2
Cycles: -1877936648
Mem Size: 13
***********************
PID: 3
Cycles: -1877936641
Mem Size: 64
***********************
PID: 4
Cycles: -1877936685
Mem Size: 4201340
***********************
Total Cycles: 30000
Average Cycles: 6000
Average Memory: 376427625 KB
</code>```

答:
You need rand() % 10000 + 1000 for your range.

Put yesterday down to a statistical anomaly.

There are better ways (this approach has statistical bias towards lower numbers). Look at std::uniform_int_distribution, and consider using Mersenne Twister as the actual generator.

Body:
I am generating random integers between 1000, and 11000. However they must have a mean of 6000. I used this snip of code in my program yesterday and it worked just fine, but now it gives me huge numbers as if my interval doesn't matter.

Edit: Stripped the code down a bit for easier reading.

srand(time(NULL));
int k = 5;
int cTotal = 0;
int cAverage = 0;

  struct process {
    int pid; // process id
    int cycles; // number of cycles required to complete the process
    int mSize; // size of the memory footprint
};

    for (int i = 0; i < k; i++) {

        processes[i].pid = i; // set the unique identifier of the process.

        // If statements for determining the number cycles in each process
        if (k == 0) {
            processes[i].cycles = 6000; // if the user decides to try only one process, the average must be 6000, so assign 6000 as its value.
            cTotal += processes[i].cycles; //update the total number of cycles, and the average.
            cAverage = cTotal / (i + 1);

        } else if (cAverage == 0) { // if we have more than 1 process and  it happens to be the first one, go ahead and randomize it since we can adjust the average after the first iteration.
            processes[i].cycles = rand() % 11000 + 1000; //update the total number of cycles, and the average.
            cTotal += processes[i].cycles;
            cAverage = cTotal / (i + 1);

        } else if (cAverage == 6000 && i != k - 1) { // if the average is already at 6000, it's safe to choose any random number so do that unless this is the last iteration of the loop.
            processes[i].cycles = rand() % 11000 + 1000; //update the total number of cycles, and the average.
            cTotal += processes[i].cycles;
            cAverage = cTotal / (i + 1);

        } else {
            processes[i].cycles = (6000 * (i + 1)) - cTotal; // set the number of cycles such that the average will be 6000
            cTotal = cTotal + processes[i].cycles; //update the total number of cycles, and the average.
            cAverage = cTotal / (i + 1);
        }
    } //for

Edit2: Here is some of the output from my program (includes this plus another identical if statement for memory size)

    How many processes would you like to simulate? - >5
  5
Simulating 5 Processes...
***********************
PID: 0
Cycles: 63
Mem Size: 1877994624
***********************
PID: 1
Cycles: -23
Mem Size: 1877936645
***********************
PID: 2
Cycles: -1877936648
Mem Size: 13
***********************
PID: 3
Cycles: -1877936641
Mem Size: 64
***********************
PID: 4
Cycles: -1877936685
Mem Size: 4201340
***********************
Total Cycles: 30000
Average Cycles: 6000
Average Memory: 376427625 KB


问:
The scroll bar disappears when a jquery confirm dialogue is shown
The scroll bar on the page disappears when a jquery confirm dialogue is shown, this causes the page to jump to the right.  The JavaScript code for the dialogue is as follows:

```<code><script src="vendor/jquery-confirm.min.js"></script>
<link href="vendor/jquery-confirm.min.css" rel="stylesheet" type="text/css">
<script>
    function confirmDialog(content, func, parameter) {
        $.confirm({
            title: "",
            content: content,
            confirmButton: "Yes",
            cancelButton: "No",
            theme: "black",
            confirm: function() { func(parameter); },
            cancel: function() { }
        });
    }
</script>
</code>```

I am using the CSS:

```<code>body {
    overflow-y: scroll;
}
</code>```

How can I prevent this from happening?

Update

I tried adding "important", but inspecting the page in Firefox I see there is this CSS:

```<code>body.jconfirm-noscroll {
    overflow: hidden !important;
}
</code>```

And there is a line through:

```<code>overflow-y: scroll !important;
</code>```

答:
Overriding CSS can be tricky...

You can try

```<code>body, body.jconfirm-noscroll {
    overflow: auto!important;
}
</code>```

But that still might not work...

If not, add a class to your body e.g.  and try this

```<code>body.please-scroll, body.please-scroll.jconfirm-noscroll {
    overflow: auto!important;
}
</code>```

I'm not sure if it will work, try it and let me know, I'd be interested!

Body:
The scroll bar on the page disappears when a jquery confirm dialogue is shown, this causes the page to jump to the right.  The JavaScript code for the dialogue is as follows:

<link href="vendor/jquery-confirm.min.css" rel="stylesheet" type="text/css">

I am using the CSS:

body {
    overflow-y: scroll;
}

How can I prevent this from happening?

Update

I tried adding "important", but inspecting the page in Firefox I see there is this CSS:

body.jconfirm-noscroll {
    overflow: hidden !important;
}

And there is a line through:

overflow-y: scroll !important;

Body:
Overriding CSS can be tricky...

You can try

body, body.jconfirm-noscroll {
    overflow: auto!important;
}

But that still might not work...

If not, add a class to your body e.g. <body class"please-scroll"> and try this

body.please-scroll, body.please-scroll.jconfirm-noscroll {
    overflow: auto!important;
}

I'm not sure if it will work, try it and let me know, I'd be interested!


问:
the difference between .bin file and .mat files
can the tensorflow read a file contain a normal images for example in JPG, .... or the tensorflow just read the .bin file contains images

what is the difference between .mat file and .bin file

Also when I rename the .bin file name to .mat, does the data of the file changed??

sorry maybe my language not clear because I cannot speak English very well

答:
A '.mat' file contains Matlab formatted Data (not matlab code like you would expect from a '.m' file). I'm not sure if you're even using Matlab since you didn't include the the tag in your question. '.mat' files are associated with matlab workspace; if you wanted to save your current workspace in Matlab, you would save it as a '.mat' file.

A '.bin' file is a binary file read by the computer. In general, executable (ready-to-run) programs are often identified as binary files. I think this is what you would want to use. I am unsure what you really want though because the wording of the question is difficult to understand and it seems like you have two questions here.

Changing the suffix of a file just changes what will run the file. For example, if I were to change test.txt to test.py, the data inside the text file remains the same, but the way the file is opened has changed. In this case, the file was a text file usually opened using Notepad (or some variation) then it was opened by python once changed. If you were to change a .jpg file to a txt file, you wouldn't be able to view it as a picture again, but instead, you would open a text file with a bunch of seemingly random characters which describe the picture. The picture data never changed, but the way you see it and are able to use it does.

Take a look at this website which describes the .bin extension pretty well. Also, a quick Google search goes a long way especially with questions like this.


问:
mt.exe : general error c101008d: Failed to write the updated manifest to the resource of file ... Access is denied
I often have this problem even when I build a new C++ project and try to build a release file.

I use Visual studio 2008. One thing that may cause this problem is my code is saved on the server disk, not on local hard disk.

mt.exe : general error c101008d: Failed to write the updated manifest to the resource of file "..\Release\PGTS_version17C.exe". The process cannot access the file because it is being used by another process.

Anyone know how to solve this? Thanks.

答:
If you are embedding a manifest file, your anti-virus program may lock and scan your exe file before embedding the manifest.

I recommend disabling anti-virus from reading your DEBUG and RELEASE output folders.


问:
Escape CSV file with sed or other command line tool
I have the following CSV, separated by "|".

```<code>101|abc|this is desc|2017
102|xyz|"thie is a long desc
des for xyz continue here."|2017
</code>```

I have two records, 101 and 102. 102 record is divided into 2 lines. How can I used sed or other command line tools to escape the new line character with "/"?

答:
awk is better tool to handle this.

Assuming you know how many columns are needed in each line. You can use this awk command:

```<code>awk -v n=4 -F '|' 'p+NF<n{p+=NF-1; print $0 "\\"; next} {p=0} 1' file

101|abc|this is desc|2017
102|xyz|"this is a long desc\
des for xyz continue here."|2017
</code>```

Body:
I have the following CSV, separated by "|".

101|abc|this is desc|2017
102|xyz|"thie is a long desc
des for xyz continue here."|2017

I have two records, 101 and 102. 102 record is divided into 2 lines. How can I used sed or other command line tools to escape the new line character with "/"?

Body:
awk is better tool to handle this.

Assuming you know how many columns are needed in each line. You can use this awk command:

awk -v n=4 -F '|' 'p+NF<n{p+=NF-1; print $0 "\\"; next} {p=0} 1' file

101|abc|this is desc|2017
102|xyz|"this is a long desc\
des for xyz continue here."|2017


问:
comparing datetime.timedelta and datetime.time in python
I have this code where I execute a sql query and get two TIME fields. Now I want to compare these two with other time type field. My current code is below

```<code>import datetime

def comp(time1,time2):

        start_time_obj = datetime.datetime.strptime(time1, '%H:%M').time()
        end_time_obj = datetime.datetime.strptime(time2, '%H:%M').time()

        sql_select2 = "select TIME(Start_Time), TIME(End_Time) from table1"
        result2 = cur.execute(sql_select2)

        resultSet2 = cur.fetchall()
        for Start_Time,End_Time in resultSet2:
             if (Start_Time <= start_time_obj <= End_Time) or (Start_Time <= end_time_obj <= End_Time):
                    print("Great!")
                    continue

if __name__ == '__main__':
    comp("08:00","10:00")
</code>```

When I execute this I get error as TypeError: '<=' not supported between instances of 'datetime.timedelta' and 'datetime.time'. How to remove this?

Note: this is the sample field structure in database - '2017-06-16 08:06:00' for both Start_Time and End_Time. What I want to do is compare the time part in the above field with the time coming as a parameter

答:
What if you do

```<code> start_time_obj = datetime.datetime.strptime(time1, '%H:%M').date()
 end_time_obj = datetime.datetime.strptime(time2, '%H:%M').date()
</code>```

using .date() instead of .time()?

Body:
I have this code where I execute a sql query and get two TIME fields. Now I want to compare these two with other time type field. My current code is below

import datetime

def comp(time1,time2):

        start_time_obj = datetime.datetime.strptime(time1, '%H:%M').time()
        end_time_obj = datetime.datetime.strptime(time2, '%H:%M').time()

        sql_select2 = "select TIME(Start_Time), TIME(End_Time) from table1"
        result2 = cur.execute(sql_select2)

        resultSet2 = cur.fetchall()
        for Start_Time,End_Time in resultSet2:
             if (Start_Time <= start_time_obj <= End_Time) or (Start_Time <= end_time_obj <= End_Time):
                    print("Great!")
                    continue

if __name__ == '__main__':
    comp("08:00","10:00")

When I execute this I get error as TypeError: '<=' not supported between instances of 'datetime.timedelta' and 'datetime.time'. How to remove this?

Note: this is the sample field structure in database - '2017-06-16 08:06:00' for both Start_Time and End_Time. What I want to do is compare the time part in the above field with the time coming as a parameter

Body:
What if you do

 start_time_obj = datetime.datetime.strptime(time1, '%H:%M').date()
 end_time_obj = datetime.datetime.strptime(time2, '%H:%M').date()

using .date() instead of .time()?


问:
Getting days since last occurence in Pandas DataFrame?
Let's say I have a Pandas DataFrame df:

```<code>Date      Value
01/01/17  0
01/02/17  0
01/03/17  1
01/04/17  0
01/05/17  0
01/06/17  0
01/07/17  1
01/08/17  0
01/09/17  0
</code>```

For each row, I want to efficiently calculate the days since the last occurence of Value=1.

So that df:

```<code>Date      Value    Last_Occurence
01/01/17  0        NaN
01/02/17  0        NaN
01/03/17  1        0
01/04/17  0        1
01/05/17  0        2
01/06/17  0        3
01/07/17  1        0
01/08/17  0        1
01/09/17  0        2
</code>```

I could do a loop:

```<code>for i in range(0, len(df)):
    last = np.where(df.loc[0:i,'Value']==1)
    df.loc[i, 'Last_Occurence'] = i-last
</code>```

But it seems very inefficient for extremely large data sets and probably isn't right anyway.

答:
Here's a NumPy approach -

```<code>def intervaled_cumsum(a, trigger_val=1, start_val = 0, invalid_specifier=-1):
    out = np.ones(a.size,dtype=int)
    idx = np.flatnonzero(a==trigger_val)
    if len(idx)==0:
        return np.full(a.size,invalid_specifier)
    else:
        out[idx[0]] = -idx[0] + 1
        out[0] = start_val
        out[idx[1:]] = idx[:-1] - idx[1:] + 1
        np.cumsum(out, out=out)
        out[:idx[0]] = invalid_specifier
        return out
</code>```

Few sample runs on array data to showcase the usage covering various scenarios of trigger and start values :

```<code>In [120]: a
Out[120]: array([0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0])

In [121]: p1 = intervaled_cumsum(a, trigger_val=1, start_val=0)
     ...: p2 = intervaled_cumsum(a, trigger_val=1, start_val=1)
     ...: p3 = intervaled_cumsum(a, trigger_val=0, start_val=0)
     ...: p4 = intervaled_cumsum(a, trigger_val=0, start_val=1)
     ...:

In [122]: np.vstack(( a, p1, p2, p3, p4 ))
Out[122]:
array([[ 0,  1,  1,  1,  0,  0,  1,  0,  0,  1,  1,  1,  1,  1,  0],
       [-1,  0,  0,  0,  1,  2,  0,  1,  2,  0,  0,  0,  0,  0,  1],
       [-1,  1,  1,  1,  2,  3,  1,  2,  3,  1,  1,  1,  1,  1,  2],
       [ 0,  1,  2,  3,  0,  0,  1,  0,  0,  1,  2,  3,  4,  5,  0],
       [ 1,  2,  3,  4,  1,  1,  2,  1,  1,  2,  3,  4,  5,  6,  1]])
</code>```

Using it to solve our case :

```<code>df['Last_Occurence'] = intervaled_cumsum(df.Value.values)
</code>```

Sample output -

```<code>In [181]: df
Out[181]:
       Date  Value  Last_Occurence
0  01/01/17      0              -1
1  01/02/17      0              -1
2  01/03/17      1               0
3  01/04/17      0               1
4  01/05/17      0               2
5  01/06/17      0               3
6  01/07/17      1               0
7  01/08/17      0               1
8  01/09/17      0               2
</code>```

Runtime test

Approaches -

```<code># @Scott Boston's soln
def pandas_groupby(df):
    mask = df.Value.cumsum().replace(0,False).astype(bool)
    return df.assign(Last_Occurance=df.groupby(df.Value.astype(bool).\
                                    cumsum()).cumcount().where(mask))

# Proposed in this post
def numpy_based(df):
    df['Last_Occurence'] = intervaled_cumsum(df.Value.values)
</code>```

Timings -

```<code>In [33]: df = pd.DataFrame((np.random.rand(10000000)>0.7).astype(int), columns=[['Value']])

In [34]: %timeit pandas_groupby(df)
1 loops, best of 3: 1.06 s per loop

In [35]: %timeit numpy_based(df)
10 loops, best of 3: 103 ms per loop

In [36]: df = pd.DataFrame((np.random.rand(100000000)>0.7).astype(int), columns=[['Value']])

In [37]: %timeit pandas_groupby(df)
1 loops, best of 3: 11.1 s per loop

In [38]: %timeit numpy_based(df)
1 loops, best of 3: 1.03 s per loop
</code>```

Body:
Let's say I have a Pandas DataFrame df:

Date      Value
01/01/17  0
01/02/17  0
01/03/17  1
01/04/17  0
01/05/17  0
01/06/17  0
01/07/17  1
01/08/17  0
01/09/17  0

For each row, I want to efficiently calculate the days since the last occurence of Value=1.

So that df:

Date      Value    Last_Occurence
01/01/17  0        NaN
01/02/17  0        NaN
01/03/17  1        0
01/04/17  0        1
01/05/17  0        2
01/06/17  0        3
01/07/17  1        0
01/08/17  0        1
01/09/17  0        2

I could do a loop:

for i in range(0, len(df)):
    last = np.where(df.loc[0:i,'Value']==1)
    df.loc[i, 'Last_Occurence'] = i-last

But it seems very inefficient for extremely large data sets and probably isn't right anyway.

Body:
Here's a NumPy approach -

def intervaled_cumsum(a, trigger_val=1, start_val = 0, invalid_specifier=-1):
    out = np.ones(a.size,dtype=int)
    idx = np.flatnonzero(a==trigger_val)
    if len(idx)==0:
        return np.full(a.size,invalid_specifier)
    else:
        out[idx[0]] = -idx[0] + 1
        out[0] = start_val
        out[idx[1:]] = idx[:-1] - idx[1:] + 1
        np.cumsum(out, out=out)
        out[:idx[0]] = invalid_specifier
        return out

Few sample runs on array data to showcase the usage covering various scenarios of trigger and start values :

In [120]: a
Out[120]: array([0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0])

In [121]: p1 = intervaled_cumsum(a, trigger_val=1, start_val=0)
     ...: p2 = intervaled_cumsum(a, trigger_val=1, start_val=1)
     ...: p3 = intervaled_cumsum(a, trigger_val=0, start_val=0)
     ...: p4 = intervaled_cumsum(a, trigger_val=0, start_val=1)
     ...:

In [122]: np.vstack(( a, p1, p2, p3, p4 ))
Out[122]:
array([[ 0,  1,  1,  1,  0,  0,  1,  0,  0,  1,  1,  1,  1,  1,  0],
       [-1,  0,  0,  0,  1,  2,  0,  1,  2,  0,  0,  0,  0,  0,  1],
       [-1,  1,  1,  1,  2,  3,  1,  2,  3,  1,  1,  1,  1,  1,  2],
       [ 0,  1,  2,  3,  0,  0,  1,  0,  0,  1,  2,  3,  4,  5,  0],
       [ 1,  2,  3,  4,  1,  1,  2,  1,  1,  2,  3,  4,  5,  6,  1]])

Using it to solve our case :

df['Last_Occurence'] = intervaled_cumsum(df.Value.values)

Sample output -

In [181]: df
Out[181]:
       Date  Value  Last_Occurence
0  01/01/17      0              -1
1  01/02/17      0              -1
2  01/03/17      1               0
3  01/04/17      0               1
4  01/05/17      0               2
5  01/06/17      0               3
6  01/07/17      1               0
7  01/08/17      0               1
8  01/09/17      0               2

Runtime test

Approaches -

# @Scott Boston's soln
def pandas_groupby(df):
    mask = df.Value.cumsum().replace(0,False).astype(bool)
    return df.assign(Last_Occurance=df.groupby(df.Value.astype(bool).\
                                    cumsum()).cumcount().where(mask))

# Proposed in this post
def numpy_based(df):
    df['Last_Occurence'] = intervaled_cumsum(df.Value.values)

Timings -

In [33]: df = pd.DataFrame((np.random.rand(10000000)>0.7).astype(int), columns=[['Value']])

In [34]: %timeit pandas_groupby(df)
1 loops, best of 3: 1.06 s per loop

In [35]: %timeit numpy_based(df)
10 loops, best of 3: 103 ms per loop

In [36]: df = pd.DataFrame((np.random.rand(100000000)>0.7).astype(int), columns=[['Value']])

In [37]: %timeit pandas_groupby(df)
1 loops, best of 3: 11.1 s per loop

In [38]: %timeit numpy_based(df)
1 loops, best of 3: 1.03 s per loop


问:
Retrieve and Show Node in Listview
Is there anyone here could help on how to retrieve those class section inside the black box and show it in listview and if i add more class section it will add automatically in my listview. Thanks

答:
So, if your database structure is like this..

```<code>teacher{
        VRdn7....f1{
                    name:"name"
                    .....
                    class{
                          key1{
               -->             className:"c1"  }
                          key2{
               -->             className:"c2"  }
                          key3{
               -->             className:"c3"  }
                         }
                   }
       }
</code>```

And if you want values of className then,

```<code>    DatabaseReference db = FirebaseDatabase.getInstance()
            .getReference("teacher").child("VRdn7......f1");

    db.child("class").addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {

            String className = dataSnapshot.child("className").getValue().toString();
            //This will get all values of className inside "teacher\VRdn7....f1\class\***\"
            // Now create adapter for listview, and then add values in a list....
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) { }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) { }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) { }

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

Title: Retrieve and Show Node in Listview

Body:
So, if your database structure is like this..

teacher{
        VRdn7....f1{
                    name:"name"
                    .....
                    class{
                          key1{
               -->             className:"c1"  }
                          key2{
               -->             className:"c2"  }
                          key3{
               -->             className:"c3"  }
                         }
                   }
       }

And if you want values of className then,

    DatabaseReference db = FirebaseDatabase.getInstance()
            .getReference("teacher").child("VRdn7......f1");

    db.child("class").addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {

            String className = dataSnapshot.child("className").getValue().toString();
            //This will get all values of className inside "teacher\VRdn7....f1\class\***\"
            // Now create adapter for listview, and then add values in a list....
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) { }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) { }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) { }

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


问:
C#: Inconsistent accessibility error within Unit Test Class
I have seen previous posts about Inconsistent accessibility errors but they have not been as specific as my case, or so I believe.

Here are my two errors:

```<code>'ConsoleApplication1.Reader' is inaccessible due to its protection level

Inconsistent accessibility: field type 'ConsoleApplication1.Reader' is less
accessible than field 'UnitTestProject1.ReaderTest.reader'
</code>```

The Reader class is public so I am not sure why the test class does not see that. I have multiple other tests that do not have this same problem, and all are set up the same way. As for the second error I believe if I fix the first one that one will be resolved as a consequence. Below I will attach a piece of the Reader class as well as the test class for it. Advice would be greatly appreciated, thanks!

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    /// <summary>
    /// Created and tested by Alexander James Bochel.
    /// Last Updated: 6/7/2017
    /// </summary>
    class Program
    {

        /// <summary>
        /// This will call the rest of the classes in the program.
        /// </summary>
        /// <param name="args"> Command line arguments. </param>
        static void Main(string[] args)
        {
            openFile();
        }

        public static void openFile()
        {
            Reader reader = new Reader(@"C:\Users\abochel\Desktop\TEST.xlsx", 0);
        }

    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    public class Reader
    {
        public Reader()
        {
            // TODO - Default constructor.
        }
    }
}

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections;
using System.Collections.Generic;
using ConsoleApplication1;

namespace AutomationProgramTests
{
    [TestClass]
    public class ReaderTest
    {

        Reader reader;

        [TestMethod]
        public void testCreateSales()
        {
            reader = new Reader();  // TODO add path and sheet.
        }
    }
}
</code>```

答: I fixed this error by deleting the code in the constructor of the Reader class and the Reader initialization in the Main method. After reading these lines of code immediately after the program still worked even though nothing had truly changed. I am not sure why this worked but it did, and I successfully replicated it multiple times after deleting all code slowly until the error no longer occurred, allowing me to pinpoint the source.</p>

Body:
I have seen previous posts about Inconsistent accessibility errors but they have not been as specific as my case, or so I believe.

Here are my two errors:

'ConsoleApplication1.Reader' is inaccessible due to its protection level

Inconsistent accessibility: field type 'ConsoleApplication1.Reader' is less
accessible than field 'UnitTestProject1.ReaderTest.reader'

The Reader class is public so I am not sure why the test class does not see that. I have multiple other tests that do not have this same problem, and all are set up the same way. As for the second error I believe if I fix the first one that one will be resolved as a consequence. Below I will attach a piece of the Reader class as well as the test class for it. Advice would be greatly appreciated, thanks!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    ///
    /// Created and tested by Alexander James Bochel.
    /// Last Updated: 6/7/2017
    ///
    class Program
    {

        ///
        /// This will call the rest of the classes in the program.
        ///
        /// <param name="args"> Command line arguments. </param>
        static void Main(string[] args)
        {
            openFile();
        }

        public static void openFile()
        {
            Reader reader = new Reader(@"C:\Users\abochel\Desktop\TEST.xlsx", 0);
        }

    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    public class Reader
    {
        public Reader()
        {
            // TODO - Default constructor.
        }
    }
}

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections;
using System.Collections.Generic;
using ConsoleApplication1;

namespace AutomationProgramTests
{
    [TestClass]
    public class ReaderTest
    {

        Reader reader;

        [TestMethod]
        public void testCreateSales()
        {
            reader = new Reader();  // TODO add path and sheet.
        }
    }
}


答:
A file-name suffix is just a suffix (which sometimes help to get info about that file; e.g. Windows decides which tool is called when double-clicked). A suffix does not need to be correct. And of course, changing the suffix will not change the content.

Every format will need their own decoder. JPG, PNG, MAT and co.

To some extent, these are automatically used by reading out metadata (giving some assumptions!). Many image-tools have some imread-function which works for jpg and png, even if there is no suffix (because there is checking for common and supported image-formats).

I'm not sure what tensorflow does automatically, but:

jpg, png, bmp should be no problem

worst-case: use scipy to read and convert

mat is usually a matrix (with infinite different encodings) and often matlab-based

scipy can read many matlab-based formats

bin can be anything (usually stands for binary; no clear mapping like the above)

Don't get me wrong, but i expect someone trying to use tensorflow (not a small, not a simple tool) to know that changing a suffix should never magically transform the content to the new format (especially in the lossless/lossy case like png, jpg). I hope you evaluated this decision and you are not running blindly into using a popular tool.

Title: the difference between .bin file and .mat files

Body:
can the tensorflow read a file contain a normal images for example in JPG, .... or the tensorflow just read the .bin file contains images

what is the difference between .mat file and .bin file

Also when I rename the .bin file name to .mat, does the data of the file changed??

sorry maybe my language not clear because I cannot speak English very well


问:
Setting ImageView width dynamically in a Xamarin Android project
I am trying to dynamically set the ImageView height in Xamarin droid project not in core.

```<code>LinearLayout layout4 = new LinearLayout(Activity);
layout4.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent);
layout4.SetGravity(GravityFlags.Center);
layout4.Orientation = Orientation.Vertical;
</code>```

I am not able to set:

```<code>layout4.Height = 20;
</code>```

Getting error: Property or indexer cannot be assigned, it is read only

答:
This is because the same as Java the height field of the LinearLayout is not accesible through the instance but with the LayoutParams.

You can set the desired height when creating the LayoutParams instance.

```<code>layout4.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, 20);
</code>```

But, if you want to modify this value after the LayoutParams has been created and set you can do it like this:

```<code>layout4.LayoutParameters.Height = 20;
</code>```

Body:
I am trying to dynamically set the ImageView height in Xamarin droid project not in core.

LinearLayout layout4 = new LinearLayout(Activity);
layout4.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent);
layout4.SetGravity(GravityFlags.Center);
layout4.Orientation = Orientation.Vertical;

I am not able to set:

layout4.Height = 20;

Getting error: Property or indexer cannot be assigned, it is read only

Body:
This is because the same as Java the height field of the LinearLayout is not accesible through the instance but with the LayoutParams.

You can set the desired height when creating the LayoutParams instance.

layout4.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, 20);

But, if you want to modify this value after the LayoutParams has been created and set you can do it like this:

layout4.LayoutParameters.Height = 20;


问:
Swift Error (EXC_BAD_INSTRUCTION)
I have one error that I can't fix. I am new to using Swift so I am a little lost here.

```<code>Basic Swift
</code>```

答:
super.viewDidLoad() should be called before you start writing code in the function. Basically, the super function is calling the behind-the-scenes viewDidLoad function before you run your own code.

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    TimeLabel.text = "\(counter)"
}
</code>```

Also, notice the way that I wrote the string. This is called string interpolation and is the correct way to place variables in a string. For example: "The value is (counter * 2/3)"

Title: Swift Error (EXC_BAD_INSTRUCTION)

Body:
I have one error that I can't fix. I am new to using Swift so I am a little lost here.

Basic Swift

Body:
super.viewDidLoad() should be called before you start writing code in the function. Basically, the super function is calling the behind-the-scenes viewDidLoad function before you run your own code.

override func viewDidLoad() {
    super.viewDidLoad()
    TimeLabel.text = "\(counter)"
}

Also, notice the way that I wrote the string. This is called string interpolation and is the correct way to place variables in a string. For example: "The value is (counter * 2/3)"


问:
How to sort a vector using sort() in c++
I want to insert an element in my already sorted vector and it'll be placed at its sorted position when it'll be sorted again.
There is a function called sort() for sorting an array.How can I use the same function to sort a vector?
Here's my code.It gives me the compilation error.

```<code>//assume g1 is already sorted with some numbers
int x;
cin >> x;
g1.push_back(x);
int s = g1.size()/g1.at(g1.begin());
//similar to int s = arr/arr[0]
sort(g1 + s,g1);
</code>```

答:
Instead of sorting, find the position where the new element should go and insert it there:

```<code>std::vector<int>::iterator loc = std::upper_bound(g1.begin(), g1.end(), x);
g1.insert(loc, x);
</code>```

Or, more briefly:

```<code>g1.insert(std::upper_bound(g1.begin(), g1.end(), x), x);
</code>```

Body:
I want to insert an element in my already sorted vector and it'll be placed at its sorted position when it'll be sorted again.
There is a function called sort() for sorting an array.How can I use the same function to sort a vector?
Here's my code.It gives me the compilation error.

//assume g1 is already sorted with some numbers
int x;
cin >> x;
g1.push_back(x);
int s = g1.size()/g1.at(g1.begin());
//similar to int s = arr/arr[0]
sort(g1 + s,g1);

Body:
Instead of sorting, find the position where the new element should go and insert it there:

std::vector<int>::iterator loc = std::upper_bound(g1.begin(), g1.end(), x);
g1.insert(loc, x);

Or, more briefly:

g1.insert(std::upper_bound(g1.begin(), g1.end(), x), x);


问:
Setting Object values from SQL Query
I am trying to iterate through an SQL query and set the objects parameters to particular values. The only value that seems to be functioning correctly is the workpack.JobCardIDs, as I can implement a foreach loop to display the results. If I try to set a Label's Text property to a workpack.WorkPackTitle for example, it will display a blank even though the database value is something for every line.

I am fairly new to the OOP so not entirely sure if there is something I am missing that's fundamental.

```<code>    public class WorkPack
    {
        public int ID { get; set; }
        public string WorkPackNumber { get; set; }
        public string WorkPackTitle { get; set; }
        public string WorkPackDescription { get; set; }
        public Boolean IFC { get; set; }
        public string SPA { get; set; }
        public string Writer { get; set; }
        public string Organization { get; set; }
        public List<int> JobCardIDs { get; set; }
        public int JobCard { get; set; }
    }

    public static WorkPack PopulateWorkPackObject(WorkPack workpack, int workPackID)
    {
        string ConnectionString = ConfigurationManager.ConnectionStrings["vmdatamanagerConnectionString"].ConnectionString;
        string sqlCall = "I HAVE REMOVED CALL BUT VERIFIED IT FUNCTIONS (SELECT columns FROM workpackdatabase where workpackname = x";

        using (SqlConnection con = new SqlConnection(ConnectionString))
        {
            using (SqlCommand cmd = new SqlCommand(sqlCall, con))
            {
                cmd.Connection.Open();
                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        if (reader.IsDBNull(reader.GetOrdinal("PARAM1")) == false)
                            workpack.WorkPackNumber = (reader.GetString(reader.GetOrdinal("PARAM1")));

                        if (reader.IsDBNull(reader.GetOrdinal("PARAM2")) == false)
                            workpack.WorkPackTitle = reader.GetString(reader.GetOrdinal("PARAM2"));

                        if (reader.IsDBNull(reader.GetOrdinal("PARAM3")) == false)
                            workpack.WorkPackDescription = reader.GetString(reader.GetOrdinal("PARAM3"));

                        if (reader.IsDBNull(reader.GetOrdinal("PARAM4")) == false)
                            workpack.IFC = reader.GetBoolean(reader.GetOrdinal("PARAM4"));

                        if (reader.IsDBNull(reader.GetOrdinal("PARAM5")) == false)
                            workpack.SPA = reader.GetString(reader.GetOrdinal("PARAM5"));

                        if (reader.IsDBNull(reader.GetOrdinal("PARAM6")) == false)
                            workpack.Writer = reader.GetString(reader.GetOrdinal("PARAM6"));

                        if (reader.IsDBNull(reader.GetOrdinal("PARAM7")) == false)
                            workpack.Organization = reader.GetString(reader.GetOrdinal("PARAM7"));

                        if (reader.IsDBNull(reader.GetOrdinal("PARAM8")) == false)
                            jobCardIDs.Add(reader.GetInt32(reader.GetOrdinal("PARAM8")));

                    }
                    workpack.JobCardIDs = jobCardIDs;
                    return workpack;
                }
            }
        }
    }
</code>```

答:
The previous answers given by the community did not fix the issue, although I did put that extra snippet it.

The issue was when the objects were being created and passed between post backs. The object would be relevant on selection of the job card tab but once the page loaded there was no code to rebuild that instance.

Adding

```<code>      Object foo = new Object();
</code>```

in the page_Load() and rebuilding fixed the issue. If anyone has any suggestions on how to keep an instance alive I am all for hearing it. I think ViewState() and also Session[] were applicable methods for doing so.

Title: Setting Object values from SQL Query

Body:
I am trying to iterate through an SQL query and set the objects parameters to particular values. The only value that seems to be functioning correctly is the workpack.JobCardIDs, as I can implement a foreach loop to display the results. If I try to set a Label's Text property to a workpack.WorkPackTitle for example, it will display a blank even though the database value is something for every line.

I am fairly new to the OOP so not entirely sure if there is something I am missing that's fundamental.

    public class WorkPack
    {
        public int ID { get; set; }
        public string WorkPackNumber { get; set; }
        public string WorkPackTitle { get; set; }
        public string WorkPackDescription { get; set; }
        public Boolean IFC { get; set; }
        public string SPA { get; set; }
        public string Writer { get; set; }
        public string Organization { get; set; }
        public List<int> JobCardIDs { get; set; }
        public int JobCard { get; set; }
    }

    public static WorkPack PopulateWorkPackObject(WorkPack workpack, int workPackID)
    {
        string ConnectionString = ConfigurationManager.ConnectionStrings["vmdatamanagerConnectionString"].ConnectionString;
        string sqlCall = "I HAVE REMOVED CALL BUT VERIFIED IT FUNCTIONS (SELECT columns FROM workpackdatabase where workpackname = x";

        using (SqlConnection con = new SqlConnection(ConnectionString))
        {
            using (SqlCommand cmd = new SqlCommand(sqlCall, con))
            {
                cmd.Connection.Open();
                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        if (reader.IsDBNull(reader.GetOrdinal("PARAM1")) == false)
                            workpack.WorkPackNumber = (reader.GetString(reader.GetOrdinal("PARAM1")));

                        if (reader.IsDBNull(reader.GetOrdinal("PARAM2")) == false)
                            workpack.WorkPackTitle = reader.GetString(reader.GetOrdinal("PARAM2"));

                        if (reader.IsDBNull(reader.GetOrdinal("PARAM3")) == false)
                            workpack.WorkPackDescription = reader.GetString(reader.GetOrdinal("PARAM3"));

                        if (reader.IsDBNull(reader.GetOrdinal("PARAM4")) == false)
                            workpack.IFC = reader.GetBoolean(reader.GetOrdinal("PARAM4"));

                        if (reader.IsDBNull(reader.GetOrdinal("PARAM5")) == false)
                            workpack.SPA = reader.GetString(reader.GetOrdinal("PARAM5"));

                        if (reader.IsDBNull(reader.GetOrdinal("PARAM6")) == false)
                            workpack.Writer = reader.GetString(reader.GetOrdinal("PARAM6"));

                        if (reader.IsDBNull(reader.GetOrdinal("PARAM7")) == false)
                            workpack.Organization = reader.GetString(reader.GetOrdinal("PARAM7"));

                        if (reader.IsDBNull(reader.GetOrdinal("PARAM8")) == false)
                            jobCardIDs.Add(reader.GetInt32(reader.GetOrdinal("PARAM8")));

                    }
                    workpack.JobCardIDs = jobCardIDs;
                    return workpack;
                }
            }
        }
    }

Body:
The previous answers given by the community did not fix the issue, although I did put that extra snippet it.

The issue was when the objects were being created and passed between post backs. The object would be relevant on selection of the job card tab but once the page loaded there was no code to rebuild that instance.

Adding

      Object foo = new Object();

in the page_Load() and rebuilding fixed the issue. If anyone has any suggestions on how to keep an instance alive I am all for hearing it. I think ViewState() and also Session[] were applicable methods for doing so.


问:
Download, Update, Compile and publish Android source code on Windows
Hey Guys,
 I want to do a nice test to the Android OS. I would like to flash my rooted Android device with my own android OS version. I am doing so because I want to change some system app and kernel framework to act differently.

So I know I can download the source code with git, but can I open it with Eclipse? how do I compile it, and the most important question, how do I flash it back (with the changes) to the device?

I need to do it on Windows...I know it suppose to run on Mac\Linux, any free solution?

Thanks
 M

答: Probably should ask the people over at xda-developers forums to see if there is a windows tool set that they recommend for Android OS development.</p>


问:
GIMP Filter in C#
I'm trying all day long to get this code run, but no chance. I would like to execute a GIMP filter on an image and save it later to a certain path. With this code:

```<code>string choosenFile = "D:\\here\\is\\the\\image";
string gimpFile = "D:\\here\\is\\my\\gimp exe";

void seamlessFilter() {
    try {
        if (!string.IsNullOrEmpty(choosenFile)) {
            string a = @"-b ""(script-fu-tile \"""
            + choosenFile
            + "100 100 0 TRUE 70"
            + @")"" -b ""(gimp-quit 0)""";
            string result = ExecuteCommandSync(a);
            Texture2D newTex = loadImage (new Vector2(200, 200), Path.GetFullPath(choosenFile));
            newTex = null;
        } else {
            UnityEngine.Debug.Log("Please select a image");
        }
    } catch (Exception ex){
        UnityEngine.Debug.Log (ex.ToString ());
    }
}

public string ExecuteCommandSync(string command) {
    ProcessStartInfo processStartInfo = new ProcessStartInfo (gimpFile, command);
    processStartInfo.RedirectStandardOutput = true;
    processStartInfo.UseShellExecute = false;
    processStartInfo.CreateNoWindow = true;

    Process process = new Process ();
    process.StartInfo = processStartInfo;

    process.Start ();
    StreamReader reader = process.StandardOutput;
    string result = reader.ReadToEnd ();
    Console.WriteLine (result);
    return result;
}
</code>```

I try to execute the filter, but I get every time an error, that the string couldn't be read.
Here is the .scm:

```<code> `
(define (script-fu-tile img
        drawable
        blend-x
        blend-y
        overlap
        square)

(let*

    (

    (sel-float1 0)

    (sel-float2 0)

    (sel-float3 0)
    (sel-float4 0)
    (high-pass-layer 0)

    (yoffset 0)

    (img-w (/ (car (gimp-image-width img)) 2))

    (img-h (/ (car (gimp-image-height img)) 2))

;(newimg (car (gimp-image-new (- (car (gimp-image-width img)) blend-x)
(- (car (gimp-image-height img)) blend-y) RGB)))

    )

    (if (= square 1)

        (set! yoffset (+ (- (* (- img-w img-h) 2) (- blend-x blend-y)) overlap))

        (set! yoffset overlap)

    )

    (gimp-undo-push-group-start img)

    (gimp-rect-select img 0 0 img-w img-h CHANNEL-OP-REPLACE FALSE 0)

    (gimp-edit-copy drawable)

    (set! sel-float1 (car (gimp-edit-paste drawable FALSE)))

    (gimp-floating-sel-to-layer sel-float1)

    (gimp-layer-translate sel-float1 (- (- img-w blend-x) yoffset) (- (- img-h blend-y) overlap))

    (gimp-rect-select img img-w 0 img-w img-h CHANNEL-OP-REPLACE FALSE 0)

    (gimp-edit-copy drawable)

    (set! sel-float2 (car (gimp-edit-paste drawable FALSE)))
    (gimp-floating-sel-to-layer sel-float2)

    (gimp-layer-translate sel-float2 (- 0 img-w) (- (- img-h blend-y) overlap))

    (gimp-rect-select img 0 img-h img-w img-h CHANNEL-OP-REPLACE FALSE 0)

    (gimp-edit-copy drawable)

    (set! sel-float3 (car (gimp-edit-paste drawable FALSE)))

    (gimp-floating-sel-to-layer sel-float3)

    (gimp-layer-translate sel-float3 (- (- img-w blend-x) yoffset) (- 0 img-h))

    (gimp-rect-select img img-w img-h img-w img-h CHANNEL-OP-REPLACE FALSE 0)

    (gimp-edit-copy drawable)

    (set! sel-float4 (car (gimp-edit-paste drawable FALSE)))

    (gimp-floating-sel-to-layer sel-float4)

    (gimp-layer-translate sel-float4 (- 0 img-w) (- 0 img-h))

    (gimp-rect-select img (- 0 blend-x) (- 0 blend-x) (+ img-w (/ blend-x 2)) (+ img-h (+ blend-x blend-x)) CHANNEL-OP-REPLACE TRUE (/ blend-x 1.68))

    (gimp-selection-invert img)

    (gimp-edit-clear sel-float4)

    (gimp-rect-select img (- 0 blend-y) (- 0 blend-y) (+ img-w (+ blend-y blend-y)) (+ img-h (/ blend-y 2)) CHANNEL-OP-REPLACE TRUE (/ blend-y 1.68))

    (gimp-selection-invert img)

    (gimp-edit-clear sel-float4)

    (gimp-rect-select img (- (- img-w (- blend-x blend-y)) yoffset) (- 0 blend-y) (+ img-w (+ blend-y blend-y)) (+ img-h (/ blend-y 2)) CHANNEL-OP-REPLACE TRUE (/ blend-y 1.68))

    (gimp-selection-invert img)

    (gimp-edit-clear sel-float3)

    (gimp-rect-select img (- 0 blend-x) (- (- img-h (+ blend-x blend-y)) overlap) (+ img-w (/ blend-x 2)) (+ img-h (+ blend-x blend-x)) CHANNEL-OP-REPLACE TRUE (/ blend-x 1.68))

    (gimp-selection-invert img)

    (gimp-edit-clear sel-float2)

    (gimp-selection-none img)

    ;(gimp-layer-delete drawable)

    (gimp-image-crop img (- (- (* img-w 2) blend-x) yoffset) (- (- (* img-h 2) blend-y) overlap) 0 0)

    ; Complete the undo group

    (gimp-undo-push-group-end img)

    ; Flush output

    (gimp-displays-flush)

)
)

 (script-fu-register "script-fu-tile"

  "<Image>/Filters/Map/Tileable..."

  "Make seamless texture"

  "Pavel aka RPG Roshchin <rpg89@post.ru>"

  "Pavel aka RPG Roshchin"

  "2011"

  "RGB*, GRAY*"

   SF-IMAGE "Image" 0

   SF-DRAWABLE "Layer to blur" 0

   SF-ADJUSTMENT "Blend x" '(100 0 1000 1 10 0 0)

   SF-ADJUSTMENT "Blend y" '(100 0 1000 1 10 0 0)

   SF-ADJUSTMENT "Overlap" '(0 0 1000 1 10 0 0)

   SF-TOGGLE
    "Make square texture"   TRUE

   ;SF-ADJUSTMENT "Homogenize brightness (%)" '(70 0 100 1 10 0 0)

   )`
</code>```

I'd be so glade if anyone could help, because I despair. Thank you!

答:
Maybe go and have a look here and give this method a try

But by the looks of things your:

```<code> string a = @"-b ""(script-fu-tile \"""
        + choosenFile
        + "100 100 0 TRUE 70"
        + @")"" -b ""(gimp-quit 0)""";
</code>```

Should look more like this:

```<code>string a = @"gimp-2.6.exe -i -b ""(script-fu-tile \""" +
               choosenFile + @"\""0 100 100 0 TRUE 70)"" -b ""(gimp-quit 0)""";
</code>```

Or Essentially:

```<code>    string draw = "0";
    string blendx = "100";
    string blendy = "100";
    string overlap = "0";
    string sqrText = "TRUE";
    string adjBright = "70";
    string a = @"gimp-2.6.exe -i -b ""(simple-unsharp-mask \""" +
              path + @"\"" " + draw + " " + blendx + " " + blendy + " " + overlap + " "+ sqrText + " " + adjBright +
              @")"" -b ""(gimp-quit 0)""";
</code>```

By the looks of what the error is saying that you have provided there is a problem with the above string in your code. Give those few a try and comment back to me.

Title: GIMP Filter in C#

Body:
I'm trying all day long to get this code run, but no chance. I would like to execute a GIMP filter on an image and save it later to a certain path. With this code:

string choosenFile = "D:\\here\\is\\the\\image";
string gimpFile = "D:\\here\\is\\my\\gimp exe";

void seamlessFilter() {
    try {
        if (!string.IsNullOrEmpty(choosenFile)) {
            string a = @"-b ""(script-fu-tile \"""
            + choosenFile
            + "100 100 0 TRUE 70"
            + @")"" -b ""(gimp-quit 0)""";
            string result = ExecuteCommandSync(a);
            Texture2D newTex = loadImage (new Vector2(200, 200), Path.GetFullPath(choosenFile));
            newTex = null;
        } else {
            UnityEngine.Debug.Log("Please select a image");
        }
    } catch (Exception ex){
        UnityEngine.Debug.Log (ex.ToString ());
    }
}

public string ExecuteCommandSync(string command) {
    ProcessStartInfo processStartInfo = new ProcessStartInfo (gimpFile, command);
    processStartInfo.RedirectStandardOutput = true;
    processStartInfo.UseShellExecute = false;
    processStartInfo.CreateNoWindow = true;

    Process process = new Process ();
    process.StartInfo = processStartInfo;

    process.Start ();
    StreamReader reader = process.StandardOutput;
    string result = reader.ReadToEnd ();
    Console.WriteLine (result);
    return result;
}

I try to execute the filter, but I get every time an error, that the string couldn't be read.
Here is the .scm:

 `
(define (script-fu-tile img
        drawable
        blend-x
        blend-y
        overlap
        square)

(let*

    (

    (sel-float1 0)

    (sel-float2 0)

    (sel-float3 0)
    (sel-float4 0)
    (high-pass-layer 0)

    (yoffset 0)

    (img-w (/ (car (gimp-image-width img)) 2))

    (img-h (/ (car (gimp-image-height img)) 2))

;(newimg (car (gimp-image-new (- (car (gimp-image-width img)) blend-x)
(- (car (gimp-image-height img)) blend-y) RGB)))

    )

    (if (= square 1)

        (set! yoffset (+ (- (* (- img-w img-h) 2) (- blend-x blend-y)) overlap))

        (set! yoffset overlap)

    )

    (gimp-undo-push-group-start img)

    (gimp-rect-select img 0 0 img-w img-h CHANNEL-OP-REPLACE FALSE 0)

    (gimp-edit-copy drawable)

    (set! sel-float1 (car (gimp-edit-paste drawable FALSE)))

    (gimp-floating-sel-to-layer sel-float1)

    (gimp-layer-translate sel-float1 (- (- img-w blend-x) yoffset) (- (- img-h blend-y) overlap))

    (gimp-rect-select img img-w 0 img-w img-h CHANNEL-OP-REPLACE FALSE 0)

    (gimp-edit-copy drawable)

    (set! sel-float2 (car (gimp-edit-paste drawable FALSE)))
    (gimp-floating-sel-to-layer sel-float2)

    (gimp-layer-translate sel-float2 (- 0 img-w) (- (- img-h blend-y) overlap))

    (gimp-rect-select img 0 img-h img-w img-h CHANNEL-OP-REPLACE FALSE 0)

    (gimp-edit-copy drawable)

    (set! sel-float3 (car (gimp-edit-paste drawable FALSE)))

    (gimp-floating-sel-to-layer sel-float3)

    (gimp-layer-translate sel-float3 (- (- img-w blend-x) yoffset) (- 0 img-h))

    (gimp-rect-select img img-w img-h img-w img-h CHANNEL-OP-REPLACE FALSE 0)

    (gimp-edit-copy drawable)

    (set! sel-float4 (car (gimp-edit-paste drawable FALSE)))

    (gimp-floating-sel-to-layer sel-float4)

    (gimp-layer-translate sel-float4 (- 0 img-w) (- 0 img-h))

    (gimp-rect-select img (- 0 blend-x) (- 0 blend-x) (+ img-w (/ blend-x 2)) (+ img-h (+ blend-x blend-x)) CHANNEL-OP-REPLACE TRUE (/ blend-x 1.68))

    (gimp-selection-invert img)

    (gimp-edit-clear sel-float4)

    (gimp-rect-select img (- 0 blend-y) (- 0 blend-y) (+ img-w (+ blend-y blend-y)) (+ img-h (/ blend-y 2)) CHANNEL-OP-REPLACE TRUE (/ blend-y 1.68))

    (gimp-selection-invert img)

    (gimp-edit-clear sel-float4)

    (gimp-rect-select img (- (- img-w (- blend-x blend-y)) yoffset) (- 0 blend-y) (+ img-w (+ blend-y blend-y)) (+ img-h (/ blend-y 2)) CHANNEL-OP-REPLACE TRUE (/ blend-y 1.68))

    (gimp-selection-invert img)

    (gimp-edit-clear sel-float3)

    (gimp-rect-select img (- 0 blend-x) (- (- img-h (+ blend-x blend-y)) overlap) (+ img-w (/ blend-x 2)) (+ img-h (+ blend-x blend-x)) CHANNEL-OP-REPLACE TRUE (/ blend-x 1.68))

    (gimp-selection-invert img)

    (gimp-edit-clear sel-float2)

    (gimp-selection-none img)

    ;(gimp-layer-delete drawable)

    (gimp-image-crop img (- (- (* img-w 2) blend-x) yoffset) (- (- (* img-h 2) blend-y) overlap) 0 0)

    ; Complete the undo group

    (gimp-undo-push-group-end img)

    ; Flush output

    (gimp-displays-flush)

)
)

 (script-fu-register "script-fu-tile"

  "<Image>/Filters/Map/Tileable..."

  "Make seamless texture"

  "Pavel aka RPG Roshchin <rpg89@post.ru>"

  "Pavel aka RPG Roshchin"

  "2011"

  "RGB*, GRAY*"

   SF-IMAGE "Image" 0

   SF-DRAWABLE "Layer to blur" 0

   SF-ADJUSTMENT "Blend x" '(100 0 1000 1 10 0 0)

   SF-ADJUSTMENT "Blend y" '(100 0 1000 1 10 0 0)

   SF-ADJUSTMENT "Overlap" '(0 0 1000 1 10 0 0)

   SF-TOGGLE
    "Make square texture"   TRUE

   ;SF-ADJUSTMENT "Homogenize brightness (%)" '(70 0 100 1 10 0 0)

   )`

I'd be so glade if anyone could help, because I despair. Thank you!

Body:
Maybe go and have a look here and give this method a try

But by the looks of things your:

 string a = @"-b ""(script-fu-tile \"""
        + choosenFile
        + "100 100 0 TRUE 70"
        + @")"" -b ""(gimp-quit 0)""";

Should look more like this:

string a = @"gimp-2.6.exe -i -b ""(script-fu-tile \""" +
               choosenFile + @"\""0 100 100 0 TRUE 70)"" -b ""(gimp-quit 0)""";

Or Essentially:

    string draw = "0";
    string blendx = "100";
    string blendy = "100";
    string overlap = "0";
    string sqrText = "TRUE";
    string adjBright = "70";
    string a = @"gimp-2.6.exe -i -b ""(simple-unsharp-mask \""" +
              path + @"\"" " + draw + " " + blendx + " " + blendy + " " + overlap + " "+ sqrText + " " + adjBright +
              @")"" -b ""(gimp-quit 0)""";

By the looks of what the error is saying that you have provided there is a problem with the above string in your code. Give those few a try and comment back to me.