问:
Kohana 3.1 ORM: Empty model property value saved as 0 (zero) instead of NULL
I have two models, Product and Product_Methodology. In my product edit view I have a select form field to select one of many methodologies or none (empty first option). In my products table I have a INT(10) methodology_id property that gets saved with the id of the methodology selected from the select form field. Everything worked OK until today that I had to make an adjustment to the system in which since now selecting a methodology can be optional. So I changed the methodology_id field of the products table to allow NULL value and removed the not_empty validation rule on the model.

The problem is that now when I save the model selecting the empty option, instead of the expected NULL, I get a 0 (zero) value.

Any clue on this?
Thanks a lot and let me know if it's not so clear.

答:
What you should do is set the key for the None value in your select box to 0.

You should leave the not_empty rule for the field. Then you should have a rule for the field that makes sure that the value is either a legitimate value for product_methodology or zero.

I extend ORM and have the following two functions:

```<code>public function exists_or_zero(Validation $validation, $field, $model, $pk)
{
    // The exists() function is only called if the field has a non-zero value
    if ($validation[$field]) {
        $this->exists($validation, $field, $model, $pk);
    }
}

public function exists(Validation $validation, $field, $model, $pk)
{
    if ( ! ORM::factory($model, $pk)->loaded()) {
        $validation->error($field, 'exists', array($validation[$field]));
    }
}
</code>```

If you were to use these functions, you're rules in the product class would look like:

```<code>public function rules()
    return array(
        'product_methodology_id' => array(
            array('not_empty'),
            array(array($this, 'exists_or_zero'), array(':validation', ':field', 'product_methodology', ':value')),
        ),
    );
}
</code>```

Body:
What you should do is set the key for the None value in your select box to 0.

You should leave the not_empty rule for the field. Then you should have a rule for the field that makes sure that the value is either a legitimate value for product_methodology or zero.

I extend ORM and have the following two functions:

public function exists_or_zero(Validation $validation, $field, $model, $pk)
{
    // The exists() function is only called if the field has a non-zero value
    if ($validation[$field]) {
        $this->exists($validation, $field, $model, $pk);
    }
}

public function exists(Validation $validation, $field, $model, $pk)
{
    if ( ! ORM::factory($model, $pk)->loaded()) {
        $validation->error($field, 'exists', array($validation[$field]));
    }
}

If you were to use these functions, you're rules in the product class would look like:

public function rules()
    return array(
        'product_methodology_id' => array(
            array('not_empty'),
            array(array($this, 'exists_or_zero'), array(':validation', ':field', 'product_methodology', ':value')),
        ),
    );
}


来源: stackexchange

问:
Oracle Case Statement Query
I am working on an Oracle Query to find if Diagnostic Pack is installed. Query is working fine.

```<code>Select case when currently_used = 'TRUE' then 1
else 0
end DIAGNOSTICS_package
from dba_feature_usage_statistics
where name like '%Diagnostic Pack%'
and CURRENTLY_USED = 'TRUE'
</code>```

In the Output I need to add another Column Installed. So if currently_used = 'TRUE' I need the output to be displayed as below.

```<code>DIAGNOSTICS_package INSTALLED
1                   YES
</code>```

I am running into an issue with the INSTALLED Column in the case statement. Please advise.

Thanks

答:
The simplest answer to your question is, just add another CASE expression for the second column:

```<code>Select case when currently_used = 'TRUE' then 1
else 0
end DIAGNOSTICS_package,
case when currently_used = 'TRUE' then 'YES' else 'NO' end INSTALLED
from dba_feature_usage_statistics
where name like '%Diagnostic Pack%'
and CURRENTLY_USED = 'TRUE'
</code>```

I don't really get why you want two columns that tell you the same thing in different ways.

I also don't get why you need a CASE statement at all, since you have and CURRENTLY_USED = 'TRUE' as part of the query conditions.

But maybe there is a larger context where these things make sense.

ContentLicense: CC BY-SA 4.0

Title: Oracle Case Statement Query

Body:
I am working on an Oracle Query to find if Diagnostic Pack is installed. Query is working fine.

Select case when currently_used = 'TRUE' then 1
else 0
end DIAGNOSTICS_package
from dba_feature_usage_statistics
where name like '%Diagnostic Pack%'
and CURRENTLY_USED = 'TRUE'

In the Output I need to add another Column Installed. So if currently_used = 'TRUE' I need the output to be displayed as below.

DIAGNOSTICS_package INSTALLED
1                   YES

I am running into an issue with the INSTALLED Column in the case statement. Please advise.

Thanks

Body:
The simplest answer to your question is, just add another CASE expression for the second column:

Select case when currently_used = 'TRUE' then 1
else 0
end DIAGNOSTICS_package,
case when currently_used = 'TRUE' then 'YES' else 'NO' end INSTALLED
from dba_feature_usage_statistics
where name like '%Diagnostic Pack%'
and CURRENTLY_USED = 'TRUE'

I don't really get why you want two columns that tell you the same thing in different ways.

I also don't get why you need a CASE statement at all, since you have and CURRENTLY_USED = 'TRUE' as part of the query conditions.

But maybe there is a larger context where these things make sense.


问:
RabbitMQ virtual host error when starting service
I've had a RabbitMQ server running for months. This morning I was unable to connect to it, my applications was timing out and the Management client was unresponsive. Rebooted the machine. Applications are still timing out. I'm able to login to the Management client but I see this message:

Virtual host / experienced an error on node rabbit@MQT01 and may be inaccessible

All my queues are there but can't see any exchanges.

I hope someone can help me figure out what going on. I've looked at the logs but can't find any good hint.

Here a part of the log:

