问:
Cannot read property 'viewContainerRef' of undefined
I am trying to display a dynamic component similar (not exact) to the example in angular docs.

I have a dynamic directive with viewContainerRef

```<code>@Directive({
   selector: '[dynamicComponent]'
})
export class DynamicComponentDirective {
   constructor(public viewContainerRef: ViewContainerRef) { }
}
</code>```

Excerpt from component code

```<code>@ViewChild(DynamicComponentDirective) adHost: DynamicComponentDirective;
..
ngAfterViewInit() {
let componentFactory = null;
                console.log(component);
                componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
                // this.adHost.viewContainerRef.clear();
                const viewContainerRef = this.adHost.viewContainerRef;
                viewContainerRef.createComponent(componentFactory);
}
</code>```

Finally added <ng-template dynamicComponent></ng-template> in template

答:
Noted that I face the same problem if directive selector (dynamicComponent in this case) is at :

first element of the component

parent element with *ngIf condition

Hence, I avoid it by put it inside at non-root tag in the component html & load component to viewContainerRef only when the condition match.

Body:
I am trying to display a dynamic component similar (not exact) to the example in angular docs.

I have a dynamic directive with viewContainerRef

@Directive({
   selector: '[dynamicComponent]'
})
export class DynamicComponentDirective {
   constructor(public viewContainerRef: ViewContainerRef) { }
}

Excerpt from component code

@ViewChild(DynamicComponentDirective) adHost: DynamicComponentDirective;
..
ngAfterViewInit() {
let componentFactory = null;
                console.log(component);
                componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
                // this.adHost.viewContainerRef.clear();
                const viewContainerRef = this.adHost.viewContainerRef;
                viewContainerRef.createComponent(componentFactory);
}

Finally added <ng-template dynamicComponent></ng-template> in template


来源: stackexchange

问:
PyHook doesn't detect key pressed in some windows
I ran this PyHook sample code:

```<code>    import pythoncom, pyHook

def OnKeyboardEvent(event):
    print 'MessageName:',event.MessageName
    print 'Message:',event.Message
    print 'Time:',event.Time
    print 'Window:',event.Window
    print 'WindowName:',event.WindowName
    print 'Ascii:', event.Ascii, chr(event.Ascii)
    print 'Key:', event.Key
    print 'KeyID:', event.KeyID
    print 'ScanCode:', event.ScanCode
    print 'Extended:', event.Extended
    print 'Injected:', event.Injected
    print 'Alt', event.Alt
    print 'Transition', event.Transition
    print '---'

# return True to pass the event to other handlers
    return True

# create a hook manager
hm = pyHook.HookManager()
# watch for all mouse events
hm.KeyDown = OnKeyboardEvent
# set the hook
hm.HookKeyboard()
# wait forever
pythoncom.PumpMessages()
</code>```

To try it out and it works in most windows but when I try it inside a game window it acts like I'm not pressing anything.

Is there a way to listen to keypresses from a specific process? what should I do?

答:
Games often use hooks to handle input in much the same way as you are trying to, the way that hooks work under windows is as a chain, IIRC the last hook added is the first hook called, so it may be that if you are starting your script before the game then the games hook is called before yours, handles the event and so nothing reaches your hook.

Another possibility is that to prevent people for scripting/automating games or otherwise making things to help the player games will re-register the hooks periodically to ensure it is always at the head of the hook chain, if this is the case then you will find it difficult to overcome.

ContentLicense: CC BY-SA 3.0

Body:
I ran this PyHook sample code:

    import pythoncom, pyHook

def OnKeyboardEvent(event):
    print 'MessageName:',event.MessageName
    print 'Message:',event.Message
    print 'Time:',event.Time
    print 'Window:',event.Window
    print 'WindowName:',event.WindowName
    print 'Ascii:', event.Ascii, chr(event.Ascii)
    print 'Key:', event.Key
    print 'KeyID:', event.KeyID
    print 'ScanCode:', event.ScanCode
    print 'Extended:', event.Extended
    print 'Injected:', event.Injected
    print 'Alt', event.Alt
    print 'Transition', event.Transition
    print '---'

# return True to pass the event to other handlers
    return True

# create a hook manager
hm = pyHook.HookManager()
# watch for all mouse events
hm.KeyDown = OnKeyboardEvent
# set the hook
hm.HookKeyboard()
# wait forever
pythoncom.PumpMessages()

To try it out and it works in most windows but when I try it inside a game window it acts like I'm not pressing anything.

Is there a way to listen to keypresses from a specific process? what should I do?

ContentLicense: CC BY-SA 4.0


问:
Regex to extract hashtags with two dot-separated parts
I'm trying to create a regular expression in order to extract some text from strings. I want to extract text from urls or normal text messages e.g.:

```<code>endpoint/?userId=#someuser.id
</code>```

OR

```<code>Hi #someuser.name, how are you?
</code>```

And from both I want to extract exactly #someuser.name from message and #someuser.id from url. There might be be many of those string to extract from the url and messages.

My regular expression currently looks like this:

```<code>(#[^\.]+?\.)([^\W]\w+\b)
</code>```

It works fine, except one for one case and I don't know how to do it - e.g.:

Those strings SHOULD NOT be matched: # .id, #.id. There must be at least one character between # and .. One or more spaces between those characters should not be matched.

How can I do it using my current regex?

答:
The redefined requirements are:

We search for pattern #A.B

A can be anything, except for only whitespaces, nor may it contain # or .

B can only be regular ASCII letters or digits

Converting those requirements into a (possible) regex:

```<code>#[^.#]+((?<!#\\s+)\\.)[A-Za-z0-9]+
</code>```

Explanation:

#[^.#]+((?<!#\\s+)\\.)[A-Za-z0-9]+  # The entire capture for the Java-Matcher:
#                                   #  A literal '#' character
 [^.#]+                             #  Followed by 1 or more characters which are NOT '.' nor '#'
       (          \\.)              #  Followed by a '.' character
        (?<!     )                  #  Which is NOT preceded by (negative lookbehind):
            #                       #   A literal '#'
             \\s+                   #   With 1 or more whitespaces
                      [A-Za-z0-9]+  #  Followed by 1 or more alphanumeric characters
                                    #  (PS: \\w+ could be used here if '_' is allowed as well)
```

<p><strong>Test code:</strong></p>

<pre class="lang-java prettyprint-override"><code>String input = "endpoint/?userId=#someuser.id Hi #someuser.name, how are you? # .id #.id %^*#@*(.H(@EH Ok, # some spaces here .but none here #$p€©ï@l.$p€©ï@l that should do it..";
System.out.println("Input: \""+ input + '"');

System.out.println("Outputs: ");
java.util.regex.Matcher matcher = java.util.regex.Pattern.compile("#[^.#]+((?<!#\\s+)\\.)[A-Za-z0-9]+")
                                                         .matcher(input);
while(matcher.find())
  System.out.println('"'+matcher.group()+'"');
</code>```

Try it online.

Which outputs:

Input: "endpoint/?userId=#someuser.id Hi #someuser.name, how are you? # .id #.id %^*#@*(.H(@EH Ok, # some spaces here .but none here #$p€©ï@l.$p€©ï@l that should do it.."
Outputs:
"#someuser.id"
"#someuser.name"
"#@*(.H"
"# some spaces here .but"
```

Body:
I'm trying to create a regular expression in order to extract some text from strings. I want to extract text from urls or normal text messages e.g.:

endpoint/?userId=#someuser.id

OR

Hi #someuser.name, how are you?

And from both I want to extract exactly #someuser.name from message and #someuser.id from url. There might be be many of those string to extract from the url and messages.

My regular expression currently looks like this:

(#[^\.]+?\.)([^\W]\w+\b)

It works fine, except one for one case and I don't know how to do it - e.g.:

Those strings SHOULD NOT be matched: # .id, #.id. There must be at least one character between # and .. One or more spaces between those characters should not be matched.

How can I do it using my current regex?

Body:
The redefined requirements are:

We search for pattern #A.B

A can be anything, except for only whitespaces, nor may it contain # or .

B can only be regular ASCII letters or digits

Converting those requirements into a (possible) regex:

#[^.#]+((?<!#\\s+)\\.)[A-Za-z0-9]+

Explanation:

#[^.#]+((?<!#\\s+)\\.)[A-Za-z0-9]+  # The entire capture for the Java-Matcher:
#                                   #  A literal '#' character
 [^.#]+                             #  Followed by 1 or more characters which are NOT '.' nor '#'
       (          \\.)              #  Followed by a '.' character
        (?<!     )                  #  Which is NOT preceded by (negative lookbehind):
            #                       #   A literal '#'
             \\s+                   #   With 1 or more whitespaces
                      [A-Za-z0-9]+  #  Followed by 1 or more alphanumeric characters
                                    #  (PS: \\w+ could be used here if '_' is allowed as well)

Test code:

String input = "endpoint/?userId=#someuser.id Hi #someuser.name, how are you? # .id #.id %^*#@*(.H(@EH Ok, # some spaces here .but none here #$p€©ï@l.$p€©ï@l that should do it..";
System.out.println("Input: \""+ input + '"');

System.out.println("Outputs: ");
java.util.regex.Matcher matcher = java.util.regex.Pattern.compile("#[^.#]+((?<!#\\s+)\\.)[A-Za-z0-9]+")
                                                         .matcher(input);
while(matcher.find())
  System.out.println('"'+matcher.group()+'"');

<a href="https://tio.run/##nVBBTsMwELzzisUB1Wkaw5VC1XJAag9VkbjRtJKbmMZtYkex3VJQL/wGCYk/wE/4SHCaVCABF3zw7npnvDuzoCvqL6JlUYQJVQqGlIvHA4DMzBIegtJU27CSPILUtvCNzrmYjydA3RIGUD0AF5nR0AHERJRJLvRJ1yiWD6KOo2TKypzYP/ocvmpBU9aCWK6B5gw20nTBgRLllNfxtOn0mpj0ce@qD6NlyzZLKqiMhkxBzCyJzOxUIQWrSuco@3h6eXt@f@0l5FsOOqYaVCxNEkEkgWtC0Hm1/0ZplhJpNMmsEp0IjAalmDYECHm1MA8aqOFWjD9pI6MtVrUB1ciFNZcYzROSszm7J0OqQ7undbKKnR@Ia6o1ywUJZZrxhGHkjKfEmXgYdy8OnSBQnhsExB1f@rfUfzj1zyYecnez/n1IvQ3eKa03X8fl9LpD7riIsLuf84t0a463B89zaTLsenvDtgfbovgE" rel="nofollow noreferrer">Try it online.

Which outputs:

Input: "endpoint/?userId=#someuser.id Hi #someuser.name, how are you? # .id #.id %^*#@*(.H(@EH Ok, # some spaces here .but none here #$p€©ï@l.$p€©ï@l that should do it.."
Outputs:
"#someuser.id"
"#someuser.name"
"#@*(.H"
"# some spaces here .but"


问:
Showing near "total_entries" in Rails
Using RoR 2.3.8

Usually we have the following code:

```<code>Showing <%= @shops.total_entries %> shops in Canada.
</code>```

yields the result:

```<code>Showing 46 shops in Canada
</code>```

What if I want it to show round-down value:

```<code>Showing 40+ shops in Canada
</code>```

Whereas for <10 total entries, it should show the exact number.

Thankyou.

答:
```<code>def round(total)
  total > 10 && total%10 != 0 ? [total/10*10,"+"].join : total.to_s
end

Showing <%= round(@shops.total_entries) %> shops in Canada.
</code>```

and of course it would be better to wrap it as a Model method

```<code>class Shop < ActiveRecord::Base
  def self.round
    total = count
    total > 10 && total%10 != 0 ? [total/10*10,"+"].join : total.to_s
    # instead of using `[total/10*10,"+"].join` you can use `(total/10*10).to_s+"+"`
  end
end

@shops = Shop.were(:region => "Canada")

Showing <%= @shops.round %> shops in Canada.
</code>```

Title: Showing near "total_entries" in Rails

Body:
Using RoR 2.3.8

Usually we have the following code:

Showing <%= @shops.total_entries %> shops in Canada.

yields the result:

Showing 46 shops in Canada

What if I want it to show round-down value:

Showing 40+ shops in Canada

Whereas for <10 total entries, it should show the exact number.

Thankyou.

Body:
def round(total)
  total > 10 && total%10 != 0 ? [total/10*10,"+"].join : total.to_s
end

Showing <%= round(@shops.total_entries) %> shops in Canada.

and of course it would be better to wrap it as a Model method

class Shop < ActiveRecord::Base
  def self.round
    total = count
    total > 10 && total%10 != 0 ? [total/10*10,"+"].join : total.to_s
    # instead of using `[total/10*10,"+"].join` you can use `(total/10*10).to_s+"+"`
  end
end

@shops = Shop.were(:region => "Canada")

Showing <%= @shops.round %> shops in Canada.


问:
Numpy slice and join
I have an array that I would like to slice into multiple arrays in the form of:

```<code>M = [1,2,3          to [ [1],[2]....[9] ]  (List of arrays)
     4,5,6
     7,8,9]
</code>```

And I would like to know how to join them back to get M again.
I can't find any other solution than to name each array and place it in its correct (row,column) position manually.

EDIT:

I found that my explanation was unclear. What I have is a big array that I would like to slice it into subarrays.

```<code>  M.shape = (5000,5000,3)    =====> L = [ subarray1, subarray2 ...]
  with subarray.shape = (500,500,3)
</code>```

Second Step: Merging back

```<code>from L = [ subarray1, ...] to M
</code>```

Thank for your help !

答:
You can do it in the following way

M = np.array([[1,2,3],[4,5,6],[7,8,9]])
A = M.reshape(-1,1)
print(A)
#for getting back in the original form
a = len(A)
c = [A[i-3:i] for i in range(3,a+1,3)]
c_new = np.array([np.concatenate(i) for i in c]).reshape(3,3)
print(c_new)
```

<p>A--</p>

<pre class="lang-py prettyprint-override"><code>[[1]
 [2]
 [3]
 [4]
 [5]
 [6]
 [7]
 [8]
 [9]]
</code>```

c_new --

[[1 2 3]
 [4 5 6]
 [7 8 9]]
```

Title: Numpy slice and join

Body:
I have an array that I would like to slice into multiple arrays in the form of:

M = [1,2,3          to [ [1],[2]....[9] ]  (List of arrays)
     4,5,6
     7,8,9]

And I would like to know how to join them back to get M again.
I can't find any other solution than to name each array and place it in its correct (row,column) position manually.

EDIT:

I found that my explanation was unclear. What I have is a big array that I would like to slice it into subarrays.

  M.shape = (5000,5000,3)    =====> L = [ subarray1, subarray2 ...]
  with subarray.shape = (500,500,3)

Second Step: Merging back

from L = [ subarray1, ...] to M

Thank for your help !

Body:
You can do it in the following way

M = np.array([[1,2,3],[4,5,6],[7,8,9]])
A = M.reshape(-1,1)
print(A)
#for getting back in the original form
a = len(A)
c = [A[i-3:i] for i in range(3,a+1,3)]
c_new = np.array([np.concatenate(i) for i in c]).reshape(3,3)
print(c_new)

A--

[[1]
 [2]
 [3]
 [4]
 [5]
 [6]
 [7]
 [8]
 [9]]

c_new --

[[1 2 3]
 [4 5 6]
 [7 8 9]]


问:
why pam_sm_authenticate is called twice when ssh login?
i am tring to make PAM module that authenticate user and password and also get a trap when logout has occurred but i don't understand why pam_sm_authenticate  is called twice?

i have build my own pam_hook.so , compiled it with:

```<code> gcc -fPIC -Wall -shared -lpam -o pam_hook.so pam_hook.c
</code>```

i have implemnted this function's :

```<code>PAM_EXTERN int pam_sm_authenticate(pam_handle_t *pamh, int flags, int argc, const char **argv);
PAM_EXTERN int pam_sm_setcred(pam_handle_t *pamh, int flags, int argc, const char **argv);
PAM_EXTERN int pam_sm_chauthtok(pam_handle_t    *pamh,const int flags,int argc,const char **argv);
PAM_EXTERN int pam_sm_acct_mgmt(pam_handle_t *pamh, int flags, int argc, const char **argv);
PAM_EXTERN int pam_sm_open_session(pam_handle_t *pamh, int flags, int argc, const char **argv);
PAM_EXTERN int pam_sm_close_session(pam_handle_t *pamh, int flags, int argc, const char **argv);
</code>```

i have printed to file each enter to this function's.
the order of the call to the function's on login of sshd user :

```<code>function :  pam_sm_authenticate
function :  pam_sm_setcred
function :  pam_sm_open_session
function :  pam_sm_setcred
function :  pam_sm_authenticate
</code>```

and on sshd logout:

```<code>function :  pam_sm_close_session
function :  pam_sm_setcred
</code>```

i can't understand why pam_sm_authenticate  it is called twice ,
my /etc/pamd.d/sshd:

```<code># cat /etc/pam.d/sshd
 session     optional       /path_to/pam_hook.so
 auth        requisite       /path_to/pam_hook.so
</code>```

答:
Just faced this problem and it took me time to find a reason.
In my case I use custom conversation in pam_sm_authenticate() to ask user for a second password.
My module called twice, but at first time my conversation was not prompted to user, althought suceeded by return value. And response was empty, so my module failed authentication.

Going through openssh code I found that if PasswordAuthentication set to yes, sshd will use "blind" method for your conversation. Your prompts will be ignored and the response will be the password provided by user before. My password was empty so my module got empty response.

Hate this undocumented magic..

Body:
i am tring to make PAM module that authenticate user and password and also get a trap when logout has occurred but i don't understand why pam_sm_authenticate  is called twice?

i have build my own pam_hook.so , compiled it with:

 gcc -fPIC -Wall -shared -lpam -o pam_hook.so pam_hook.c

i have implemnted this function's :

PAM_EXTERN int pam_sm_authenticate(pam_handle_t *pamh, int flags, int argc, const char **argv);
PAM_EXTERN int pam_sm_setcred(pam_handle_t *pamh, int flags, int argc, const char **argv);
PAM_EXTERN int pam_sm_chauthtok(pam_handle_t    *pamh,const int flags,int argc,const char **argv);
PAM_EXTERN int pam_sm_acct_mgmt(pam_handle_t *pamh, int flags, int argc, const char **argv);
PAM_EXTERN int pam_sm_open_session(pam_handle_t *pamh, int flags, int argc, const char **argv);
PAM_EXTERN int pam_sm_close_session(pam_handle_t *pamh, int flags, int argc, const char **argv);

i have printed to file each enter to this function's.
the order of the call to the function's on login of sshd user :

function :  pam_sm_authenticate
function :  pam_sm_setcred
function :  pam_sm_open_session
function :  pam_sm_setcred
function :  pam_sm_authenticate

and on sshd logout:

function :  pam_sm_close_session
function :  pam_sm_setcred

i can't understand why pam_sm_authenticate  it is called twice ,
my /etc/pamd.d/sshd:

# cat /etc/pam.d/sshd
 session     optional       /path_to/pam_hook.so
 auth        requisite       /path_to/pam_hook.so


问:
access DOM and change element font and colour

I want to access some character from string and change the style of them
for example "hello"
i want to change "h" character's color and font
how can i do this
i try this

```<code>var txt=document.getElementById('d1').getElementsByTagName('p')[0]
            txt.innerHTML="H"
            txt.style.color="red"
</code>```

答:
If you want first character of the string and change its color and font (which i am getting from your question), you can do something like :</p>

```<code>var text_array = document.getElementById('d1').getElementsByTagName('p')[0].textContent.split("");
text_array[0] = "<span style='color:green; font-family:Arial'>"+text_array[0]+"</span>";
document.getElementById('d1').getElementsByTagName('p')[0].innerHtml = text_array.join("");
</code>```

Body:
I want to access some character from string and change the style of them
for example "hello"
i want to change "h" character's color and font
how can i do this
i try this

var txt=document.getElementById('d1').getElementsByTagName('p')[0]
            txt.innerHTML="H"
            txt.style.color="red"

Body:
If you want first character of the string and change its color and font (which i am getting from your question), you can do something like :

var text_array = document.getElementById('d1').getElementsByTagName('p')[0].textContent.split("");
text_array[0] = "<span style='color:green; font-family:Arial'>"+text_array[0]+"</span>";
document.getElementById('d1').getElementsByTagName('p')[0].innerHtml = text_array.join("");


问:
How to generate a pseudorandom 32-byte string for use as a salt in a cryptographic hash function?
I am trying to code a password encryption function in C++ (Note: for educational purposes only. I won't actually be storing my passwords with it.) but I am not sure how to create a random 32-byte salt using a predefined characterset. How would I do this?

```<code>#include <random>
#include <iostream>

using namespace std;

void genSalt() {

    const char charset[] = {

        "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz"
        "!£$%^&*():@~#'?/><.,|`¬¦"

    };

}
</code>```

The code should generate a random 32-byte string based on the defined character set 'charset'. I am not sure how to achieve this.

答:
If you can use C++11 you can use random_shuffle to shuffle your array of elements and then always return the first 32 elements.

Something like the following should work for your case:

```<code>void genSalt() {
   static char charset[] = {
        "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!£$%^&*():@~#'?/><.,|`¬¦" };

    random_shuffle(begin(charset), end(charset));

    for(int i = 0 ; i < 32; i++)
       cout<<charset[i];
    cout<<endl;
}
</code>```

Please not that this approach does not return salt sequences with repetition. This is somehow ok for educational purpouses only as it works and it is easy to implement.

Another approach would be to randomly pick elements from the sequence one by one as in the following:

```<code>void genSalt() {
    static const char charset[] = {
        "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!£$%^&*():@~#'?/><.,|`¬¦" };

    for (int i = 0; i < 32; ++i) {
        cout<<charset[rand() % (sizeof(charset) - 1)];
    }
}
</code>```

Body:
I am trying to code a password encryption function in C++ (Note: for educational purposes only. I won't actually be storing my passwords with it.) but I am not sure how to create a random 32-byte salt using a predefined characterset. How would I do this?

#include <random>
#include <iostream>

using namespace std;

void genSalt() {

    const char charset[] = {

        "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz"
        "!£$%^&*():@~#'?/><.,|`¬¦"

    };

}

