问:
Prolog recursively replace elements of list with elements of another list
Apologies for lack of clarity in title. The following is a very specific predicate I'm building, which is only partially working as intended.

```<code>% replace_elements(+SearchingElementsList,+ReplacementsList,+OriginalList,-ResultingList).
% ResultingList consists of all elements of SearchingElementsList replaced by elements of ReplacementsList respectively.

replace_elements([],[],_,_).
replace_elements([H|T],[H2|T2],[H3|T3],List) :-
    H \= H3,                                 % H is not H3, therefore
    replace_elements([H|T],[H2|T2],T3,List). % Skip this element and continue with T3.
replace_elements([H|T],[H2|T2],[H|T3],[H2|List]) :-
    replace_elements(T,T2,T3,List).          % H is found in OriginalList. Continue with tails.
</code>```

Currently:

```<code>?- replace_elements([1,2,3],[one,two,three],[1,2,3,4,5],Result).
?- Result = [one,two,three|_7636].
</code>```

Expected:

```<code>?- Result = [one,two,three,4,5].
</code>```

Any hint would be appreciated!

Edit: Came up with a working answer for my specific problem.

```<code>% Eventually, recursion starts from all empty lists.
replace_elements([],[],[],[]).
% Rules are empty, push remaining H to List.
replace_elements([],[],[H|T],[H|List]) :-
    replace_elements([],[],T,List).
% Empty list, just go through remaining rules.
replace_elements([H|T],[H2|T2],[],List) :-
    replace_elements(T,T2,[],List).
% H < H3, move to next element in rules.
replace_elements([H|T],[H2|T2],[H3|T3],List) :-
    H < H3,
    replace_elements(T,T2,[H3|T3],List).
% H > H3, move to next element in original list.
replace_elements([H|T],[H2|T2],[H3|T3],[H3|List]) :-
    H > H3,
    replace_elements([H|T],[H2|T2],T3,List).
% Element is the same, push replacement H2 to List.
replace_elements([H|T],[H2|T2],[H|T3],[H2|List]) :-
    replace_elements(T,T2,T3,List).
</code>```

答:
This relation can be expressed quite compactly with if_/3, =/3 and maplist/3:

```<code>:- use_module(library(apply)).   % for maplist/3

from_to_elem_repl([],[],E,E).
from_to_elem_repl([X|Xs],[Y|Ys],E,R) :-
   if_(E=X,R=Y,from_to_elem_repl(Xs,Ys,E,R)).

from_to_list_mapped(Fs,Ts,L,M) :-
   maplist(from_to_elem_repl(Fs,Ts),L,M).
</code>```

The predicate from_to_elem_repl/4 describes the relation between an element and its replacement. If the element E occurs in the from-list then it's replaced by the element at the corresponding position in the to-list: Y (recursive rule). If E does not occur in the from-list it is not replaced (base case). The predicate from_to_list_mapped/4 uses maplist/3 to map the predicate from_to_elem_repl/4 to the list L thus yielding the list with the replacements M. Your example query succeeds deterministically:

```<code>?- from_to_list_mapped([1,2,3],[one,two,three],[1,2,3,4,5],M).
M = [one, two, three, 4, 5].
</code>```

In the other direction all eight solutions are found:

```<code>?- from_to_list_mapped([1,2,3],[one,two,three],L [one,two,three,4,5]).
L = [1, 2, 3, 4, 5] ;
L = [1, 2, three, 4, 5] ;
L = [1, two, 3, 4, 5] ;
L = [1, two, three, 4, 5] ;
L = [one, 2, 3, 4, 5] ;
L = [one, 2, three, 4, 5] ;
L = [one, two, 3, 4, 5] ;
L = [one, two, three, 4, 5].
</code>```

You could also ask for possible mapping pairs for a given list and its replacement:

```<code>?- from_to_list_mapped(Fs,Ts,[1,2,3,4,5],[one,two,three,4,5]).
Fs = [1, 2, 3],
Ts = [one, two, three] ;
Fs = [1, 2, 3, 4],
Ts = [one, two, three, 4] ;
Fs = [1, 2, 3, 4, 5|_G5111],
Ts = [one, two, three, 4, 5|_G5114] ;
Fs = [1, 2, 3, 4, _G5258],
Ts = [one, two, three, 4, _G5279],
dif(_G5258, 5) ;
Fs = [1, 2, 3, 4, _G5275, 5|_G5279],
Ts = [one, two, three, 4, _G5299, 5|_G5303],
dif(_G5275, 5) ;
Fs = [1, 2, 3, 4, _G5316, _G5319],
Ts = [one, two, three, 4, _G5340, _G5343],
dif(_G5316, 5),
dif(_G5319, 5) ;
Fs = [1, 2, 3, 4, _G5333, _G5336, 5|_G5340],
Ts = [one, two, three, 4, _G5360, _G5363, 5|_G5367],
dif(_G5333, 5),
dif(_G5336, 5) ;
.
.
.
</code>```

Obviously there are infinitely many possibilities. But if you ask for a fixed length, the predicate terminates:

```<code>?- Fs=[_,_,_],from_to_list_mapped(Fs,Ts,[1,2,3,4,5],[one,two,three,4,5]).
Fs = [1, 2, 3],
Ts = [one, two, three] ;
Fs = [1, 3, 2],
Ts = [one, three, two] ;
Fs = [2, 1, 3],
Ts = [two, one, three] ;
Fs = [3, 1, 2],
Ts = [three, one, two] ;
Fs = [2, 3, 1],
Ts = [two, three, one] ;
Fs = [3, 2, 1],
Ts = [three, two, one] ;
false.
</code>```

You can also ask for a mapping without specifying the replacement elements:

```<code>?- from_to_list_mapped([1,2,3],Ts,[1,2,3,4,5],R).
Ts = [_G4920, _G4937, _G4965],
R = [_G4920, _G4937, _G4965, 4, 5].
</code>```

As you see the predicate is quite versatile. Play around with it to find other possible uses.

Body:
Apologies for lack of clarity in title. The following is a very specific predicate I'm building, which is only partially working as intended.

% replace_elements(+SearchingElementsList,+ReplacementsList,+OriginalList,-ResultingList).
% ResultingList consists of all elements of SearchingElementsList replaced by elements of ReplacementsList respectively.

replace_elements([],[],_,_).
replace_elements([H|T],[H2|T2],[H3|T3],List) :-
    H \= H3,                                 % H is not H3, therefore
    replace_elements([H|T],[H2|T2],T3,List). % Skip this element and continue with T3.
replace_elements([H|T],[H2|T2],[H|T3],[H2|List]) :-
    replace_elements(T,T2,T3,List).          % H is found in OriginalList. Continue with tails.

Currently:

?- replace_elements([1,2,3],[one,two,three],[1,2,3,4,5],Result).
?- Result = [one,two,three|_7636].

Expected:

?- Result = [one,two,three,4,5].

Any hint would be appreciated!

Edit: Came up with a working answer for my specific problem.

% Eventually, recursion starts from all empty lists.
replace_elements([],[],[],[]).
% Rules are empty, push remaining H to List.
replace_elements([],[],[H|T],[H|List]) :-
    replace_elements([],[],T,List).
% Empty list, just go through remaining rules.
replace_elements([H|T],[H2|T2],[],List) :-
    replace_elements(T,T2,[],List).
% H  H3,
    replace_elements([H|T],[H2|T2],T3,List).
% Element is the same, push replacement H2 to List.
replace_elements([H|T],[H2|T2],[H|T3],[H2|List]) :-
    replace_elements(T,T2,T3,List).

Body:
This relation can be expressed quite compactly with if_/3, =/3 and maplist/3:

:- use_module(library(apply)).   % for maplist/3

from_to_elem_repl([],[],E,E).
from_to_elem_repl([X|Xs],[Y|Ys],E,R) :-
   if_(E=X,R=Y,from_to_elem_repl(Xs,Ys,E,R)).

from_to_list_mapped(Fs,Ts,L,M) :-
   maplist(from_to_elem_repl(Fs,Ts),L,M).

The predicate from_to_elem_repl/4 describes the relation between an element and its replacement. If the element E occurs in the from-list then it's replaced by the element at the corresponding position in the to-list: Y (recursive rule). If E does not occur in the from-list it is not replaced (base case). The predicate from_to_list_mapped/4 uses maplist/3 to map the predicate from_to_elem_repl/4 to the list L thus yielding the list with the replacements M. Your example query succeeds deterministically:

?- from_to_list_mapped([1,2,3],[one,two,three],[1,2,3,4,5],M).
M = [one, two, three, 4, 5].

In the other direction all eight solutions are found:

?- from_to_list_mapped([1,2,3],[one,two,three],L [one,two,three,4,5]).
L = [1, 2, 3, 4, 5] ;
L = [1, 2, three, 4, 5] ;
L = [1, two, 3, 4, 5] ;
L = [1, two, three, 4, 5] ;
L = [one, 2, 3, 4, 5] ;
L = [one, 2, three, 4, 5] ;
L = [one, two, 3, 4, 5] ;
L = [one, two, three, 4, 5].

You could also ask for possible mapping pairs for a given list and its replacement:

?- from_to_list_mapped(Fs,Ts,[1,2,3,4,5],[one,two,three,4,5]).
Fs = [1, 2, 3],
Ts = [one, two, three] ;
Fs = [1, 2, 3, 4],
Ts = [one, two, three, 4] ;
Fs = [1, 2, 3, 4, 5|_G5111],
Ts = [one, two, three, 4, 5|_G5114] ;
Fs = [1, 2, 3, 4, _G5258],
Ts = [one, two, three, 4, _G5279],
dif(_G5258, 5) ;
Fs = [1, 2, 3, 4, _G5275, 5|_G5279],
Ts = [one, two, three, 4, _G5299, 5|_G5303],
dif(_G5275, 5) ;
Fs = [1, 2, 3, 4, _G5316, _G5319],
Ts = [one, two, three, 4, _G5340, _G5343],
dif(_G5316, 5),
dif(_G5319, 5) ;
Fs = [1, 2, 3, 4, _G5333, _G5336, 5|_G5340],
Ts = [one, two, three, 4, _G5360, _G5363, 5|_G5367],
dif(_G5333, 5),
dif(_G5336, 5) ;
.
.
.

Obviously there are infinitely many possibilities. But if you ask for a fixed length, the predicate terminates:

?- Fs=[_,_,_],from_to_list_mapped(Fs,Ts,[1,2,3,4,5],[one,two,three,4,5]).
Fs = [1, 2, 3],
Ts = [one, two, three] ;
Fs = [1, 3, 2],
Ts = [one, three, two] ;
Fs = [2, 1, 3],
Ts = [two, one, three] ;
Fs = [3, 1, 2],
Ts = [three, one, two] ;
Fs = [2, 3, 1],
Ts = [two, three, one] ;
Fs = [3, 2, 1],
Ts = [three, two, one] ;
false.

You can also ask for a mapping without specifying the replacement elements:

?- from_to_list_mapped([1,2,3],Ts,[1,2,3,4,5],R).
Ts = [_G4920, _G4937, _G4965],
R = [_G4920, _G4937, _G4965, 4, 5].

As you see the predicate is quite versatile. Play around with it to find other possible uses.


来源: stackexchange

问:
F5 to run Visual Studio Test in debugger
I'm using Visual Studio Test for C++, and am debugging a specific test. Microsoft has provided all kinds of ways to run the test in the debugger, but none that I really like. I am getting tired of having to go find the test code and then press Ctrl+R, Ctrl+T (or mousing around which I hate). I want Ctrl+R, Ctrl+T behavior from any source code context.

Is there a way to hook F5 to run the selected test(s) in the debugger?

I've tried setting my test project as startup, but that makes F5 "unable to start" because the test is a DLL.

答:
Locate your vstest.console.exe to run the test DLL via F5.

In my Visual Studio 2017 Community edition that would be putting the following path into Start external program under Debug settings:

```<code> C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.console.exe
</code>```

And as Command line arguments just put the DLLs file name. Now you can use F5 to start debugging a test when Set as StartUp Project.

ContentLicense: CC BY-SA 3.0

Body:
Locate your vstest.console.exe to run the test DLL via F5.

In my Visual Studio 2017 Community edition that would be putting the following path into Start external program under Debug settings:

 C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.console.exe

And as Command line arguments just put the DLLs file name. Now you can use F5 to start debugging a test when Set as StartUp Project.


问:
How Do I Prevent Duplicates When Adding Leads to SuiteCRM?
The developer guide for SuiteCRM is kind of incomplete (at least here in Q4 2017) compared to the old SugarCRM one that it was based on before the software fork. So, by downloading the WordPress Plugin for SugarCRM, I was able to figure out the REST API and JSON for adding a sales lead into SuiteCRM with the following code.

Now how do I prevent duplicates by home phone, mobile phone, or email address?

```<code><?php

error_reporting(E_ALL);
ini_set('display_errors','On');

header('Content-Type: text/plain');

CRM::loginCRM('admin','xxxxPASSWORDxxxxxx');

$aResult = CRM::addLead(array(
  'name' => 'John Doe',
  'description' => 'sample description',
  'salutation' => 'Mr.',
  'first_name' => 'John',
  'last_name' => 'Doe',
  'do_not_call' => 'No',
  'phone_home' => '202-111-2222',
  'phone_mobile' => '202-111-2222',
  'email1' => 'test@example.com',
  'primary_address_street' => '123 Main Street',
  'primary_address_street2' => '',
  'primary_address_street3' => '',
  'primary_address_city' => 'New York',
  'primary_address_state' => 'NY'
));

print_r($aResult);
CRM::logoutCRM();

die('OK');
/////////////////////////

class CRM {

private static $SessionID = '';

private static $URL = 'https://mycrmserver-example.com/service/v4_1/rest.php';

private static $User = '';
private static $Shadow = '';

public static function sendJSON($a) {
  $s = file_get_contents(
    self::$URL,
    false,
    stream_context_create(
      array(
        'http' => array (
          'method' => 'POST',
          'header' => 'Content-Type: application/x-www-form-urlencoded',
          'content' => http_build_query($a)
        )
      )
    )
  );
  $a2 = json_decode($s);
  return $a2;
}

public static function loginCRM($sUser,$sPass) {
  $sShadow = md5($sPass);
  self::$User = $sUser;
  self::$Shadow = $sShadow;
  $asLogin = array (
    'method' => 'login',
    'input_type' => 'JSON',
    'response_type' => 'JSON',
    'rest_data' => json_encode(array(
      'user_auth' => array(
        'user_name' => $sUser,
        'password' => $sShadow,
        'version' => 1
      ),
      'application_name' => 'RestTest',
      'name_value_list' => array()
    ))
  );
  $a = self::sendJSON($asLogin);
  self::$SessionID = $a->id;
}

public static function logoutCRM() {
  $asLogin = array (
    'method' => 'logout',
    'input_type' => 'JSON',
    'response_type' => 'JSON',
    'rest_data' => json_encode(array(
      'user_auth' => array(
        'user_name' => self::$User,
        'password' => self::$Shadow,
        'version' => 1
      ),
      'application_name' => 'RestTest',
      'name_value_list' => array()
    ))
  );
  self::sendJSON($asLogin);
}

public static function addLead($a) {
  $asNameValueList = array();
  foreach($a as $sKey => $sVal) {
    $asNameValueList[] = array('name'=>$sKey,'value'=>$sVal);
  }
  $asAddEntry = array (
    'method' => 'set_entry',
    'input_type' => 'JSON',
    'response_type' => 'JSON',
    'rest_data' => json_encode(array(
      'session' => self::$SessionID,
      'module_name' => 'Leads',
      'name_value_list' => $asNameValueList
    ))
  );
  $a = self::sendJSON($asAddEntry);
  return $a;
}

} // end CRM
</code>```