2018-09-11 09:39:42 =ERROR REPORT====
** Generic server <0.281.0> terminating
** Last message in was {'$gen_cast',{submit_async,#Fun<rabbit_queue_index.36.122888644>}}
** When Server state == undefined
** Reason for termination ==
** {function_clause,[{rabbit_queue_index,journal_minus_segment1,[{{true,<<172,190,166,92,192,205,125,125,36,223,114,188,53,139,128,108,0,0,0,0,0,0,0,0,0,0,26,151>>,<<>>},no_del,no_ack},{{true,<<89,173,78,227,188,37,119,171,231,189,220,236,244,79,138,177,0,0,0,0,0,0,0,0,0,0,23,40>>,<<>>},no_del,no_ack}],[{file,"src/rabbit_queue_index.erl"},{line,1231}]},{rabbit_queue_index,'-journal_minus_segment/3-fun-0-',4,[{file,"src/rabbit_queue_index.erl"},{line,1208}]},{array,sparse_foldl_3,7,[{file,"array.erl"},{line,1684}]},{array,sparse_foldl_2,9,[{file,"array.erl"},{line,1678}]},{rabbit_queue_index,'-recover_journal/1-fun-0-',1,[{file,"src/rabbit_queue_index.erl"},{line,915}]},{lists,map,2,[{file,"lists.erl"},{line,1239}]},{rabbit_queue_index,segment_map,2,[{file,"src/rabbit_queue_index.erl"},{line,1039}]},{rabbit_queue_index,recover_journal,1,[{file,"src/rabbit_queue_index.erl"},{line,906}]}]}
2018-09-11 09:39:42 =CRASH REPORT====
  crasher:
    initial call: worker_pool_worker:init/1
    pid: <0.281.0>
    registered_name: []
    exception exit: {{function_clause,[{rabbit_queue_index,journal_minus_segment1,[{{true,<<172,190,166,92,192,205,125,125,36,223,114,188,53,139,128,108,0,0,0,0,0,0,0,0,0,0,26,151>>,<<>>},no_del,no_ack},{{true,<<89,173,78,227,188,37,119,171,231,189,220,236,244,79,138,177,0,0,0,0,0,0,0,0,0,0,23,40>>,<<>>},no_del,no_ack}],[{file,"src/rabbit_queue_index.erl"},{line,1231}]},{rabbit_queue_index,'-journal_minus_segment/3-fun-0-',4,[{file,"src/rabbit_queue_index.erl"},{line,1208}]},{array,sparse_foldl_3,7,[{file,"array.erl"},{line,1684}]},{array,sparse_foldl_2,9,[{file,"array.erl"},{line,1678}]},{rabbit_queue_index,'-recover_journal/1-fun-0-',1,[{file,"src/rabbit_queue_index.erl"},{line,915}]},{lists,map,2,[{file,"lists.erl"},{line,1239}]},{rabbit_queue_index,segment_map,2,[{file,"src/rabbit_queue_index.erl"},{line,1039}]},{rabbit_queue_index,recover_journal,1,[{file,"src/rabbit_queue_index.erl"},{line,906}]}]},[{gen_server2,terminate,3,[{file,"src/gen_server2.erl"},{line,1161}]},{proc_lib,init_p_do_apply,3,[{file,"proc_lib.erl"},{line,247}]}]}
    ancestors: [worker_pool_sup,rabbit_sup,<0.262.0>]
    message_queue_len: 0
    messages: []
    links: [<0.276.0>,<0.336.0>,#Port<0.31196>]
    dictionary: [{fhc_age_tree,{1,{{10352640,#Ref<0.1077581647.1695285251.67028>},true,nil,nil}}},{worker_pool_worker,true},{rand_seed,{#{jump => #Fun<rand.16.15449617>,max => 288230376151711743,next => #Fun<rand.15.15449617>,type => exsplus},[257570830250844431|246837015578235662]}},{worker_pool_name,worker_pool},{{"c:/Users/dfpsb/AppData/Roaming/RabbitMQ/db/RABBIT~1/msg_stores/vhosts/628WB79CIFDYO9LJI6DKMI09L/queues/9GD33C2I2PKZ7A8QHZ4MWWCKE/journal.jif",fhc_file},{file,1,true}},{{#Ref<0.1077581647.1695285251.67028>,fhc_handle},{handle,{file_descriptor,prim_file,{#Port<0.31196>,1808}},#Ref<0.1077581647.1695285251.67028>,240,false,0,infinity,[],<<>>,0,0,0,0,0,false,"c:/Users/dfpsb/AppData/Roaming/RabbitMQ/db/RABBIT~1/msg_stores/vhosts/628WB79CIFDYO9LJI6DKMI09L/queues/9GD33C2I2PKZ7A8QHZ4MWWCKE/journal.jif",[write,binary,raw,read],[{write_buffer,infinity}],true,true,10352640}}]
    trap_exit: false
    status: running
    heap_size: 10958
    stack_size: 27
    reductions: 104391
  neighbours:
    neighbour: [{pid,<0.279.0>},{registered_name,[]},{initial_call,{worker_pool_worker,init,['Argument__1']}},{current_function,{gen,do_call,4}},{ancestors,[worker_pool_sup,rabbit_sup,<0.262.0>]},{message_queue_len,0},{links,[<0.276.0>,<0.336.0>]},{trap_exit,false},{status,waiting},{heap_size,4185},{stack_size,42},{reductions,21548},{current_stacktrace,[{gen,do_call,4,[{file,"gen.erl"},{line,169}]},{gen_server,call,3,[{file,"gen_server.erl"},{line,210}]},{file,call,2,[{file,"file.erl"},{line,1499}]},{rabbit_queue_index,get_journal_handle,1,[{file,"src/rabbit_queue_index.erl"},{line,881}]},{rabbit_queue_index,load_journal,1,[{file,"src/rabbit_queue_index.erl"},{line,894}]},{rabbit_queue_index,recover_journal,1,[{file,"src/rabbit_queue_index.erl"},{line,904}]},{rabbit_queue_index,scan_queue_segments,3,[{file,"src/rabbit_queue_index.erl"},{line,724}]},{rabbit_queue_index,queue_index_walker_reader,2,[{file,"src/rabbit_queue_index.erl"},{line,712}]}]}]
    neighbour: [{pid,<0.278.0>},{registered_name,[]},{initial_call,{worker_pool_worker,init,['Argument__1']}},{current_function,{gen,do_call,4}},{ancestors,[worker_pool_sup,rabbit_sup,<0.262.0>]},{message_queue_len,0},{links,[<0.276.0>,<0.336.0>,#Port<0.31157>]},{trap_exit,false},{status,waiting},{heap_size,6772},{stack_size,102},{reductions,129623},{current_stacktrace,[{gen,do_call,4,[{file,"gen.erl"},{line,169}]},{gen_server2,call,3,[{file,"src/gen_server2.erl"},{line,323}]},{array,sparse_foldr_3,6,[{file,"array.erl"},{line,1848}]},{array,sparse_foldr_2,8,[{file,"array.erl"},{line,1837}]},{lists,foldr,3,[{file,"lists.erl"},{line,1276}]},{rabbit_queue_index,scan_queue_segments,3,[{file,"src/rabbit_queue_index.erl"},{line,725}]},{rabbit_queue_index,queue_index_walker_reader,2,[{file,"src/rabbit_queue_index.erl"},{line,712}]},{rabbit_queue_index,'-queue_index_walker/1-fun-0-',2,[{file,"src/rabbit_queue_index.erl"},{line,694}]}]}]
    neighbour: [{pid,<0.280.0>},{registered_name,[]},{initial_call,{worker_pool_worker,init,['Argument__1']}},{current_function,{array,set_1,4}},{ancestors,[worker_pool_sup,rabbit_sup,<0.262.0>]},{message_queue_len,0},{links,[<0.276.0>,<0.336.0>,#Port<0.31170>]},{trap_exit,false},{status,runnable},{heap_size,121536},{stack_size,44},{reductions,122988},{current_stacktrace,[{array,set_1,4,[{file,"array.erl"},{line,590}]},{array,set_1,4,[{file,"array.erl"},{line,592}]},{array,set_1,4,[{file,"array.erl"},{line,592}]},{array,set,3,[{file,"array.erl"},{line,574}]},{rabbit_queue_index,parse_segment_publish_entry,5,[{file,"src/rabbit_queue_index.erl"},{line,1135}]},{rabbit_queue_index,segment_entries_foldr,3,[{file,"src/rabbit_queue_index.erl"},{line,1091}]},{lists,foldr,3,[{file,"lists.erl"},{line,1276}]},{rabbit_queue_index,scan_queue_segments,3,[{file,"src/rabbit_queue_index.erl"},{line,725}]}]}]
    neighbour: [{pid,<0.336.0>},{registered_name,[]},{initial_call,{gatherer,init,['Argument__1']}},{current_function,{gen_server2,process_next_msg,1}},{ancestors,[<0.332.0>,<0.324.0>,<0.323.0>,rabbit_vhost_sup_sup,rabbit_sup,<0.262.0>]},{message_queue_len,2},{links,[<0.280.0>,<0.332.0>,<0.281.0>,<0.278.0>,<0.279.0>]},{trap_exit,false},{status,runnable},{heap_size,987},{stack_size,8},{reductions,73223},{current_stacktrace,[{gen_server2,process_next_msg,1,[{file,"src/gen_server2.erl"},{line,666}]},{proc_lib,init_p_do_apply,3,[{file,"proc_lib.erl"},{line,247}]}]}]
2018-09-11 09:39:42 =CRASH REPORT====
  crasher:
    initial call: rabbit_msg_store:init/1
    pid: <0.332.0>
    registered_name: []
    exception exit: {{{function_clause,[{rabbit_queue_index,journal_minus_segment1,[{{true,<<172,190,166,92,192,205,125,125,36,223,114,188,53,139,128,108,0,0,0,0,0,0,0,0,0,0,26,151>>,<<>>},no_del,no_ack},{{true,<<89,173,78,227,188,37,119,171,231,189,220,236,244,79,138,177,0,0,0,0,0,0,0,0,0,0,23,40>>,<<>>},no_del,no_ack}],[{file,"src/rabbit_queue_index.erl"},{line,1231}]},{rabbit_queue_index,'-journal_minus_segment/3-fun-0-',4,[{file,"src/rabbit_queue_index.erl"},{line,1208}]},{array,sparse_foldl_3,7,[{file,"array.erl"},{line,1684}]},{array,sparse_foldl_2,9,[{file,"array.erl"},{line,1678}]},{rabbit_queue_index,'-recover_journal/1-fun-0-',1,[{file,"src/rabbit_queue_index.erl"},{line,915}]},{lists,map,2,[{file,"lists.erl"},{line,1239}]},{rabbit_queue_index,segment_map,2,[{file,"src/rabbit_queue_index.erl"},{line,1039}]},{rabbit_queue_index,recover_journal,1,[{file,"src/rabbit_queue_index.erl"},{line,906}]}]},{gen_server2,call,[<0.336.0>,out,infinity]}},[{gen_server2,init_it,6,[{file,"src/gen_server2.erl"},{line,589}]},{proc_lib,init_p_do_apply,3,[{file,"proc_lib.erl"},{line,247}]}]}
    ancestors: [<0.324.0>,<0.323.0>,rabbit_vhost_sup_sup,rabbit_sup,<0.262.0>]
    message_queue_len: 1
    messages: [{'EXIT',<0.336.0>,{function_clause,[{rabbit_queue_index,journal_minus_segment1,[{{true,<<172,190,166,92,192,205,125,125,36,223,114,188,53,139,128,108,0,0,0,0,0,0,0,0,0,0,26,151>>,<<>>},no_del,no_ack},{{true,<<89,173,78,227,188,37,119,171,231,189,220,236,244,79,138,177,0,0,0,0,0,0,0,0,0,0,23,40>>,<<>>},no_del,no_ack}],[{file,"src/rabbit_queue_index.erl"},{line,1231}]},{rabbit_queue_index,'-journal_minus_segment/3-fun-0-',4,[{file,"src/rabbit_queue_index.erl"},{line,1208}]},{array,sparse_foldl_3,7,[{file,"array.erl"},{line,1684}]},{array,sparse_foldl_2,9,[{file,"array.erl"},{line,1678}]},{rabbit_queue_index,'-recover_journal/1-fun-0-',1,[{file,"src/rabbit_queue_index.erl"},{line,915}]},{lists,map,2,[{file,"lists.erl"},{line,1239}]},{rabbit_queue_index,segment_map,2,[{file,"src/rabbit_queue_index.erl"},{line,1039}]},{rabbit_queue_index,recover_journal,1,[{file,"src/rabbit_queue_index.erl"},{line,906}]}]}}]
    links: [<0.335.0>,<0.324.0>]
    dictionary: []
    trap_exit: true
    status: running
    heap_size: 2586
    stack_size: 27
    reductions: 57377
  neighbours:
    neighbour: [{pid,<0.335.0>},{registered_name,[]},{initial_call,{rabbit_msg_store_gc,init,['Argument__1']}},{current_function,{gen_server2,process_next_msg,1}},{ancestors,[<0.332.0>,<0.324.0>,<0.323.0>,rabbit_vhost_sup_sup,rabbit_sup,<0.262.0>]},{message_queue_len,0},{links,[<0.332.0>]},{trap_exit,false},{status,waiting},{heap_size,987},{stack_size,8},{reductions,174},{current_stacktrace,[{gen_server2,process_next_msg,1,[{file,"src/gen_server2.erl"},{line,666}]},{proc_lib,init_p_do_apply,3,[{file,"proc_lib.erl"},{line,247}]}]}]
2018-09-11 09:39:42 =SUPERVISOR REPORT====
     Supervisor: {local,worker_pool_sup}
     Context:    child_terminated
     Reason:     {function_clause,[{rabbit_queue_index,journal_minus_segment1,[{{true,<<172,190,166,92,192,205,125,125,36,223,114,188,53,139,128,108,0,0,0,0,0,0,0,0,0,0,26,151>>,<<>>},no_del,no_ack},{{true,<<89,173,78,227,188,37,119,171,231,189,220,236,244,79,138,177,0,0,0,0,0,0,0,0,0,0,23,40>>,<<>>},no_del,no_ack}],[{file,"src/rabbit_queue_index.erl"},{line,1231}]},{rabbit_queue_index,'-journal_minus_segment/3-fun-0-',4,[{file,"src/rabbit_queue_index.erl"},{line,1208}]},{array,sparse_foldl_3,7,[{file,"array.erl"},{line,1684}]},{array,sparse_foldl_2,9,[{file,"array.erl"},{line,1678}]},{rabbit_queue_index,'-recover_journal/1-fun-0-',1,[{file,"src/rabbit_queue_index.erl"},{line,915}]},{lists,map,2,[{file,"lists.erl"},{line,1239}]},{rabbit_queue_index,segment_map,2,[{file,"src/rabbit_queue_index.erl"},{line,1039}]},{rabbit_queue_index,recover_journal,1,[{file,"src/rabbit_queue_index.erl"},{line,906}]}]}
     Offender:   [{pid,<0.281.0>},{id,4},{mfargs,{worker_pool_worker,start_link,[worker_pool]}},{restart_type,transient},{shutdown,4294967295},{child_type,worker}]

2018-09-11 09:39:42 =CRASH REPORT====
  crasher:
initial call: rabbit_vhost_process:init/1
pid: <0.325.0>
registered_name: []
exception exit: {{error,{{{function_clause,[{rabbit_queue_index,journal_minus_segment1,[{{true,<<172,190,166,92,192,205,125,125,36,223,114,188,53,139,128,108,0,0,0,0,0,0,0,0,0,0,26,151>>,<<>>},no_del,no_ack},{{true,<<89,173,78,227,188,37,119,171,231,189,220,236,244,79,138,177,0,0,0,0,0,0,0,0,0,0,23,40>>,<<>>},no_del,no_ack}],[{file,"src/rabbit_queue_index.erl"},{line,1231}]},{rabbit_queue_index,'-journal_minus_segment/3-fun-0-',4,[{file,"src/rabbit_queue_index.erl"},{line,1208}]},{array,sparse_foldl_3,7,[{file,"array.erl"},{line,1684}]},{array,sparse_foldl_2,9,[{file,"array.erl"},{line,1678}]},{rabbit_queue_index,'-recover_journal/1-fun-0-',1,[{file,"src/rabbit_queue_index.erl"},{line,915}]},{lists,map,2,[{file,"lists.erl"},{line,1239}]},{rabbit_queue_index,segment_map,2,[{file,"src/rabbit_queue_index.erl"},{line,1039}]},{rabbit_queue_index,recover_journal,1,[{file,"src/rabbit_queue_index.erl"},{line,906}]}]},{gen_server2,call,[<0.336.0>,out,infinity]}},{child,undefined,msg_store_persistent,{rabbit_msg_store,start_link,[msg_store_persistent,"c:/Users/dfpsb/AppData/Roaming/RabbitMQ/db/RABBIT~1/msg_stores/vhosts/628WB79CIFDYO9LJI6DKMI09L",[],{#Fun<rabbit_queue_index.2.122888644>,{start,[{resource,<<"/">>,queue,<<"DF-9ID59RK-WS.InterchangeFragtbrevEnvelope.TurPlan">>},{resource,<<"/">>,queue,<<"Test1.InterchangeFragtbrevEnvelope.RET">>},{resource,<<"/">>,queue,<<"Test2.DfLoggingEvent.Debug">>},{resource,<<"/">>,queue,<<"DF-9ID59RK-WS.InterchangeTurEnvelope.DFMobil">>},{resource,<<"/">>,queue,<<"Paw.DfLoggingEvent.Debug">>},{resource,<<"/">>,queue,<<"DevUnitTest.TruckLoadingEnvelope.UnitTest">>},{resource,<<"/">>,queue,<<"Test1.InterchangeFragtbrevEnvelope.RET_error">>},{resource,<<"/">>,queue,<<"Paw.InterchangeFragtbrevEnvelope.TurPlan">>},{resource,<<"/">>,queue,<<"DevUnitTest.TestMsg.UnitTest_error">>},{resource,<<"/">>,queue,<<"DevUnitTest.TestMsg.UnitTest">>},{resource,<<"/">>,queue,<<"Paw.InterchangeTurEnvelope.DFMobil">>},{resource,<<"/">>,queue,<<"Test2.InterchangeFragtbrevEnvelope.TurPlan">>},{resource,<<"/">>,queue,<<"Paw.InterchangeFragtbrevEnvelope.TurPlan_error">>},{resource,<<"/">>,queue,<<"Paw.TruckLoadingEnvelope.TurPlan">>},{resource,<<"/">>,queue,<<"Test2.InterchangeFragtbrevEnvelope.TurPlan_error">>},{resource,<<"/">>,queue,<<"Test2.TruckLoadingEnvelope.TurPlan">>},{resource,<<"/">>,queue,<<"Paw.DfLoggingEvent.Warning">>},{resource,<<"/">>,queue,<<"DF-9ID59RK-WS.InterchangeFragtbrevEnvelope.RET">>},{resource,<<"/">>,queue,<<"Test2.InterchangeTurEnvelope.DFMobil">>},{resource,<<"/">>,queue,<<"Test2.DfLoggingEvent.Warning">>}]}}]},transient,30000,worker,[rabbit_msg_store]}}},[{gen_server2,init_it,6,[{file,"src/gen_server2.erl"},{line,581}]},{proc_lib,init_p_do_apply,3,[{file,"proc_lib.erl"},{line,247}]}]}
ancestors: [<0.323.0>,rabbit_vhost_sup_sup,rabbit_sup,<0.262.0>]
message_queue_len: 0
messages: []
links: [<0.323.0>]
dictionary: []
trap_exit: true
status: running
heap_size: 10958
stack_size: 27
reductions: 63314
  neighbours:
2018-09-11 09:39:42 =SUPERVISOR REPORT====
 Supervisor: {<0.323.0>,rabbit_vhost_sup_wrapper}
 Context:    start_error
 Reason:     {error,{{{function_clause,[{rabbit_queue_index,journal_minus_segment1,[{{true,<<172,190,166,92,192,205,125,125,36,223,114,188,53,139,128,108,0,0,0,0,0,0,0,0,0,0,26,151>>,<<>>},no_del,no_ack},{{true,<<89,173,78,227,188,37,119,171,231,189,220,236,244,79,138,177,0,0,0,0,0,0,0,0,0,0,23,40>>,<<>>},no_del,no_ack}],[{file,"src/rabbit_queue_index.erl"},{line,1231}]},{rabbit_queue_index,'-journal_minus_segment/3-fun-0-',4,[{file,"src/rabbit_queue_index.erl"},{line,1208}]},{array,sparse_foldl_3,7,[{file,"array.erl"},{line,1684}]},{array,sparse_foldl_2,9,[{file,"array.erl"},{line,1678}]},{rabbit_queue_index,'-recover_journal/1-fun-0-',1,[{file,"src/rabbit_queue_index.erl"},{line,915}]},{lists,map,2,[{file,"lists.erl"},{line,1239}]},{rabbit_queue_index,segment_map,2,[{file,"src/rabbit_queue_index.erl"},{line,1039}]},{rabbit_queue_index,recover_journal,1,[{file,"src/rabbit_queue_index.erl"},{line,906}]}]},{gen_server2,call,[<0.336.0>,out,infinity]}},{child,undefined,msg_store_persistent,{rabbit_msg_store,start_link,[msg_store_persistent,"c:/Users/dfpsb/AppData/Roaming/RabbitMQ/db/RABBIT~1/msg_stores/vhosts/628WB79CIFDYO9LJI6DKMI09L",[],{#Fun<rabbit_queue_index.2.122888644>,{start,[{resource,<<"/">>,queue,<<"DF-9ID59RK-WS.InterchangeFragtbrevEnvelope.TurPlan">>},{resource,<<"/">>,queue,<<"Test1.InterchangeFragtbrevEnvelope.RET">>},{resource,<<"/">>,queue,<<"Test2.DfLoggingEvent.Debug">>},{resource,<<"/">>,queue,<<"DF-9ID59RK-WS.InterchangeTurEnvelope.DFMobil">>},{resource,<<"/">>,queue,<<"Paw.DfLoggingEvent.Debug">>},{resource,<<"/">>,queue,<<"DevUnitTest.TruckLoadingEnvelope.UnitTest">>},{resource,<<"/">>,queue,<<"Test1.InterchangeFragtbrevEnvelope.RET_error">>},{resource,<<"/">>,queue,<<"Paw.InterchangeFragtbrevEnvelope.TurPlan">>},{resource,<<"/">>,queue,<<"DevUnitTest.TestMsg.UnitTest_error">>},{resource,<<"/">>,queue,<<"DevUnitTest.TestMsg.UnitTest">>},{resource,<<"/">>,queue,<<"Paw.InterchangeTurEnvelope.DFMobil">>},{resource,<<"/">>,queue,<<"Test2.InterchangeFragtbrevEnvelope.TurPlan">>},{resource,<<"/">>,queue,<<"Paw.InterchangeFragtbrevEnvelope.TurPlan_error">>},{resource,<<"/">>,queue,<<"Paw.TruckLoadingEnvelope.TurPlan">>},{resource,<<"/">>,queue,<<"Test2.InterchangeFragtbrevEnvelope.TurPlan_error">>},{resource,<<"/">>,queue,<<"Test2.TruckLoadingEnvelope.TurPlan">>},{resource,<<"/">>,queue,<<"Paw.DfLoggingEvent.Warning">>},{resource,<<"/">>,queue,<<"DF-9ID59RK-WS.InterchangeFragtbrevEnvelope.RET">>},{resource,<<"/">>,queue,<<"Test2.InterchangeTurEnvelope.DFMobil">>},{resource,<<"/">>,queue,<<"Test2.DfLoggingEvent.Warning">>}]}}]},transient,30000,worker,[rabbit_msg_store]}}}
 Offender:   [{pid,undefined},{id,rabbit_vhost_process},{mfargs,{rabbit_vhost_process,start_link,[<<"/">>]}},{restart_type,permanent},{shutdown,30000},{child_type,worker}]```

答:
I opted to recreate the vhost which resolved the issue for me.

Clearing the data in transient msg_stores & queues didn't work for me in my scenario. Since data loss wasn't an issue for me.


问:
Gradle issue with sceneform - Program type already present: com.google.ar.schemas.lull
I am working on a project that will have a 3D model viewer in one fragment. In order to do so, I decided to use sceneform.

I downloaded sceneform plugin into Adnroid studio, downloaded and extracted sdk from Github, and I also copied libsceneform_runtime_schemas library into my project. I've added to my sceneform buil.gradle file line

```<code>implementation files("../libs/libsceneform_runtime_schemas.jar")
</code>```

but that results in an error:

```<code>Program type already present: com.google.ar.schemas.lull.AabbDef
</code>```

It is worth noticing that this is the first file in the jar under this path - which probably means that there will be more collisions.

If I'd try not to implement this library, then I get an error:

```<code>error: package com.google.ar.schemas.sceneform does not exist
</code>```

I am using ar:core:1.17.0, and minSdkVersion 24 in sceneform gradle.
I've cleaned and rebuilt the project, Invalidate Caches/Restart, and added multiDexEnabled- although I am not sure if I did it correctly.
By using gradlew sceneform:dependencies I didn't find mentioned file.

I don't know how I can move forward, any help is much appreciated. If I can provide additional information, please let me know.

Edit 1:
I've also tried to work with

```<code>implementation files("../libs/libsceneform_runtime_schemas.jar"){
   exclude ...
}
</code>```

But I couldn't make it work. I wonder if that could be my solution.

Also, why does it try to implement this class since it already exists? Shouldn't there be some sort of check for that?

答:
I solved my problem by restoring my project from repo to the last moment before including sceneform, and I proceeded with all of the steps again; Gradle dependencies to the libsceneform_runtime_schemas, min java 8, min SDK version, copying scenformscr and sceneformux to my project again, and lastly - upgrading all classes to AndroidX.

After two days almost I couldn't remove the error, and I don't know what went wrong before, but this time it works like a charm.

TL;DR - I removed the sceneform from my project and imported it again.

Body:
I am working on a project that will have a 3D model viewer in one fragment. In order to do so, I decided to use sceneform.

I downloaded sceneform plugin into Adnroid studio, downloaded and extracted sdk from Github, and I also copied libsceneform_runtime_schemas library into my project. I've added to my sceneform buil.gradle file line

implementation files("../libs/libsceneform_runtime_schemas.jar")

but that results in an error:

Program type already present: com.google.ar.schemas.lull.AabbDef

It is worth noticing that this is the first file in the jar under this path - which probably means that there will be more collisions.

If I'd try not to implement this library, then I get an error:

error: package com.google.ar.schemas.sceneform does not exist

I am using ar:core:1.17.0, and minSdkVersion 24 in sceneform gradle.
I've cleaned and rebuilt the project, Invalidate Caches/Restart, and added multiDexEnabled- although I am not sure if I did it correctly.
By using gradlew sceneform:dependencies I didn't find mentioned file.

I don't know how I can move forward, any help is much appreciated. If I can provide additional information, please let me know.

Edit 1:
I've also tried to work with

implementation files("../libs/libsceneform_runtime_schemas.jar"){
   exclude ...
}

But I couldn't make it work. I wonder if that could be my solution.

Also, why does it try to implement this class since it already exists? Shouldn't there be some sort of check for that?


问:
Here Maps Routing API V8 - mutiple waypoints
I am very new to the Here Maps Routing API v8.

I have tried the example provided here:
https://developer.here.com/documentation/maps/3.1.15.1/dev_guide/topics/routing.html

I have used the routingParameters as shown below:

```<code>var routingParameters = {
  'routingMode': 'fast',
  'transportMode': 'car',
  'origin': '50.1120,8.6834',
  'destination': '52.5309,13.3846',
  'return': 'polyline'
};
</code>```

Now I want to add multiple waypoints in the routingParameters and I tried the below format for the same:

'via' : ['50.1234,8.7654', '51.2234,9.1123']

But the request is failing when I use the above line in the routingParameters.

Can you please suggest the correct format of the request with multiple waypoints ?

答:
Check the version of the HERE Maps JS API you are using. This is supported starting from version 3.1.19.0.

So the way to calculate a route with multiple waypoints would be:

// departure point (origin)
var start = '52.550464,13.384223';

// collection of waypoints
var waypoints = [
  '52.529791,13.401389'
  '52.513079,13.424392'
  '52.487581,13.425079'
];

// end point (destination)
var end = '52.477545,13.447395'

// routing parameters
var routingParameters = {
  'origin': start,
  'destination': end,
  'via': new H.service.Url.MultiValueQueryParameter( waypoints ),

  'routingMode': 'fast',
  'transportMode': 'car',

  'return': 'polyline'
};

// Get an instance of the routing service version 8:
var router = platform.getRoutingService(null, 8);

// Call `calculateRoute` with the routing parameters,
// the success callback and an error callback function
// The implementation of the two callback functions is left out for brevity
// see documentation link below for callback examples
router.calculateRoute(routingParameters, onResultCallback, onErrorCallback)
```

Calculate routes with HERE Maps JS API: documentation

Body:
I am very new to the Here Maps Routing API v8.

I have tried the example provided here:
https://developer.here.com/documentation/maps/3.1.15.1/dev_guide/topics/routing.html

I have used the routingParameters as shown below:

var routingParameters = {
  'routingMode': 'fast',
  'transportMode': 'car',
  'origin': '50.1120,8.6834',
  'destination': '52.5309,13.3846',
  'return': 'polyline'
};

Now I want to add multiple waypoints in the routingParameters and I tried the below format for the same:

'via' : ['50.1234,8.7654', '51.2234,9.1123']

But the request is failing when I use the above line in the routingParameters.

Can you please suggest the correct format of the request with multiple waypoints ?

Body:
Check the version of the HERE Maps JS API you are using. This is supported starting from version 3.1.19.0.

So the way to calculate a route with multiple waypoints would be:

// departure point (origin)
var start = '52.550464,13.384223';

// collection of waypoints
var waypoints = [
  '52.529791,13.401389'
  '52.513079,13.424392'
  '52.487581,13.425079'
];

// end point (destination)
var end = '52.477545,13.447395'

// routing parameters
var routingParameters = {
  'origin': start,
  'destination': end,
  'via': new H.service.Url.MultiValueQueryParameter( waypoints ),

  'routingMode': 'fast',
  'transportMode': 'car',

  'return': 'polyline'
};

// Get an instance of the routing service version 8:
var router = platform.getRoutingService(null, 8);

// Call `calculateRoute` with the routing parameters,
// the success callback and an error callback function
// The implementation of the two callback functions is left out for brevity
// see documentation link below for callback examples
router.calculateRoute(routingParameters, onResultCallback, onErrorCallback)

Calculate routes with HERE Maps JS API: documentation


问:
Writing create_tree_digraph plot to a png file in Python
I want the tree of my lightgbm model to save to a .png format. I have tried two plotting methods from lightgbm API - plot_tree and create_tree_diagraph.

```<code>import lightgbm as lgb
from sklearn.datasets import load_iris

X, y = load_iris(True)
clf = lgb.LGBMClassifier()
clf.fit(X, y)
</code>```

When I use plot_tree, it displays the tree but in place of values there are small blank boxes

```<code>lgb.plot_tree(clf, tree_index=0)
</code>```

When I try the create_tree_diagraph, I get the graph but I cant save it as it is.

```<code>lgb.create_tree_digraph(clf)
</code>```

I used the below code to save it a file but that gets saved as the first plot (using plot_tree)

```<code>import graphviz
s = graphviz.Source(graph_b.source, filename = "test1.gv", format = "png")
s.view()
</code>```

Any suggestions to save the plot as an image. I ultimately want to write these tree plots to excel.
I am using graphviz version 0.8.3
Thanks,

答:
I suppose you are using a jupyter notebook or something like that.
This worked for me, but surely is not the best way.</p>

```<code>ax = lgb.create_tree_digraph(clf)
with open('fst.svg', 'w') as f:
    f.write(ax._repr_svg_())
</code>```

Body:
I want the tree of my lightgbm model to save to a .png format. I have tried two plotting methods from lightgbm API - plot_tree and create_tree_diagraph.

import lightgbm as lgb
from sklearn.datasets import load_iris

X, y = load_iris(True)
clf = lgb.LGBMClassifier()
clf.fit(X, y)

When I use plot_tree, it displays the tree but in place of values there are small blank boxes

lgb.plot_tree(clf, tree_index=0)

When I try the create_tree_diagraph, I get the graph but I cant save it as it is.

lgb.create_tree_digraph(clf)

I used the below code to save it a file but that gets saved as the first plot (using plot_tree)

import graphviz
s = graphviz.Source(graph_b.source, filename = "test1.gv", format = "png")
s.view()

Any suggestions to save the plot as an image. I ultimately want to write these tree plots to excel.
I am using graphviz version 0.8.3
Thanks,

Body:
I suppose you are using a jupyter notebook or something like that.
This worked for me, but surely is not the best way.

ax = lgb.create_tree_digraph(clf)
with open('fst.svg', 'w') as f:
    f.write(ax._repr_svg_())


问:
Python XLWings Anaconda Newbie - Install / Basic issues
Thanks for your time.  Im an old programmer coming back to Python

I have a new install of Anaconda3, Windows 10 and Microsoft Office 2010

I tried install xlwings via pip straight into Python3 - didn't seem to work

Ive then installed anaconda3, spyder.

Ive installed inside anaconda at the command prompt
xlwings addin install
xlwings addin update

initially I got an error going into excel, saying 2 spreadsheets of the same name can not be open - I guess that was something to do with when I was trying to get the original python3 / pip/ addin manager to work....
Ive spent all day trying to sort that. It no longer appears in the addin menu (developer), just in the ribbon - xlwings

Ive run a program as per the documentation spyder/python and get Hello xlwings inside excel (created the python and excel spreadsheet with the xlwings quickstart myproject)

But when I try and use a fuction that sends data to python I get an error.  if I click on run main, import functions or restart UDF server I get a missing DLL error

Run Time error 53 - file not found xlwings32.0.19.2.dll.
ive tried copying it to System32, removing the addin (xlwings addin remove) and reinstalling it

I completely unsinstalled Microsoft office and reinstalled it - the addins was still there anyway !

Sorry a lot of explanation for what is actually a DLL issue, but ive been going around and around for hours.

So in summary, I don't had xlwings under the addins/developer in excel, but it does appear on the ribbon.  I can run a python program that puts "hello world" into excel but excel does not recognise the python function and when I try and interact with excel I get a missing .dll error.

What should I do ? rip out python / accoconda etc and start all over again ?

cheers
Older and Greyer !

答: I don't know if this will fix your problem, I was having the same error with Excel's "sorry you can't have two workbooks of the same name open at the same time" and solved it. The error only happened when the Excel add-in "xlwings" was checked. I fixed the error by moving the location of the xlwings add-in from C:\Users\MYNAME\AppData\Roaming\Microsoft\Excel\XLSTART where it had automatically put itself to C:\Users\MYNAME\AppData\Roaming\Microsoft\AddIns.


问:
How can i show the doctor Name in Laravel
i need some help to solve my problem .
I want to show the name of a doctor with the patient have an appointment with him.
The patient will make an appointment with a doctor, and after when the patient gets connected he must see the list of his appointments.
I get the error : syntax error, unexpected 'endforeach'

This is the index.blade.php

```<code>     @if(Session::has('log_in'))
@foreach($getpatient as $getpat)
    @foreach ($patient as $gp)
     @foreach ($doc as $d)

       @if( $getpat->IDP == $gp->id)
       @if( $getpat->IDD == $d->ID)
    <p> {{$gp->Nom}} {{$gp->Prénom}}  </p>
   <p>  {{$d->Nom}} {{$d->Prénom}} </p>

    @endif
@endforeach
@endforeach

  @endif
</code>```

And this is the controller :

```<code>**  public function  index  () {
        $articles=blog::orderBy('created_at','desc')->paginate(3);
        $ville=Vil::orderBy('Ville','desc')->get();
        $specialité=spec::orderBy('id','desc')->get();
        $pati=patient::orderBy('id','desc')->get();
        $rdvvv=rendezvous::orderBy('id','desc')->get();
        $docdoc=doc::orderBy('id','desc')->get();

        return view ('index',[
              'sp'=>$specialité,
              'vi'=>$ville,
              'pub'=> $articles,
              'getpatient' => $rdvvv,
               'patient' =>$pati,
               'doc'=>$docdoc
        ]);
}**
</code>```

i'm new in laravel and i hope that you can help me
Thank you

答:
i forget to add @endif and @endforeach  , so it would be like this :</p>

```<code> @if(Session::has('log_in'))
     @foreach($getpatient as $getpat)
        @foreach ($patient as $gp)
           @foreach ($doc as $d)

           @if( $getpat->IDP == $gp->id)
         @if( $getpat->IDD == $d->ID)
         <p> {{$gp->Nom}} {{$gp->Prénom}}  </p>
         <p>  {{$d->Nom}} {{$d->Prénom}} </p>
          @endif
        @endif
          @endforeach
      @endforeach
    @endforeach
 @endif
</code>```

Body:
i need some help to solve my problem .
I want to show the name of a doctor with the patient have an appointment with him.
The patient will make an appointment with a doctor, and after when the patient gets connected he must see the list of his appointments.
I get the error : syntax error, unexpected 'endforeach'

This is the index.blade.php

     @if(Session::has('log_in'))
@foreach($getpatient as $getpat)
    @foreach ($patient as $gp)
     @foreach ($doc as $d)

       @if( $getpat->IDP == $gp->id)
       @if( $getpat->IDD == $d->ID)

 {{$gp->Nom}} {{$gp->Prénom}}

  {{$d->Nom}} {{$d->Prénom}}

    @endif
@endforeach
@endforeach

  @endif

And this is the controller :

**  public function  index  () {
        $articles=blog::orderBy('created_at','desc')->paginate(3);
        $ville=Vil::orderBy('Ville','desc')->get();
        $specialité=spec::orderBy('id','desc')->get();
        $pati=patient::orderBy('id','desc')->get();
        $rdvvv=rendezvous::orderBy('id','desc')->get();
        $docdoc=doc::orderBy('id','desc')->get();

        return view ('index',[
              'sp'=>$specialité,
              'vi'=>$ville,
              'pub'=> $articles,
              'getpatient' => $rdvvv,
               'patient' =>$pati,
               'doc'=>$docdoc
        ]);
}**

i'm new in laravel and i hope that you can help me
Thank you

Body:
i forget to add @endif and @endforeach  , so it would be like this :

 @if(Session::has('log_in'))
     @foreach($getpatient as $getpat)
        @foreach ($patient as $gp)
           @foreach ($doc as $d)

           @if( $getpat->IDP == $gp->id)
         @if( $getpat->IDD == $d->ID)
         <p> {{$gp->Nom}} {{$gp->Prénom}}  </p>
         <p>  {{$d->Nom}} {{$d->Prénom}} </p>
          @endif
        @endif
          @endforeach
      @endforeach
    @endforeach
 @endif


问:
Upgrading to Django 3.0: 'django.contrib.admin.templatetags.admin_static': cannot import name 'RemovedInDjango30Warning'
My project was created with Django 2.2 and I would like to upgrade it to use 3. My problem is the same as django error cannot import name 'RemovedInDjango30Warning' . The accepted answer is to manually edit files in the Python packages which I don't think is a good practice(?). The other answers say to downgrade, so is there really no way to upgrade the project without creating it from scratch?</p>

答:
The file where that error is coming from has been removed in Django 3 (https://github.com/django/django/tree/3.0/django/contrib/admin/templatetags has no admin_static.py), so you might not have upgraded properly.

Try to delete your virtualenv and re-create it from scratch.


问:
Windbg: How to show thread details inside thread execute command?
In Windbg, I'm trying to run a set of commands on all threads with ~*e and I want the first command to show the same details I get with ~.

I attempted ~*e .echo DETAILS:; ~. but it give me this output:

```<code>DETAILS:
Ignoring recursive thread command
DETAILS:
Ignoring recursive thread command
DETAILS:
...
</code>```

Yes, I already know about ~*, but I want to show custom information with each thread, and I need this to work inside of ~*e

答:
if it is just the thread identifier you need then use  @$thread Pseudo Register instead of ~.

```<code>0:035> ~*e .printf "DETAILS:%I64x\n" , @$thread
DETAILS:d54d765000
DETAILS:d54d767000
DETAILS:d54d769000
DETAILS:d54d76b000
</code>```

or write a script that uses @$thread

0:035>

```<code> ~*e .printf "%-4x:%-4x TEB:%I64x\n" , @@c++(@$thread->ClientId.UniqueProcess), @@c++(@$thread->ClientId.UniqueThread),@@c++(@$thread->NtTib.Self)
eec :18f8 TEB:d54d765000
eec :f98  TEB:d54d767000
eec :25c4 TEB:d54d769000
eec :2f10 TEB:d54d76b000
eec :1edc TEB:d54d76d000
eec :26a4 TEB:d54d771000
eec :1934 TEB:d54d773000
eec :26fc TEB:d54d775000
eec :2dcc TEB:d54d777000
eec :c50  TEB:d54d779000
eec :5b4  TEB:d54d77d000
</code>```

Body:
In Windbg, I'm trying to run a set of commands on all threads with ~*e and I want the first command to show the same details I get with ~.

I attempted ~*e .echo DETAILS:; ~. but it give me this output:

DETAILS:
Ignoring recursive thread command
DETAILS:
Ignoring recursive thread command
DETAILS:
...

Yes, I already know about ~*, but I want to show custom information with each thread, and I need this to work inside of ~*e

Body:
if it is just the thread identifier you need then use  @$thread Pseudo Register instead of ~.

0:035> ~*e .printf "DETAILS:%I64x\n" , @$thread
DETAILS:d54d765000
DETAILS:d54d767000
DETAILS:d54d769000
DETAILS:d54d76b000

or write a script that uses @$thread

0:035>

 ~*e .printf "%-4x:%-4x TEB:%I64x\n" , @@c++(@$thread->ClientId.UniqueProcess), @@c++(@$thread->ClientId.UniqueThread),@@c++(@$thread->NtTib.Self)
eec :18f8 TEB:d54d765000
eec :f98  TEB:d54d767000
eec :25c4 TEB:d54d769000
eec :2f10 TEB:d54d76b000
eec :1edc TEB:d54d76d000
eec :26a4 TEB:d54d771000
eec :1934 TEB:d54d773000
eec :26fc TEB:d54d775000
eec :2dcc TEB:d54d777000
eec :c50  TEB:d54d779000
eec :5b4  TEB:d54d77d000


问:
Resolving generic interface from generic static method - is using container most simple?
I have a code similar to this:

```<code>    public static IEnumerable<T> ParseInput<T>(string input)
    {
        var xml = XElement.Parse(input);
// some more code here
        var parser = Container.Current.Resolve<IParser<T>>();
        return parser.Parse(xml);
    }
</code>```

It contains some common processing of the data followed by a call to parser interface which is very different between the specializations. Currently, I am resolving the parser interface from a container - but I'm a bit uncomfortable with using a container from a static method.

Is there a better or alternative way to resolve the interface, besides this and the switch statement?

Edit: In my opinion, the shagginess of this comes from an attempt to marry unit-testable OO programming (IoC, no static classes) to functional programming. Where is the cleanest line of separation? Probably resolving the parser earlier and passing it into the static method.

答:
The consensus seems to be that you should resolve the parser first and pass it into the static method. Assuming you already know the T you are parsing, that seems like a fine approach. It simply pushes the responsibility for obtaining the parser instance up one level, into the class which calls ParseInput.

I assume this means you will have code like this:

```<code>var orderParser = new OrderParser();

var orders = InputParser.ParseInput(input, orderParser);
</code>```

Again, this assumes that you know the T you need (Order in this case). If you are parsing things generically, you won't know T, and thus won't know that OrderParser is the class you should use. In this case, you face the same problem: you still need to use either a switch statement or a container to abstract away the various IParser<T> implementations.

Generic Parsing

If this is your situation, you can combine an instance method with a parser factory to avoid referencing a container directly from the consuming class:

```<code>public class InputParser
{
    private readonly IParserFactory _parserFactory;

    public InputParser(IParserFactory parserFactory)
    {
        _parserFactory = parserFactory;
    }

    public IEnumerable<T> ParseInput<T>(string input)
    {
        var xml = XElement.Parse(input);

        // some more code here

        var parser = _parserFactory.CreateParser<T>();

        return parser.Parse(xml);
    }
}
</code>```

The implementation of IParserFactory can handle the communication with the container:

```<code>public sealed class ResolvedParserFactory : IParserFactory
{
    private readonly IContainer _container;

    public ResolvedParserFactory(IContainer container)
    {
        _container = container;
    }

    public IParser<T> CreateParser<T>()
    {
        return _container.Resolve<IParser<T>>();
    }
}
</code>```

Some containers, such as Autofac, may generate this factory for you or provide other ways to decouple the factory class from directly referencing a container.

Non-generic Parsing

If the code which calls ParseInput really does know which T to parse, such as with OrderParser above, you don't need the complexity of a factory. In this case, I have some suggestions for improving the API.

ParseInput is a great candidate for an extension method on IParser<T>. You could also decouple the XML parsing from the other code and T parsing:

```<code>public static IEnumerable<T> ParseInput(this IParser<T> parser, XElement input)
{
    // some more code here

    return parser.Parse(input);
}

public static IEnumerable<T> ParseInput(this IParser<T> parser, string input)
{
    return parser.ParseInput(XElement.Parse(input));
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a code similar to this:

    public static IEnumerable<T> ParseInput<T>(string input)
    {
        var xml = XElement.Parse(input);
// some more code here
        var parser = Container.Current.Resolve<IParser<T>>();
        return parser.Parse(xml);
    }

It contains some common processing of the data followed by a call to parser interface which is very different between the specializations. Currently, I am resolving the parser interface from a container - but I'm a bit uncomfortable with using a container from a static method.

Is there a better or alternative way to resolve the interface, besides this and the switch statement?

Edit: In my opinion, the shagginess of this comes from an attempt to marry unit-testable OO programming (IoC, no static classes) to functional programming. Where is the cleanest line of separation? Probably resolving the parser earlier and passing it into the static method.

Body:
The consensus seems to be that you should resolve the parser first and pass it into the static method. Assuming you already know the T you are parsing, that seems like a fine approach. It simply pushes the responsibility for obtaining the parser instance up one level, into the class which calls ParseInput.

I assume this means you will have code like this:

var orderParser = new OrderParser();

var orders = InputParser.ParseInput(input, orderParser);

Again, this assumes that you know the T you need (Order in this case). If you are parsing things generically, you won't know T, and thus won't know that OrderParser is the class you should use. In this case, you face the same problem: you still need to use either a switch statement or a container to abstract away the various IParser<T> implementations.

Generic Parsing

If this is your situation, you can combine an instance method with a parser factory to avoid referencing a container directly from the consuming class:

public class InputParser
{
    private readonly IParserFactory _parserFactory;

    public InputParser(IParserFactory parserFactory)
    {
        _parserFactory = parserFactory;
    }

    public IEnumerable<T> ParseInput<T>(string input)
    {
        var xml = XElement.Parse(input);

        // some more code here

        var parser = _parserFactory.CreateParser<T>();

        return parser.Parse(xml);
    }
}

The implementation of IParserFactory can handle the communication with the container:

public sealed class ResolvedParserFactory : IParserFactory
{
    private readonly IContainer _container;

    public ResolvedParserFactory(IContainer container)
    {
        _container = container;
    }

    public IParser<T> CreateParser<T>()
    {
        return _container.Resolve<IParser<T>>();
    }
}

Some containers, such as Autofac, may generate this factory for you or provide other ways to decouple the factory class from directly referencing a container.

Non-generic Parsing

If the code which calls ParseInput really does know which T to parse, such as with OrderParser above, you don't need the complexity of a factory. In this case, I have some suggestions for improving the API.

ParseInput is a great candidate for an extension method on IParser<T>. You could also decouple the XML parsing from the other code and T parsing:

public static IEnumerable<T> ParseInput(this IParser<T> parser, XElement input)
{
    // some more code here

    return parser.Parse(input);
}

public static IEnumerable<T> ParseInput(this IParser<T> parser, string input)
{
    return parser.ParseInput(XElement.Parse(input));
}


问:
Most elegant way to store (persist) the value of a single (numeric) variable
I need to store the value of a counter between executions of a script, so I can trigger a specific subroutine every hundred counts. I know I can write my integer into a text file and re-read it, and I know I can pickle my variable to much the same effect (the script currently uses the latter approach).

The concern I have is to find the approach that makes the code as elegant - simple and easily comprehensible - as possible, particularly to a non-technical audience.

The pickle module name is not helpful in that regard - once you grok the metaphor, it is entirely memorable, but if you don't know it, a comment (or verbal explanation) is required to explain that it is a module for serialising Python objects to disk.

Although 'nice to have', I'm not particularly concerned about the atomicity of the storage operation, nor about strongly protecting the stored value from loss [although I do need it to persist through a server reboot].

My interest is elegance of code to access and update the value of my variable, not the elegance of code to initialise whatever is storing the value (so, if the value were to be stored in a file, I'm interested in the code to read and write to a file that already exists and holds a value, not in creating the file on first execution).

What is the most elegant (and/or most pythonic) way to store a single (numeric) value so it persists between executions of a script?

答:
The shelve module of the standard library was designed exactly for this use case: object persistence. Here you can simply do:

```<code>with shelve.open('counter') as db:
    db['value'] = counter
</code>```

It will automatically create that file and store the value of the counter in it.

Body:
The shelve module of the standard library was designed exactly for this use case: object persistence. Here you can simply do:

with shelve.open('counter') as db:
    db['value'] = counter

It will automatically create that file and store the value of the counter in it.


问:
Global setting for AsNoTracking()?
Originally I believed that

```<code>context.Configuration.AutoDetectChangesEnabled = false;
</code>```

would disable change tracking. But no. Currently I need to use AsNoTracking() on all my LINQ queries (for my read only layer). Is there a global setting to disable tracking on the DbContext?

答:
In EntityFramework.Core it is very easy.

For this purpose you can use UseQueryTrackingBehavior method.

Code snippet is here:

```<code>services.AddDbContext<DatabaseContext>(options =>
{
    options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
    options.UseSqlServer(databaseSettings.DefaultConnection);
});
</code>```

Title: Global setting for AsNoTracking()?

Body:
Originally I believed that

context.Configuration.AutoDetectChangesEnabled = false;

would disable change tracking. But no. Currently I need to use AsNoTracking() on all my LINQ queries (for my read only layer). Is there a global setting to disable tracking on the DbContext?

Body:
In EntityFramework.Core it is very easy.

For this purpose you can use UseQueryTrackingBehavior method.

Code snippet is here:

services.AddDbContext<DatabaseContext>(options =>
{
    options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
    options.UseSqlServer(databaseSettings.DefaultConnection);
});


问:
How to select an option from the dropdown menu using Selenium and Python
I am trying to get the fares for all combinations of stations in Metro-North using Selenium in Python. I wanted to go to their fare page, put station names into the select fields, click on the fare button, and then copy the needed values to the dataframe.

I tried all possible options to select stations from the dropdown menu but nothing works as I get the error: ElementNotInteractableException.

The code I tried:

```<code>driver = webdriver.Safari()
driver.get('http://as0.mta.info/mnr/schedules/sched_form.cfm')

select = Select(driver.find_element_by_id('Vorig_station'))
print([o.text for o in select.options])
time.sleep(3)
select.select_by_visible_text('ANSONIA')
element = driver.find_element_by_xpath('//*[@id="frmindex"]/table[2]/tbody/tr[6]/td/input[2]')
element.click()
driver.close()
</code>```

print command shows the options but I cannot choose and go to the next fares page.

Help please!

答:
To get the fares for all combinations of stations in Metro-North using Selenium and python selecting the  option ANSONIA from the From Staion drop-down-menu you need to induce WebDriverWait for the element_to_be_clickable() and you can use the following Locator Strategies:

Using CSS_SELECTOR:

```<code>driver.get("http://as0.mta.info/mnr/schedules/sched_form.cfm")
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "select#Vorig_station"))).click()
select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "select#Vorig_station"))))
print([o.text for o in select.options])
select.select_by_visible_text('ANSONIA')
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[value='fares']"))).click()
</code>```

Using XPATH:

```<code>driver.get("http://as0.mta.info/mnr/schedules/sched_form.cfm")
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//select[@id='Vorig_station']"))).click()
select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//select[@id='Vorig_station']"))))
print([o.text for o in select.options])
select.select_by_visible_text('ANSONIA')
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//input[@value='fares']"))).click()
</code>```

Console Output:

```<code>['ANSONIA', 'APPALACHIAN TRAIL', 'ARDSLEY-ON-HUDSON', 'BEACON', 'BEACON FALLS', 'BEDFORD HILLS', 'BETHEL', 'BOTANICAL GARDEN', 'BRANCHVILLE', 'BREAKNECK RIDGE', 'BREWSTER', 'BRIDGEPORT', 'BRONXVILLE', 'CANNONDALE', 'CHAPPAQUA', 'COLD SPRING', 'CORTLANDT', 'COS COB', 'CRESTWOOD', 'CROTON FALLS', 'CROTON-HARMON', 'DANBURY', 'DARIEN', 'DERBY', 'DOBBS FERRY', 'DOVER PLAINS', 'EAST NORWALK', 'FAIRFIELD', 'FAIRFIELD METRO', 'FLEETWOOD', 'FORDHAM', 'GARRISON', 'GLENBROOK', 'GLENWOOD', 'GOLDENS BRIDGE', 'GRAND CENTRAL', "GREEN'S FARMS", 'GREENWICH', 'GREYSTONE', 'HARLEM - 125TH ST.', 'HARLEM VALLEY-WINGDALE', 'HARRISON', 'HARTSDALE', 'HASTINGS-ON-HUDSON', 'HAWTHORNE', 'IRVINGTON', 'KATONAH', 'LARCHMONT', 'LUDLOW', 'MAMARONECK', 'MANITOU', 'MARBLE HILL', 'MEADOWLANDS SPORTS COMPLEX', 'MELROSE', 'MERRITT 7', 'MILFORD', 'MORRIS HEIGHTS', 'MOUNT KISCO', 'MOUNT PLEASANT', 'MT VERNON EAST ', 'MT VERNON WEST', 'NAUGATUCK', 'NEW CANAAN', 'NEW HAMBURG', 'NEW HAVEN', 'NEW ROCHELLE', 'NH-STATE ST.', 'NOROTON HEIGHTS', 'NORTH WHITE PLAINS', 'OLD GREENWICH', 'OSSINING', 'PATTERSON', 'PAWLING', 'PEEKSKILL', 'PELHAM', 'PHILIPSE MANOR', 'PLEASANTVILLE', 'PORT CHESTER', 'POUGHKEEPSIE', "PURDY'S", 'REDDING', 'RIVERDALE', 'RIVERSIDE', 'ROWAYTON', 'RYE', 'SCARBOROUGH', 'SCARSDALE', 'SEYMOUR', 'SOUTH NORWALK', 'SOUTHEAST', 'SOUTHPORT', 'SPRINGDALE', 'SPUYTEN DUYVIL', 'STAMFORD', 'STRATFORD', 'TALMADGE HILL', 'TARRYTOWN', 'TENMILE RIVER', 'TREMONT', 'TUCKAHOE', 'UNIVERSITY HEIGHTS', 'VALHALLA', 'WAKEFIELD', 'WASSAIC', 'WATERBURY', 'WEST HAVEN', 'WESTPORT', 'WHITE PLAINS', 'WILLIAMS BRIDGE', 'WILTON', 'WOODLAWN', 'YANKEES-E153 ST.', 'YONKERS']
</code>```

Note : You have to add the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import Select
</code>```

Browser Snapshot:

Body:
I am trying to get the fares for all combinations of stations in Metro-North using Selenium in Python. I wanted to go to their fare page, put station names into the select fields, click on the fare button, and then copy the needed values to the dataframe.

I tried all possible options to select stations from the dropdown menu but nothing works as I get the error: ElementNotInteractableException.

The code I tried:

driver = webdriver.Safari()
driver.get('http://as0.mta.info/mnr/schedules/sched_form.cfm')

select = Select(driver.find_element_by_id('Vorig_station'))
print([o.text for o in select.options])
time.sleep(3)
select.select_by_visible_text('ANSONIA')
element = driver.find_element_by_xpath('//*[@id="frmindex"]/table[2]/tbody/tr[6]/td/input[2]')
element.click()
driver.close()

print command shows the options but I cannot choose and go to the next fares page.

Help please!

Body:
To get the fares for all combinations of stations in Metro-North using Selenium and python selecting the  option ANSONIA from the From Staion drop-down-menu you need to induce WebDriverWait for the element_to_be_clickable() and you can use the following Locator Strategies:

Using CSS_SELECTOR:

driver.get("http://as0.mta.info/mnr/schedules/sched_form.cfm")
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "select#Vorig_station"))).click()
select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "select#Vorig_station"))))
print([o.text for o in select.options])
select.select_by_visible_text('ANSONIA')
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[value='fares']"))).click()

Using XPATH:

driver.get("http://as0.mta.info/mnr/schedules/sched_form.cfm")
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//select[@id='Vorig_station']"))).click()
select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//select[@id='Vorig_station']"))))
print([o.text for o in select.options])
select.select_by_visible_text('ANSONIA')
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//input[@value='fares']"))).click()

Console Output:

['ANSONIA', 'APPALACHIAN TRAIL', 'ARDSLEY-ON-HUDSON', 'BEACON', 'BEACON FALLS', 'BEDFORD HILLS', 'BETHEL', 'BOTANICAL GARDEN', 'BRANCHVILLE', 'BREAKNECK RIDGE', 'BREWSTER', 'BRIDGEPORT', 'BRONXVILLE', 'CANNONDALE', 'CHAPPAQUA', 'COLD SPRING', 'CORTLANDT', 'COS COB', 'CRESTWOOD', 'CROTON FALLS', 'CROTON-HARMON', 'DANBURY', 'DARIEN', 'DERBY', 'DOBBS FERRY', 'DOVER PLAINS', 'EAST NORWALK', 'FAIRFIELD', 'FAIRFIELD METRO', 'FLEETWOOD', 'FORDHAM', 'GARRISON', 'GLENBROOK', 'GLENWOOD', 'GOLDENS BRIDGE', 'GRAND CENTRAL', "GREEN'S FARMS", 'GREENWICH', 'GREYSTONE', 'HARLEM - 125TH ST.', 'HARLEM VALLEY-WINGDALE', 'HARRISON', 'HARTSDALE', 'HASTINGS-ON-HUDSON', 'HAWTHORNE', 'IRVINGTON', 'KATONAH', 'LARCHMONT', 'LUDLOW', 'MAMARONECK', 'MANITOU', 'MARBLE HILL', 'MEADOWLANDS SPORTS COMPLEX', 'MELROSE', 'MERRITT 7', 'MILFORD', 'MORRIS HEIGHTS', 'MOUNT KISCO', 'MOUNT PLEASANT', 'MT VERNON EAST ', 'MT VERNON WEST', 'NAUGATUCK', 'NEW CANAAN', 'NEW HAMBURG', 'NEW HAVEN', 'NEW ROCHELLE', 'NH-STATE ST.', 'NOROTON HEIGHTS', 'NORTH WHITE PLAINS', 'OLD GREENWICH', 'OSSINING', 'PATTERSON', 'PAWLING', 'PEEKSKILL', 'PELHAM', 'PHILIPSE MANOR', 'PLEASANTVILLE', 'PORT CHESTER', 'POUGHKEEPSIE', "PURDY'S", 'REDDING', 'RIVERDALE', 'RIVERSIDE', 'ROWAYTON', 'RYE', 'SCARBOROUGH', 'SCARSDALE', 'SEYMOUR', 'SOUTH NORWALK', 'SOUTHEAST', 'SOUTHPORT', 'SPRINGDALE', 'SPUYTEN DUYVIL', 'STAMFORD', 'STRATFORD', 'TALMADGE HILL', 'TARRYTOWN', 'TENMILE RIVER', 'TREMONT', 'TUCKAHOE', 'UNIVERSITY HEIGHTS', 'VALHALLA', 'WAKEFIELD', 'WASSAIC', 'WATERBURY', 'WEST HAVEN', 'WESTPORT', 'WHITE PLAINS', 'WILLIAMS BRIDGE', 'WILTON', 'WOODLAWN', 'YANKEES-E153 ST.', 'YONKERS']

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import Select

Browser Snapshot:


问:
MS Access multiple filter in the same field satisfying all of them
I am fairly new to access. I have a table similar to the following
enter image description here
I am trying to create a query that shows suppliers that are capable of BOTH Grinding and Milling.
This the outcome I am Hopping to get

```<code>A    Grinding
A    Milling
B    Grinding
B    Milling
</code>```

and Ignore the rest. Any help?

答:
If you wanted to find out just the suppliers with both capabilities, you would join your table to itself like so:

```<code>SELECT Table1.Supplier
FROM Table1 INNER JOIN Table1 AS Table1_1 ON Table1.Supplier = Table1_1.Supplier
WHERE Table1.Capability="Grinding" AND Table1_1.Capability="Milling"
</code>```

Your result for that however will just be:

```<code>A
B
</code>```

If you wanted to include the capabilities on separate rows then you have to link the table one more time to itself like so:

```<code>SELECT Table1.Supplier, Table1_2.Capability
FROM (Table1 INNER JOIN Table1 AS Table1_1 ON Table1.Supplier = Table1_1.Supplier)
INNER JOIN Table1 AS Table1_2 ON Table1.Supplier = Table1_2.Supplier
WHERE Table1.Capability="Grinding" AND Table1_1.Capability="Milling"
</code>```

And your result will be:

```<code>A   Milling
A   Grinding
B   Milling
B   Grinding
</code>```

Body:
I am fairly new to access. I have a table similar to the following
enter image description here
I am trying to create a query that shows suppliers that are capable of BOTH Grinding and Milling.
This the outcome I am Hopping to get

A    Grinding
A    Milling
B    Grinding
B    Milling

and Ignore the rest. Any help?

Body:
If you wanted to find out just the suppliers with both capabilities, you would join your table to itself like so:

SELECT Table1.Supplier
FROM Table1 INNER JOIN Table1 AS Table1_1 ON Table1.Supplier = Table1_1.Supplier
WHERE Table1.Capability="Grinding" AND Table1_1.Capability="Milling"

Your result for that however will just be:

A
B

If you wanted to include the capabilities on separate rows then you have to link the table one more time to itself like so:

SELECT Table1.Supplier, Table1_2.Capability
FROM (Table1 INNER JOIN Table1 AS Table1_1 ON Table1.Supplier = Table1_1.Supplier)
INNER JOIN Table1 AS Table1_2 ON Table1.Supplier = Table1_2.Supplier
WHERE Table1.Capability="Grinding" AND Table1_1.Capability="Milling"

And your result will be:

A   Milling
A   Grinding
B   Milling
B   Grinding


问:
ggplot2: x axis breaks doesn't work with 7 days breaks
I'm trying to figure it out why this function for x axis breaks works perfectly for 2 to 6 days breaks, but gives me an error when I change to 7 days (Error: breaks and labels must have the same length). Thank you

Data Frame

```<code>library(tidyverse)

    df <- data.frame(date = seq(as.Date("2019-01-01"), as.Date("2019-12-31"), by = "day"))
    df$counts <-sample(seq(from = 20, to = 50, by = 5), size = 365, replace = TRUE)

    df<- df %>%
    mutate(date = as.Date(date),
           counts = as.numeric(counts))

</code>```

Code

```<code>    breaks_daily = seq(from = min(df$date), to = max(df$date), by = "1 day")

    # Then make the 7 days interval labels
    labels_7_days = format(seq(from = min(df$date), to = max(df$date), by = "7 days"), "%b-%d")
    labels_final = c(sapply(labels_7_days, function(x) {
      c(x, rep("", 6))
    }))
    #

     if ((length(breaks_daily) %% 7) == 0) {
        labels_final <- labels_final
      } else {
        labels_final<- labels_final[-length(labels_final)]
     }

    myplot <- ggplot(df,
                       aes(y = counts, x = date)) +
      geom_bar(stat = "identity", position = "dodge", fill = "#99CCFF", width=1) +
      labs(x="Date", y="Quantity of Fruits") +

      scale_x_date(labels = labels_final, breaks = breaks_daily, expand=c(0,0)) +
      scale_y_continuous(limits = c(0, 70),
                         breaks = seq(0, 70, 10),
                         expand = c(0, 0)) +
      ggtitle(paste0("Figure 2: Fruits Example" )) +

      theme(axis.text.x = element_text(angle = 90, vjust = 0.5, size = 35),
            axis.text.y = element_text(size = 35),
            axis.text = element_text(size = 35),
            axis.title = element_text(size = 40, face="bold"),
            axis.title.y = element_text(vjust = -2),
            axis.title.x =  element_text(vjust = -1),
            axis.ticks.length = unit(.5, "cm"))

    myplot
</code>```

答:
Not a direct answer to your question, but why don't you just use the inbuilt functionality? Sometimes it is not necessary to reinvent the wheel... ?

library(tidyverse)
df <- data.frame(date = seq(as.Date("2019-01-01"), as.Date("2019-12-31"), by = "day"))
df$counts <-sample(seq(from = 20, to = 50, by = 5), size = 365, replace = TRUE)

ggplot(df, aes(y = counts, x = date)) +
  geom_col() +
  scale_x_date(date_breaks = "1 week",date_labels = "%b %d")+
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5))
```

<p><img src="https://i.imgur.com/8FvySw1.png" alt=""></p>

<p><strong>update</strong></p>

<p>Here how to keep the ticks in-between (although I don't think your visualisation gains a lot with it)
You need to bring the two vectors to the same length. When using your label creator, you are creating six empty spaces for each week until the maximum (and including it!), then of course making "too many labels". Just subset the vector by using only the length of your breaks. </p>

<p>P.S. <code>geom_col</code> is identical to <code>geom_bar(stat = "identity")</code> , and in your example you don't need <code>position = position_dodge</code>, as you have no group defined. This argument only makes sense when you are dodging by a group. </p>

<pre class="lang-r prettyprint-override"><code>library(tidyverse)
df <- data.frame(date = seq(as.Date("2019-01-01"), as.Date("2019-12-31"), by = "day"))
df$counts <-sample(seq(from = 20, to = 50, by = 5), size = 365, replace = TRUE)

breaks_daily <- seq(from = min(df$date), to = max(df$date), by = "1 day")

labels_7_days <- format(seq(from = min(df$date), to = max(df$date), by = "7 days"), "%b-%d")
labels_final <- c(sapply(labels_7_days, function(x) {
  c(x, rep("", 6))
})) [1:length(breaks_daily)] #that is the crucial bit

ggplot(df, aes(y = counts, x = date)) +
  geom_col(fill = "#99CCFF", width=1) +
  labs(x="Date", y="Quantity of Fruits") +
  scale_x_date(labels = labels_final, breaks = breaks_daily, expand=c(0,0)) +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5))
</code>```

Created on 2020-05-30 by the reprex package (v0.3.0)

Body:
I'm trying to figure it out why this function for x axis breaks works perfectly for 2 to 6 days breaks, but gives me an error when I change to 7 days (Error: breaks and labels must have the same length). Thank you

Data Frame

library(tidyverse)

    df <- data.frame(date = seq(as.Date("2019-01-01"), as.Date("2019-12-31"), by = "day"))
    df$counts <-sample(seq(from = 20, to = 50, by = 5), size = 365, replace = TRUE)

    df<- df %>%
    mutate(date = as.Date(date),
           counts = as.numeric(counts))

Code

    breaks_daily = seq(from = min(df$date), to = max(df$date), by = "1 day")

    # Then make the 7 days interval labels
    labels_7_days = format(seq(from = min(df$date), to = max(df$date), by = "7 days"), "%b-%d")
    labels_final = c(sapply(labels_7_days, function(x) {
      c(x, rep("", 6))
    }))
    #

     if ((length(breaks_daily) %% 7) == 0) {
        labels_final <- labels_final
      } else {
        labels_final<- labels_final[-length(labels_final)]
     }

    myplot <- ggplot(df,
                       aes(y = counts, x = date)) +
      geom_bar(stat = "identity", position = "dodge", fill = "#99CCFF", width=1) +
      labs(x="Date", y="Quantity of Fruits") +

      scale_x_date(labels = labels_final, breaks = breaks_daily, expand=c(0,0)) +
      scale_y_continuous(limits = c(0, 70),
                         breaks = seq(0, 70, 10),
                         expand = c(0, 0)) +
      ggtitle(paste0("Figure 2: Fruits Example" )) +

      theme(axis.text.x = element_text(angle = 90, vjust = 0.5, size = 35),
            axis.text.y = element_text(size = 35),
            axis.text = element_text(size = 35),
            axis.title = element_text(size = 40, face="bold"),
            axis.title.y = element_text(vjust = -2),
            axis.title.x =  element_text(vjust = -1),
            axis.ticks.length = unit(.5, "cm"))

    myplot

Body:
Not a direct answer to your question, but why don't you just use the inbuilt functionality? Sometimes it is not necessary to reinvent the wheel... ?

library(tidyverse)
df <- data.frame(date = seq(as.Date("2019-01-01"), as.Date("2019-12-31"), by = "day"))
df$counts <-sample(seq(from = 20, to = 50, by = 5), size = 365, replace = TRUE)

ggplot(df, aes(y = counts, x = date)) +
  geom_col() +
  scale_x_date(date_breaks = "1 week",date_labels = "%b %d")+
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5))

update

Here how to keep the ticks in-between (although I don't think your visualisation gains a lot with it)
You need to bring the two vectors to the same length. When using your label creator, you are creating six empty spaces for each week until the maximum (and including it!), then of course making "too many labels". Just subset the vector by using only the length of your breaks.

P.S. geom_col is identical to geom_bar(stat = "identity") , and in your example you don't need position = position_dodge, as you have no group defined. This argument only makes sense when you are dodging by a group.

library(tidyverse)
df <- data.frame(date = seq(as.Date("2019-01-01"), as.Date("2019-12-31"), by = "day"))
df$counts <-sample(seq(from = 20, to = 50, by = 5), size = 365, replace = TRUE)

breaks_daily <- seq(from = min(df$date), to = max(df$date), by = "1 day")

labels_7_days <- format(seq(from = min(df$date), to = max(df$date), by = "7 days"), "%b-%d")
labels_final <- c(sapply(labels_7_days, function(x) {
  c(x, rep("", 6))
})) [1:length(breaks_daily)] #that is the crucial bit

ggplot(df, aes(y = counts, x = date)) +
  geom_col(fill = "#99CCFF", width=1) +
  labs(x="Date", y="Quantity of Fruits") +
  scale_x_date(labels = labels_final, breaks = breaks_daily, expand=c(0,0)) +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5))

Created on 2020-05-30 by the reprex package (v0.3.0)


问:
Images in HTML keep stacking vertically outside of division
I am trying to create a background image that scales with the size of the division. The images I am using need to be laid out in a 3X3 grid with the corners remaining fixed in size and the other parts expanding to fit the division.

However, when I try to place the images they all keep stacking vertically and not relative to the division they are in.

The test pattern should have the corners as blue, the edges as red, and the middle as orange.

body {
  background-color:black
}
#test > #Background_UL {
  background-color: powderblue;
  background-size: 40px 40px;
  height: 40px;
  width: 40px;
  position: relative;
}

#test > #Background_ML {
  background-color: red;
  background-size: 100% 100%;
  height: calc(100% - 80px);
  width: 40px;
  position: relative;
}

#test > #Background_LL {
  background-color: powderblue;
  background-size: 40px 40px;
  height: 40px;
  width: 40px;
  position: relative;
}

#test > #Background_UM {
  background-color: red;
  background-size: 100% 100%;
  height: 40px;
  width: calc(100% - 80px);
  top: 0;
  position: relative;
  left: 40px;
}

#test > #Background_MM {
  background-color: orange;
  background-size: 100% 100%;
  height: calc(100% - 80px);
  width: calc(100% - 80px);
  top: 40px;
  position: relative;
  left: 40px;
}

#test > #Background_LM {
  background-color: red;
  background-size: 100% 100%;
  height: 40px;
  width: calc(100% - 80px);
  bottom: 0;
  position: relative;
  left: 40px;
}

#test > #Background_UR {
  background-color: powderblue;
  background-size: 40px 40px;
  height: 40px;
  width: 40px;
  position: relative;
  right: 40px;
}

#test > #Background_MR {
  background-color: red;
  background-size: 100% 100%;
  height: calc(100% - 80px);
  width: 40px;
  position: relative;
  right: 40px;
}

#test > #Background_LR {
  background-color: powderblue;
  background-size: 40px 40px;
  height: 40px;
  width: 40px;
  position: relative;
  right: 40px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="test" style="width:400px;height:400px;">
  <div id="Background_UL"></div>
  <div id="Background_ML"></div>
  <div id="Background_LL"></div>
  <div id="Background_UM"></div>
  <div id="Background_MM"></div>
  <div id="Background_LM"></div>
  <div id="Background_UR"></div>
  <div id="Background_MR"></div>
  <div id="Background_LR"></div>
</div></code>```

Example

答:
You can achieve this quite easily with a display: grid; on the container and specify the grid-template-columns and grid-template-columns and a lot less code is needed. You also need to reorganize your divs as well to go from left to right then trunkate downwards.  The important code I added is this:

```<code>#test {
  display: grid;
  grid-template-columns: 40px auto 40px;
  grid-template-rows: 40px auto 40px;
}
</code>```

Please see this example I made for you:

body {
  background-color:black
}
#test > #Background_UL {
  background-color: powderblue;
}

#test > #Background_ML {
  background-color: red;
}

#test > #Background_LL {
  background-color: powderblue;
}

#test > #Background_UM {
  background-color: red;
}

#test > #Background_MM {
  background-color: orange;
}

#test > #Background_LM {
  background-color: red;
}

#test > #Background_UR {
  background-color: powderblue;

}

#test > #Background_MR {
  background-color: red;

}

#test > #Background_LR {
  background-color: powderblue;
}

#test {
  display: grid;
  grid-template-columns: 40px auto 40px;
  grid-template-rows: 40px auto 40px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="test" style="width:400px;height:400px;">
  <div id="Background_UL"></div>
  <div id="Background_UM"></div>
  <div id="Background_UR"></div>
  <div id="Background_ML"></div>
  <div id="Background_MM"></div>
  <div id="Background_MR"></div>
  <div id="Background_LL"></div>
  <div id="Background_LM"></div>
  <div id="Background_LR"></div>
</div></code>```