The code should generate a random 32-byte string based on the defined character set 'charset'. I am not sure how to achieve this.

Body:
If you can use C++11 you can use random_shuffle to shuffle your array of elements and then always return the first 32 elements.

Something like the following should work for your case:

void genSalt() {
   static char charset[] = {
        "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!£$%^&*():@~#'?/><.,|`¬¦" };

    random_shuffle(begin(charset), end(charset));

    for(int i = 0 ; i < 32; i++)
       cout<<charset[i];
    cout<<endl;
}

Please not that this approach does not return salt sequences with repetition. This is somehow ok for educational purpouses only as it works and it is easy to implement.

Another approach would be to randomly pick elements from the sequence one by one as in the following:

void genSalt() {
    static const char charset[] = {
        "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!£$%^&*():@~#'?/><.,|`¬¦" };

    for (int i = 0; i < 32; ++i) {
        cout<<charset[rand() % (sizeof(charset) - 1)];
    }
}


问:
How to cancel the keyboard in UISearchbar?
I'm using UISearchBar in my application and it serves as both an edit field as well as a search.  So when I want to disappear the keyboard I have to use cancel button in UISearchBar but I can't have that cancel button on screen, so how could T make keyboard disappear when not used without using cancel button.  Please help me as i'm new to iPhone application development.

Thanks in advance!

答:
simply all you need to do is to get UITextfield control from the UISearchbar and then set UITextfield's delegate to whatever delegate that will perform -(void) textFieldShouldReturn:(UITextField *)textField

```<code>-(void)viewDidLoad{
    UIView * subView;
    NSArray * subViews = [searchbar subviews];
    for(subView in subViews)
    {
        if( [subView isKindOfClass:[UITextField class]] )
        {
           ((UITextField*)subView).delegate=self;
            ((UITextField*)subView).returnKeyType=UIReturnKeyDone;
            break;
        }
    }
}

-(BOOL) textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return TRUE;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
simply all you need to do is to get UITextfield control from the UISearchbar and then set UITextfield's delegate to whatever delegate that will perform -(void) textFieldShouldReturn:(UITextField *)textField

-(void)viewDidLoad{
    UIView * subView;
    NSArray * subViews = [searchbar subviews];
    for(subView in subViews)
    {
        if( [subView isKindOfClass:[UITextField class]] )
        {
           ((UITextField*)subView).delegate=self;
            ((UITextField*)subView).returnKeyType=UIReturnKeyDone;
            break;
        }
    }
}

-(BOOL) textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return TRUE;
}


问:
Wrong date returned from Location.getTime after 6 April 2019 (week number rollover)
I have a rooted phone Samsung N7100 (kitkat 4.4.2). After 6 April 2019 I started getting locations with date of 1999 year.

Sometimes locations come with a date of 2019, but after that the device stops receiving any locations.

Only the adb comand helps, but after some time the device stops receiving any locations.

```<code>settings put secure location_providers_allowed -gps
settings put secure location_providers_allowed +gps
</code>```

I have tried update firmware to android 6 and 7. Nothings helps.

```<code>mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 0, this);
....

public void onLocationChanged(Location location) {
  Log.d(TAG, (new Date(location.getTime())).toLocaleString());
}
</code>```

答:
This is related to the GPS Week Number Rollover issue that appears on some types of GPS chips.

One way to work around it by detecting that the value returned from location.getTime() is too old (say, before 2019) and if so - add the difference (1024 weeks).

This code should work for the next ~20 years:

```<code>long gpsTime = location.getTime();

// Adding 1024 weeks to fix Week Number Rollover issue for old GPS chips
// 619315200000L = 1024 * 7 * 24 * 60 * 60 * 1000   ->  means 1024 weeks
// Note: This fix works for next 20 years since provided timestamp below
// See: https://stackoverflow.com/questions/56147606/
// See: https://www.cisa.gov/gps-week-number-roll-over
if ((gpsTime > 0) && (gpsTime < 1673000000000L))
  gpsTime += 619315200000L;
</code>```

Body:
I have a rooted phone Samsung N7100 (kitkat 4.4.2). After 6 April 2019 I started getting locations with date of 1999 year.

Sometimes locations come with a date of 2019, but after that the device stops receiving any locations.

Only the adb comand helps, but after some time the device stops receiving any locations.

settings put secure location_providers_allowed -gps
settings put secure location_providers_allowed +gps

I have tried update firmware to android 6 and 7. Nothings helps.

mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 0, this);
....

public void onLocationChanged(Location location) {
  Log.d(TAG, (new Date(location.getTime())).toLocaleString());
}

Body:
This is related to the GPS Week Number Rollover issue that appears on some types of GPS chips.

One way to work around it by detecting that the value returned from location.getTime() is too old (say, before 2019) and if so - add the difference (1024 weeks).

This code should work for the next ~20 years:

long gpsTime = location.getTime();

// Adding 1024 weeks to fix Week Number Rollover issue for old GPS chips
// 619315200000L = 1024 * 7 * 24 * 60 * 60 * 1000   ->  means 1024 weeks
// Note: This fix works for next 20 years since provided timestamp below
// See: https://stackoverflow.com/questions/56147606/
// See: https://www.cisa.gov/gps-week-number-roll-over
if ((gpsTime > 0) && (gpsTime < 1673000000000L))
  gpsTime += 619315200000L;


问:
Robot Framework using Python, key press without selecting any button or element in the page
I am automating one application using Robot Framework using Python. In a certain situation I need to press Enter without selecting any button or element of the page once the page is loaded.

I have tried with the below example (using Press Key), but it didn't work as I don't want to select any specific button or element of the page before press Enter on the page.

Examples:

```<code>Press Key    text_field     q
Press Key    login_button   \\\13    # ASCII code for the Enter key
</code>```

The below keyword is not recognized by the IDE, most probably because of version:

```<code>Press Key Native
</code>```

Is there a solution to get rid of this problem?

答:
You can do it with the Press Keys keyword:

Press Keys \ ENTER

Press Keys \ Example Write Words

Press Keys \ TAB

and so on... I have Robot Framework 3.1.1 (Python 2.7.9 on win32) and SeleniumLibrary.

Body:
I am automating one application using Robot Framework using Python. In a certain situation I need to press Enter without selecting any button or element of the page once the page is loaded.

I have tried with the below example (using Press Key), but it didn't work as I don't want to select any specific button or element of the page before press Enter on the page.

Examples:

Press Key    text_field     q
Press Key    login_button   \\\13    # ASCII code for the Enter key

The below keyword is not recognized by the IDE, most probably because of version:

Press Key Native

Is there a solution to get rid of this problem?


问:
JSX adjacent on react.js
the code below is divided into two parts one deals with the management of the head the other "body" when I execute the code the exception below is raised, how can I solve the error?
I can't figure out what the error below is due to, the error is on the parsing of react

Error:

```<code>  Line 48:  Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?

         <Link rel="stylesheet" type="text/css" href="css/main.css" />
     </HeadProvider>
</code>```

Code:

```<code>import * as React from 'react';
import { Button, Form, FormGroup, FormControl, ControlLabel } from "react-bootstrap";
import logo from './logo.svg';
import { HeadProvider, Title, Link, Meta } from 'react-head';

import './Home.css';

class Home extends Component {
  ...

  render() {
    return (
      <HeadProvider>
        <Meta charset="UTF-8" />
        <Meta name="viewport" content="width=device-width, initial-scale=1" />
        <Link rel="icon" type="image/png" href="images/icons/favicon.ico" />
        <Link rel="stylesheet" type="text/css" href="vendor/bootstrap/css/bootstrap.min.css" />
        <Link rel="stylesheet" type="text/css" href="fonts/font-awesome-4.7.0/css/font-awesome.min.css" />
        <Link rel="stylesheet" type="text/css" href="fonts/iconic/css/material-design-iconic-font.min.css" />
        <Link rel="stylesheet" type="text/css" href="vendor/animate/animate.css" />
        <Link rel="stylesheet" type="text/css" href="vendor/css-hamburgers/hamburgers.min.css" />
        <Link rel="stylesheet" type="text/css" href="vendor/animsition/css/animsition.min.css" />
        <Link rel="stylesheet" type="text/css" href="vendor/select2/select2.min.css" />
        <Link rel="stylesheet" type="text/css" href="vendor/daterangepicker/daterangepicker.css" />
        <Link rel="stylesheet" type="text/css" href="css/util.css" />
        <Link rel="stylesheet" type="text/css" href="css/main.css" />
      </HeadProvider>
        <div className="Login">
          <Form onSubmit={this.handleSubmit}>
            <Form.Group controlId="email" bsSize="large">
              <label> Email: </label>
              <Form.Control
                autoFocus
                type="email"
                value={this.state.email}
                onChange={this.handleChange}
              />

            </Form.Group>
            <br></br>
            <Form.Group controlId="password" bsSize="large">
              <label> Password: </label>
              <Form.Control
                value={this.state.password}
                onChange={this.handleChange}
                type="password"
              />
            </Form.Group>
            <Button
              block
              bsSize="large"
              disabled={!this.validateForm()}
              type="submit"
            >
              Login
              </Button>
          </Form>
        </div>
    );
  }
}