答:
Add these functions into your CRM class and check them before adding a lead. I had a little help from this answer that incidentally gave me some insights. Also, I recommend you do things to tighten down your security such as add an .htaccess or NGINX rule that only allows certain IP addresses or require certain headers to reach anything in your /service folder, and /service/* subfolders either over HTTP or HTTPS.

public static function leadExistsByPhone($sHomePhone,$sMobilePhone) {
  $sHomePhone = (empty($sHomePhone)) ? 'xxxxxinvalid' : $sHomePhone;
  $sMobilePhone = (empty($sMobilePhone)) ? 'xxxxxinvalid' : $sMobilePhone;
  $asCheck = array (
    'method' => 'get_entry_list',
    'input_type' => 'JSON',
    'response_type' => 'JSON',
    'rest_data' => json_encode(array(
      'session' => self::$SessionID,
      'module_name' => 'Leads',
      'query' => "
        leads.phone_home = '$sHomePhone'
        OR leads.phone_mobile = '$sMobilePhone'
      ",
      'order_by' => 'leads.date_entered DESC',
      'offset' => '0',
      'select_fields' => array(),
      'link_name_to_fields_array' => array(),
      'max_results' => 999999,
      'deleted' => false
    ))
  );
  $a = self::sendJSON($asCheck);
  $nCount = @ $a->result_count;
  $nCount = intval($nCount);
  return ($nCount > 0);
}

public static function leadExistsByEmail($sEmail) {
  if (!filter_var($sEmail, FILTER_VALIDATE_EMAIL)) {
    die('DENIED: invalid email address format');
  }
  $asCheck = array (
    'method' => 'get_entry_list',
    'input_type' => 'JSON',
    'response_type' => 'JSON',
    'rest_data' => json_encode(array(
      'session' => self::$SessionID,
      'module_name' => 'Leads',
      'query' => "
        leads.id IN
        (
          SELECT email_addr_bean_rel.bean_id
          FROM   email_addr_bean_rel
          JOIN   email_addresses
          ON     email_addr_bean_rel.email_address_id = email_addresses.id
          WHERE
          email_addresses.email_address = '$sEmail'
        )
      ",
      'order_by' => 'leads.date_entered DESC',
      'offset' => '0',
      'select_fields' => array(),
      'link_name_to_fields_array' => array(),
      'max_results' => 999999,
      'deleted' => false
    ))
  );
  $a = self::sendJSON($asCheck);
  $nCount = @ $a->result_count;
  $nCount = intval($nCount);
  return ($nCount > 0);
}
```

Body:
The developer guide for SuiteCRM is kind of incomplete (at least here in Q4 2017) compared to the old SugarCRM one that it was based on before the software fork. So, by downloading the WordPress Plugin for SugarCRM, I was able to figure out the REST API and JSON for adding a sales lead into SuiteCRM with the following code.

Now how do I prevent duplicates by home phone, mobile phone, or email address?

<?php

error_reporting(E_ALL);
ini_set('display_errors','On');

header('Content-Type: text/plain');

CRM::loginCRM('admin','xxxxPASSWORDxxxxxx');

$aResult = CRM::addLead(array(
  'name' => 'John Doe',
  'description' => 'sample description',
  'salutation' => 'Mr.',
  'first_name' => 'John',
  'last_name' => 'Doe',
  'do_not_call' => 'No',
  'phone_home' => '202-111-2222',
  'phone_mobile' => '202-111-2222',
  'email1' => 'test@example.com',
  'primary_address_street' => '123 Main Street',
  'primary_address_street2' => '',
  'primary_address_street3' => '',
  'primary_address_city' => 'New York',
  'primary_address_state' => 'NY'
));

print_r($aResult);
CRM::logoutCRM();

die('OK');
/////////////////////////

class CRM {

private static $SessionID = '';

private static $URL = 'https://mycrmserver-example.com/service/v4_1/rest.php';

private static $User = '';
private static $Shadow = '';

public static function sendJSON($a) {
  $s = file_get_contents(
    self::$URL,
    false,
    stream_context_create(
      array(
        'http' => array (
          'method' => 'POST',
          'header' => 'Content-Type: application/x-www-form-urlencoded',
          'content' => http_build_query($a)
        )
      )
    )
  );
  $a2 = json_decode($s);
  return $a2;
}

public static function loginCRM($sUser,$sPass) {
  $sShadow = md5($sPass);
  self::$User = $sUser;
  self::$Shadow = $sShadow;
  $asLogin = array (
    'method' => 'login',
    'input_type' => 'JSON',
    'response_type' => 'JSON',
    'rest_data' => json_encode(array(
      'user_auth' => array(
        'user_name' => $sUser,
        'password' => $sShadow,
        'version' => 1
      ),
      'application_name' => 'RestTest',
      'name_value_list' => array()
    ))
  );
  $a = self::sendJSON($asLogin);
  self::$SessionID = $a->id;
}

public static function logoutCRM() {
  $asLogin = array (
    'method' => 'logout',
    'input_type' => 'JSON',
    'response_type' => 'JSON',
    'rest_data' => json_encode(array(
      'user_auth' => array(
        'user_name' => self::$User,
        'password' => self::$Shadow,
        'version' => 1
      ),
      'application_name' => 'RestTest',
      'name_value_list' => array()
    ))
  );
  self::sendJSON($asLogin);
}

public static function addLead($a) {
  $asNameValueList = array();
  foreach($a as $sKey => $sVal) {
    $asNameValueList[] = array('name'=>$sKey,'value'=>$sVal);
  }
  $asAddEntry = array (
    'method' => 'set_entry',
    'input_type' => 'JSON',
    'response_type' => 'JSON',
    'rest_data' => json_encode(array(
      'session' => self::$SessionID,
      'module_name' => 'Leads',
      'name_value_list' => $asNameValueList
    ))
  );
  $a = self::sendJSON($asAddEntry);
  return $a;
}

} // end CRM


问:
IE title changes to <afterHash> if the page has a url with '#' , and has flash/swf embedded in it
The issue is, if IE (6.0+) , has flash content embedded in it, and the url of the page has a # somewhere in it, then when the flash content loads ,or if the user interacts with it, then the title of the window, changes to the content that is places after hash.

e.g http://adobeflashwebsite.com/index.html#somediv

Then the title of the page changes to 'somediv' , the moment a user will click on flash content, or many a times even the moment the flash content loads.

This happens only in IE.

This below is a very specific case I was facing:

The following is the environment I am facing issues with:

Shinding engine to show an iGoogle like page

Sammy.js

Gadgets rendering flash/swf

The issue here is, no matter which plugin I try to embed flash with, I end up having the following problem

When the flash loads completely, it appends something like #tab/xx , which actually is a string used by sammy to store the last navigational history within the page

When, a user starts interacting with the flash, then the title is completely removed and only #tab/xx remains as the title.

When a gadget is refreshed, even then there is issue like #2.

Could someone suggest, what the issue could be?
Most probably is it related to sammy.js, as iGoogle doesn't have that issue.

答:
I'm not really familiar with sammy.js but:

1) the Flash object is somehow 'taking ownership' of the title property.

OR

2) sammy.js is clearing the title value on HTML losing focus aka Flash gaining it (less likley and don't know why would someone do that)

If 1) -> define the title property in the Flash object itself (not a Flash user, dunno if it can be done easily)

If 2) -> the javascript is dumping a variable string value connected to the title property?

SUGGESTION:

Enclose your flash object in a new
 element, assigning the
 a .click() event handler that changes the title property of a document. Try this:

```<code>$('title').text('YourTitleHere');
</code>```

Body:
I'm not really familiar with sammy.js but:

1) the Flash object is somehow 'taking ownership' of the title property.

OR

2) sammy.js is clearing the title value on HTML losing focus aka Flash gaining it (less likley and don't know why would someone do that)

If 1) -> define the title property in the Flash object itself (not a Flash user, dunno if it can be done easily)

If 2) -> the javascript is dumping a variable string value connected to the title property?

SUGGESTION:

Enclose your flash object in a new <div> element, assigning the <div> a .click() event handler that changes the title property of a document. Try this:

$('title').text('YourTitleHere');

ContentLicense: CC BY-SA 2.5


问:
JavaScript regular expression check number only
I want a regular expression for the following values:

```<code>1) .1 = False.
2) 0.1 = True.
3) 1.1245 = True.
4) 1.2. = False.
5) 1.24.35 = False.
6) 21.152 = true.
</code>```

This regex should check that the string represents an integer or is composed of only numbers and a single . representing a decimal point.

I am using: /^[\+\-]?\d*\.?\d+(?:[Ee][\+\-]?\d+)?$/ but it takes "1.2." as true.

答:
If you use the following regex

(?:\d*.)?\d+

It will match only real numbers.

If the input is like 1.2.3 it will return 1.2.

Hope it helps!

Body:
I want a regular expression for the following values:

1) .1 = False.
2) 0.1 = True.
3) 1.1245 = True.
4) 1.2. = False.
5) 1.24.35 = False.
6) 21.152 = true.

This regex should check that the string represents an integer or is composed of only numbers and a single . representing a decimal point.

I am using: /^[\+\-]?\d*\.?\d+(?:[Ee][\+\-]?\d+)?$/ but it takes "1.2." as true.


问:
Ruby date format difference between %-d vs %e or "no-padded" vs "blank-padded"
In Ruby documentation, there are two very similar values for formatting a date(time) string

%-d described as no-padded (1..31)

%e described as blank-padded ( 1..31)

What's the difference between these two?

答:
The difference between these two is the following:

%-d will print out the number without leading zero nor space ex:

```<code>DateTime.new(2016, 02, 01, 16, 00).strftime('%m/%-d/%Y')
> "02/1/2016"
</code>```

%e will print out a leading space but not a leading zero

```<code>DateTime.new(2016, 02, 01, 16, 00).strftime('%m/%e/%Y')
> "02/ 1/2016"
</code>```

Body:
The difference between these two is the following:

%-d will print out the number without leading zero nor space ex:

DateTime.new(2016, 02, 01, 16, 00).strftime('%m/%-d/%Y')
> "02/1/2016"

%e will print out a leading space but not a leading zero

DateTime.new(2016, 02, 01, 16, 00).strftime('%m/%e/%Y')
> "02/ 1/2016"


问:
Additional firebase database field being added automatically?
I have a book class as

```<code>public class Books {

    public String bookName;
    public String author;
    public String copies;

    public Books() {
        // Default constructor required for calls to DataSnapshot.getValue(User.class)
    }

    public Books(String name, String author, String copies) {
        this.bookName = name;
        this.author = author;
        this.copies = copies;
    }

    public String getBookName() {
        return bookName;
    }

    public String getAuthorName() {
        return author;
    }

    public String getCopies() {
        return copies;
    }

}
</code>```

And i'm adding to firebase realtime cloud database as

```<code>mDatabase = FirebaseDatabase.getInstance("https://cmpe-2b339.firebaseio.com").getReference();

Books book = new Books(bookName,author,copies);
                    mDatabase.push().setValue(book);
</code>```

However in firebase concole, its coming as

```<code>{
  "-KzAt3eHDBtD7gFvLIbn" : {
    "author" : "J",
    "authorName" : "J",
    "bookName" : "Hi",
    "copies" : "5"
  }
}
</code>```

There is added author field, which i dont understand

答:
Replace your class with this</p>

```<code>public class Books {
private String bookName;
private String author;
private String copies;

public Books () {

}

public Books(String bookName, String author, String copies) {
    this.bookName = bookName;
    this.author = author;
    this.copies = copies;
}

public String getBookName() {
    return bookName;
}

public void setBookName(String bookName) {
    this.bookName = bookName;
}

public String getAuthor() {
    return author;
}

public void setAuthor(String author) {
    this.author = author;
}

public String getCopies() {
    return copies;
}

public void setCopies(String copies) {
    this.copies = copies;
}
}
</code>```

Body:
I have a book class as

public class Books {

    public String bookName;
    public String author;
    public String copies;

    public Books() {
        // Default constructor required for calls to DataSnapshot.getValue(User.class)
    }

    public Books(String name, String author, String copies) {
        this.bookName = name;
        this.author = author;
        this.copies = copies;
    }

    public String getBookName() {
        return bookName;
    }

    public String getAuthorName() {
        return author;
    }

    public String getCopies() {
        return copies;
    }

}

And i'm adding to firebase realtime cloud database as

mDatabase = FirebaseDatabase.getInstance("https://cmpe-2b339.firebaseio.com").getReference();

Books book = new Books(bookName,author,copies);
                    mDatabase.push().setValue(book);

However in firebase concole, its coming as

{
  "-KzAt3eHDBtD7gFvLIbn" : {
    "author" : "J",
    "authorName" : "J",
    "bookName" : "Hi",
    "copies" : "5"
  }
}

There is added author field, which i dont understand

Body:
Replace your class with this

public class Books {
private String bookName;
private String author;
private String copies;

public Books () {

}

public Books(String bookName, String author, String copies) {
    this.bookName = bookName;
    this.author = author;
    this.copies = copies;
}

public String getBookName() {
    return bookName;
}

public void setBookName(String bookName) {
    this.bookName = bookName;
}

public String getAuthor() {
    return author;
}

public void setAuthor(String author) {
    this.author = author;
}

public String getCopies() {
    return copies;
}

public void setCopies(String copies) {
    this.copies = copies;
}
}


问:
Wrong python interpreter being used when debugging embedded target
I'm running CLion (2017.3 RC) with MinGW-w64 (5.0.3) and using gcc/g++ (7.2.0) + CMake (3.9.3) on Windows 10 x64 to compile a target that embeds python (3.6.3 64 bit). Everything works fine when run, however when I try to debug it and step through with CLion, I get

File "C:\Python36\Lib/site.py", line 178
    file=sys.stderr)
        ^
SyntaxError: invalid syntax

I have my PYTHONPATH pointing towards a Python 3 installation. I do not have Python 2 installed on my system yet it seems like a Python 2 interpreter is trying to use the Python 3 Lib. After some digging I noticed that MinGW-w64 has Python 2 bundled with it but even if I delete the libs, include, and exe, I get the same error.

答:
After some more digging I learned that python2 has been embedded in gdb from version 7.0+. Because of this, if you try to run MinGW64's gdb (like trying to debug from CLion) and you have PYTHONPATH pointing towards a python3 installation, you'll run into a syntax error. This happens because the embedded python2 is trying to use the python3 libs.

I am still unable to debug my C++ target that embeds python but that's a different issue...


问:
JSON to YAML: convert fields with embedded newlines "\n" to literal block "|"
How to convert JSON file, where some field values are multiline strings, with embedded newlines (as "\n") to YAML, where values with embedded newlines and only those values are written using literal block notation.

For example given the following JSON:

{
   "01ea672a": {
        "summary": "A short one-line summary",
        "description": "first line\nsecond line",
        "content": "1st line\n2nd line\n"
   }
}
```

<p>should generate something like the following YAML (the details may differ):</p>

<pre class="lang-yaml prettyprint-override"><code>---
01ea672a:
  summary: A short one-line summary
  description: |-
    first line
    second line
  content: |
    1st line
    2nd line
</code>```

I would prefer solution in a scripting language, be it Python, Perl, Ruby or other, or using a command-line conversion tool like Catmandu.

The json2yaml.com on-line can do this, but I'd rather not try to use it for 40 MB file.

答:
It turns out that I was able to modify the dnozay answer to the "Any yaml libraries in Python that support dumping of long strings as block literals or folded blocks?" question.

It turns out to be a bit faster than flyx answer, though you needs some additional tricks (borrowed with modification from drbild/json2yaml) to preserve the order of keys.

The major part is to use Representer.add_representer:

class maybe_literal_str(str): pass
class maybe_literal_unicode(unicode): pass

def change_maybe_style(representer):
    def new_maybe_representer(dumper, data):
        scalar = representer(dumper, data)
        if isinstance(data, basestring) and "\n" in data:
            scalar.style = '|'
        else:
            scalar.style = None
        return scalar
    return new_maybe_representer

from yaml.representer import SafeRepresenter

# represent_str does handle some corner cases, so use that
# instead of calling represent_scalar directly
represent_maybe_literal_str     = change_maybe_style(SafeRepresenter.represent_str)
represent_maybe_literal_unicode = change_maybe_style(SafeRepresenter.represent_unicode)

# I needed to use it in yaml.safe_dump() with older PyYAML,
# hence explicit Dumper=yaml=SafeDumper
yaml.add_representer(maybe_literal_str, represent_maybe_literal_str,
                     Dumper=yaml.SafeDumper)
yaml.add_representer(maybe_literal_unicode, represent_maybe_literal_unicode,
                     Dumper=yaml.SafeDumper)
```

<p>For it to work I had to wrap strings with one of those two classes:</p>

<pre class="lang-py prettyprint-override"><code>def wrap_strings(arg):
    """Wrap {str,unicode} arguments in maybe_literal_{str,unicode}"""
    if isinstance(arg, str):
        return maybe_literal_str(arg)
    elif isinstance(arg, unicode):
        return maybe_literal_unicode(arg)
    else:
        return arg
</code>```

I have used this hacky function to modify the structure

def transform(obj, leaf_callback):
    try:
        # is it dict or something like it?
        enum = obj.iteritems()
    except AttributeError:
        # if not dict-like, it is list-like object
        enum = enumerate(obj)
    for k, v in enum:
        # is value 'v' collection or scalar (leaf value)?
        if isinstance(v, (dict, list)):
            transform(v, leaf_callback)
        else:
            newval = leaf_callback(v)
            if newval is not None:
                obj[k] = newval
```

<p>The conversion from JSON to YAML was done with:</p>

<pre class="lang-py prettyprint-override"><code>def convert_dom(json_file, yaml_file):
    loaded_json = json.load(json_file)
    transform(loaded_json, wrap_strings)
    yaml.safe_dump(loaded_json, yaml_file,
                   explicit_start=True, # start with "---\n"
                   default_flow_style=False)

with open('in.json', 'r') as json_file:
    with open('out.yaml', 'w') as yaml_file:
        convert_events(json_file, yaml_file)
</code>```

Body:
How to convert JSON file, where some field values are multiline strings, with embedded newlines (as "\n") to YAML, where values with embedded newlines and only those values are written using literal block notation.

For example given the following JSON:

{
   "01ea672a": {
        "summary": "A short one-line summary",
        "description": "first line\nsecond line",
        "content": "1st line\n2nd line\n"
   }
}

should generate something like the following YAML (the details may differ):

---
01ea672a:
  summary: A short one-line summary
  description: |-
    first line
    second line
  content: |
    1st line
    2nd line

I would prefer solution in a scripting language, be it Python, Perl, Ruby or other, or using a command-line conversion tool like Catmandu.

The json2yaml.com on-line can do this, but I'd rather not try to use it for 40 MB file.

Body:
It turns out that I was able to modify the dnozay answer to the "Any yaml libraries in Python that support dumping of long strings as block literals or folded blocks?" question.

It turns out to be a bit faster than flyx answer, though you needs some additional tricks (borrowed with modification from drbild/json2yaml) to preserve the order of keys.

The major part is to use Representer.add_representer:

class maybe_literal_str(str): pass
class maybe_literal_unicode(unicode): pass

def change_maybe_style(representer):
    def new_maybe_representer(dumper, data):
        scalar = representer(dumper, data)
        if isinstance(data, basestring) and "\n" in data:
            scalar.style = '|'
        else:
            scalar.style = None
        return scalar
    return new_maybe_representer

from yaml.representer import SafeRepresenter

# represent_str does handle some corner cases, so use that
# instead of calling represent_scalar directly
represent_maybe_literal_str     = change_maybe_style(SafeRepresenter.represent_str)
represent_maybe_literal_unicode = change_maybe_style(SafeRepresenter.represent_unicode)

# I needed to use it in yaml.safe_dump() with older PyYAML,
# hence explicit Dumper=yaml=SafeDumper
yaml.add_representer(maybe_literal_str, represent_maybe_literal_str,
                     Dumper=yaml.SafeDumper)
yaml.add_representer(maybe_literal_unicode, represent_maybe_literal_unicode,
                     Dumper=yaml.SafeDumper)

For it to work I had to wrap strings with one of those two classes:

def wrap_strings(arg):
    """Wrap {str,unicode} arguments in maybe_literal_{str,unicode}"""
    if isinstance(arg, str):
        return maybe_literal_str(arg)
    elif isinstance(arg, unicode):
        return maybe_literal_unicode(arg)
    else:
        return arg

I have used this hacky function to modify the structure

def transform(obj, leaf_callback):
    try:
        # is it dict or something like it?
        enum = obj.iteritems()
    except AttributeError:
        # if not dict-like, it is list-like object
        enum = enumerate(obj)
    for k, v in enum:
        # is value 'v' collection or scalar (leaf value)?
        if isinstance(v, (dict, list)):
            transform(v, leaf_callback)
        else:
            newval = leaf_callback(v)
            if newval is not None:
                obj[k] = newval

The conversion from JSON to YAML was done with:

def convert_dom(json_file, yaml_file):
    loaded_json = json.load(json_file)
    transform(loaded_json, wrap_strings)
    yaml.safe_dump(loaded_json, yaml_file,
                   explicit_start=True, # start with "---\n"
                   default_flow_style=False)

with open('in.json', 'r') as json_file:
    with open('out.yaml', 'w') as yaml_file:
        convert_events(json_file, yaml_file)


问:
OpenCV-Python cv2.videocapture window shrinks
I am trying to get a simple opencv-python video capture to work which shows the live stream of the camera. However, when I run the code the camera window frame opens up and then immediately shrinks into a tiny line. here is a picture to show:

In the top right hand corner is a white line which should be the frame window.

I have tried installing the V4L2 driver and the red light comes on on the pi cam but I am not able to view through the window.

答:
Think you need to change imshow to

cv2.imshow('frame',frame)

The first argument is just the title of the window.


问:
How to remove default mouse-over effect on WPF buttons?
My problem is that in WPF, whenever I try and change the colour of a button's background using triggers or animations, the default mouseover effect (of being grey with that orange glow) seems to take priority.

After extensive searches I'm clueless as to how to remove this effect.

答:
The Muffin Man had a very simple answer which worked for me.

To add a little more specific direction, at least for VS 2013:

Right-click the control

Select Edit Template => Edit a copy...

I selected 'Application' for where to save the style

From here you can directly edit App.xaml and see the intuitively named properties. For my purposes, I just set RenderMouseOver="False"

Then, in the MainWindow.xaml or wherever your GUI is, you can paste the new style at the end of the Button tag, e.g. ... Style="{DynamicResource MouseOverNonDefault}"/>


问:
what is the default access modifier for controls created on .aspx page. Private or something else?
What is the default access modifier for controls created on .aspx page. Private or something else?</p>

答: I believe the controls on the aspx as considered protected by default and any methods in the code behind (.aspx.cs or aspx.vb) are private by default.  You can expose those controls by adding a public page property if you need to access it.</p>


问:
Retrieve graphical representation of an alphabet letter
I spacial representation of characters ( eg 'A' ) in android. Something like an array of Points or a Path object or Vectors. I am going to draw characters on screen myself, instead of using canvas.drawText(). Is this possible?</p>

答:
You can get a Path using the following code. I'm still trying to see if there is a way to get a more useful path as the one generated by this code is a native path and not a simple path.

```<code>Path path = new Path();
Paint paint = new Paint();
paint.getTextPath("A", 0, 1, 0f, 0f, path);
</code>```

Body:
You can get a Path using the following code. I'm still trying to see if there is a way to get a more useful path as the one generated by this code is a native path and not a simple path.

Path path = new Path();
Paint paint = new Paint();
paint.getTextPath("A", 0, 1, 0f, 0f, path);


问:
Background color rectangles in ggplot according to a factor value
I am looking for a way to display color rectangles in a ggplot2 background according to a factor level.
Here is a dput of the data :

```<code>    structure(list(date = structure(c(6L, 8L, 3L, 4L, 5L, 7L, 1L,
2L), .Label = c("01/05/2012", "10/05/2012", "17/05/2011", "18/05/2011",
"19/05/2011", "20/12/2013", "24/04/2012", "26/12/2013"), class = "factor"),
    Polyols = c(122, 5.25, 48.21, 41.59, 84.97, 64.75, 153.97,
    49.14), Year = c(2013L, 2013L, 2011L, 2011L, 2011L, 2012L,
    2012L, 2012L), Season = structure(c(2L, 2L, 1L, 1L, 1L, 1L,
    1L, 1L), .Label = c("Spring", "Winter"), class = "factor"),
    Site = structure(c(3L, 3L, 1L, 1L, 1L, 2L, 2L, 2L), .Label = c("GAP",
    "OPE-ANDRA", "Peyrusse Vieille"), class = "factor"), Typology = structure(c(1L,
    1L, 2L, 2L, 2L, 1L, 1L, 1L), .Label = c("Rural", "Urban"), class = "factor")), .Names = c("date",
"Polyols", "Year", "Season", "Site", "Typology"), class = "data.frame", row.names = c(NA,
-8L))
</code>```

What I'd like to get is a color rectangle behind each "typology" as shown in  the picture below

I found This topic but couldn't find a way to adjust it to my case.

I tried

```<code>g <- ggplot(data) +
     geom_bar(aes(x= Site, y= Polyols, fill= Season, colour= Season),
              show.legend = TRUE,stat="identity",position= position_dodge()) +
    theme(axis.text.x = element_text(angle=90, hjust=1, vjust=0))

g <- g + geom_rect(data=data, (aes(xmin=Typology, xmax=Typology,
                   ymin=0,ymax=200,fill=factor(Typology))))
g
</code>```

Could someone help ?

答:
Here is an attempt:

```<code>ggplot(dat)+
  geom_rect(fill = hue_pal()(4)[as.numeric(dat$Typology)],xmin = -Inf,xmax = Inf,
            ymin = -Inf,ymax = Inf, alpha = 0.1, color = "black") +
  geom_col(aes(x = Site, y = Polyols, fill = Season))+
  coord_cartesian(ylim = c(-50, max(aggregate(Polyols ~ Site, sum, data = dat)[,2])))+
  facet_grid(~Typology, scales = "free_x", space="free_x", switch = "x") +
  geom_text(aes(x = Site, y = -1, label = Site), angle = 90, hjust = 1) +
  theme(axis.text.x = element_blank(),
        axis.ticks.x = element_blank(),
        panel.spacing = unit(0, "lines"))+
  xlab("")
</code>```

Facet the plot according to the background fill, use geom_rect to fill the background. Remove x axis ticks and labels, use geom_text to annotate the x axis. Remove spacing from facets.

Body:
I am looking for a way to display color rectangles in a ggplot2 background according to a factor level.
Here is a dput of the data :

    structure(list(date = structure(c(6L, 8L, 3L, 4L, 5L, 7L, 1L,
2L), .Label = c("01/05/2012", "10/05/2012", "17/05/2011", "18/05/2011",
"19/05/2011", "20/12/2013", "24/04/2012", "26/12/2013"), class = "factor"),
    Polyols = c(122, 5.25, 48.21, 41.59, 84.97, 64.75, 153.97,
    49.14), Year = c(2013L, 2013L, 2011L, 2011L, 2011L, 2012L,
    2012L, 2012L), Season = structure(c(2L, 2L, 1L, 1L, 1L, 1L,
    1L, 1L), .Label = c("Spring", "Winter"), class = "factor"),
    Site = structure(c(3L, 3L, 1L, 1L, 1L, 2L, 2L, 2L), .Label = c("GAP",
    "OPE-ANDRA", "Peyrusse Vieille"), class = "factor"), Typology = structure(c(1L,
    1L, 2L, 2L, 2L, 1L, 1L, 1L), .Label = c("Rural", "Urban"), class = "factor")), .Names = c("date",
"Polyols", "Year", "Season", "Site", "Typology"), class = "data.frame", row.names = c(NA,
-8L))

What I'd like to get is a color rectangle behind each "typology" as shown in  the picture below

I found This topic but couldn't find a way to adjust it to my case.

I tried

g <- ggplot(data) +
     geom_bar(aes(x= Site, y= Polyols, fill= Season, colour= Season),
              show.legend = TRUE,stat="identity",position= position_dodge()) +
    theme(axis.text.x = element_text(angle=90, hjust=1, vjust=0))

g <- g + geom_rect(data=data, (aes(xmin=Typology, xmax=Typology,
                   ymin=0,ymax=200,fill=factor(Typology))))
g

Could someone help ?

Body:
Here is an attempt:

ggplot(dat)+
  geom_rect(fill = hue_pal()(4)[as.numeric(dat$Typology)],xmin = -Inf,xmax = Inf,
            ymin = -Inf,ymax = Inf, alpha = 0.1, color = "black") +
  geom_col(aes(x = Site, y = Polyols, fill = Season))+
  coord_cartesian(ylim = c(-50, max(aggregate(Polyols ~ Site, sum, data = dat)[,2])))+
  facet_grid(~Typology, scales = "free_x", space="free_x", switch = "x") +
  geom_text(aes(x = Site, y = -1, label = Site), angle = 90, hjust = 1) +
  theme(axis.text.x = element_blank(),
        axis.ticks.x = element_blank(),
        panel.spacing = unit(0, "lines"))+
  xlab("")

Facet the plot according to the background fill, use geom_rect to fill the background. Remove x axis ticks and labels, use geom_text to annotate the x axis. Remove spacing from facets.


问:
How to do URL mapping in Crafter 3.0
I was wondering if crafter (3.0) has the ability to do url mapping.

For example, to have a content at a given path like /site/website/foobar/mycontent/index.xml, and its url being /news/2017/11/17/my-content (notice the added / which can't be used in a file-name field since they are automatically converted to - in studio).

Thanks,

Nicolas

答:
A built-in router is on our roadmap (https://github.com/craftercms/craftercms/issues/1622), but for now, you can add one to your blueprint easily:

Create a component that contains a "routing table". This component
has a repeating table where each entry is an inbound URL and
outbound URL.

Create a Groovy filter script that will intercept all calls and
checks if the URL matches one of the inbound URLs. If it does, it
forwards the request to the corresponding outbound URL. Below is the
possible code for such filter:

```<code>def routingTableItem = siteItemService.getSiteItem("/site/components/system/routing-table.xml")
def routingTable = routingTableItem.urlRoutingTable.item
def currentURL = request.requestURI

def matchedEntry = routingTable.find { entry ->
    return currentURL == entry.inboundURL.text
}

if (matchedEntry) {
    def inboundURL = matchedEntry.inboundURL.text
    def outboundURL = matchedEntry.outboundURL.text

    logger.info("Forwarding URL ${inboundURL} to ${outboundURL}")

    request.getRequestDispatcher(outboundURL).forward(request, response)
} else {
    filterChain.doFilter(request, response)
}
</code>```

Title: How to do URL mapping in Crafter 3.0

Body:
A built-in router is on our roadmap (https://github.com/craftercms/craftercms/issues/1622), but for now, you can add one to your blueprint easily:

Create a component that contains a "routing table". This component
has a repeating table where each entry is an inbound URL and
outbound URL.

Create a Groovy filter script that will intercept all calls and
checks if the URL matches one of the inbound URLs. If it does, it
forwards the request to the corresponding outbound URL. Below is the
possible code for such filter:

def routingTableItem = siteItemService.getSiteItem("/site/components/system/routing-table.xml")
def routingTable = routingTableItem.urlRoutingTable.item
def currentURL = request.requestURI

def matchedEntry = routingTable.find { entry ->
    return currentURL == entry.inboundURL.text
}

if (matchedEntry) {
    def inboundURL = matchedEntry.inboundURL.text
    def outboundURL = matchedEntry.outboundURL.text

    logger.info("Forwarding URL ${inboundURL} to ${outboundURL}")

    request.getRequestDispatcher(outboundURL).forward(request, response)
} else {
    filterChain.doFilter(request, response)
}


问:
REST API naming convention for search parameter
I need to format the RestAPI for my application. This API filters data on the basis of the search query parameters. I need to understand what is the proper format to handle the keys of the search query parameters in terms of the naming convention(camelCase/snake-case)

Following is only a hypothetical example. I am focussed to finding the exact case that is followed for the search parameters of the RestAPI

-- Question 1: Which is the correct casing format to be used for the search query parameter keys when the key is a combination of multiple words.
eg: which of the following are correct : ....?searchType=A or ....?search_type=A

-- Question 2: Suppose I have 5 search types and for each search type, there is a value to be searched for. So to send this value in the search query parameters there should be only one generic key of "value" or if I can use "a", "b" etc per search type.
eg:

Format 1 : ....?search_type=A&a=testvaluea/....?search_type=B&b=testvalueb

Format 2: ....?search_type=A&value=testvaluea/....?search_type=B&value=testvalueb

I am pinning for format 1 cz of the following features:

-- using "a" and "b" etc search parameters makes sure that for a particular search type we can expect a certain parameter.

-- should this be a bad approach as in various forms the data is sent in particular search parameters.

答:
REST doesn't care what spelling you use for your URI.

Information encoded into the URI is done at the server's discretion and for its own use.

Which is the correct casing format to be used for the search query parameter keys when the key is a combination of multiple words

Whatever conforms to your local spelling conventions; it's just like a variable name in that respect.

should be only one generic key of "value" or if I can use "a", "b" etc per search type.

Again, follow local convention.

When in doubt, keep in mind that the reference implementation of REST is the web.  When you are filling out a form on the web, you don't care what the variable names are.  The form tells you what the variable name is, and the browser completely automates the process for you.


问:
Two versions of glibc on the same system
I currently have glibc 2.10.2 on my system. I upgraded an android installation on this same system the other day. Post the upgrade, however, I am unable to run the emulator. The emulator shuts down after posting an error which says something like: "Need glibc 2.11". My question is as follows:

Is there any way that I can use two versions of glibc on the same system at the same time?  There are some very important C/C++ programs that depend on the current installation of glibc.

Please let me know in case my question is not clear. Any help is most welcome.

Sriram.

Edit: I found some questions on stackoverflow about this issue. However, those questions were unanswered. Hoping this does not go down the same path!

答:
You can modify the include path in your android project to v2.11 glibc path and the rest of the projects will look into the path where you have already installed version 2.10.2.

Look into the Shared Libraries How-To in TDLP and read section 3.3.1 Shared Library Names where it talks about how you can modify LD_LIBRARY_PATH to temporarily substituting a different library for a particular execution.


问:
Way to execute Google Standalone Script directly from Drive
Well, I've been reading the documentation for a long time but, as per usual, it's really unclear...

I'm developing a Google Script with the Script Editor that is already working as expected (it have nothing to see with any G suite program but with Drive).

By now, the only way to execute it is opening the script editor and press on the "play" button or the "execute" bar and press on the function.

Obviously this is not a solution since anyone from the bussines could modify/see the code.

So the question is this: how can I make from this script something like an "exe" that I just have to double ckick (its obviously located at Drive) and it executes the script?

I saw this but seems it says no way to do it except from opening the code and execute from the google app script editor...

答:
Try this:

Build the menu first.

Click "Run My Code".

Click the "Run My Code" button.

runmycode.html:

```<code><!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script>
    function runMyCode()
    {
      google.script.run
         .withSuccessHandler(updateMyDiv)
         .myFunctionName();
    }
    function updateMyDiv(hl)
    {
      document.getElementById('MyDiv').innerHTML+='<br />'+ hl;
    }
    </script>
  </head>
  <body>
  <input type="button" value="Run My Code" onclick="runMyCode()" />
   <div id="MyDiv"></div>
  </body>
</html>
</code>```

runMyCode.gs:

```<code>function myFunctionName() {
  return "Your function has run";
}

function startYourSideBar()
{
   var ui=HtmlService.createHtmlOutputFromFile('runmycode');
   SpreadsheetApp.getUi().showSidebar(ui);
}

function buildMenu()
{
  SpreadsheetApp.getUi().createMenu('Run My Code')
     .addItem('Run My Code', 'startYourSideBar')
     .addToUi()
}
</code>```

Body:
Try this:

Build the menu first.

Click "Run My Code".

Click the "Run My Code" button.

runmycode.html:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script>
    function runMyCode()
    {
      google.script.run
         .withSuccessHandler(updateMyDiv)
         .myFunctionName();
    }
    function updateMyDiv(hl)
    {
      document.getElementById('MyDiv').innerHTML+='<br />'+ hl;
    }
    </script>
  </head>
  <body>
  <input type="button" value="Run My Code" onclick="runMyCode()" />
   <div id="MyDiv"></div>
  </body>
</html>

runMyCode.gs:

function myFunctionName() {
  return "Your function has run";
}

function startYourSideBar()
{
   var ui=HtmlService.createHtmlOutputFromFile('runmycode');
   SpreadsheetApp.getUi().showSidebar(ui);
}

function buildMenu()
{
  SpreadsheetApp.getUi().createMenu('Run My Code')
     .addItem('Run My Code', 'startYourSideBar')
     .addToUi()
}


问:
How to run headless REMOTE chrome using robot framework
I'm trying to run chrome headless with my robot framework tests suites.
I managed to do it independtly with python using selenium as follows:

```<code>options = webdriver.ChromeOptions()
options.add_argument('--headless')
my_driver = webdriver.Remote(command_executer=my_remote_address, desired_capabilities=options.to_capabilities)
</code>```

The following code is what I did in robot but didn't work:

```<code>${options}=  Evaluate  sys.modules['selenium.webdriver'].ChromeOptions()  sys, selenium.webdriver
${options.add_argument}=  Set Variable  add_argument=--headless
Create WebDriver  Chrome  chrome_options=${options}

Open Browser   http://www.google.com   chrome
</code>```

答:
```<code>${options}=  Evaluate  sys.modules['selenium.webdriver'].ChromeOptions()  sys, selenium.webdriver
Call Method    ${options}    add_argument    headless
Call Method    ${options}    add_argument    disable-gpu
Create WebDriver  Chrome  chrome_options=${options}
Goto  https://www.cnn.com/
Wait Until Page Contains    Politics today
Close Browser
</code>```

Body:
I'm trying to run chrome headless with my robot framework tests suites.
I managed to do it independtly with python using selenium as follows:

options = webdriver.ChromeOptions()
options.add_argument('--headless')
my_driver = webdriver.Remote(command_executer=my_remote_address, desired_capabilities=options.to_capabilities)

The following code is what I did in robot but didn't work:

${options}=  Evaluate  sys.modules['selenium.webdriver'].ChromeOptions()  sys, selenium.webdriver
${options.add_argument}=  Set Variable  add_argument=--headless
Create WebDriver  Chrome  chrome_options=${options}

Open Browser   http://www.google.com   chrome


问:
Missing debug symbols in statically linked binary
I'm building statically linked binary using stack and I try to add debug symbols to it (following: https://downloads.haskell.org/~ghc/master/users-guide/debug-info.html). However GDB reports: no debugging symbols found.

What am I missing?

I've added to the ghc-options in the .cabal file: -g -rtsopts and to the ld-options: -static. I am building using stack with the following command:

```<code>stack install \
    --install-ghc \
    --split-objs \
    --ghc-options="-fPIC -fllvm -pgmlo opt -pgmlc llc"
</code>```

GDB is invoked as follows: gdb --args nodebug-exe +RTS -V0

GHC 8.2.1

Whole source code is here: https://github.com/carbolymer/haskell-missing-debug-symbols

答:
--no-strip prevents debugging information being removed in the stack build.

From the documentation:

stack now supports debugging and profiling with DWARF information,
  using the --no-strip, --no-library-stripping, and
  --no-executable-stripping flags to disable the default behavior of removing such information from compiled libraries and executables.

Body:
I'm building statically linked binary using stack and I try to add debug symbols to it (following: https://downloads.haskell.org/~ghc/master/users-guide/debug-info.html). However GDB reports: no debugging symbols found.

What am I missing?

I've added to the ghc-options in the .cabal file: -g -rtsopts and to the ld-options: -static. I am building using stack with the following command:

stack install \
    --install-ghc \
    --split-objs \
    --ghc-options="-fPIC -fllvm -pgmlo opt -pgmlc llc"

GDB is invoked as follows: gdb --args nodebug-exe +RTS -V0

GHC 8.2.1

Whole source code is here: https://github.com/carbolymer/haskell-missing-debug-symbols


问:
How can I read in and bind together several data frames without using a for loop?
for() loops in R always seem to be my go-to for reading in multiple things but there must be a better way of doing what I want to do.

Let's say I have several data sets that all come from an automated data-pull system:

```<code>#Fake data set up
library(lubridate)

dir_path <- tempdir()
file_1 <- paste0(Sys.Date() - days(2), ".rds")
file_2 <-paste0(Sys.Date() - days(1), ".rds")
file_3 <- paste0(Sys.Date(), ".rds")

data.frame(thing = rnorm(100)) %>%
    saveRDS(file.path(dir_path, file_1))

data.frame(thing = rnorm(100)) %>%
    saveRDS(file.path(dir_path, file_2))

data.frame(thing = rnorm(100)) %>%
    saveRDS(file.path(dir_path, file_3))
</code>```

I want to read each of these into my R session, do a small bit of processing, to each, then stick them all into the same dataframe:

```<code>read_in_data <- function(file_name, dir){

    d <- substr(file_name, 1, 10)
    thing <-
        readRDS(file.path(dir, file_name)) %>%
        mutate(date = d)
}

files <- list.files(temp_dir(), pattern = "^2017-1")

this_thing <- NULL

for(i in 1:length(files)){
    this_thing <-
        this_thing %>%
        bind_rows(read_in_data(files[i], dir_path))
}
</code>```

This is great and does exactly what I want, but I have the sneaking suspicion that, as the number of files I want to read in and bind together grows, the for() loop will end up being very slow.

I could do something like

```<code>this_thing <-
    read_in_data(files[1], dir_path) %>%
    bind_rows(read_in_data(files[2], dir_path)) %>%
    bind_rows(read_in_data(files[3], dir_path))
</code>```

but this is gross and will be impossible to maintain, especially as the number of files I want to read in grows.

How can I get rid of this for loop? I know that growing things in a for() loop is a bad idea but I don't know how else to do this kind of operation. What am I missing? Probably something pretty simple.

答:
I ended up using the purrr package:

```<code>library(purrr)

files %>%
    map(safely(read_in_data, quiet = FALSE)) %>%
    transpose() %>%
    simplify_all() %>%
    .result() %>%
    bind_rows() %>%
    saveRDS(file.path("path to .rds file"))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
for() loops in R always seem to be my go-to for reading in multiple things but there must be a better way of doing what I want to do.

Let's say I have several data sets that all come from an automated data-pull system:

#Fake data set up
library(lubridate)

dir_path <- tempdir()
file_1 <- paste0(Sys.Date() - days(2), ".rds")
file_2 <-paste0(Sys.Date() - days(1), ".rds")
file_3 <- paste0(Sys.Date(), ".rds")

data.frame(thing = rnorm(100)) %>%
    saveRDS(file.path(dir_path, file_1))

data.frame(thing = rnorm(100)) %>%
    saveRDS(file.path(dir_path, file_2))

data.frame(thing = rnorm(100)) %>%
    saveRDS(file.path(dir_path, file_3))

I want to read each of these into my R session, do a small bit of processing, to each, then stick them all into the same dataframe:

read_in_data <- function(file_name, dir){

    d <- substr(file_name, 1, 10)
    thing <-
        readRDS(file.path(dir, file_name)) %>%
        mutate(date = d)
}

files <- list.files(temp_dir(), pattern = "^2017-1")

this_thing <- NULL

for(i in 1:length(files)){
    this_thing <-
        this_thing %>%
        bind_rows(read_in_data(files[i], dir_path))
}

This is great and does exactly what I want, but I have the sneaking suspicion that, as the number of files I want to read in and bind together grows, the for() loop will end up being very slow.

I could do something like

this_thing <-
    read_in_data(files[1], dir_path) %>%
    bind_rows(read_in_data(files[2], dir_path)) %>%
    bind_rows(read_in_data(files[3], dir_path))

but this is gross and will be impossible to maintain, especially as the number of files I want to read in grows.

How can I get rid of this for loop? I know that growing things in a for() loop is a bad idea but I don't know how else to do this kind of operation. What am I missing? Probably something pretty simple.

Body:
I ended up using the purrr package:

library(purrr)

files %>%
    map(safely(read_in_data, quiet = FALSE)) %>%
    transpose() %>%
    simplify_all() %>%
    .result() %>%
    bind_rows() %>%
    saveRDS(file.path("path to .rds file"))


问:
jQuery Sortable List - scroll bar jumps up when sorting
I created a demo: http://pastebin.me/584b9a86d715c9ba85b7bebf0375e237

When the scroll bar is at the bottom and you drag items to sort them, it causes the scroll bar to jump up. It seems to do this in FF, Safari, Chrome, and IE (at least IE8).

In Firefox on my Mac, it does the jump up when the scroll bar is at the bottom, but also adds a nice flash to the whole list. It just flashes the whole list right as it scrolls it up. I believe that if I figure out what is causing the scroll up (and if I can stop it), the flashing will stop as well.

I don't like it jumping up like that b/c I find it jarring and confusing. I know this is a bit of a corner case, but I'd like to fix it if I could.

So, is there any way to prevent it from scrolling up? Alternately, what is causing it to scroll up?

Thanks

答:
The problem is very simple.

First let's set up the scenario.  You have a list of sortable elements, your page is higher than your screen so it has a scrollbar, your page is at the very bottom, the scroll bar all the way down.

The issue, you go to drag an element which causes jQuery to remove it from the dom then add in a placeholder.  Let’s slow it down, it removes the element first, now the list is shorter causing the page to be shorter, causing the scrollbar to be shorter.  Then it adds the placeholder, now the page is longer, now the srollbar is longer (but the window doesnt scroll back down, so it appears the scroll bar jumped up).

Best way I found to counteract this would be to ensure the sortable list has a static height, so removing an element doesn't cause it to go shorter.  One method of doing this would be

```<code>create:function(){
    jQuery(this).height(jQuery(this).height());
}
</code>```

The above will be called upon the creation of the sortable list, staticly setting its height to it's current height.

If you have pictures in one of the sortable elements, the above code will not work unless you pre-define the dimensions in the  tag.  Reason is that when the height() is called and set, it's calculating before the image is filled out.  No dimension, then the image accounts for no space.  Once the image loads, then will it take up space.

Here is a way around having to define dimensions.  Simply resize the list height every time an image within is detected to be loaded.

```<code>create:function(){
    var list=this;
    jQuery(list).find('img').load(function(){
        jQuery(list).height(jQuery(list).height());
    });
}
</code>```

Final version:

```<code>jQuery(document).ready(function(){
    jQuery("div#todoList").sortable({
        handle:'img.moveHandle',
        opacity: 0.6,
        cursor: 'move',
        tolerance: 'pointer',
        forcePlaceholderSize: true,
        update:function(){
            jQuery("body").css('cursor','progress');
            var order = jQuery(this).sortable('serialize');
            jQuery.post("/ajax.php?do=sort&"+order,function(data){jQuery("body").css('cursor','default');});
        },
        create:function(){
            var list=this;
            var resize=function(){
                jQuery(list).css("height","auto");
                jQuery(list).height(jQuery(list).height());
            };
            jQuery(list).height(jQuery(list).height());
            jQuery(list).find('img').load(resize).error(resize);
        }
    });
});
</code>```

Body:
The problem is very simple.

First let's set up the scenario.  You have a list of sortable elements, your page is higher than your screen so it has a scrollbar, your page is at the very bottom, the scroll bar all the way down.

The issue, you go to drag an element which causes jQuery to remove it from the dom then add in a placeholder.  Let’s slow it down, it removes the element first, now the list is shorter causing the page to be shorter, causing the scrollbar to be shorter.  Then it adds the placeholder, now the page is longer, now the srollbar is longer (but the window doesnt scroll back down, so it appears the scroll bar jumped up).

Best way I found to counteract this would be to ensure the sortable list has a static height, so removing an element doesn't cause it to go shorter.  One method of doing this would be

create:function(){
    jQuery(this).height(jQuery(this).height());
}

The above will be called upon the creation of the sortable list, staticly setting its height to it's current height.

If you have pictures in one of the sortable elements, the above code will not work unless you pre-define the dimensions in the  tag.  Reason is that when the height() is called and set, it's calculating before the image is filled out.  No dimension, then the image accounts for no space.  Once the image loads, then will it take up space.

Here is a way around having to define dimensions.  Simply resize the list height every time an image within is detected to be loaded.

create:function(){
    var list=this;
    jQuery(list).find('img').load(function(){
        jQuery(list).height(jQuery(list).height());
    });
}

Final version:

jQuery(document).ready(function(){
    jQuery("div#todoList").sortable({
        handle:'img.moveHandle',
        opacity: 0.6,
        cursor: 'move',
        tolerance: 'pointer',
        forcePlaceholderSize: true,
        update:function(){
            jQuery("body").css('cursor','progress');
            var order = jQuery(this).sortable('serialize');
            jQuery.post("/ajax.php?do=sort&"+order,function(data){jQuery("body").css('cursor','default');});
        },
        create:function(){
            var list=this;
            var resize=function(){
                jQuery(list).css("height","auto");
                jQuery(list).height(jQuery(list).height());
            };
            jQuery(list).height(jQuery(list).height());
            jQuery(list).find('img').load(resize).error(resize);
        }
    });
});


问:
jquery UI Datepicker fails to update month or year -- must select date
Datepicker selection does not change the year or month unless the user selects a date. Looking for month/year to update even if date is not selected:</p>

```<code><input class="childdob dateinput datepickers hasDatepicker valid"
placeholder="Date of Birth*" name="child_dob[0]" type="text">

$(function() {

        $('form').on('focus', '.datepickers', function(event){
            event.preventDefault();
                 $(this).datepicker( {
                    changeMonth: true,
                    changeYear: true,
                    yearRange: '1990:+0',
                    showButtonPanel: true,
                    dateFormat: 'mm/dd/y',
                    constrainInput: false
                }).datepicker('show');
        });

    });
</code>```

答:
Here's an example that demonstrates updating the selected month and year when the month/year dropdown menus are changed or the month arrows are clicked without a date being directly selected. It arbitrarily sets the day to the 1st of each month, so you would need to modify if you wanted that to persist after a day has been selected.

$(function() {
  $(".datepickers").datepicker({
    changeMonth: true,
    changeYear: true,
    yearRange: '1990:+0',
    showButtonPanel: true,
    dateFormat: 'mm/dd/yy',
    constrainInput: false,
    onChangeMonthYear: function(year, month) {
      var selectedMonth = month;
      var selectedYear = year;
      $(this).datepicker("setDate", month + "/01/" + year);
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<p>Date: <input type="text" class="datepickers"></p></code>```

Body:
Datepicker selection does not change the year or month unless the user selects a date. Looking for month/year to update even if date is not selected:

<input class="childdob dateinput datepickers hasDatepicker valid"
placeholder="Date of Birth*" name="child_dob[0]" type="text">

$(function() {

        $('form').on('focus', '.datepickers', function(event){
            event.preventDefault();
                 $(this).datepicker( {
                    changeMonth: true,
                    changeYear: true,
                    yearRange: '1990:+0',
                    showButtonPanel: true,
                    dateFormat: 'mm/dd/y',
                    constrainInput: false
                }).datepicker('show');
        });

    });

Body:
Here's an example that demonstrates updating the selected month and year when the month/year dropdown menus are changed or the month arrows are clicked without a date being directly selected. It arbitrarily sets the day to the 1st of each month, so you would need to modify if you wanted that to persist after a day has been selected.

$(function() {
  $(".datepickers").datepicker({
    changeMonth: true,
    changeYear: true,
    yearRange: '1990:+0',
    showButtonPanel: true,
    dateFormat: 'mm/dd/yy',
    constrainInput: false,
    onChangeMonthYear: function(year, month) {
      var selectedMonth = month;
      var selectedYear = year;
      $(this).datepicker("setDate", month + "/01/" + year);
    }
  });
});

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<p>Date: <input type="text" class="datepickers"></p>


问:
Unit testing singleton without using PowerMock or PowerMockito
I am writing unit tests (using JUnit and Mockito) for a singleton Java class. I cannot change the class implementation itself.

With PowerMockito, it was like this (and works):

```<code>@Mock
    private TheSingleton theSingleton;

@Before
    public final void setUp()
        throws Exception
    {
        MockitoAnnotations.initMocks( this );

        PowerMockito.mockStatic( TheSingleton.class );
        when( TheSingleton.getInstance() ).thenReturn( theSingleton );
        ...
    }
</code>```

The ask is to rewrite the test without using PowerMock or PowerMockito or any other static mocking API. Since I cannot change the singleton class to instead use dependency injection, I am not sure what would be a good way of doing this.

Any help will be greatly appreciated.

答:
You essentially don't have other options.  Without any sort of static mocking framework, such as PowerMock or PowerMockito or writing your own code that does the same sort of thing that these do, you won't be able to do what you want.  Sorry, I know that's not the answer you want, but I do believe it is the answer.

See also How to change method behaviour through reflection? and Why does Mockito not mock static methods? for more insight.

Body:
I am writing unit tests (using JUnit and Mockito) for a singleton Java class. I cannot change the class implementation itself.

With PowerMockito, it was like this (and works):

@Mock
    private TheSingleton theSingleton;

@Before
    public final void setUp()
        throws Exception
    {
        MockitoAnnotations.initMocks( this );

        PowerMockito.mockStatic( TheSingleton.class );
        when( TheSingleton.getInstance() ).thenReturn( theSingleton );
        ...
    }

The ask is to rewrite the test without using PowerMock or PowerMockito or any other static mocking API. Since I cannot change the singleton class to instead use dependency injection, I am not sure what would be a good way of doing this.

Any help will be greatly appreciated.


问:
MobX + React makes me mad
First of all, I am not experienced React developer. Just let you know.

I have a store:

```<code>import {observable, action, reaction, computed, autorun} from 'mobx';
import scrollTo from 'react-scroll-to-component'
</code>```

class ActivePostsStore {

```<code>  @observable _posts = new Map()
  @observable _visiblePosts = new Set()

  @computed get visiblePosts() {
    return this._visiblePosts
  }

  @action
  addPost(uuid, ref) {
    // console.log('add post')
    this._posts.set(uuid, ref)
  }

  @action
  scrollToPost(uuid) {
    // console.log('scroll to post')
    scrollTo(this._posts.get(uuid), {})
  }

  @action
  addVisiblePost(uuid) {
    console.log('add vis post', this._visiblePosts.values())
    this._visiblePosts.add(uuid)
  }

  @action
  removeVisiblePost(uuid) {
    console.log('rem vis post', this._visiblePosts.values())
    this._visiblePosts = new Set([...this._visiblePosts].filter(el => el !== uuid))
  }

  // reacts = reaction(() => this._visiblePosts, () => console.log('===='))
  // reactToVisiblePosts() {
  //
  // }
}

const store = new ActivePostsStore()
export default store
</code>```

My first problem, that I can pass store through Provider in my Layout Component or _document.js (I use Next.js).

```<code>/*Doesn't work. In root layout*/
<Provider store={ActivePostsStore}>
  <Content />