Body:
I am trying to create a background image that scales with the size of the division. The images I am using need to be laid out in a 3X3 grid with the corners remaining fixed in size and the other parts expanding to fit the division.

However, when I try to place the images they all keep stacking vertically and not relative to the division they are in.

The test pattern should have the corners as blue, the edges as red, and the middle as orange.

body {
  background-color:black
}
#test > #Background_UL {
  background-color: powderblue;
  background-size: 40px 40px;
  height: 40px;
  width: 40px;
  position: relative;
}

#test > #Background_ML {
  background-color: red;
  background-size: 100% 100%;
  height: calc(100% - 80px);
  width: 40px;
  position: relative;
}

#test > #Background_LL {
  background-color: powderblue;
  background-size: 40px 40px;
  height: 40px;
  width: 40px;
  position: relative;
}

#test > #Background_UM {
  background-color: red;
  background-size: 100% 100%;
  height: 40px;
  width: calc(100% - 80px);
  top: 0;
  position: relative;
  left: 40px;
}

#test > #Background_MM {
  background-color: orange;
  background-size: 100% 100%;
  height: calc(100% - 80px);
  width: calc(100% - 80px);
  top: 40px;
  position: relative;
  left: 40px;
}

#test > #Background_LM {
  background-color: red;
  background-size: 100% 100%;
  height: 40px;
  width: calc(100% - 80px);
  bottom: 0;
  position: relative;
  left: 40px;
}