export default Home;
</code>```

答:
You are trying to return multiple elements from render function. You must return only one element. You can fix this by wrapping your <HeadProvider> and
 in parent div or in React.Fragment:

```<code>
render() {
    return (
        <React.Fragment>
            <HeadProvider>
                <Meta charset="UTF-8"/>
                <Meta name="viewport" content="width=device-width, initial-scale=1"/>
                <Link rel="icon" type="image/png" href="images/icons/favicon.ico"/>
                <Link rel="stylesheet" type="text/css"
                      href="vendor/bootstrap/css/bootstrap.min.css"/>
                <Link rel="stylesheet" type="text/css"
                      href="fonts/font-awesome-4.7.0/css/font-awesome.min.css"/>
                <Link rel="stylesheet" type="text/css"
                      href="fonts/iconic/css/material-design-iconic-font.min.css"/>
                <Link rel="stylesheet" type="text/css" href="vendor/animate/animate.css"/>
                <Link rel="stylesheet" type="text/css"
                      href="vendor/css-hamburgers/hamburgers.min.css"/>
                <Link rel="stylesheet" type="text/css"
                      href="vendor/animsition/css/animsition.min.css"/>
                <Link rel="stylesheet" type="text/css" href="vendor/select2/select2.min.css"/>
                <Link rel="stylesheet" type="text/css"
                      href="vendor/daterangepicker/daterangepicker.css"/>
                <Link rel="stylesheet" type="text/css" href="css/util.css"/>
                <Link rel="stylesheet" type="text/css" href="css/main.css"/>
            </HeadProvider>
            <div className="Login">
                <Form onSubmit={this.handleSubmit}>
                    <Form.Group controlId="email" bsSize="large">
                        <label> Email: </label>
                        <Form.Control
                            autoFocus
                            type="email"
                            value={this.state.email}
                            onChange={this.handleChange}
                        />

                    </Form.Group>
                    <br></br>
                    <Form.Group controlId="password" bsSize="large">
                        <label> Password: </label>
                        <Form.Control
                            value={this.state.password}
                            onChange={this.handleChange}
                            type="password"
                        />
                    </Form.Group>
                    <Button
                        block
                        bsSize="large"
                        disabled={!this.validateForm()}
                        type="submit"
                    >
                        Login
                    </Button>
                </Form>
            </div>
        </React.Fragment>
    );
}

</code>```

Title: JSX adjacent on react.js

Body:
the code below is divided into two parts one deals with the management of the head the other "body" when I execute the code the exception below is raised, how can I solve the error?
I can't figure out what the error below is due to, the error is on the parsing of react

Error:

  Line 48:  Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?

         <Link rel="stylesheet" type="text/css" href="css/main.css" />
     </HeadProvider>

Code:

import * as React from 'react';
import { Button, Form, FormGroup, FormControl, ControlLabel } from "react-bootstrap";
import logo from './logo.svg';
import { HeadProvider, Title, Link, Meta } from 'react-head';

import './Home.css';

class Home extends Component {
  ...

  render() {
    return (
      <HeadProvider>
        <Meta charset="UTF-8" />
        <Meta name="viewport" content="width=device-width, initial-scale=1" />
        <Link rel="icon" type="image/png" href="images/icons/favicon.ico" />
        <Link rel="stylesheet" type="text/css" href="vendor/bootstrap/css/bootstrap.min.css" />
        <Link rel="stylesheet" type="text/css" href="fonts/font-awesome-4.7.0/css/font-awesome.min.css" />
        <Link rel="stylesheet" type="text/css" href="fonts/iconic/css/material-design-iconic-font.min.css" />
        <Link rel="stylesheet" type="text/css" href="vendor/animate/animate.css" />
        <Link rel="stylesheet" type="text/css" href="vendor/css-hamburgers/hamburgers.min.css" />
        <Link rel="stylesheet" type="text/css" href="vendor/animsition/css/animsition.min.css" />
        <Link rel="stylesheet" type="text/css" href="vendor/select2/select2.min.css" />
        <Link rel="stylesheet" type="text/css" href="vendor/daterangepicker/daterangepicker.css" />
        <Link rel="stylesheet" type="text/css" href="css/util.css" />
        <Link rel="stylesheet" type="text/css" href="css/main.css" />
      </HeadProvider>

          <Form onSubmit={this.handleSubmit}>
            <Form.Group controlId="email" bsSize="large">
               Email:
              <Form.Control
                autoFocus
                type="email"
                value={this.state.email}
                onChange={this.handleChange}
              />

            </Form.Group>

            <Form.Group controlId="password" bsSize="large">
               Password:
              <Form.Control
                value={this.state.password}
                onChange={this.handleChange}
                type="password"
              />
            </Form.Group>
            <Button
              block
              bsSize="large"
              disabled={!this.validateForm()}
              type="submit"
            >
              Login
              </Button>
          </Form>

    );
  }
}

export default Home;

Body:
You are trying to return multiple elements from render function. You must return only one element. You can fix this by wrapping your <HeadProvider> and <div className="Login"> in parent div or in React.Fragment:

render() {
    return (
        <React.Fragment>
            <HeadProvider>
                <Meta charset="UTF-8"/>
                <Meta name="viewport" content="width=device-width, initial-scale=1"/>
                <Link rel="icon" type="image/png" href="images/icons/favicon.ico"/>
                <Link rel="stylesheet" type="text/css"
                      href="vendor/bootstrap/css/bootstrap.min.css"/>
                <Link rel="stylesheet" type="text/css"
                      href="fonts/font-awesome-4.7.0/css/font-awesome.min.css"/>
                <Link rel="stylesheet" type="text/css"
                      href="fonts/iconic/css/material-design-iconic-font.min.css"/>
                <Link rel="stylesheet" type="text/css" href="vendor/animate/animate.css"/>
                <Link rel="stylesheet" type="text/css"
                      href="vendor/css-hamburgers/hamburgers.min.css"/>
                <Link rel="stylesheet" type="text/css"
                      href="vendor/animsition/css/animsition.min.css"/>
                <Link rel="stylesheet" type="text/css" href="vendor/select2/select2.min.css"/>
                <Link rel="stylesheet" type="text/css"
                      href="vendor/daterangepicker/daterangepicker.css"/>
                <Link rel="stylesheet" type="text/css" href="css/util.css"/>
                <Link rel="stylesheet" type="text/css" href="css/main.css"/>
            </HeadProvider>
            <div className="Login">
                <Form onSubmit={this.handleSubmit}>
                    <Form.Group controlId="email" bsSize="large">
                        <label> Email: </label>
                        <Form.Control
                            autoFocus
                            type="email"
                            value={this.state.email}
                            onChange={this.handleChange}
                        />

                    </Form.Group>
                    <br></br>
                    <Form.Group controlId="password" bsSize="large">
                        <label> Password: </label>
                        <Form.Control
                            value={this.state.password}
                            onChange={this.handleChange}
                            type="password"
                        />
                    </Form.Group>
                    <Button
                        block
                        bsSize="large"
                        disabled={!this.validateForm()}
                        type="submit"
                    >
                        Login
                    </Button>
                </Form>
            </div>
        </React.Fragment>
    );
}


问:
What is the use of overriding the finalize() method of Object class?
As far as I know , in java if we want to manually call the garbage collector we can do System.gc().

1.What are the operations that we do inside our overriden finalize() method?

2.Is it required to override the finalize() method if we want to manually call the JVM garbage collector?

答:
Overriding the finalize method is often done if you need to manually release resources (particularly those that would use large amounts of memory or cause locks, if they weren't released). For example, if you have an object that has a lock on a file or database table, you may want to override your finalize method in order to release those objects for use when your object is garbage collected.

As for whether or not overriding finalize is required, it absolutely is not. You can call System.gc() without ever overriding a finalize method. One word of caution, though - calling System.gc() doesn't absolutely dictate that the garbage collector will do anything. Consider it more of a "recommendation" to the JVM to run garbage collection, as opposed to a "mandate".


问:
Nested FormGroups in FormArray not working
I have a simple reactive form with a FormArray that will contain FromGroups.

I know this has been asked many times, but I can't still figure out why it's not working. I've tried many ways. This is are two simplified examples put together with what I've read from the docs and found online.

Component:

@Component({
  selector: 'app-professional-info-form',
  templateUrl: './professional-info-form.component.html',
  styleUrls: ['./professional-info-form.component.scss']
})
export class ProfessionalInfoFormComponent implements OnInit {

  protected professionalInfo: FormGroup;

  constructor() { }

  ngOnInit() {
    this.initForm();
  }

  private initForm() {
    this.professionalInfo = new FormGroup({
      trainings: new FormArray([
        new FormGroup({
          institutionId: new FormControl(null, null),
          title: new FormControl(null, null),
          description: new FormControl(null, null),
          institution: new FormControl(null, Validators.required),
          grade: new FormControl(null, null),
          from: new FormControl(null, Validators.required),
          to: new FormControl(null, null)
        })
      ])
    });

  }

}
```
<p>HTML:</p>
```<form [formGroup]="professionalInfo" (ngSubmit)="onSubmit()" novalidate *ngIf="professionalInfo">

      <input type="text" [formControlName]="title" placeholder="Titolo" />
      <input type="text" [formControlName]="institution" placeholder="Istituto" />
      <input type="text" placeholder="Inizio" [formControlName]="from">
      <input type="text" placeholder="Fine" [formControlName]="to">
      <input type="text" placeholder="Voto" [formControlName]="grade" maxlength="5">

</form>
```
<p>Console error:</p>
```ERROR TypeError: Cannot read property 'controls' of undefined
    at Object.eval [as updateDirectives] (ProfessionalInfoFormComponent.html:19)
```
<p>If I add this method to the component:</p>
<pre class="lang-js prettyprint-override"><code>get trainingsFormArray() {
    return (<FormArray>this.professionalInfo.get('trainings'));
  }