</Provider>
</code>```

Every time when I tried to use Provider I got my store undefined. In RootLayout or _document.js too. Sure, I provided @observer annotation for component which use store. But store is still undefined.

Then, I tried to use @inject('activePostsStore') result is Error, that tells me, like I didn't provide any store at all. But, actually, I did.

SO! I decided to inject it directly like:

```<code>@inject(() => ({
  store: ActivePostsStore
}))
@observer
</code>```

Finally, I can use actions to add or remove elements for visiblePosts (i log it). BUT! My store props does not react at all, if I change state of store. For example it does not react to adding new entries to visiblePosts. Or it even can be undefined if I reload page. My code for component is:

```<code>render() {
    const {classes} = this.props
    return (
      <div className={classNames(classes.postsTree)}>
        {this.props.store.visiblePosts}
        {this.state.groupedDates !== undefined && this.state.groupedDates.map(([date, posts], index) =>
          <PostsTreeGroup
            active={_.some(posts.map(([uuid]) => uuid), uuid => this.props.store.visiblePosts.has(uuid))}
            key={date}
            date={date}
            posts={posts}/>
        )}
      </div>
    )
  }
</code>```

Can somebody help me to make things works, please!

答: Small addition: it seems at first sight that you are passing a class to the provider rather then an instance thereof (ActivePostsStore). Make sure to instantiate your class so that you get an actual store to work with. (If you did create an instance, then best stick the convention to use lowercase first letter)

Title: MobX + React makes me mad

Body:
First of all, I am not experienced React developer. Just let you know.

I have a store:

import {observable, action, reaction, computed, autorun} from 'mobx';
import scrollTo from 'react-scroll-to-component'

class ActivePostsStore {

  @observable _posts = new Map()
  @observable _visiblePosts = new Set()

  @computed get visiblePosts() {
    return this._visiblePosts
  }

  @action
  addPost(uuid, ref) {
    // console.log('add post')
    this._posts.set(uuid, ref)
  }

  @action
  scrollToPost(uuid) {
    // console.log('scroll to post')
    scrollTo(this._posts.get(uuid), {})
  }

  @action
  addVisiblePost(uuid) {
    console.log('add vis post', this._visiblePosts.values())
    this._visiblePosts.add(uuid)
  }

  @action
  removeVisiblePost(uuid) {
    console.log('rem vis post', this._visiblePosts.values())
    this._visiblePosts = new Set([...this._visiblePosts].filter(el => el !== uuid))
  }

  // reacts = reaction(() => this._visiblePosts, () => console.log('===='))
  // reactToVisiblePosts() {
  //
  // }
}

const store = new ActivePostsStore()
export default store

My first problem, that I can pass store through Provider in my Layout Component or _document.js (I use Next.js).

/*Doesn't work. In root layout*/
<Provider store={ActivePostsStore}>
  <Content />
</Provider>

Every time when I tried to use Provider I got my store undefined. In RootLayout or _document.js too. Sure, I provided @observer annotation for component which use store. But store is still undefined.

Then, I tried to use @inject('activePostsStore') result is Error, that tells me, like I didn't provide any store at all. But, actually, I did.

SO! I decided to inject it directly like:

@inject(() => ({
  store: ActivePostsStore
}))
@observer

Finally, I can use actions to add or remove elements for visiblePosts (i log it). BUT! My store props does not react at all, if I change state of store. For example it does not react to adding new entries to visiblePosts. Or it even can be undefined if I reload page. My code for component is:

render() {
    const {classes} = this.props
    return (

        {this.props.store.visiblePosts}
        {this.state.groupedDates !== undefined && this.state.groupedDates.map(([date, posts], index) =>
          <PostsTreeGroup
            active={_.some(posts.map(([uuid]) => uuid), uuid => this.props.store.visiblePosts.has(uuid))}
            key={date}
            date={date}
            posts={posts}/>
        )}

    )
  }

Can somebody help me to make things works, please!


问:
Disable swipe to view sidemenu ionic 2
I'm using a sidemenu ionic 2.  when I swipe this page from left to right the side menu slides out i need to disable sidemenu swipe in particular page.

app.html

```<code>    <ion-menu [content]="content">
     <ion-content>
      <ion-list>
       <button ion-item *ngFor="let p of pages" menuClose (click)="openPage(p)" >
        <ion-icon name="{{p.icon}}" item-left></ion-icon>
        {{p.title}}
      </button>
     </ion-list>
  </ion-content>