#test > #Background_UR {
  background-color: powderblue;
  background-size: 40px 40px;
  height: 40px;
  width: 40px;
  position: relative;
  right: 40px;
}

#test > #Background_MR {
  background-color: red;
  background-size: 100% 100%;
  height: calc(100% - 80px);
  width: 40px;
  position: relative;
  right: 40px;
}

#test > #Background_LR {
  background-color: powderblue;
  background-size: 40px 40px;
  height: 40px;
  width: 40px;
  position: relative;
  right: 40px;
}

Example

Body:
You can achieve this quite easily with a display: grid; on the container and specify the grid-template-columns and grid-template-columns and a lot less code is needed. You also need to reorganize your divs as well to go from left to right then trunkate downwards.  The important code I added is this:

#test {
  display: grid;
  grid-template-columns: 40px auto 40px;
  grid-template-rows: 40px auto 40px;
}

Please see this example I made for you:

body {
  background-color:black
}
#test > #Background_UL {
  background-color: powderblue;
}

#test > #Background_ML {
  background-color: red;
}

#test > #Background_LL {
  background-color: powderblue;
}

#test > #Background_UM {
  background-color: red;
}

#test > #Background_MM {
  background-color: orange;
}

#test > #Background_LM {
  background-color: red;
}

#test > #Background_UR {
  background-color: powderblue;

}