</code>```

And edit the *ngFor like this:

```<code><div *ngFor="let training of trainingsFormArray.controls; index as t" [formGroupName]="t">
</code>```

The console error is:

```<code>ERROR Error: Cannot find control with path: 'trainings -> 0 -> '
</code>```

Which is kind of crazy because if console.log 'trainingsFormArray' after initializing the form the output is the following:

console.log output

Every time I have to work with angular's reactive forms I encounter problems like this one. I can't seem to figure out a consistent way for making them work with dynamic controls like in this case. Please help me.

答:
You are using [formControlName]='title' , this would need the title to be a variable with the control name. You can get rid of the enclosing []and it would work fine. Use as:

```<code>formControlName='title'
</code>```

Body:
I have a simple reactive form with a FormArray that will contain FromGroups.

I know this has been asked many times, but I can't still figure out why it's not working. I've tried many ways. This is are two simplified examples put together with what I've read from the docs and found online.

Component:

@Component({
  selector: 'app-professional-info-form',
  templateUrl: './professional-info-form.component.html',
  styleUrls: ['./professional-info-form.component.scss']
})
export class ProfessionalInfoFormComponent implements OnInit {

  protected professionalInfo: FormGroup;

  constructor() { }

  ngOnInit() {
    this.initForm();
  }

  private initForm() {
    this.professionalInfo = new FormGroup({
      trainings: new FormArray([
        new FormGroup({
          institutionId: new FormControl(null, null),
          title: new FormControl(null, null),
          description: new FormControl(null, null),
          institution: new FormControl(null, Validators.required),
          grade: new FormControl(null, null),
          from: new FormControl(null, Validators.required),
          to: new FormControl(null, null)
        })
      ])
    });

  }

}

HTML:

<form [formGroup]="professionalInfo" (ngSubmit)="onSubmit()" novalidate *ngIf="professionalInfo">

      <input type="text" [formControlName]="title" placeholder="Titolo" />
      <input type="text" [formControlName]="institution" placeholder="Istituto" />
      <input type="text" placeholder="Inizio" [formControlName]="from">
      <input type="text" placeholder="Fine" [formControlName]="to">
      <input type="text" placeholder="Voto" [formControlName]="grade" maxlength="5">

</form>

Console error:

ERROR TypeError: Cannot read property 'controls' of undefined
    at Object.eval [as updateDirectives] (ProfessionalInfoFormComponent.html:19)

If I add this method to the component:

get trainingsFormArray() {
    return (<FormArray>this.professionalInfo.get('trainings'));
  }

And edit the *ngFor like this:

The console error is:

ERROR Error: Cannot find control with path: 'trainings -> 0 -> '

Which is kind of crazy because if console.log 'trainingsFormArray' after initializing the form the output is the following:

console.log output

Every time I have to work with angular's reactive forms I encounter problems like this one. I can't seem to figure out a consistent way for making them work with dynamic controls like in this case. Please help me.

Body:
You are using [formControlName]='title' , this would need the title to be a variable with the control name. You can get rid of the enclosing []and it would work fine. Use as:

formControlName='title'


问:
How do I change the value of a variable for a short time span?
I wanna change the value of a variable for a short time span only! If a user presses the up-key/down-key the value should be changed for 3 seconds. How could I implement this in Python?

I've tried some things such as time.sleep() but with this method the Tron is not moving in this time.

#Controls of Tron-Bike
#Up-Key increases the forward speed
def up():
      thread_sleep_time = 0.5
    # THIS code is ONLY for the POC (proof of concept)
    # normally in TRON, the "bike" moves with a constant speed
    # therefore you can use this hook
      print("heading P1:", t1.heading())
```

I wanna change the code that the thread_sleep_time is set to 0.5 and after 3 seconds it should change back to 1.

答:
You should get the value returned by a function that checks the time elapsed and evaluates which value return.

Here an hint on how to calc the elapsed time:

```<code>import time

start_time = time.time()
elapsed_time = time.time() - start_time
</code>```

Body:
I wanna change the value of a variable for a short time span only! If a user presses the up-key/down-key the value should be changed for 3 seconds. How could I implement this in Python?

I've tried some things such as time.sleep() but with this method the Tron is not moving in this time.

#Controls of Tron-Bike
#Up-Key increases the forward speed
def up():
      thread_sleep_time = 0.5
    # THIS code is ONLY for the POC (proof of concept)
    # normally in TRON, the "bike" moves with a constant speed
    # therefore you can use this hook
      print("heading P1:", t1.heading())

I wanna change the code that the thread_sleep_time is set to 0.5 and after 3 seconds it should change back to 1.

Body:
You should get the value returned by a function that checks the time elapsed and evaluates which value return.

Here an hint on how to calc the elapsed time:

import time

start_time = time.time()
elapsed_time = time.time() - start_time


问:
Hide names in Highcharts Venn Diagram
I'm drawing a Venn diagram using Highcharts and only want to show the names of the three main circles, not the intersections, i.e. just show reading, writing and maths.