</ion-menu>

<ion-nav id="nav" [root]="rootPage" #content swipeBackEnabled="true"></ion-nav>
</code>```

page.html I went to disable swipemenu in this page, Disable only when i swipe

```<code>import {Component} from '@angular/core';
import {NavController} from 'ionic-angular';
@Component({
  templateUrl: 'build/pages/portrait/portrait.html'
})
export class Portrait {
}
</code>```

page.html

```<code><ion-navbar persianred *navbar>
  <button menuToggle>
    <ion-icon name="menu"></ion-icon>
  </button>
  <ion-title>
   Portrait
  </ion-title>
</ion-navbar>
</code>```

答:
Based on that "swipeEnabled" option, what I did was set a conditional using a boolean variable.

```<code><ion-menu [content]="content" [swipeEnabled]="(userLogged) ? true : false">
</code>```

It worked great for me.

Just an advice: Maybe anyone notice that in case the variable is not a global one, the app will stay without the swipe even after jump to another page. However, beyond setting the variabel as global will resolve, after the user close and reopen the app, the swipe will work normally.

Title: Disable swipe to view sidemenu ionic 2

Body:
I'm using a sidemenu ionic 2.  when I swipe this page from left to right the side menu slides out i need to disable sidemenu swipe in particular page.

app.html

    <ion-menu [content]="content">
     <ion-content>
      <ion-list>
       <button ion-item *ngFor="let p of pages" menuClose (click)="openPage(p)" >
        <ion-icon name="{{p.icon}}" item-left></ion-icon>
        {{p.title}}
      </button>
     </ion-list>
  </ion-content>
</ion-menu>

<ion-nav id="nav" [root]="rootPage" #content swipeBackEnabled="true"></ion-nav>

page.html I went to disable swipemenu in this page, Disable only when i swipe

import {Component} from '@angular/core';
import {NavController} from 'ionic-angular';
@Component({
  templateUrl: 'build/pages/portrait/portrait.html'
})
export class Portrait {
}

page.html

<ion-navbar persianred *navbar>
  <button menuToggle>
    <ion-icon name="menu"></ion-icon>
  </button>
  <ion-title>
   Portrait
  </ion-title>
</ion-navbar>

Body:
Based on that "swipeEnabled" option, what I did was set a conditional using a boolean variable.

<ion-menu [content]="content" [swipeEnabled]="(userLogged) ? true : false">

It worked great for me.

Just an advice: Maybe anyone notice that in case the variable is not a global one, the app will stay without the swipe even after jump to another page. However, beyond setting the variabel as global will resolve, after the user close and reopen the app, the swipe will work normally.


问:
Align Multiple Views at the bottom of screen
I'm new to Android and I want to create an activity with 3 set (line) of Buttons at the bottom of screen .For my example I wrote this code for 2 set (line) of buttons:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:layout_alignParentBottom="true">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="1" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="2" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="3" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="4" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="5" />
</LinearLayout>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:layout_alignParentBottom="true">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="6" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="7" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="8" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="9" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="10" />
</LinearLayout>
</RelativeLayout>
</code>```