#test > #Background_MR {
  background-color: red;

}

#test > #Background_LR {
  background-color: powderblue;
}

#test {
  display: grid;
  grid-template-columns: 40px auto 40px;
  grid-template-rows: 40px auto 40px;
}

<div id="test" style="width:400px;height:400px;">
  <div id="Background_UL"></div>
  <div id="Background_UM"></div>
  <div id="Background_UR"></div>
  <div id="Background_ML"></div>
  <div id="Background_MM"></div>
  <div id="Background_MR"></div>
  <div id="Background_LL"></div>
  <div id="Background_LM"></div>
  <div id="Background_LR"></div>
</div>


问:
Getting "hexadecimal value 0x3C, is an invalid attribute character" in correct Japanese XML
All, I'm getting

hexadecimal value 0x3C, is an invalid attribute character

error while trying to read XML on computer with Japanese locale and Japanese characters in the file:

```<code>  $xml = [xml]@(Get-Content $file)
</code>```

Specific place in the XML is pretty benign:

```<code><Control type="select">
</code>```

As far as I can tell almost every error like that is caused by "<" somewhere in the string. So I checked my XML and did not see any extra "<" where it shouldn't be.
But then I've found one hotfix description that says this:

Consider the following scenario: You have a computer that is running Windows Server 2012. The system locale setting of the computer is set
  to Japanese. You install the Network Policy and Access Services (NPAS)
  server role with default settings on the computer. You try to run the
  Best Practices Analyzer tool to scan Network Access Protection (NAP)
  components.