I've tried setting 'name' to an empty string and NULL, but can't get it to work, though note on the fiddle setting name to "" does work for the intersection of all three circles (I think this is probably Highcharts deciding there isn't room to show it).

```<code>Highcharts.chart('report', {

  chart: {
    type: 'venn'
  },

  series: [{
    data: [{
      "name": ["Reading"],
      "sets": ["Reading"],
      "value": 100
    }, {
      "name": ["Writing"],
      "sets": ["Writing"],
      "value": 100
    }, {
      "name": ["Maths"],
      "sets": ["Maths"],
      "value": 100
    }, {
      "name": null,
      "sets": ["Reading", "Writing"],
      "value": 20
    }, {
      "name": "",
      "sets": ["Reading", "Maths"],
      "value": 20
    }, {
      "name": "",
      "sets": ["Writing", "Maths"],
      "value": 20
    }, {
      "name": "",
      "sets": ["Reading", "Writing", "Maths"],
      "value": 10
    }]
  }]
});
</code>```

Example code: https://jsfiddle.net/4vg0d7ao/6/

Thanks for any help you can give.

答:
Set name to an empty array:

```<code>Highcharts.chart('report', {
  chart: {
    type: 'venn'
  },
  tooltip: {
    enabled: false
  },
  series: [{
    data: [{
      "name": ["Reading"],
      "sets": ["Reading"],
      "value": 100
    }, {
      "name": ["Writing"],
      "sets": ["Writing"],
      "value": 100
    }, {
      "name": ["Maths"],
      "sets": ["Maths"],
      "value": 100
    }, {
      "name": [],
      "sets": ["Reading", "Writing"],
      "value": 20
    }, {
      "name": [],
      "sets": ["Reading", "Maths"],
      "value": 20
    }, {
      "name": [],
      "sets": ["Writing", "Maths"],
      "value": 20
    }, {
      "name": [],
      "sets": ["Reading", "Writing", "Maths"],
      "value": 10
    }]
  }]
});
</code>```

Edited fiddle: https://jsfiddle.net/rLmd97n5/

Title: Hide names in Highcharts Venn Diagram

Body:
I'm drawing a Venn diagram using Highcharts and only want to show the names of the three main circles, not the intersections, i.e. just show reading, writing and maths.

I've tried setting 'name' to an empty string and NULL, but can't get it to work, though note on the fiddle setting name to "" does work for the intersection of all three circles (I think this is probably Highcharts deciding there isn't room to show it).

Highcharts.chart('report', {

  chart: {
    type: 'venn'
  },

  series: [{
    data: [{
      "name": ["Reading"],
      "sets": ["Reading"],
      "value": 100
    }, {
      "name": ["Writing"],
      "sets": ["Writing"],
      "value": 100
    }, {
      "name": ["Maths"],
      "sets": ["Maths"],
      "value": 100
    }, {
      "name": null,
      "sets": ["Reading", "Writing"],
      "value": 20
    }, {
      "name": "",
      "sets": ["Reading", "Maths"],
      "value": 20
    }, {
      "name": "",
      "sets": ["Writing", "Maths"],
      "value": 20
    }, {
      "name": "",
      "sets": ["Reading", "Writing", "Maths"],
      "value": 10
    }]
  }]
});

Example code: https://jsfiddle.net/4vg0d7ao/6/

Thanks for any help you can give.

Body:
Set name to an empty array:

Highcharts.chart('report', {
  chart: {
    type: 'venn'
  },
  tooltip: {
    enabled: false
  },
  series: [{
    data: [{
      "name": ["Reading"],
      "sets": ["Reading"],
      "value": 100
    }, {
      "name": ["Writing"],
      "sets": ["Writing"],
      "value": 100
    }, {
      "name": ["Maths"],
      "sets": ["Maths"],
      "value": 100
    }, {
      "name": [],
      "sets": ["Reading", "Writing"],
      "value": 20
    }, {
      "name": [],
      "sets": ["Reading", "Maths"],
      "value": 20
    }, {
      "name": [],
      "sets": ["Writing", "Maths"],
      "value": 20
    }, {
      "name": [],
      "sets": ["Reading", "Writing", "Maths"],
      "value": 10
    }]
  }]
});

Edited fiddle: https://jsfiddle.net/rLmd97n5/


问:
Stuts2 Tiles Tomcat suspected of changing UTF-8 to?
I'm having some internationalisation woes:

My UTF-8 string fields are being rendered in the browser as ???? after being returned from the database.

After retrieval from the database using Hibernate, the String fields are presented correctly on inspection using the eclipse debugger.

However Struts2/Tiles is rendering these strings as ???? in the HTML sent to the browser.

The charset directive is present in the HTML header:

Perhaps I need to add something to my struts2 or tiles configurations?

答:
Try setting the lang attribute on the  element.

HTML example:

```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="ja">
```

XHTML example:

```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja">
```

OwnerDisplayName: chickeninabiscuit

Body:
Try setting the lang attribute on the <html/> element.

HTML example:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="ja">

XHTML example:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja">


问:
Getting data from file stream in c
I am trying to retreive data out of a FILE pointer and into a string. What is the best way to determine the size of the string buffer?

```<code>char string[WHAT_SIZE?];
FILE *fp;
fp = fopen("info.dat", "r");

fgets(string, sizeof string, fp);
</code>```

Do I set the buffer size to something I think is suitable for that particular file? Or is there a more efficient way to do this without using strings with non variable buffer sizes?

答:
If you're actually intending to read lines from the file (which is the usual reason for using fgets rather than, say, fread) then what you need is for the buffer to be long enough to hold a line. You often can't know that in advance, so allocate it dynamically with malloc (or new if you're using C++, though in that case you might do better to use C++'s I/O facilities) and enlarge it when you run across a line that's too long. Something like this:

```<code>size_t line_size = 256; /* reasonable initial default */
char * line_buffer = malloc(line_size);
line_buffer[line_size-2] = '\n'; /* yes, 2 */
/* You should check for malloc failure here */
while (whatever) {
  /* ... */
  fgets(line_buffer, line_size, fp); /* should check for failure and EOF here too */
  while (line_buffer[line_size-2] != '\n') {
    /* we filled the buffer, and the last character wasn't a newline */
    size_t new_line_size = 2*line_size;
    line_buffer = realloc(line_buffer, new_line_size); /* should check for failure here */
    line_buffer[new_line_size-2] = '\n';
    fgets(line_buffer+line_size-1, new_line_size-line_size+1, fp); /* should check for failure and EOF */
    line_size = new_line_size;
  }
  /* ... */
}
</code>```

(Warning: completely untested code; may consist entirely of bugs and toxic waste. Certainly doesn't have all the testing for error conditions that real code should have.)

You would probably be well advised not to let the buffer grow without limit if some idiot feeds you a file with insanely long lines; give up at some point. You might well want to encapsulate the behaviour above into a function, especially if you have multiple bits of code doing the same thing. In that case, you might also want to encapsulate its state -- the buffer and its current size -- into a struct too. (Or, if you're using C++, a class, of which the buffer-expanding-reading thing would be a member function. But, again, if you're using C++ then you should probably use the facilities it already provides for this.)

Title: Getting data from file stream in c

Body:
I am trying to retreive data out of a FILE pointer and into a string. What is the best way to determine the size of the string buffer?

char string[WHAT_SIZE?];
FILE *fp;
fp = fopen("info.dat", "r");

fgets(string, sizeof string, fp);

Do I set the buffer size to something I think is suitable for that particular file? Or is there a more efficient way to do this without using strings with non variable buffer sizes?

Body:
If you're actually intending to read lines from the file (which is the usual reason for using fgets rather than, say, fread) then what you need is for the buffer to be long enough to hold a line. You often can't know that in advance, so allocate it dynamically with malloc (or new if you're using C++, though in that case you might do better to use C++'s I/O facilities) and enlarge it when you run across a line that's too long. Something like this:

size_t line_size = 256; /* reasonable initial default */
char * line_buffer = malloc(line_size);
line_buffer[line_size-2] = '\n'; /* yes, 2 */
/* You should check for malloc failure here */
while (whatever) {
  /* ... */
  fgets(line_buffer, line_size, fp); /* should check for failure and EOF here too */
  while (line_buffer[line_size-2] != '\n') {
    /* we filled the buffer, and the last character wasn't a newline */
    size_t new_line_size = 2*line_size;
    line_buffer = realloc(line_buffer, new_line_size); /* should check for failure here */
    line_buffer[new_line_size-2] = '\n';
    fgets(line_buffer+line_size-1, new_line_size-line_size+1, fp); /* should check for failure and EOF */
    line_size = new_line_size;
  }
  /* ... */
}

(Warning: completely untested code; may consist entirely of bugs and toxic waste. Certainly doesn't have all the testing for error conditions that real code should have.)

You would probably be well advised not to let the buffer grow without limit if some idiot feeds you a file with insanely long lines; give up at some point. You might well want to encapsulate the behaviour above into a function, especially if you have multiple bits of code doing the same thing. In that case, you might also want to encapsulate its state -- the buffer and its current size -- into a struct too. (Or, if you're using C++, a class, of which the buffer-expanding-reading thing would be a member function. But, again, if you're using C++ then you should probably use the facilities it already provides for this.)


问:
Identifying duplicate rows among discrete sets of records in a MYSQL query
I'm sure this has been answered elsewhere, however I'm struggling to find the correct terminology…

Here is some data (Facebook audience sizes, as it happens) that I'm collecting at regular intervals.

Each test is a target and there are two batches, 18 and 19 (but there will be many more in the full dataset).

```<code>+--------+-------+----------+-------+---------------------+
| target | batch | location | daily | created_at          |
+--------+-------+----------+-------+---------------------+
|  53003 |    18 | Austria  | 12117 | 2019-05-27 10:55:48 |
|  53003 |    19 | Austria  | 12663 | 2019-05-29 01:18:25 |
|  53004 |    18 | Austria  |  4999 | 2019-05-27 10:55:49 |
|  53004 |    19 | Austria  |  4999 | 2019-05-29 01:18:26 |
|  53005 |    18 | Austria  |   999 | 2019-05-27 10:55:50 |
|  53005 |    19 | Austria  |   997 | 2019-05-28 22:19:25 |
+--------+-------+----------+-------+---------------------+
</code>```

I want to filter by days where batch 18 and 19 for the same target have the same daily value.

So I'd get something like the following (because target 53004 is the only one with the same result for both days).

Note: the important thing is I want each target to be compared first, in isolation, so if another target had daily=4999 for both batches, it would count separately, and if two targets by coincidence had, say, daily=123, but for one batch only each, they also wouldn't count as a match.

```<code>+--------+-------+----------+-------+---------------------+
| target | batch | location | daily | created_at          |
+--------+-------+----------+-------+---------------------+
|  53004 |   n/a | Austria  |  4999 | n/a                 |
+--------+-------+----------+-------+---------------------+
</code>```

(The n/a s are just to indicate those columns will no longer be single values and I don't care about them.)

答:
You can aggreagte and check in a HAVING clause that the minimum and the maximum are equal.

```<code>SELECT target,
       'n/a' batch,
       location,
       max(daily) daily,
       'n/a' created_at
       FROM elbat
       GROUP BY target,
                location
       HAVING min(daily) = max(daily);
</code>```

Body:
I'm sure this has been answered elsewhere, however I'm struggling to find the correct terminology…

Here is some data (Facebook audience sizes, as it happens) that I'm collecting at regular intervals.

Each test is a target and there are two batches, 18 and 19 (but there will be many more in the full dataset).

+--------+-------+----------+-------+---------------------+
| target | batch | location | daily | created_at          |
+--------+-------+----------+-------+---------------------+
|  53003 |    18 | Austria  | 12117 | 2019-05-27 10:55:48 |
|  53003 |    19 | Austria  | 12663 | 2019-05-29 01:18:25 |
|  53004 |    18 | Austria  |  4999 | 2019-05-27 10:55:49 |
|  53004 |    19 | Austria  |  4999 | 2019-05-29 01:18:26 |
|  53005 |    18 | Austria  |   999 | 2019-05-27 10:55:50 |
|  53005 |    19 | Austria  |   997 | 2019-05-28 22:19:25 |
+--------+-------+----------+-------+---------------------+

I want to filter by days where batch 18 and 19 for the same target have the same daily value.

So I'd get something like the following (because target 53004 is the only one with the same result for both days).

Note: the important thing is I want each target to be compared first, in isolation, so if another target had daily=4999 for both batches, it would count separately, and if two targets by coincidence had, say, daily=123, but for one batch only each, they also wouldn't count as a match.

+--------+-------+----------+-------+---------------------+
| target | batch | location | daily | created_at          |
+--------+-------+----------+-------+---------------------+
|  53004 |   n/a | Austria  |  4999 | n/a                 |
+--------+-------+----------+-------+---------------------+

(The n/a s are just to indicate those columns will no longer be single values and I don't care about them.)

Body:
You can aggreagte and check in a HAVING clause that the minimum and the maximum are equal.

SELECT target,
       'n/a' batch,
       location,
       max(daily) daily,
       'n/a' created_at
       FROM elbat
       GROUP BY target,
                location
       HAVING min(daily) = max(daily);


问:
Powershell not able to convert while converting values from "&" to JSON

RoleFullPath

```<code>Applications\User Admin & Support-DEMO
</code>```

PowerShell Code

```<code>$NewJSON.roleFullPath = $Line.RoleFullPath
.
.
.
.
$JSONPath = $RolePath + $FolderName  + "-JSON.json"
Convertto-JSON $NewJSON | Out-file -Encoding "UTF8" $JSONPath
</code>```

Output:

```<code>"roleFullPath":  "Applications\\User Admin \u0026 Support-DEMO"
</code>```

While converting from csv to json, character '&' is getting converted to '\u0026'

Any help?

答:
To stop Powershell from doing this pipe your Json output through this

$jsonOutput | ForEach-Object { [System.Text.RegularExpressions.Regex]::Unescape($_) } | Set-Content $jsonPath -Encoding UTF8;
```

This will prevent the & being converted :)

Body:
RoleFullPath

Applications\User Admin & Support-DEMO

PowerShell Code

$NewJSON.roleFullPath = $Line.RoleFullPath
.
.
.
.
$JSONPath = $RolePath + $FolderName  + "-JSON.json"
Convertto-JSON $NewJSON | Out-file -Encoding "UTF8" $JSONPath

Output:

"roleFullPath":  "Applications\\User Admin \u0026 Support-DEMO"

While converting from csv to json, character '&' is getting converted to '\u0026'

Any help?

Body:
To stop Powershell from doing this pipe your Json output through this

$jsonOutput | ForEach-Object { [System.Text.RegularExpressions.Regex]::Unescape($_) } | Set-Content $jsonPath -Encoding UTF8;

This will prevent the & being converted :)


问:
Get the last item in an array
Here is my JavaScript code so far:

```<code>var linkElement = document.getElementById("BackButton");
var loc_array = document.location.href.split('/');
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2])));
linkElement.appendChild(newT);
</code>```

Currently it takes the second to last item in the array from the URL. However, I want to do a check for the last item in the array to be "index.html" and if so, grab the third to last item instead.

答:
const [lastItem] = array.slice(-1);

Array.prototype.slice with -1 can be used to create a new Array containing only the last item of the original Array, you can then use Destructuring Assignment to create a variable using the first item of that new Array.

const lotteryNumbers = [12, 16, 4, 33, 41, 22];
const [lastNumber] = lotteryNumbers.slice(-1);

console.log(lotteryNumbers.slice(-1));
// => [22]
console.log(lastNumber);
// => 22```

Title: Get the last item in an array

Body:
Here is my JavaScript code so far:

var linkElement = document.getElementById("BackButton");
var loc_array = document.location.href.split('/');
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2])));
linkElement.appendChild(newT);

Currently it takes the second to last item in the array from the URL. However, I want to do a check for the last item in the array to be "index.html" and if so, grab the third to last item instead.


问:
Combining test-Path -Path with a regular expression
In Jenkins I'm creating a PowerShell script. This is working:

```<code>if (Test-Path -Path "$baseDirectory\s*") {...}
</code>```

But this is "dangerous" and not "safe" enough.

The directory name will be: sdd or sddd (d=digits).
So the name starts with the character "s" and is 2 and later three digits long.

I have tried the following:

```<code>if (Test-Path -Path "$baseDirectory\ -match 's(\d{2,3})'") {...}
</code>```

and

```<code>if (Test-Path -Path "-match '$baseDirectory\s(\d{2,3})'") {...}
</code>```

and all kind of little differences.

If I do this with s* than the script returns directory name s54, s55 etc.

I'm expecthing, if possible, the same result with the regular expression instead of "no directory found".

答:
Try use the follow regex:

```<code>s\d{2,3}
</code>```

For Example, Click Here

Good Luck!

Body:
In Jenkins I'm creating a PowerShell script. This is working:

if (Test-Path -Path "$baseDirectory\s*") {...}

But this is "dangerous" and not "safe" enough.

The directory name will be: sdd or sddd (d=digits).
So the name starts with the character "s" and is 2 and later three digits long.

I have tried the following:

if (Test-Path -Path "$baseDirectory\ -match 's(\d{2,3})'") {...}

and

if (Test-Path -Path "-match '$baseDirectory\s(\d{2,3})'") {...}

and all kind of little differences.

If I do this with s* than the script returns directory name s54, s55 etc.

I'm expecthing, if possible, the same result with the regular expression instead of "no directory found".

Body:
Try use the follow regex:

s\d{2,3}

For Example, Click Here

Good Luck!


问:
Glide not Loading image from StorageReference
I have problem when loading image from StorageReference to ImageView using Glide 4.9.0 (latest).

It's stuck on PlaceHolder..
When I try to put the downloadable url of my ref, it's working..

```<code>StorageReference ref = FirebaseStorage.getInstance().getReference().child("myImage")

//It's not working
Glide.with(mContext)
   .load(ref)
   .placeholder(R.drawable.ic_loading_circle)
   .error(R.drawable.ic_loading_circle)
   .into(mImageView);

//It's working
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
{
    @Override
    public void onSuccess(Uri downloadUrl)
    {
        Glide.with(mContext)
            .load(downloadUrl.toString())
            .placeholder(R.drawable.ic_loading_circle)
            .error(R.drawable.ic_loading_circle)
            .into(mImageView);
    }
});
</code>```