I want to buttons 6-10 put on (above) the buttons 1-5 (like Stack).

How I can do this?

Thanks

答:
Try to wrap your two LinearLayout in a parent linearLayout.
That parent layout need to be aligned to the bottom.

Something like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:layout_alignParentBottom="true"
    android:orientation="vertical">

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    >

      <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="1" />

      <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="2" />

      <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="3" />

      <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="4" />

      <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="5" />
  </LinearLayout>

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    >

      <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="6" />

      <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="7" />

      <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="8" />

      <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="9" />

      <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="10" />
  </LinearLayout>
</LinearLayout>
</RelativeLayout>
</code>```

Body:
I'm new to Android and I want to create an activity with 3 set (line) of Buttons at the bottom of screen .For my example I wrote this code for 2 set (line) of buttons:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:layout_alignParentBottom="true">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="1" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="2" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="3" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="4" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="5" />
</LinearLayout>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:layout_alignParentBottom="true">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="6" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="7" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="8" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="9" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="10" />
</LinearLayout>
</RelativeLayout>

I want to buttons 6-10 put on (above) the buttons 1-5 (like Stack).

How I can do this?

Thanks

Body:
Try to wrap your two LinearLayout in a parent linearLayout.
That parent layout need to be aligned to the bottom.

Something like this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:layout_alignParentBottom="true"
    android:orientation="vertical">

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    >

      <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="1" />

      <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="2" />

      <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="3" />

      <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="4" />

      <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="5" />
  </LinearLayout>

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    >

      <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="6" />

      <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="7" />

      <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="8" />

      <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="9" />

      <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="10" />
  </LinearLayout>
</LinearLayout>
</RelativeLayout>


问:
.NET how to avoid cancellation of Button Click event after a Textbox TextChanged event
I have a textbox using [OnTextChange] event (VB.NET), and have to use [AutoPostBack="True"] to check itself value from DB:

```<code><asp:TextBox ID="Item1" TabIndex="7" runat="server" AutoPostBack="True"></asp:TextBox>
</code>```

Scenario is:

Inputs anything on textbox and not yet focus out of textbox.

Click any button in same form of that textbox.

Unwanted Result:

Event [On Click] of that button has been canceled, only OnTextChange event fired.

Have to click on that button again.

Wanted Result:

Event [On Click] of button will be fire after event OnTextChanged fired

I searched around google and known that's an issue with .NET event. But still doesn't findout any helpful solution.

Please help.

答:
I just ran into the same problem. The reason the button event was not firing was that in the subroutine to process the text changed event, I had to reload the page. I combined several approaches and came up with this solution which seems to work: 1) I added a hidden field on the page which stores a state of whether or not the button has been clicked with initial value of false; 2) I added an OnClientClick to the button which calls a javascript function to set the hidden field value to true; 3) in the code behind subroutine that processes the text changed event, I check the value of the hidden field before I use a Response.Redirect to reload the page. Below are the code snippets:

```<code><asp:HiddenField ID="addtocarthiddenfield" runat="server" Value="false" ClientIDMode="Static" />