Kinda sounds familiar, so I suspect it's due to Japanese locale or due to Japanese characters in some of the values for the XML.

The file itself starts like this:

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

Any ideas?

答:
What helped in this case was explicitly specifying encoding when getting file contents:</p>

```<code> $xml = [xml]@(Get-Content $file -Encoding UTF8)
</code>```

Body:
All, I'm getting

hexadecimal value 0x3C, is an invalid attribute character

error while trying to read XML on computer with Japanese locale and Japanese characters in the file:

  $xml = [xml]@(Get-Content $file)

Specific place in the XML is pretty benign:

<Control type="select">

As far as I can tell almost every error like that is caused by "<" somewhere in the string. So I checked my XML and did not see any extra "<" where it shouldn't be.
But then I've found one hotfix description that says this:

Consider the following scenario: You have a computer that is running Windows Server 2012. The system locale setting of the computer is set
  to Japanese. You install the Network Policy and Access Services (NPAS)
  server role with default settings on the computer. You try to run the
  Best Practices Analyzer tool to scan Network Access Protection (NAP)
  components.

Kinda sounds familiar, so I suspect it's due to Japanese locale or due to Japanese characters in some of the values for the XML.

The file itself starts like this:

<?xml version="1.0" encoding="utf-8"?>

Any ideas?