I didn't see any error using try-catch, I already put Internet permission in Manifest. Other image from drawable are working also

Note: My firebase is used by 2 apps, the first app is working without any problem with Glide, but this 2nd app got unknown problem.

any solution or alternative? because using getDownloadUrl().addOnSuccessListener to get URI are so slow

答:
Using FirebaseUI you can quickly and easily download, cache, and
  display images from Cloud Storage using our integration with Glide.

First, add FirebaseUI to your app/build.gradle:

dependencies {
      // FirebaseUI Storage only
      implementation 'com.firebaseui:firebase-ui-storage:4.3.1' }

Then you can load images directly from Storage into an ImageView:

```<code>// Reference to an image file in Cloud Storage
StorageReference storageReference = FirebaseStorage.getInstance().getReference();

// ImageView in your Activity
ImageView imageView = findViewById(R.id.imageView);

// Download directly from StorageReference using Glide
// (See MyAppGlideModule for Loader registration)
GlideApp.with(this /* context */)
        .load(storageReference)
        .into(imageView);
</code>```

Firebase Documentation for loading image directly via Glide

Body:
I have problem when loading image from StorageReference to ImageView using Glide 4.9.0 (latest).

It's stuck on PlaceHolder..
When I try to put the downloadable url of my ref, it's working..

StorageReference ref = FirebaseStorage.getInstance().getReference().child("myImage")

//It's not working
Glide.with(mContext)
   .load(ref)
   .placeholder(R.drawable.ic_loading_circle)
   .error(R.drawable.ic_loading_circle)
   .into(mImageView);

//It's working
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
{
    @Override
    public void onSuccess(Uri downloadUrl)
    {
        Glide.with(mContext)
            .load(downloadUrl.toString())
            .placeholder(R.drawable.ic_loading_circle)
            .error(R.drawable.ic_loading_circle)
            .into(mImageView);
    }
});

I didn't see any error using try-catch, I already put Internet permission in Manifest. Other image from drawable are working also

Note: My firebase is used by 2 apps, the first app is working without any problem with Glide, but this 2nd app got unknown problem.

any solution or alternative? because using getDownloadUrl().addOnSuccessListener to get URI are so slow

Body:
Using FirebaseUI you can quickly and easily download, cache, and
  display images from Cloud Storage using our integration with Glide.

First, add FirebaseUI to your app/build.gradle:

dependencies {
      // FirebaseUI Storage only
      implementation 'com.firebaseui:firebase-ui-storage:4.3.1' }

Then you can load images directly from Storage into an ImageView:

// Reference to an image file in Cloud Storage
StorageReference storageReference = FirebaseStorage.getInstance().getReference();

// ImageView in your Activity
ImageView imageView = findViewById(R.id.imageView);

// Download directly from StorageReference using Glide
// (See MyAppGlideModule for Loader registration)
GlideApp.with(this /* context */)
        .load(storageReference)
        .into(imageView);

Firebase Documentation for loading image directly via Glide


问:
How to merge the duplicate records
How to merge the duplicate records in single rows.

答:
from the image output it seems you need just null checking for getting your output

```<code>select t.* from table_name t
where t.DB_NPI is not null
</code>```

But your question need more clarification with proper text data not image

Title: How to merge the duplicate records

Body:
from the image output it seems you need just null checking for getting your output

select t.* from table_name t
where t.DB_NPI is not null

But your question need more clarification with proper text data not image


问:
Iterate over an Array and push elements to an Object
I have an array object which looks like this

```<code>identificationType: "DL",
identificationDesc: "Test",
referenceNumber: "123456789",
country: "US",
province: "Illinois"
</code>```

I want my data model to look like this

```<code>identificationType: "DL",
identificationDesc: "Test",
referenceNumber: "123456789",
issuedEntity:{
country: "US",
province: "Illinois"
}
</code>```

Initially I assign array of Objects to a variable

```<code>identification: this.model['identificationArray'].
</code>```

IdentificationArray is an array of Object and contains all the details but in a simple json format. I want to be able to somehow manipulate it and insert data by creating an issuedEntity object and then country and province details inside that object.

For that I tried iterating over the array but I am getting error.Can someone help me figure out how to do it.

```<code>myModel.identification.forEach(identificationObj => {
issuedEntity: {
province = identificationObj.issuedEntity.province,
country = identificationObj.issuedEntity.country,
}
}
);
</code>```

答:
Just in case you might want to use ES6 Syntax, you'd do the same thing like this:

let data = [{
  identificationType: "DL",
  identificationDesc: "Test",
  referenceNumber: "123456789",
  country: "US",
  province: "Illinois"
}]

let newData = data.map(({
  identificationType,
  identificationDesc,
  referenceNumber,
  country,
  province
}) => ({
  identificationType,
  identificationDesc,
  referenceNumber,
  issuedEntity: {
    country,
    province
  }
}));

console.log(newData)```

Body:
I have an array object which looks like this

identificationType: "DL",
identificationDesc: "Test",
referenceNumber: "123456789",
country: "US",
province: "Illinois"

I want my data model to look like this

identificationType: "DL",
identificationDesc: "Test",
referenceNumber: "123456789",
issuedEntity:{
country: "US",
province: "Illinois"
}

Initially I assign array of Objects to a variable

identification: this.model['identificationArray'].

IdentificationArray is an array of Object and contains all the details but in a simple json format. I want to be able to somehow manipulate it and insert data by creating an issuedEntity object and then country and province details inside that object.

For that I tried iterating over the array but I am getting error.Can someone help me figure out how to do it.

myModel.identification.forEach(identificationObj => {
issuedEntity: {
province = identificationObj.issuedEntity.province,
country = identificationObj.issuedEntity.country,
}
}
);


问:
htaccess remove index.php from url
I have a problem whereby google has indexed some pages with the wrong url.

The url they are indexing is:

```<code>http://www.example.com/index.php/section1/section2
</code>```

I need it to redirect to:

```<code>http://www.example.com/section1/section2
</code>```

.htaccess isn't my forte, so any help would be much appreciated.

答:
For more detail

create .htaccess file on project root directory and put below code for remove index.php

```<code>  RewriteEngine on
  RewriteCond $1 !^(index.php|resources|robots.txt)
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php/$1 [L,QSA]
</code>```

Title: htaccess remove index.php from url

Body:
I have a problem whereby google has indexed some pages with the wrong url.

The url they are indexing is:

http://www.example.com/index.php/section1/section2

I need it to redirect to:

http://www.example.com/section1/section2

.htaccess isn't my forte, so any help would be much appreciated.

Body:
For more detail

create .htaccess file on project root directory and put below code for remove index.php

  RewriteEngine on
  RewriteCond $1 !^(index.php|resources|robots.txt)
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php/$1 [L,QSA]


问:
AttributeError: 'MSVCCompiler' object has no attribute 'compiler' when trying to install a numpy extension
I'm having an issue when installing the numpy extension py_find_1st 1.1.3. When I try to install it via cmd on Windows, I get the following message:

```<code>D:\Chrome dl\py_find_1st-1.0.6\py_find_1st-1.0.6>python setup.py install
running install
running bdist_egg
running egg_info
writing top-level names to py_find_1st.egg-info\top_level.txt
writing dependency_links to py_find_1st.egg-info\dependency_links.txt
writing py_find_1st.egg-info\PKG-INFO
reading manifest file 'py_find_1st.egg-info\SOURCES.txt'
writing manifest file 'py_find_1st.egg-info\SOURCES.txt'
installing library code to build\bdist.win-amd64\egg
running install_lib
running build_py
running build_ext
Traceback (most recent call last):
  File "setup.py", line 117, in <module>
    zip_safe = False,
  File "D:\Anaconda\lib\distutils\core.py", line 148, in setup
    dist.run_commands()
  File "D:\Anaconda\lib\distutils\dist.py", line 955, in run_commands
    self.run_command(cmd)
  File "D:\Anaconda\lib\distutils\dist.py", line 974, in run_command
    cmd_obj.run()
  File "D:\Anaconda\lib\site-packages\setuptools-27.2.0-py3.5.egg\setuptools\command\install.py", line 67, in run
  File "D:\Anaconda\lib\site-packages\setuptools-27.2.0-py3.5.egg\setuptools\command\install.py", line 109, in do_egg_install
  File "D:\Anaconda\lib\distutils\cmd.py", line 313, in run_command
    self.distribution.run_command(command)
  File "D:\Anaconda\lib\distutils\dist.py", line 974, in run_command
    cmd_obj.run()
  File "D:\Anaconda\lib\site-packages\setuptools-27.2.0-py3.5.egg\setuptools\command\bdist_egg.py", line 161, in run
  File "D:\Anaconda\lib\site-packages\setuptools-27.2.0-py3.5.egg\setuptools\command\bdist_egg.py", line 147, in call_command
  File "D:\Anaconda\lib\distutils\cmd.py", line 313, in run_command
    self.distribution.run_command(command)
  File "D:\Anaconda\lib\distutils\dist.py", line 974, in run_command
    cmd_obj.run()
  File "D:\Anaconda\lib\site-packages\setuptools-27.2.0-py3.5.egg\setuptools\command\install_lib.py", line 11, in run
  File "D:\Anaconda\lib\distutils\command\install_lib.py", line 107, in build
    self.run_command('build_ext')
  File "D:\Anaconda\lib\distutils\cmd.py", line 313, in run_command
    self.distribution.run_command(command)
  File "D:\Anaconda\lib\distutils\dist.py", line 974, in run_command
    cmd_obj.run()
  File "D:\Anaconda\lib\distutils\command\build_ext.py", line 338, in run
    self.build_extensions()
  File "setup.py", line 42, in build_extensions
    if compiler_is_clang(self.compiler.compiler):