OnClientClick="setAddCartClicked();"

<script type="text/javascript">
        function setAddCartClicked() {
            document.getElementById('addtocarthiddenfield').value = 'true';
        }
    </script>

Dim addtocart As Boolean = addtocarthiddenfield.Value

If addtocart = False Then
    Response.Redirect("MyAccount_Favorites.aspx")
End If
</code>```

I hope this helps.

Body:
I have a textbox using [OnTextChange] event (VB.NET), and have to use [AutoPostBack="True"] to check itself value from DB:

<asp:TextBox ID="Item1" TabIndex="7" runat="server" AutoPostBack="True"></asp:TextBox>

Scenario is:

Inputs anything on textbox and not yet focus out of textbox.

Click any button in same form of that textbox.

Unwanted Result:

Event [On Click] of that button has been canceled, only OnTextChange event fired.

Have to click on that button again.

Wanted Result:

Event [On Click] of button will be fire after event OnTextChanged fired

I searched around google and known that's an issue with .NET event. But still doesn't findout any helpful solution.

Please help.

Body:
I just ran into the same problem. The reason the button event was not firing was that in the subroutine to process the text changed event, I had to reload the page. I combined several approaches and came up with this solution which seems to work: 1) I added a hidden field on the page which stores a state of whether or not the button has been clicked with initial value of false; 2) I added an OnClientClick to the button which calls a javascript function to set the hidden field value to true; 3) in the code behind subroutine that processes the text changed event, I check the value of the hidden field before I use a Response.Redirect to reload the page. Below are the code snippets:

<asp:HiddenField ID="addtocarthiddenfield" runat="server" Value="false" ClientIDMode="Static" />

OnClientClick="setAddCartClicked();"

<script type="text/javascript">
        function setAddCartClicked() {
            document.getElementById('addtocarthiddenfield').value = 'true';
        }
    </script>

Dim addtocart As Boolean = addtocarthiddenfield.Value

If addtocart = False Then
    Response.Redirect("MyAccount_Favorites.aspx")
End If

I hope this helps.