Body:
What helped in this case was explicitly specifying encoding when getting file contents:

 $xml = [xml]@(Get-Content $file -Encoding UTF8)


问:
Javascript form validation
How do I let users know that "there are changes left to be saved on the form if they try to close the browser window?"

I have a form with couple of fields, Now if the user changes some of the fields and clicks on Close button on the browser window, my script should alert him of unsaved changes. How do I implement this? I have put in basic form validation but can't seem to think of a solution for window.close() event. Any sample links would be helpful.

答:
Equivalent, but in JavaScript you could do something like:

```<code>if ( undefined !== window.onbeforeunload )
{
    window.onbeforeunload = function ()
    {
        var f = window.onbeforeunload;
        var ret = f();
        if (ret)
        {
            return doValidation();
        } else
        {
            return false;
        }
    };
} else
{
    window.onbeforeunload = function ()
    {
        return doValidation();
    };
}
</code>```

where doValidation() is your custom validation function.

Title: Javascript form validation

Body:
Equivalent, but in JavaScript you could do something like:

if ( undefined !== window.onbeforeunload )
{
    window.onbeforeunload = function ()
    {
        var f = window.onbeforeunload;
        var ret = f();
        if (ret)
        {
            return doValidation();
        } else
        {
            return false;
        }
    };
} else
{
    window.onbeforeunload = function ()
    {
        return doValidation();
    };
}