AttributeError: 'MSVCCompiler' object has no attribute 'compiler'
</code>```

I have no knowledge of C or Fortran but if I understand it correctly, numpy extensions are often created using these languages. I was told that I might need a compiler installed on my computer and thus I installed Visual Studio 2017 but I still get the same message.

Does anybody know a way to successfully install this extension?

P.S: The "cl" command is recognized on the command prompt.

答:
This is less of an answer and more of a heads up for people running into this in the future:

According to this link, "compiler is an attribute on [GNU/]Linux but not Windows." Thus, it's highly likely that something is wrong with the setup scripts whenever you run into this problem. Most probably, the package author didn't consider Windows installation routines and needs to be notified.

If you want to fix this yourself, I recommend looking for any line of your setup.py file containing the "self.compiler.compiler[0]" part and commenting it out.

Body:
I'm having an issue when installing the numpy extension py_find_1st 1.1.3. When I try to install it via cmd on Windows, I get the following message:

D:\Chrome dl\py_find_1st-1.0.6\py_find_1st-1.0.6>python setup.py install
running install
running bdist_egg
running egg_info
writing top-level names to py_find_1st.egg-info\top_level.txt
writing dependency_links to py_find_1st.egg-info\dependency_links.txt
writing py_find_1st.egg-info\PKG-INFO
reading manifest file 'py_find_1st.egg-info\SOURCES.txt'
writing manifest file 'py_find_1st.egg-info\SOURCES.txt'
installing library code to build\bdist.win-amd64\egg
running install_lib
running build_py
running build_ext
Traceback (most recent call last):
  File "setup.py", line 117, in <module>
    zip_safe = False,
  File "D:\Anaconda\lib\distutils\core.py", line 148, in setup
    dist.run_commands()
  File "D:\Anaconda\lib\distutils\dist.py", line 955, in run_commands
    self.run_command(cmd)
  File "D:\Anaconda\lib\distutils\dist.py", line 974, in run_command
    cmd_obj.run()
  File "D:\Anaconda\lib\site-packages\setuptools-27.2.0-py3.5.egg\setuptools\command\install.py", line 67, in run
  File "D:\Anaconda\lib\site-packages\setuptools-27.2.0-py3.5.egg\setuptools\command\install.py", line 109, in do_egg_install
  File "D:\Anaconda\lib\distutils\cmd.py", line 313, in run_command
    self.distribution.run_command(command)
  File "D:\Anaconda\lib\distutils\dist.py", line 974, in run_command
    cmd_obj.run()
  File "D:\Anaconda\lib\site-packages\setuptools-27.2.0-py3.5.egg\setuptools\command\bdist_egg.py", line 161, in run
  File "D:\Anaconda\lib\site-packages\setuptools-27.2.0-py3.5.egg\setuptools\command\bdist_egg.py", line 147, in call_command
  File "D:\Anaconda\lib\distutils\cmd.py", line 313, in run_command
    self.distribution.run_command(command)
  File "D:\Anaconda\lib\distutils\dist.py", line 974, in run_command
    cmd_obj.run()
  File "D:\Anaconda\lib\site-packages\setuptools-27.2.0-py3.5.egg\setuptools\command\install_lib.py", line 11, in run
  File "D:\Anaconda\lib\distutils\command\install_lib.py", line 107, in build
    self.run_command('build_ext')
  File "D:\Anaconda\lib\distutils\cmd.py", line 313, in run_command
    self.distribution.run_command(command)
  File "D:\Anaconda\lib\distutils\dist.py", line 974, in run_command
    cmd_obj.run()
  File "D:\Anaconda\lib\distutils\command\build_ext.py", line 338, in run
    self.build_extensions()
  File "setup.py", line 42, in build_extensions
    if compiler_is_clang(self.compiler.compiler):
AttributeError: 'MSVCCompiler' object has no attribute 'compiler'

I have no knowledge of C or Fortran but if I understand it correctly, numpy extensions are often created using these languages. I was told that I might need a compiler installed on my computer and thus I installed Visual Studio 2017 but I still get the same message.

Does anybody know a way to successfully install this extension?

P.S: The "cl" command is recognized on the command prompt.


问:
How to start listing keys after a new line in a block
Using the built-in yaml package in Python is it possible to dump the items of a list starting in a new line after the list indicator dash?

Instead of this structure:

```<code>root:
  - name: a
    id: 0
  - name: b
    id: 1
</code>```

I need the following structure:

```<code>root:
  -
    name: a
    id: 0
  -
    name: b
    id: 1
</code>```

答:
AFAIK PyYAML doesn't even support the first output that you indicate:

```<code>import sys
import yaml as pyyaml

data = dict(root=[dict(name="a", id=0), dict(name="b", id=1)])
pyyaml.safe_dump(data, sys.stdout, default_flow_style=False, indent=4)
</code>```

as this gives:

```<code>root:
-   id: 0
    name: a
-   id: 1
    name: b
</code>```

As you can see the block sequence item indicator (-) is not
offset within the indent of the sequence item, and to do that and/or to get the
extra line newline, you would have to change theinternals of PyYAML's emitter.

The other built-in YAML library, ruamel.yaml (disclaimer: I am the author of that package), can
do exactly what you want:

```<code>import sys
import ruamel.yaml

data = dict(root=[dict(name="a", id=0), dict(name="b", id=1)])

yaml = ruamel.yaml.YAML()
yaml.indent(sequence=4, offset=2)
yaml.compact_seq_map = False

yaml.dump(data, sys.stdout)
</code>```

which gives:

```<code>root:
  -
    name: a
    id: 0
  -
    name: b
    id: 1
</code>```

BTW I would call neither PyYAML nor ruamel.yaml built-in, whatever
you mean by that. Python has a standard library (as it comes with
batteries included), which e.g. contains a JSON parser. But there is
no YAML parser in the standard library.

Body:
Using the built-in yaml package in Python is it possible to dump the items of a list starting in a new line after the list indicator dash?

Instead of this structure:

root:
  - name: a
    id: 0
  - name: b
    id: 1

I need the following structure:

root:
  -
    name: a
    id: 0
  -
    name: b
    id: 1

Body:
AFAIK PyYAML doesn't even support the first output that you indicate:

import sys
import yaml as pyyaml

data = dict(root=[dict(name="a", id=0), dict(name="b", id=1)])
pyyaml.safe_dump(data, sys.stdout, default_flow_style=False, indent=4)

as this gives:

root:
-   id: 0
    name: a
-   id: 1
    name: b

As you can see the block sequence item indicator (-) is not
offset within the indent of the sequence item, and to do that and/or to get the
extra line newline, you would have to change theinternals of PyYAML's emitter.

The other built-in YAML library, ruamel.yaml (disclaimer: I am the author of that package), can
do exactly what you want:

import sys
import ruamel.yaml

data = dict(root=[dict(name="a", id=0), dict(name="b", id=1)])

yaml = ruamel.yaml.YAML()
yaml.indent(sequence=4, offset=2)
yaml.compact_seq_map = False

yaml.dump(data, sys.stdout)

which gives:

root:
  -
    name: a
    id: 0
  -
    name: b
    id: 1

BTW I would call neither PyYAML nor ruamel.yaml built-in, whatever
you mean by that. Python has a standard library (as it comes with
batteries included), which e.g. contains a JSON parser. But there is
no YAML parser in the standard library.


问:
How do i get the Instance of the class when i use winrt::static_lifetime?
I switched from C++/CX to C++/winrt not long ago and I'm currently stuck because I want to create a singleton winrt-class. I read about winrt::static_lifetime (https://learn.microsoft.com/en-us/uwp/cpp-ref-for-winrt/static-lifetime), but they don't provide any code example on how to use it.
So my Question is how do I get the Instance of the class with this?

Thanks for the help in advance.

答:
winrt::static_lifetime specifies that the factory is a singleton so you basically need to implement the singleton instance as a property of the (now singleton) factory.

Namely:

```<code>namespace Foo::implementation {
    struct Foo : FooT<Foo> {
        Foo() {
        }

        static Foo Singleton() {
            auto fooFactory = winrt::make<factory_implementation::Foo>();
            return fooFactory->Singleton();
        }
    };
}

namespace Foo::factory_implementation {
    // specifies the factory is a singleton
    struct Foo : FooT<Foo, implementation::Foo, winrt::static_lifetime>
    {
        Foo Singleton() {
            slim_lock_guard lock{ m_lock };
            if (!m_singleton) {
                m_singleton = winrt::make<Foo>();
            }
            return m_singleton;
        }

    private:
        winrt::slim_mutex m_lock;
        Foo m_singleton;
    };
}
</code>```

So why is this preferred at all in comparison to something like:

```<code>static Foo Singleton() {
    static auto single = winrt::make<Foo>();
    return single;
}
</code>```

The reason to do this is because process statics may be destroyed after RoUninitialize resulting in a crash. winrt::static_lifetime basically puts the factory into CoreApplication.Properties which is uninitialized safely before the process does RoUninitialize. It's basically for the same reason why storing legacy COM objects into process globals needed to be avoided in the past.

Body:
winrt::static_lifetime specifies that the factory is a singleton so you basically need to implement the singleton instance as a property of the (now singleton) factory.

Namely:

namespace Foo::implementation {
    struct Foo : FooT<Foo> {
        Foo() {
        }

        static Foo Singleton() {
            auto fooFactory = winrt::make<factory_implementation::Foo>();
            return fooFactory->Singleton();
        }
    };
}

namespace Foo::factory_implementation {
    // specifies the factory is a singleton
    struct Foo : FooT<Foo, implementation::Foo, winrt::static_lifetime>
    {
        Foo Singleton() {
            slim_lock_guard lock{ m_lock };
            if (!m_singleton) {
                m_singleton = winrt::make<Foo>();
            }
            return m_singleton;
        }

    private:
        winrt::slim_mutex m_lock;
        Foo m_singleton;
    };
}

So why is this preferred at all in comparison to something like:

static Foo Singleton() {
    static auto single = winrt::make<Foo>();
    return single;
}

The reason to do this is because process statics may be destroyed after RoUninitialize resulting in a crash. winrt::static_lifetime basically puts the factory into CoreApplication.Properties which is uninitialized safely before the process does RoUninitialize. It's basically for the same reason why storing legacy COM objects into process globals needed to be avoided in the past.


问:
how can i add spinner to the datatable buttons
I'm using datatables and I export them in csv and excel format.
But while downloading the .csv file and .execl file I need to show a spinner inside the export button which is in the datatable.

Is this possible? If possible how to do it.

答:
i found answer for this.....

```<code> 'buttons': [
            {
                extend: "excelHtml5",
                title: '',
                text: "Execl <span class=\"loading_spinner_ex initial_hide\"><i class=\"fa fa-spinner fa-spin\"></i></span>",
                    className: "btn btn-md btn-success btn-track1",
            }
        ]
</code>```

and after that,

```<code> $( ".btn-track" )
        .mouseup(function() {
            $(".loading_spinner_ex").hide();
        })
        .mousedown(function() {
            $(".loading_spinner_ex").show();
        });
</code>```

Body:
i found answer for this.....

 'buttons': [
            {
                extend: "excelHtml5",
                title: '',
                text: "Execl <span class=\"loading_spinner_ex initial_hide\"><i class=\"fa fa-spinner fa-spin\"></i></span>",
                    className: "btn btn-md btn-success btn-track1",
            }
        ]

and after that,

 $( ".btn-track" )
        .mouseup(function() {
            $(".loading_spinner_ex").hide();
        })
        .mousedown(function() {
            $(".loading_spinner_ex").show();
        });