where doValidation() is your custom validation function.


问:
How to send signal to running gtk process
I'm making a gtk application in C that once executed, I want to be able to somehow contact the process (hopefully from python) and tell it to execute a function.
I have everything else working, just need some way to execute a function from outside the process.

Current main (based on gtk tutorial):

```<code>int
main (int    argc,
      char **argv)
{
  GtkApplication *app;
  int status;
  app = gtk_application_new(NULL, G_APPLICATION_FLAGS_NONE);

  custom_setup();
  g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);

  status = g_application_run (G_APPLICATION (app), NULL, NULL);
  g_object_unref (app);

  return status;
}
</code>```

Thank you.

答:
Your app will have to expose a DBus interface to other apps, with a method they can call which executes your function.

A nice shortcut to doing this is to add a GAction to your app, which is described here. Then other apps can call the org.gtk.Actions.Activate DBus method to activate the GAction and execute your function.

Body:
I'm making a gtk application in C that once executed, I want to be able to somehow contact the process (hopefully from python) and tell it to execute a function.
I have everything else working, just need some way to execute a function from outside the process.

Current main (based on gtk tutorial):

int
main (int    argc,
      char **argv)
{
  GtkApplication *app;
  int status;
  app = gtk_application_new(NULL, G_APPLICATION_FLAGS_NONE);

  custom_setup();
  g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);

  status = g_application_run (G_APPLICATION (app), NULL, NULL);
  g_object_unref (app);

  return status;
}

Thank you.


问:
How to search for a single word in multiple gvim files from the command line?
I want to open up multiple files in different tabs and search for the same word in all of them. Then I want to jump to the first occurrence of the found word in each file.

Doing this works, but it doesn't jump to the first occurrence:

```<code>gvim -p -cmd "/word" file1 file2 file3 file4 file5 file6 file7
</code>```

I need to manually press 'n' to go to the next match.

答:
You might be interested in :grep and :vimgrep, which populate the quickfix list:

```<code>$ gvim file*
:vimgrep /pattern/ ##
</code>```

The ## means search the argument list, which you can view with :args. It’s what :next and :prev use.

Now, you can navigate the searches with :cnext and :cprev; or, you can open the quickfix window :copen and hit enter on any line.

You could still pop open all the files in tabs with :cfdo tabedit but at this point it might not be necessary!

Body:
I want to open up multiple files in different tabs and search for the same word in all of them. Then I want to jump to the first occurrence of the found word in each file.

Doing this works, but it doesn't jump to the first occurrence:

gvim -p -cmd "/word" file1 file2 file3 file4 file5 file6 file7

I need to manually press 'n' to go to the next match.

Body:
You might be interested in :grep and :vimgrep, which populate the quickfix list:

$ gvim file*
:vimgrep /pattern/ ##

The ## means search the argument list, which you can view with :args. It’s what :next and :prev use.

Now, you can navigate the searches with :cnext and :cprev; or, you can open the quickfix window :copen and hit enter on any line.

You could still pop open all the files in tabs with :cfdo tabedit but at this point it might not be necessary!


问:
Im making a quiz using windows forms and C# but it keeps displaying the same question
It reads in questions/answers/topics etc from a .txt file and stores it in an array called ‘questionArray’ which is split by commas into another array called ‘splitDetails’. The if statement selects questions of a particular difficulty level and topic from the list and creates a new question ‘newQ’ of type MultipleChoice which has properties like QuestionText, Choice1, Choice2 etc. and its added to a list called ‘allQuestions’. populateTextboxes() picks a random question from the ‘allQuestions’ list and sets it to the object ‘currentQ’ which is of type MultipleChoice, then deletes it from the list so it isn’t shown again. </p>

```<code>{
if (File.Exists("MultipleChoice questions.txt")) //checking file exists
{
   string[] questionArray = File.ReadAllLines("MultipleChoice questions.txt"); //create array of all questions

   foreach (string Q in questionArray)
   {
        string[] splitDetails = Q.Split(',');  //create new array split by commas
if (splitDetails[6] == Quiz.DifficultyLevel && splitDetails[7] == Quiz.CurrentTopic)
       {
            newQ.QuestionText = splitDetails[0];
              newQ.Choice1 = splitDetails[1];
              newQ.Choice2 = splitDetails[2];
              newQ.Choice3 = splitDetails[3];
              newQ.Choice4 = splitDetails[4];
              newQ.Answer = splitDetails[5];
              newQ.Difficulty = splitDetails[6];
              newQ.Topic = splitDetails[7];
              newQ.QuestionType = splitDetails[8];

              allQuestions.Add(newQ);

         }
      }
   }
   Else MessageBox.Show("No question file found", "File not found");
}

//add text to blank question form
public MultipleChoice populateTextboxes()
{
  Random myNum = new Random();

  if (allQuestions.Count > 0)
  {
    questionCount += 1;

       //select random question from all questions
       int randomNumber = myNum.Next(0, allQuestions.Count);
       currentQ = allQuestions[randomNumber];
       allQuestions.Remove(currentQ);//remove used uestion so it isnt used again
  }

  //when the round is over (3 questions asked)
  if (questionCount == 4)
  {
    //open keyboardQuestion
    this.Close();
    KeyboardInput k = new KeyboardInput();
    k.Show();

   }

   lblQuestion.Text = currentQ.QuestionText;
   btnChoice1.Text = currentQ.Choice1;
   btnChoice2.Text = currentQ.Choice2;
   btnChoice3.Text = currentQ.Choice3;
   btnChoice4.Text = currentQ.Choice4;

   return currentQ;
}

</code>```

答:
I bet it always displays the last question?

If newQ is globally declared, then that code is going to generate a bunch of different questions that are in fact all composed of a same object. The line allQuestions.add() will keep adding the same object to the collection. You can change one of the properties before or after adding it to collection and it will change in all the questions. Imagine 10 people reading the same newspapers article. What you want is 1 person reading 10 different articles, really.

Declare newQ locally, inside foreach() loop, and it will result in creating a new object with unique properties during each iteration.

Body:
It reads in questions/answers/topics etc from a .txt file and stores it in an array called ‘questionArray’ which is split by commas into another array called ‘splitDetails’. The if statement selects questions of a particular difficulty level and topic from the list and creates a new question ‘newQ’ of type MultipleChoice which has properties like QuestionText, Choice1, Choice2 etc. and its added to a list called ‘allQuestions’. populateTextboxes() picks a random question from the ‘allQuestions’ list and sets it to the object ‘currentQ’ which is of type MultipleChoice, then deletes it from the list so it isn’t shown again.

{
if (File.Exists("MultipleChoice questions.txt")) //checking file exists
{
   string[] questionArray = File.ReadAllLines("MultipleChoice questions.txt"); //create array of all questions

   foreach (string Q in questionArray)
   {
        string[] splitDetails = Q.Split(',');  //create new array split by commas
if (splitDetails[6] == Quiz.DifficultyLevel && splitDetails[7] == Quiz.CurrentTopic)
       {
            newQ.QuestionText = splitDetails[0];
              newQ.Choice1 = splitDetails[1];
              newQ.Choice2 = splitDetails[2];
              newQ.Choice3 = splitDetails[3];
              newQ.Choice4 = splitDetails[4];
              newQ.Answer = splitDetails[5];
              newQ.Difficulty = splitDetails[6];
              newQ.Topic = splitDetails[7];
              newQ.QuestionType = splitDetails[8];

              allQuestions.Add(newQ);

         }
      }
   }
   Else MessageBox.Show("No question file found", "File not found");
}

//add text to blank question form
public MultipleChoice populateTextboxes()
{
  Random myNum = new Random();

  if (allQuestions.Count > 0)
  {
    questionCount += 1;

       //select random question from all questions
       int randomNumber = myNum.Next(0, allQuestions.Count);
       currentQ = allQuestions[randomNumber];
       allQuestions.Remove(currentQ);//remove used uestion so it isnt used again
  }

  //when the round is over (3 questions asked)
  if (questionCount == 4)
  {
    //open keyboardQuestion
    this.Close();
    KeyboardInput k = new KeyboardInput();
    k.Show();

   }

   lblQuestion.Text = currentQ.QuestionText;
   btnChoice1.Text = currentQ.Choice1;
   btnChoice2.Text = currentQ.Choice2;
   btnChoice3.Text = currentQ.Choice3;
   btnChoice4.Text = currentQ.Choice4;

   return currentQ;
}