问:
How can I simplify this process of splitting/counting numpy subarrays?
I have a large dataset for which I would like to implement an efficient numpy solution. As a simpler example, consider a small array of numbers.

```<code>import numpy as np
arr = np.linspace(1, 10, 10)
</code>```

The code further below is very close to being my ideal solution, but I have hit a roadblock. First, I create a boolean mask to indicate the indices of the array at which array values are greater than a pre-defined lower bound and lesser than a pre-defined upper bound. I then split the boolean mask into subarrays, each of which consist of identical values by consecutive index. As an example, [0, 0, 0, 1, 1, 0, 0, 1, 1, 1] splits into [0, 0, 0], [1, 1], [0, 0], [1, 1, 1]. Lastly, I would like to take all subarrays consisting of only 1s and split them into individual subarrays. As an example, [1, 1, 1] should split into [1], [1], [1].

The code below does most of what I'd like, but in an inconvenient fashion. I would like all subarrays to be stored in a single array, from which I can count the number of subarrays and the number of elements in each subarray. Unfortunately, this is tricky for me as the function outputs are numpy arrays that are array(...) instead of just (...). I'm thinking there's a way to do this using np.ndarray.T that I get True/False values from and apply the axis kwarg to, though I have not had any success implementing this approach so far. How can I simplify this process?

```<code>def get_groups_by_difference(array, difference):
    """ This function splits arrays into subarrays in which every element is identical. """
    return np.split(array[:], np.where(abs(np.diff(array)) != difference)[0] + 1)

def check_consecutive_nested_arrays(array, repeated_value):
    """ This function returns a boolean array mask - True if all elements of a subarray contain the repeated value; False otherwise. """
    return np.array([np.all(subarray == repeated_value) for subarray in array])

def get_solution(array, lbound, ubound):
    # get boolean mask for array values within bounds
    bool_cnd = np.logical_and(array>lbound, array<ubound)
    # convert True/False into 1/0
    bool_cnd = bool_cnd * 1
    # split array into subarrays of identical values by consecutive index
    stay_idx = np.array(get_groups_by_difference(bool_cnd, 0))
    # find indices of subarrays of ones
    bool_chk = check_consecutive_nested_arrays(stay_idx, 1)
    # get full subarrays of ones
    ones_sub = stay_idx[bool_chk]
    return bool_cnd, stay_idx, bool_chk, ones_sub

bool_cnd, stay_idx, bool_chk, ones_sub = get_solution(arr, 3, 7)
print(bool_cnd)
>> [0 0 0 1 1 1 0 0 0 0]
print(stay_idx)
>> [array([0, 0, 0]) array([1, 1, 1]) array([0, 0, 0, 0])]
print(bool_chk)
>> [False  True False]
print(ones_sub)
>> [array([1, 1, 1])]
</code>```

My goal is to obtain an array result like the following:

```<code>[[0 0 0]
[1]
[1]
[1]
[0 0 0 0]]
</code>```

This way, I can find the number of elements per subarray and the number of subarrays (ie, 5 subarrays with lengths of [3, 1, 1, 1, 4].

答:
Couldn't you then process your results like so:

```<code>ret = []
for idx, check in zip(stay_idx, bool_chk):
    if check:
        ret += idx.tolist()
    else:
        ret.append(idx)
ret = np.array(ret)
</code>```

Not particularly beautiful, but maybe good enough for your specific needs.

Body:
I have a large dataset for which I would like to implement an efficient numpy solution. As a simpler example, consider a small array of numbers.

import numpy as np
arr = np.linspace(1, 10, 10)

The code further below is very close to being my ideal solution, but I have hit a roadblock. First, I create a boolean mask to indicate the indices of the array at which array values are greater than a pre-defined lower bound and lesser than a pre-defined upper bound. I then split the boolean mask into subarrays, each of which consist of identical values by consecutive index. As an example, [0, 0, 0, 1, 1, 0, 0, 1, 1, 1] splits into [0, 0, 0], [1, 1], [0, 0], [1, 1, 1]. Lastly, I would like to take all subarrays consisting of only 1s and split them into individual subarrays. As an example, [1, 1, 1] should split into [1], [1], [1].

The code below does most of what I'd like, but in an inconvenient fashion. I would like all subarrays to be stored in a single array, from which I can count the number of subarrays and the number of elements in each subarray. Unfortunately, this is tricky for me as the function outputs are numpy arrays that are array(...) instead of just (...). I'm thinking there's a way to do this using np.ndarray.T that I get True/False values from and apply the axis kwarg to, though I have not had any success implementing this approach so far. How can I simplify this process?

def get_groups_by_difference(array, difference):
    """ This function splits arrays into subarrays in which every element is identical. """
    return np.split(array[:], np.where(abs(np.diff(array)) != difference)[0] + 1)

def check_consecutive_nested_arrays(array, repeated_value):
    """ This function returns a boolean array mask - True if all elements of a subarray contain the repeated value; False otherwise. """
    return np.array([np.all(subarray == repeated_value) for subarray in array])

def get_solution(array, lbound, ubound):
    # get boolean mask for array values within bounds
    bool_cnd = np.logical_and(array>lbound, array<ubound)
    # convert True/False into 1/0
    bool_cnd = bool_cnd * 1
    # split array into subarrays of identical values by consecutive index
    stay_idx = np.array(get_groups_by_difference(bool_cnd, 0))
    # find indices of subarrays of ones
    bool_chk = check_consecutive_nested_arrays(stay_idx, 1)
    # get full subarrays of ones
    ones_sub = stay_idx[bool_chk]
    return bool_cnd, stay_idx, bool_chk, ones_sub

bool_cnd, stay_idx, bool_chk, ones_sub = get_solution(arr, 3, 7)
print(bool_cnd)
>> [0 0 0 1 1 1 0 0 0 0]
print(stay_idx)
>> [array([0, 0, 0]) array([1, 1, 1]) array([0, 0, 0, 0])]
print(bool_chk)
>> [False  True False]
print(ones_sub)
>> [array([1, 1, 1])]

My goal is to obtain an array result like the following:

[[0 0 0]
[1]
[1]
[1]
[0 0 0 0]]

This way, I can find the number of elements per subarray and the number of subarrays (ie, 5 subarrays with lengths of [3, 1, 1, 1, 4].

Body:
Couldn't you then process your results like so:

ret = []
for idx, check in zip(stay_idx, bool_chk):
    if check:
        ret += idx.tolist()
    else:
        ret.append(idx)
ret = np.array(ret)

Not particularly beautiful, but maybe good enough for your specific needs.


来源: stackexchange

问:
Razor view returns empty when using Authorize attrib on controller
I am getting an empty page and this exception (configure web.config to write log) from Login.cshtml when trying to setup authentication in a asp.net core 2 project hosted on iis 10.

```<code>fail: Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingProvider[48]
      An error occurred while reading the key ring.
System.UnauthorizedAccessException: Access to the path 'C:\Windows\system32\config\systemprofile\AppData\Local\ASP.NET\DataProtection-Keys\key-a269af3e-9a68-43f4-95c0-0dbebb957639.xml' is denied.
   at System.IO.FileStream.OpenHandle(FileMode mode, FileShare share, FileOptions options)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileA...
</code>```

Web.config to write to log:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
    </handlers>
      <!--on iis 10-->
      <aspNetCore
        processPath="dotnet"
        arguments=".\GotoLink.Web.dll"
        stdoutLogEnabled="true"
        stdoutLogFile=".\logs\stdout" />
    </system.webServer>
</configuration>
</code>```

How do I get authentication to work?

答:
It turned out to be easily fixed:

See "Data protection"
https://learn.microsoft.com/en-us/aspnet/core/publishing/iis?tabs=aspnetcore2x#data-protection

I selected option 2

ContentLicense: CC BY-SA 3.0

Body:
I am getting an empty page and this exception (configure web.config to write log) from Login.cshtml when trying to setup authentication in a asp.net core 2 project hosted on iis 10.

fail: Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingProvider[48]
      An error occurred while reading the key ring.
System.UnauthorizedAccessException: Access to the path 'C:\Windows\system32\config\systemprofile\AppData\Local\ASP.NET\DataProtection-Keys\key-a269af3e-9a68-43f4-95c0-0dbebb957639.xml' is denied.
   at System.IO.FileStream.OpenHandle(FileMode mode, FileShare share, FileOptions options)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileA...

Web.config to write to log:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
    </handlers>

      <aspNetCore
        processPath="dotnet"
        arguments=".\GotoLink.Web.dll"
        stdoutLogEnabled="true"
        stdoutLogFile=".\logs\stdout" />
    </system.webServer>
</configuration>

How do I get authentication to work?


问:
How to Setup HA for Kubernetes on CentOS, Runing 1 Master 2 Worker already using kubeadm
I have successfully setup Normal Cluster, Now when I am trying for HA setup following doc https://kubernetes.io/docs/admin/high-availability/

Here after copying etcd.yaml file in /etc/kubernetes/manifest I see 3 etcd container inside my cluster

default         etcd-server-kuber-poc-app1                  1/1       Running   1          2d
default         etcd-server-kuber-poc-app2                  1/1       Running   72         20h
kube-system     etcd-kuber-poc-app1                         1/1       Running   4          13d

But when I check logs for any etcd pods I see error like

2017-11-15 08:53:25.398815 E | discovery: error #0: x509: failed to
  load system roots and no roots provided

2017-11-15 08:53:25.398907 I | discovery: cluster status check: error
  connecting to https://discovery.etcd.io, retrying in 18h12m16s

Seems like missing certs for them

But I am not sure which certs to create and where to place

Yaml Content

```<code>apiVersion: v1
kind: Pod
metadata:
  name: etcd-server
spec:
  hostNetwork: true
  containers:
  - image: gcr.io/google_containers/etcd:3.0.17
    name: etcd-container
    command:
    - /usr/local/bin/etcd
    - --name
    - NODE-1
    - --initial-advertise-peer-urls
    - http://10.127.38.18:2380
    - --listen-peer-urls
    - http://10.127.38.18:2380
    - --advertise-client-urls
    - http://10.127.38.18:4001
    - --listen-client-urls
    - http://127.0.0.1:4001
    - --data-dir
    - /var/etcd/data
    - --discovery
    - https://discovery.etcd.io/9458bcd46077d558fd26ced5cb9f2a6a
    ports:
    - containerPort: 2380
      hostPort: 2380
      name: serverport
    - containerPort: 4001
      hostPort: 4001
      name: clientport
    volumeMounts:
    - mountPath: /var/etcd
      name: varetcd
    - mountPath: /etc/ssl
      name: etcssl
      readOnly: true
    - mountPath: /usr/share/ssl
      name: usrsharessl
      readOnly: true
    - mountPath: /var/ssl
      name: varssl
      readOnly: true
    - mountPath: /usr/ssl
      name: usrssl
      readOnly: true
    - mountPath: /usr/lib/ssl
      name: usrlibssl
      readOnly: true
    - mountPath: /usr/local/openssl
      name: usrlocalopenssl
      readOnly: true
    - mountPath: /etc/openssl
      name: etcopenssl
      readOnly: true
    - mountPath: /etc/pki/tls
      name: etcpkitls
      readOnly: true
  volumes:
  - hostPath:
      path: /var/etcd/data
    name: varetcd
  - hostPath:
      path: /etc/ssl
    name: etcssl
  - hostPath:
      path: /usr/share/ssl
    name: usrsharessl
  - hostPath:
      path: /var/ssl
    name: varssl
  - hostPath:
      path: /usr/ssl
    name: usrssl
  - hostPath:
      path: /usr/lib/ssl
    name: usrlibssl
  - hostPath:
      path: /usr/local/openssl
    name: usrlocalopenssl
  - hostPath:
      path: /etc/openssl
    name: etcopenssl
  - hostPath:
      path: /etc/pki/tls
    name: etcpkitls
</code>```

So 2 Issue

1) How to Create Certs?

2) Where to Keep them?

答:
I don't think we can make kubeadm cluster as HA.  your option is to recreate the cluster with kubespray https://github.com/kubespray/kubespray-cli tool, this will create the certificate with all the nodes.

for step by step instruction follow Kubernetes The Hard Way https://github.com/kelseyhightower/kubernetes-the-hard-way

Body:
I have successfully setup Normal Cluster, Now when I am trying for HA setup following doc https://kubernetes.io/docs/admin/high-availability/

Here after copying etcd.yaml file in /etc/kubernetes/manifest I see 3 etcd container inside my cluster

default         etcd-server-kuber-poc-app1                  1/1       Running   1          2d
default         etcd-server-kuber-poc-app2                  1/1       Running   72         20h
kube-system     etcd-kuber-poc-app1                         1/1       Running   4          13d

But when I check logs for any etcd pods I see error like

2017-11-15 08:53:25.398815 E | discovery: error #0: x509: failed to
  load system roots and no roots provided

2017-11-15 08:53:25.398907 I | discovery: cluster status check: error
  connecting to https://discovery.etcd.io, retrying in 18h12m16s

Seems like missing certs for them

But I am not sure which certs to create and where to place

Yaml Content

apiVersion: v1
kind: Pod
metadata:
  name: etcd-server
spec:
  hostNetwork: true
  containers:
  - image: gcr.io/google_containers/etcd:3.0.17
    name: etcd-container
    command:
    - /usr/local/bin/etcd
    - --name
    - NODE-1
    - --initial-advertise-peer-urls
    - http://10.127.38.18:2380
    - --listen-peer-urls
    - http://10.127.38.18:2380
    - --advertise-client-urls
    - http://10.127.38.18:4001
    - --listen-client-urls
    - http://127.0.0.1:4001
    - --data-dir
    - /var/etcd/data
    - --discovery
    - https://discovery.etcd.io/9458bcd46077d558fd26ced5cb9f2a6a
    ports:
    - containerPort: 2380
      hostPort: 2380
      name: serverport
    - containerPort: 4001
      hostPort: 4001
      name: clientport
    volumeMounts:
    - mountPath: /var/etcd
      name: varetcd
    - mountPath: /etc/ssl
      name: etcssl
      readOnly: true
    - mountPath: /usr/share/ssl
      name: usrsharessl
      readOnly: true
    - mountPath: /var/ssl
      name: varssl
      readOnly: true
    - mountPath: /usr/ssl
      name: usrssl
      readOnly: true
    - mountPath: /usr/lib/ssl
      name: usrlibssl
      readOnly: true
    - mountPath: /usr/local/openssl
      name: usrlocalopenssl
      readOnly: true
    - mountPath: /etc/openssl
      name: etcopenssl
      readOnly: true
    - mountPath: /etc/pki/tls
      name: etcpkitls
      readOnly: true
  volumes:
  - hostPath:
      path: /var/etcd/data
    name: varetcd
  - hostPath:
      path: /etc/ssl
    name: etcssl
  - hostPath:
      path: /usr/share/ssl
    name: usrsharessl
  - hostPath:
      path: /var/ssl
    name: varssl
  - hostPath:
      path: /usr/ssl
    name: usrssl
  - hostPath:
      path: /usr/lib/ssl
    name: usrlibssl
  - hostPath:
      path: /usr/local/openssl
    name: usrlocalopenssl
  - hostPath:
      path: /etc/openssl
    name: etcopenssl
  - hostPath:
      path: /etc/pki/tls
    name: etcpkitls

So 2 Issue

1) How to Create Certs?

2) Where to Keep them?


问:
UIButton that has an interupptable animation with UIViewPropertyAnimator
I want a button to expand (Scale up) when the user touches the button, and shrink back to normal when the touch leaves. Similar to iOS stock calculator before iOS 11. This is the class that I created a subclass of the button. It uses touchesbegan and touchesended to start, and or pause and revers the animation, but it does not shrink properly, and it doesn't animate.</p>

```<code>class UIOutlineButton: UIButton {

var squishAnimation:UIPropertyAnimator!

override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesBegan(touches, with: event)

    squishAnimation = UIViewPropertyAnimator(duration: 0.5, dampingRatio: 30, animations: {
        let scale = self.transform.scaledBy(x: 0.8, y: 0.8)

        let rotate = self.transform.rotated(by: 0.3)
        self.transform.concatenating(rotate)
        self.transform = scale
    })
    squishAnimation.isReversed = true
    squishAnimation.startAnimation()

    self.next?.touchesBegan(touches, with: event)

}

override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesEnded(touches, with: event)
    colorAnimation = UIViewPropertyAnimator(duration: 0.5, dampingRatio: 30, animations: {

    })

    squishAnimation = UIViewPropertyAnimator(duration: 0.5, dampingRatio: 30, animations: {
        self.transform = CGAffineTransform.identity
    })

    squishAnimation.stopAnimation(true)

    squishAnimation.startAnimation()
}

}
</code>```

答:
Here is an little snippet which will 'grow' a UIView and then return it to it's original size after a short delay:

```<code>  /// Expands & Then Returns A UIView To It's Original Size
  ///
  /// - Parameters:
  ///   - view: UIView
  ///   - duration: Double
  ///   - enable: (Void)
  func animate(view: UIView, duration: Double, enable: @escaping () -> ()){

       view.isUserInteractionEnabled = false

       UIView.animate(withDuration: duration, animations: {

           view.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)

       }) { (continueSequence) in

           UIView.animate(withDuration: duration, animations: {

                view.transform = .identity

           }, completion: { (seqeunceFinished) in
               enable()
        })
      }
   }
</code>```

You can then call it within an IBAction as follows:

```<code>@IBAction func enlargeButton(_ sender: UIButton){

      sender.isUserInteractionEnabled = false

      enlarge(view: sender duration: 1) { sender.isUserInteractionEnabled = true }
}
</code>```

Body:
I want a button to expand (Scale up) when the user touches the button, and shrink back to normal when the touch leaves. Similar to iOS stock calculator before iOS 11. This is the class that I created a subclass of the button. It uses touchesbegan and touchesended to start, and or pause and revers the animation, but it does not shrink properly, and it doesn't animate.

class UIOutlineButton: UIButton {

var squishAnimation:UIPropertyAnimator!

override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesBegan(touches, with: event)

    squishAnimation = UIViewPropertyAnimator(duration: 0.5, dampingRatio: 30, animations: {
        let scale = self.transform.scaledBy(x: 0.8, y: 0.8)

        let rotate = self.transform.rotated(by: 0.3)
        self.transform.concatenating(rotate)
        self.transform = scale
    })
    squishAnimation.isReversed = true
    squishAnimation.startAnimation()

    self.next?.touchesBegan(touches, with: event)

}

override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesEnded(touches, with: event)
    colorAnimation = UIViewPropertyAnimator(duration: 0.5, dampingRatio: 30, animations: {

    })

    squishAnimation = UIViewPropertyAnimator(duration: 0.5, dampingRatio: 30, animations: {
        self.transform = CGAffineTransform.identity
    })

    squishAnimation.stopAnimation(true)

    squishAnimation.startAnimation()
}

}

Body:
Here is an little snippet which will 'grow' a UIView and then return it to it's original size after a short delay:

  /// Expands & Then Returns A UIView To It's Original Size
  ///
  /// - Parameters:
  ///   - view: UIView
  ///   - duration: Double
  ///   - enable: (Void)
  func animate(view: UIView, duration: Double, enable: @escaping () -> ()){

       view.isUserInteractionEnabled = false

       UIView.animate(withDuration: duration, animations: {

           view.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)

       }) { (continueSequence) in

           UIView.animate(withDuration: duration, animations: {

                view.transform = .identity

           }, completion: { (seqeunceFinished) in
               enable()
        })
      }
   }

You can then call it within an IBAction as follows:

@IBAction func enlargeButton(_ sender: UIButton){

      sender.isUserInteractionEnabled = false

      enlarge(view: sender duration: 1) { sender.isUserInteractionEnabled = true }
}


问:
Javascript shorthand way to duplicate strings
I have this code in a function, and want to shorten it -  it applies the same style to every item in an array.

```<code>document.getElementById(divsArray[0]).style.visibility = 'hidden';
document.getElementById(divsArray[1]).style.visibility = 'hidden';
document.getElementById(divsArray[2]).style.visibility = 'hidden';
document.getElementById(divsArray[3]).style.visibility = 'hidden';
</code>```

NO answer to date worked (Because I am looping thru the code??)

Resolved it by setting only the previously displayed slide visibility to hidden

```<code>x = i;
i = i+1;

document.getElementById(divsArray[x]).style.visibility = 'hidden';
</code>```

答:
We can iterate over array containing ids using Array.prototype.forEach() and ES6's Arrow Functions:

var elemIds = ['two', 'four', 'six'];

elemIds.forEach(id => {document.getElementById(id).style.visibility = 'hidden';});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="one">One</div>
<div id="two">Two</div>
<div id="three">Three</div>
<div id="four">Four</div>
<div id="five">Five</div>
<div id="six">Six</div>
<div id="seven">Seven</div></code>```

Body:
I have this code in a function, and want to shorten it -  it applies the same style to every item in an array.

document.getElementById(divsArray[0]).style.visibility = 'hidden';
document.getElementById(divsArray[1]).style.visibility = 'hidden';
document.getElementById(divsArray[2]).style.visibility = 'hidden';
document.getElementById(divsArray[3]).style.visibility = 'hidden';

NO answer to date worked (Because I am looping thru the code??)

Resolved it by setting only the previously displayed slide visibility to hidden

x = i;
i = i+1;

document.getElementById(divsArray[x]).style.visibility = 'hidden';

Body:
We can iterate over array containing ids using Array.prototype.forEach() and ES6's Arrow Functions:

var elemIds = ['two', 'four', 'six'];

elemIds.forEach(id => {document.getElementById(id).style.visibility = 'hidden';});

<div id="one">One</div>
<div id="two">Two</div>
<div id="three">Three</div>
<div id="four">Four</div>
<div id="five">Five</div>
<div id="six">Six</div>
<div id="seven">Seven</div>


问:
Get file url from sharepoint by name
I'm able to save document in Sharepoint documents. Once the document is saved I want to be able to get the url of that document so I can share the url with a user.

This is the code I'm using to save the document:

using (ClientContext clientContext = new ClientContext("https://mydomain.sharepoint.com"))
{
    SecureString passWord = new SecureString();
    foreach (char c in "mypassword".ToCharArray()) passWord.AppendChar(c);
    clientContext.Credentials = new SharePointOnlineCredentials("myaccount@mydomain.com", passWord);
    Web web = clientContext.Web;
    FileCreationInformation newFile = new FileCreationInformation();
    //newFile.Content = System.IO.File.ReadAllBytes(filePath);
    byte[] docData = null;
    byte[] buffer = new byte[16 * 1024];
    using (MemoryStream ms = new MemoryStream())
    {
        int read;
        while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0)
        {
            ms.Write(buffer, 0, read);
        }
        docData = ms.ToArray();
    }
    newFile.Content = docData;
    newFile.Url = originalFileName;

    List docs = web.Lists.GetByTitle("DOCUMENTS");
    Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
    clientContext.ExecuteQuery();
}
```

How I can get the URL of that document once it's uploaded?

答:
To get url of uploaded file you could utilize the following properties:

EncodedAbsUrl - gets the absolute url of file

EncodedAbsUrl - gets the server relative url of file

They need to requested explicitly once the file is getting uploaded like this:

```<code>var uploadFile = list.RootFolder.Files.Add(fileInfo);
ctx.Load(uploadFile.ListItemAllFields,item => item["EncodedAbsUrl"], item => item["FileRef"]);
ctx.ExecuteQuery();
</code>```

Example

```<code>var fileInfo = new FileCreationInformation();
fileInfo.Content = System.IO.File.ReadAllBytes(filePath);
fileInfo.Url = Path.GetFileName(filePath);

var list = ctx.Web.Lists.GetByTitle(listTitle);
var uploadFile = list.RootFolder.Files.Add(fileInfo);
ctx.Load(uploadFile.ListItemAllFields,item => item["EncodedAbsUrl"], item => item["FileRef"]);
ctx.ExecuteQuery();

Console.WriteLine(uploadFile.ListItemAllFields["EncodedAbsUrl"]);
Console.WriteLine(uploadFile.ListItemAllFields["FileRef"]);
</code>```

Update

To get the url of display form of document you could

```<code>ctx.Load(list, l => l.DefaultDisplayFormUrl);
ctx.Load(uploadFile.ListItemAllFields,item => item.Id);
ctx.Load(ctx.Site, s => s.Url);
ctx.ExecuteQuery();

var itemUrl = String.Format("{0}{1}?ID={2}",ctx.Site.Url,list.DefaultDisplayFormUrl, uploadFile.ListItemAllFields.Id);
</code>```

ContentLicense: CC BY-SA 4.0

Title: Get file url from sharepoint by name

Body:
I'm able to save document in Sharepoint documents. Once the document is saved I want to be able to get the url of that document so I can share the url with a user.

This is the code I'm using to save the document:

using (ClientContext clientContext = new ClientContext("https://mydomain.sharepoint.com"))
{
    SecureString passWord = new SecureString();
    foreach (char c in "mypassword".ToCharArray()) passWord.AppendChar(c);
    clientContext.Credentials = new SharePointOnlineCredentials("myaccount@mydomain.com", passWord);
    Web web = clientContext.Web;
    FileCreationInformation newFile = new FileCreationInformation();
    //newFile.Content = System.IO.File.ReadAllBytes(filePath);
    byte[] docData = null;
    byte[] buffer = new byte[16 * 1024];
    using (MemoryStream ms = new MemoryStream())
    {
        int read;
        while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0)
        {
            ms.Write(buffer, 0, read);
        }
        docData = ms.ToArray();
    }
    newFile.Content = docData;
    newFile.Url = originalFileName;

    List docs = web.Lists.GetByTitle("DOCUMENTS");
    Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
    clientContext.ExecuteQuery();
}

How I can get the URL of that document once it's uploaded?

Body:
To get url of uploaded file you could utilize the following properties:

EncodedAbsUrl - gets the absolute url of file

EncodedAbsUrl - gets the server relative url of file

They need to requested explicitly once the file is getting uploaded like this:

var uploadFile = list.RootFolder.Files.Add(fileInfo);
ctx.Load(uploadFile.ListItemAllFields,item => item["EncodedAbsUrl"], item => item["FileRef"]);
ctx.ExecuteQuery();

Example

var fileInfo = new FileCreationInformation();
fileInfo.Content = System.IO.File.ReadAllBytes(filePath);
fileInfo.Url = Path.GetFileName(filePath);

var list = ctx.Web.Lists.GetByTitle(listTitle);
var uploadFile = list.RootFolder.Files.Add(fileInfo);
ctx.Load(uploadFile.ListItemAllFields,item => item["EncodedAbsUrl"], item => item["FileRef"]);
ctx.ExecuteQuery();

Console.WriteLine(uploadFile.ListItemAllFields["EncodedAbsUrl"]);
Console.WriteLine(uploadFile.ListItemAllFields["FileRef"]);

Update

To get the url of display form of document you could

ctx.Load(list, l => l.DefaultDisplayFormUrl);
ctx.Load(uploadFile.ListItemAllFields,item => item.Id);
ctx.Load(ctx.Site, s => s.Url);
ctx.ExecuteQuery();

var itemUrl = String.Format("{0}{1}?ID={2}",ctx.Site.Url,list.DefaultDisplayFormUrl, uploadFile.ListItemAllFields.Id);


问:
Cloud FireStore minimum deployment target
I'm getting the following error when trying to enable an app with Cloud FireStore:

```<code>[!] Unable to satisfy the following requirements:

- `Firebase/Firestore` required by `Podfile`

Specs satisfying the `Firebase/Firestore` dependency were found, but they required a higher minimum deployment target.
</code>```

I changed the podfile requirement to 10.2 and my xcode deployment to 10.2 and I am still getting this error.  Any suggestions?

Edit:

Solution for me: I did

```<code>pod repo update
pod install
pod update
</code>```

in that order and it worked.

答:
I have had the same problem. I tried pod repo update, pod install, pod update and even updated cocoapods.

Turned out I still had the FirebaseDatabase pod in the podfile.

Removing that solved the problem.

Body:
I'm getting the following error when trying to enable an app with Cloud FireStore:

[!] Unable to satisfy the following requirements:

- `Firebase/Firestore` required by `Podfile`

Specs satisfying the `Firebase/Firestore` dependency were found, but they required a higher minimum deployment target.

I changed the podfile requirement to 10.2 and my xcode deployment to 10.2 and I am still getting this error.  Any suggestions?

Edit:

Solution for me: I did

pod repo update
pod install
pod update

in that order and it worked.


问:
Getting 'unable to build chain to self-signed root for signer "".' when installing into physical device
When I run my app into my iPhone I get this Warning:

```<code>unable to build chain to self-signed root for signer "".
</code>```

My application Installed in iphone but it closed suddenly.

答: You are using Distribution certificate instead of Development Certificate if you are able to install app in debug mode but it closes automatically once installation completed.</p>

Body:
When I run my app into my iPhone I get this Warning:

unable to build chain to self-signed root for signer "".

My application Installed in iphone but it closed suddenly.


问:
equals() method comparison for two different list implementations
Below is the program to compare two different list implementations. When I run this, getting true as a result.

I want to understand the behaviour of this equals() method in this case.

```<code>package com.tests;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class ListsTest {
    public static void main(String[] args) {
        List listA = new ArrayList<>();
        List listB = new LinkedList<>();
        Object object = new Object();
        Integer integer = new Integer(4);
        listA.add(object);
        listB.add(object);
        System.out.println(listA.equals(listB));
    }
}
</code>```

答:
When you have a question on a specific method, the best place to start is the javadoc - extract:

In other words, two lists are defined to be equal if they contain the same elements in the same order. This definition ensures that the equals method works properly across different implementations of the List interface.

Side comment: you are using raw types when you write List listA = new ArrayList<>(); - you should use something like List<Object> listA = new ArrayList<>(); instead.

Body:
Below is the program to compare two different list implementations. When I run this, getting true as a result.

I want to understand the behaviour of this equals() method in this case.

package com.tests;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class ListsTest {
    public static void main(String[] args) {
        List listA = new ArrayList<>();
        List listB = new LinkedList<>();
        Object object = new Object();
        Integer integer = new Integer(4);
        listA.add(object);
        listB.add(object);
        System.out.println(listA.equals(listB));
    }
}


问:
Setting up JPDA for Tomcat7 in ubuntu-server
I am attempting to setup the JPDA for Tomcat7 in ubuntu.

I have used the apt-get method of installing Tomcat7.

By attempting to edit the /usr/share/tomcat7/startup.sh file with the following lines I try to get tomcat7 to boot into debug mode and allow remote debugging via eclipse.

```<code> JPDA_TRANSPORT="dt_socket"
 JPDA_ADDRESS="8000"
 exec "$PRGDIR"/"$EXECUTABLE" jpda start "$@"
</code>```

After editing the startup.sh file, I reboot tomcat7 using:

```<code> sudo service tomcat7 restart
</code>```

Then attempt to connect to the tomcat jpda in eclipse with the IP address and port 8000. I receive a "Connection Refused" error from Eclipse.

I have attempted to manually start tomcat7 using the startup.sh script rather than the service executable method as I thought perhaps the startup.sh was not being called.

```<code>sudo ./startup.sh
</code>```

This failed with the following output:

```<code> Using CATALINA_BASE:   /usr/share/tomcat7
 Using CATALINA_HOME:   /usr/share/tomcat7
 Using CATALINA_TMPDIR: /usr/share/tomcat7/temp
 Using JRE_HOME:        /usr
 Using CLASSPATH:       /usr/share/tomcat7/bin/bootstrap.jar:/usr/share/tomcat7/bin/tomcat-juli.jar
 touch: cannot touch `/usr/share/tomcat7/logs/catalina.out': No such file or directory
 ./catalina.sh: 389: ./catalina.sh: cannot create /usr/share/tomcat7/logs/catalina.out: Directory nonexistent
</code>```

I have also attempted to alter the startup script at /etc/init.d/tomcat7 as I am using service to start/restart tomcat7 to no avail...

What am I doing wrong?

答:
Settings required in Tomcat:

1)Create setenv.sh file under */tomcat/bin/. The location will be same as the catalina.sh file

2)Place the below content inside it.

export CATALINA_OPTS="-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n"
Now start the Tomcat server. Once it is started please proceed with the below steps.

Settings required in Eclipse:

3)In Eclipse go to Windows-->Preference--> General-->Network Connection --> Active Provider should be Direct. After changing to direct restart the eclipse.

4)In eclipse right click on project and debug as ->debug configuration ->Remote java application ->Create new configuration.

Fill the below fields

Name: as your wish

Project: Select the project which you need to debug.

ConnectionType: Standard socket attach

Host: Localhost Port: 8000(It should be same as mentioned in point 2)

Then click debug.

The debug will start at port 8000. Now you can verify by keeping breakpoints.

Body:
I am attempting to setup the JPDA for Tomcat7 in ubuntu.

I have used the apt-get method of installing Tomcat7.

By attempting to edit the /usr/share/tomcat7/startup.sh file with the following lines I try to get tomcat7 to boot into debug mode and allow remote debugging via eclipse.

 JPDA_TRANSPORT="dt_socket"
 JPDA_ADDRESS="8000"
 exec "$PRGDIR"/"$EXECUTABLE" jpda start "$@"

After editing the startup.sh file, I reboot tomcat7 using:

 sudo service tomcat7 restart

Then attempt to connect to the tomcat jpda in eclipse with the IP address and port 8000. I receive a "Connection Refused" error from Eclipse.

I have attempted to manually start tomcat7 using the startup.sh script rather than the service executable method as I thought perhaps the startup.sh was not being called.

sudo ./startup.sh

This failed with the following output:

 Using CATALINA_BASE:   /usr/share/tomcat7
 Using CATALINA_HOME:   /usr/share/tomcat7
 Using CATALINA_TMPDIR: /usr/share/tomcat7/temp
 Using JRE_HOME:        /usr
 Using CLASSPATH:       /usr/share/tomcat7/bin/bootstrap.jar:/usr/share/tomcat7/bin/tomcat-juli.jar
 touch: cannot touch `/usr/share/tomcat7/logs/catalina.out': No such file or directory
 ./catalina.sh: 389: ./catalina.sh: cannot create /usr/share/tomcat7/logs/catalina.out: Directory nonexistent

I have also attempted to alter the startup script at /etc/init.d/tomcat7 as I am using service to start/restart tomcat7 to no avail...

What am I doing wrong?


问:
@font-face and Header set Access-Control-Allow-Origin "*"
I have used the following rule to allow our static domain to host fonts, but I've run into a problem font's not being used by the browser (firefox, safari) when the browser cache is enabled.

```<code><Directory "/site/http/web/assets/fonts">
    <FilesMatch "\.(eot|otf|woff|ttf)$">
        SetEnvIf Origin "^http://(.*)?main-domain.com$" origin_is=$0
        Header set Access-Control-Allow-Origin %{origin_is}e env=origin_is
    </FilesMatch>
</Directory>
</code>```

I've also used the below rule to let browsers know it's ok to cache static content:

```<code>ExpiresActive On
ExpiresDefault "modification plus 10 years"
</code>```

If I browse the site with the browser cache off, the fonts load and display every time.

If I turn my browser cache off and load a page, the fonts get loaded (firebug > net) but aren't displayed!

Is the 304 Content Not Modified Header causing the browser to ignore my efforts?

答:
If you want your header addition to be used on a non-2xx response, use</p>

```<code>Header set always Access-Con...
</code>```

Body:
I have used the following rule to allow our static domain to host fonts, but I've run into a problem font's not being used by the browser (firefox, safari) when the browser cache is enabled.

<Directory "/site/http/web/assets/fonts">
    <FilesMatch "\.(eot|otf|woff|ttf)$">
        SetEnvIf Origin "^http://(.*)?main-domain.com$" origin_is=$0
        Header set Access-Control-Allow-Origin %{origin_is}e env=origin_is
    </FilesMatch>
</Directory>

I've also used the below rule to let browsers know it's ok to cache static content:

ExpiresActive On
ExpiresDefault "modification plus 10 years"

If I browse the site with the browser cache off, the fonts load and display every time.

If I turn my browser cache off and load a page, the fonts get loaded (firebug > net) but aren't displayed!

Is the 304 Content Not Modified Header causing the browser to ignore my efforts?

Body:
If you want your header addition to be used on a non-2xx response, use

Header set always Access-Con...

ContentLicense: CC BY-SA 2.5


问:
SELECT multivalues from same table in one row
I have the below table. as a reference table for values in the system.

```<code>Item    Item_code
Turkey  c01
KSA     c02
USA     c03
NY      s01
JED     s03
Dubai   j01
London  j02
.       .
.       .
.       .
</code>```

In the display page for users I want to show readable data " KSA, NY ..." not the codes. having the results in one row would save a lot code line.I don't want to do 5 select statements to get each value separately

example: I want to display the Item column of c02, s01 and s03 in one row.

desired result :

```<code>first Item     second Item    third Item ...
KSA             JED           NY
</code>```

this goes for 5 columns.

答:
You can use a pivot table like so</p>

```<code>select * from (
    select item, code from @table
) as x
pivot
(
    max(item)
    for code in (c02, s03, s01)
) as pvt
</code>```

Body:
I have the below table. as a reference table for values in the system.

Item    Item_code
Turkey  c01
KSA     c02
USA     c03
NY      s01
JED     s03
Dubai   j01
London  j02
.       .
.       .
.       .

In the display page for users I want to show readable data " KSA, NY ..." not the codes. having the results in one row would save a lot code line.I don't want to do 5 select statements to get each value separately

example: I want to display the Item column of c02, s01 and s03 in one row.

desired result :

first Item     second Item    third Item ...
KSA             JED           NY

this goes for 5 columns.

Body:
You can use a pivot table like so

select * from (
    select item, code from @table
) as x
pivot
(
    max(item)
    for code in (c02, s03, s01)
) as pvt


问:
React Native Android: Component names stripped in production?
I'm hitting some JavaScript runtime issues in production on my React Native Android app, but I'm having a hard time debugging them because the component names are being re-named to random letters (and in some instances "Unknown") in production:

```<code>com.facebook.react.common.JavascriptException: TypeError: undefined is not an object (evaluating 's.profileType.toLowerCase')
This error is located at:
in t
in InjectIntl(t)
in Apollo(InjectIntl(t))
in Apollo(Apollo(InjectIntl(t)))
in Apollo(Apollo(Apollo(InjectIntl(t))))
in Apollo(Apollo(Apollo(Apollo(InjectIntl(t)))))
in Connect(Apollo(Apollo(Apollo(Apollo(InjectIntl(t))))))
in t
in RCTView
in RCTView
in RCTView
in n
in t
in n
</code>```

Is there a way I can preserve my class / component names so I can track down these errors?

答:
This happens because of an Android tool called Proguard.

It obfuscates classes in release builds so it's harder for hackers to figure out what a class does, and how to exploit it.

There's 2 things you can do:

1) Disable Proguard completely on release builds.

2) Setup correct "Proguard rules" which tells Proguard what classes to not obfuscate, but still obfuscates the rest.

Nr 1 is by far the easiest, and just google "disable proguard react native" or so, and you'll find answers.

Nr 2 is by far the best option. This way you still protect most of the code, and only allow certain elements to not be obfuscated (so it still works). Though this also takes more work, and a bit of knowledge about how Proguard works. If you want to go down this round, try googling "proguard rules javascript react native" or so, and you can find some help.

Body:
I'm hitting some JavaScript runtime issues in production on my React Native Android app, but I'm having a hard time debugging them because the component names are being re-named to random letters (and in some instances "Unknown") in production:

com.facebook.react.common.JavascriptException: TypeError: undefined is not an object (evaluating 's.profileType.toLowerCase')
This error is located at:
in t
in InjectIntl(t)
in Apollo(InjectIntl(t))
in Apollo(Apollo(InjectIntl(t)))
in Apollo(Apollo(Apollo(InjectIntl(t))))
in Apollo(Apollo(Apollo(Apollo(InjectIntl(t)))))
in Connect(Apollo(Apollo(Apollo(Apollo(InjectIntl(t))))))
in t
in RCTView
in RCTView
in RCTView
in n
in t
in n

Is there a way I can preserve my class / component names so I can track down these errors?


问:
How to read a too long repo diff
I'm trying to read the output of the repo diff command but it is too long to be shown on the terminal, so I can't read the whole thing. Is there any solution like exporting the output in a file so I can read all the lines?

答:
You can simply use an I/O redirection to save the output to a file (named repo.diff in my example):

```<code>repo diff > repo.diff
</code>```

Title: How to read a too long repo diff

Body:
You can simply use an I/O redirection to save the output to a file (named repo.diff in my example):

repo diff > repo.diff


问:
Qt Stop worker thread loop from GUI Thread
i have a worker thread which i try to stop through a button. i sometimes get the following error:

```<code>Fatal: QThread: Destroyed while thread is still running
</code>```

Here is my code. By pushing the disconnect button a signal is emitted to stop the thread's while loop.

```<code>if (ui->connectButton->text() == "Connect") {
    mUDPThread = new QThread;
    mUDPWorker = new  UDPThread(ui->HostTextEdit->toPlainText(), ui->portTextEdit->toPlainText().toInt());
    mUDPWorker->moveToThread(mUDPThread);
    connect(mUDPThread, SIGNAL(started()), mUDPWorker, SLOT(process()));
    connect(mUDPWorker, SIGNAL(finished()), mUDPThread, SLOT(quit()));
    connect(mUDPWorker, SIGNAL(finished()), mUDPWorker, SLOT(deleteLater()));
    connect(mUDPWorker, SIGNAL(finished()), mUDPThread, SLOT(deleteLater()));
    connect(this, SIGNAL(onExitThread()), mUDPWorker, SLOT(onExitThread()));
    connect(this, SIGNAL(onDataIncome(QString)), mUDPWorker, SLOT(onDataIncome(QString)));
    mUDPThread->start();
    ui->connectButton->setText("Disconnect");
} else if (ui->connectButton->text() == "Disconnect") {
    emit onExitThread();
    ui->connectButton->setText("Connect");
}
</code>```

the worker Thread:

```<code>void UDPThread::process() {
    while (isRunning) {
    QCoreApplication::processEvents();
      ...
    }
    emit finished();
}
void UDPThread::onExitThread() {
    qDebug() << "onExitThread" << isRunning;
    isRunning = false;
}
</code>```

答:
Solved it. The error was within the connect commands:

```<code>connect(mUDPWorker, SIGNAL(finished()), mUDPThread, SLOT(deleteLater()));
</code>```

to

```<code>connect(mUDPThread, SIGNAL(finished()), mUDPThread, SLOT(deleteLater()));
</code>```

result:

```<code>connect(mUDPThread, SIGNAL(started()), mUDPWorker, SLOT(process()));
connect(mUDPWorker, SIGNAL(finished()), mUDPThread, SLOT(quit()));
connect(mUDPWorker, SIGNAL(finished()), mUDPWorker, SLOT(deleteLater()));
connect(mUDPThread, SIGNAL(finished()), mUDPThread, SLOT(deleteLater()));
connect(this, SIGNAL(onExitThread()), mUDPWorker, SLOT(onExitThread()));
connect(this, SIGNAL(onDataIncome(QString)), mUDPWorker, SLOT(onDataIncome(QString)));
</code>```

Body:
i have a worker thread which i try to stop through a button. i sometimes get the following error:

Fatal: QThread: Destroyed while thread is still running

Here is my code. By pushing the disconnect button a signal is emitted to stop the thread's while loop.

if (ui->connectButton->text() == "Connect") {
    mUDPThread = new QThread;
    mUDPWorker = new  UDPThread(ui->HostTextEdit->toPlainText(), ui->portTextEdit->toPlainText().toInt());
    mUDPWorker->moveToThread(mUDPThread);
    connect(mUDPThread, SIGNAL(started()), mUDPWorker, SLOT(process()));
    connect(mUDPWorker, SIGNAL(finished()), mUDPThread, SLOT(quit()));
    connect(mUDPWorker, SIGNAL(finished()), mUDPWorker, SLOT(deleteLater()));
    connect(mUDPWorker, SIGNAL(finished()), mUDPThread, SLOT(deleteLater()));
    connect(this, SIGNAL(onExitThread()), mUDPWorker, SLOT(onExitThread()));
    connect(this, SIGNAL(onDataIncome(QString)), mUDPWorker, SLOT(onDataIncome(QString)));
    mUDPThread->start();
    ui->connectButton->setText("Disconnect");
} else if (ui->connectButton->text() == "Disconnect") {
    emit onExitThread();
    ui->connectButton->setText("Connect");
}

the worker Thread:

void UDPThread::process() {
    while (isRunning) {
    QCoreApplication::processEvents();
      ...
    }
    emit finished();
}
void UDPThread::onExitThread() {
    qDebug() << "onExitThread" << isRunning;
    isRunning = false;
}

Body:
Solved it. The error was within the connect commands:

connect(mUDPWorker, SIGNAL(finished()), mUDPThread, SLOT(deleteLater()));

to

connect(mUDPThread, SIGNAL(finished()), mUDPThread, SLOT(deleteLater()));

result:

connect(mUDPThread, SIGNAL(started()), mUDPWorker, SLOT(process()));
connect(mUDPWorker, SIGNAL(finished()), mUDPThread, SLOT(quit()));
connect(mUDPWorker, SIGNAL(finished()), mUDPWorker, SLOT(deleteLater()));
connect(mUDPThread, SIGNAL(finished()), mUDPThread, SLOT(deleteLater()));
connect(this, SIGNAL(onExitThread()), mUDPWorker, SLOT(onExitThread()));
connect(this, SIGNAL(onDataIncome(QString)), mUDPWorker, SLOT(onDataIncome(QString)));


问:
"Uncaught SyntaxError: Unexpected token :" JSONP response
I make a JSONP request to server, from which I get application/json response.

My function:

```<code>  function testJSONP(url) {
    $.ajax({
      url: url,
      jsonp: "callback",
      contentType: 'application/json',
      dataType: "jsonp",
      success: function (response) {
        console.log(response);
      }
    });
  }
</code>```

In Chrome console I get the following error message, and there's no output in console:

Uncaught SyntaxError: Unexpected token :

I have validated my json response manually, and it's ok.

What could be the problem then?

答:
Write like this...</p>

```<code>function testJSONP(url) {
    $.getJSON(url,{},function(response){
        console.log(response);
    });
}
</code>```

Body:
I make a JSONP request to server, from which I get application/json response.

My function:

  function testJSONP(url) {
    $.ajax({
      url: url,
      jsonp: "callback",
      contentType: 'application/json',
      dataType: "jsonp",
      success: function (response) {
        console.log(response);
      }
    });
  }

In Chrome console I get the following error message, and there's no output in console:

Uncaught SyntaxError: Unexpected token :

I have validated my json response manually, and it's ok.

What could be the problem then?

Body:
Write like this...

function testJSONP(url) {
    $.getJSON(url,{},function(response){
        console.log(response);
    });
}


问:
How to remove "Never ask again" text in this popup?
How can I request the permission popup without “Never ask again” text?

Here java Code ,

```<code>    if
 (intent.getAction().equals("com.finish.canceltrip.DriverMapActivity")) {
                if (!checkAccessFineLocationPermission() || !checkAccessCoarseLocationPermission() || !checkWriteExternalStoragePermission()) {
                    requestPermission();
                } else {
                    Intent i = new Intent(DriverMapActivity.this, DriverMapActivity.class);
                    i.putExtra("availability", "Yes");
                    finish();
                    startActivity(i);

                }
</code>```

答:
No u can not remove Never ask again from that dialog

If the user declines again the app should either shut down if it absolutely needs that permission or keep running with limited functionality.

If the user reconsiders (and selects re-try), the permission is requested again. This time the prompt looks like this:

Body:
How can I request the permission popup without “Never ask again” text?

Here java Code ,

    if
 (intent.getAction().equals("com.finish.canceltrip.DriverMapActivity")) {
                if (!checkAccessFineLocationPermission() || !checkAccessCoarseLocationPermission() || !checkWriteExternalStoragePermission()) {
                    requestPermission();
                } else {
                    Intent i = new Intent(DriverMapActivity.this, DriverMapActivity.class);
                    i.putExtra("availability", "Yes");
                    finish();
                    startActivity(i);

                }


问:
CSS highlight label BEFORE an invalid input
Ciao, I have this element here:

```<code><div class="uk-form-row">
    <div class="md-input-wrapper md-input-filled md-input-focus">
        <label>Label</label>
        <input type="text" class="md-input">
        <span class="md-input-bar"></span>
    </div>
</div>
</code>```

This is from a material design theme (Altair Admin v2) so the element once the page is loaded does this:

As you can see the label is moving around (but maybe is not a big deal).

With other elements, if they are empty (invalid) I can underline them or change their color using css:

```<code>input:invalid::-webkit-input-placeholder{
    color: #e53935 !important;
}
</code>```

But being this a label BEFORE the input I don't know how I can select it with CSS. How do I turn the LABEL into a different color if the input is invalid?

答:
Look at CSS code (simplified to illustrate my point):

```<code>.md-input-wrapper {
  position: relative;
}

.md-input-wrapper > label {
  position: absolute;
  top: 16px;
  left: 4px;
  right: 0;
}
</code>```

Label is positioned absolutely relative to wrapper, so you can put label element after input element in HTML:

```<code><div class="md-input-wrapper">
    <input type="text" class="md-input">
    <span class="md-input-bar"></span>
    <label>Label</label>
</div>
</code>```

After that, you can use General sibling combinator to select label of invalid input:

```<code>input:invalid ~ label {
   color: red;
}
</code>```

Body:
Ciao, I have this element here:

        Label
        <input type="text" class="md-input">

This is from a material design theme (Altair Admin v2) so the element once the page is loaded does this:

As you can see the label is moving around (but maybe is not a big deal).

With other elements, if they are empty (invalid) I can underline them or change their color using css:

input:invalid::-webkit-input-placeholder{
    color: #e53935 !important;
}

But being this a label BEFORE the input I don't know how I can select it with CSS. How do I turn the LABEL into a different color if the input is invalid?

Body:
Look at CSS code (simplified to illustrate my point):

.md-input-wrapper {
  position: relative;
}

.md-input-wrapper > label {
  position: absolute;
  top: 16px;
  left: 4px;
  right: 0;
}

Label is positioned absolutely relative to wrapper, so you can put label element after input element in HTML:

<div class="md-input-wrapper">
    <input type="text" class="md-input">
    <span class="md-input-bar"></span>
    <label>Label</label>
</div>

After that, you can use General sibling combinator to select label of invalid input:

input:invalid ~ label {
   color: red;
}


问:
Unit Testing xUnit Asserting 2 Collections with Moq Interface
Good day everyone,

I'm new in xunit and even in unit testing. I have a code here and I'm trying to assert two collection of list. But I have no idea how to assert and pass this test. Here's my code

```<code>    [Theory]
    [InlineData(1)]
    public void GetAllStudents_Exempt1(int number)
    {
        // arrange
        var studentRepo = new Mock<IStudentRepository>();
        var listOfStudents = new List<Student> { new Student { StudentId = 1, Firstname = "Firstname1", Lastname = "Firstname1" },
        new Student{StudentId=2, Firstname="Firstname2",Lastname="Lastname2"} };

        var getAllStudentDetailsExempt1 = studentRepo.Setup(s => s.GetStudents()).Returns(listOfStudents.Where(x => x.StudentId != number));

        var studentService = new StudentService(studentRepo.Object);

        // act
        var getStudentsDetails = studentService.ListOfStudentsExempt1(1);

        // assert
        // I don't have any idea how to assert
    }
</code>```

答:
First a few notes:

```<code>var getAllStudentDetailsExempt1 = studentRepo
    .Setup(s => s.GetStudents())
    .Returns(listOfStudents.Where(x => x.StudentId != number));
</code>```

you don't need var getAllStudentDetailsExempt1, you can just setup your repo-mock...

```<code>studentRepo
    .Setup(s => s.GetStudents())
    .Returns(listOfStudents.Where(x => x.StudentId != number));
</code>```

You probably want to change:

```<code>// act
var getStudentsDetails = studentService.ListOfStudentsExempt1(1);
</code>```

to use the number variable...

```<code>// act
var getStudentsDetails = studentService.ListOfStudentsExempt1(number);
</code>```

So then you can assert by checking some properties:

```<code>Assert.Equals(1, getStudentsDetails.Count);
Assert.Equals("FirstName1", getStudentsDetails.First().Firstname);
</code>```

etc. etc.

Give it a shot!

Body:
Good day everyone,

I'm new in xunit and even in unit testing. I have a code here and I'm trying to assert two collection of list. But I have no idea how to assert and pass this test. Here's my code

    [Theory]
    [InlineData(1)]
    public void GetAllStudents_Exempt1(int number)
    {
        // arrange
        var studentRepo = new Mock<IStudentRepository>();
        var listOfStudents = new List<Student> { new Student { StudentId = 1, Firstname = "Firstname1", Lastname = "Firstname1" },
        new Student{StudentId=2, Firstname="Firstname2",Lastname="Lastname2"} };

        var getAllStudentDetailsExempt1 = studentRepo.Setup(s => s.GetStudents()).Returns(listOfStudents.Where(x => x.StudentId != number));

        var studentService = new StudentService(studentRepo.Object);

        // act
        var getStudentsDetails = studentService.ListOfStudentsExempt1(1);

        // assert
        // I don't have any idea how to assert
    }

Body:
First a few notes:

var getAllStudentDetailsExempt1 = studentRepo
    .Setup(s => s.GetStudents())
    .Returns(listOfStudents.Where(x => x.StudentId != number));

you don't need var getAllStudentDetailsExempt1, you can just setup your repo-mock...

studentRepo
    .Setup(s => s.GetStudents())
    .Returns(listOfStudents.Where(x => x.StudentId != number));

You probably want to change:

// act
var getStudentsDetails = studentService.ListOfStudentsExempt1(1);

to use the number variable...

// act
var getStudentsDetails = studentService.ListOfStudentsExempt1(number);

So then you can assert by checking some properties:

Assert.Equals(1, getStudentsDetails.Count);
Assert.Equals("FirstName1", getStudentsDetails.First().Firstname);

etc. etc.

Give it a shot!


问:
Why does TypeScript allow duplicate component while implements?
Why does TypeScript allow duplicate component while implements?

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

export class CreateVersionComponent implements OnInit, OnInit, OnInit { }// no error
export class CreateVersionComponent extends OnInit, OnInit, OnInit { }// getting error
</code>```

But it throwing duplicate identifier error while component extends.

So what is the reason for typescript accepting duplicate component while implements? which situation we need to use it?

答:
TypeScript doesn't allow multiple inheritance, much like Java, C# etc. So the second example won't work firstly because TSC thinks you're trying to extend more than one class, before it fails because it's the same class.

For the first case, I agree it should say something because it's probably a small mistake. On the other hand, it's not semantically wrong. When you're implementing the methods in the first OnInit, you're implementing it for the second and third as well, so you should be covered.

Body:
Why does TypeScript allow duplicate component while implements?

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

export class CreateVersionComponent implements OnInit, OnInit, OnInit { }// no error
export class CreateVersionComponent extends OnInit, OnInit, OnInit { }// getting error

But it throwing duplicate identifier error while component extends.

So what is the reason for typescript accepting duplicate component while implements? which situation we need to use it?


问:
How to tidy huge blank spaces in data_frame?
I've got some data pulled from the web that has about 15,000 rows. The date column has a date at the beginning of each 'block section' of data. About 25% of which is blank. So it's a column that will have one cell of 2010, then NA's for a while, then 2010 again. Basically, the date is the same . . . until it changes. I've pulled a date variable out and it looks like the Date_from source column in the following code:

```<code>data_frame(
  Date_from_source =
    c(2010,rep(NA,2),2010,rep(NA,2),2011,rep(NA,3),2011,rep(NA,2),2012),
  Date_tidy = c(rep(2010,6),rep(2011,7),2012))
</code>```

I'm stuck on how to code the Data_from_source column into a Date_tidy column. I've tried using a group_by and lag approach, but I'm spinning my wheels.  Thanks.

答:
You're looking for tidyr::fill

```<code>library(tidyr)
library(dplyr)
df1 <- data_frame(
  Gender = sample(c('male','female'),14,T),
  Date_from_source =
    c(2010,rep(NA,2),2010,rep(NA,2),2011,rep(NA,3),2011,rep(NA,2),2012),
  Date_tidy = c(rep(2010,6),rep(2011,7),2012))

df1 %>% group_by(Gender) %>% fill(Date_from_source)

    # # A tibble: 14 x 3
    # # Groups:   Gender [2]
    # Gender Date_from_source Date_tidy
    # <chr>            <dbl>     <dbl>
    #  1 female               NA      2010
    #  2 female             2011      2011
    #  3 female             2011      2011
    #  4 female             2011      2011
    #  5 female             2011      2011
    #  6   male             2010      2010
    #  7   male             2010      2010
    #  8   male             2010      2010
    #  9   male             2010      2010
    # 10   male             2010      2010
    # 11   male             2010      2011
    # 12   male             2010      2011
    # 13   male             2010      2011
    # 14   male             2012      2012
</code>```

Body:
I've got some data pulled from the web that has about 15,000 rows. The date column has a date at the beginning of each 'block section' of data. About 25% of which is blank. So it's a column that will have one cell of 2010, then NA's for a while, then 2010 again. Basically, the date is the same . . . until it changes. I've pulled a date variable out and it looks like the Date_from source column in the following code:

data_frame(
  Date_from_source =
    c(2010,rep(NA,2),2010,rep(NA,2),2011,rep(NA,3),2011,rep(NA,2),2012),
  Date_tidy = c(rep(2010,6),rep(2011,7),2012))

I'm stuck on how to code the Data_from_source column into a Date_tidy column. I've tried using a group_by and lag approach, but I'm spinning my wheels.  Thanks.

Body:
You're looking for tidyr::fill

library(tidyr)
library(dplyr)
df1 <- data_frame(
  Gender = sample(c('male','female'),14,T),
  Date_from_source =
    c(2010,rep(NA,2),2010,rep(NA,2),2011,rep(NA,3),2011,rep(NA,2),2012),
  Date_tidy = c(rep(2010,6),rep(2011,7),2012))

df1 %>% group_by(Gender) %>% fill(Date_from_source)

    # # A tibble: 14 x 3
    # # Groups:   Gender [2]
    # Gender Date_from_source Date_tidy
    # <chr>            <dbl>     <dbl>
    #  1 female               NA      2010
    #  2 female             2011      2011
    #  3 female             2011      2011
    #  4 female             2011      2011
    #  5 female             2011      2011
    #  6   male             2010      2010
    #  7   male             2010      2010
    #  8   male             2010      2010
    #  9   male             2010      2010
    # 10   male             2010      2010
    # 11   male             2010      2011
    # 12   male             2010      2011
    # 13   male             2010      2011
    # 14   male             2012      2012


问:
Which operator (+ vs +=) should be used for performance? (In-place Vs not-in-place)
Let's say I have this two snippet of code in python :

```<code>1 --------------------------
import numpy as np
x = np.array([1,2,3,4])
y = x
x = x + np.array([1,1,1,1])
print y

2 --------------------------
import numpy as np
x = np.array([1,2,3,4])
y = x
x += np.array([1,1,1,1])
print y
</code>```

I thought the result of y will be the same in both examples since y point out to x and x become (2,3,4,5), BUT it wasn't

The results were (1,2,3,4) for 1 and (2,3,4,5) for 2.

After some research I find out that in first example

```<code>#-First example---------------------------------------
x = np.array([1,2,3,4]) # create x --> [1,2,3,4]
y = x                   # made y point to x
# unril now we have x --> [1,2,3,4]
#                          |
#                          y
x = x + np.array([1,1,1,1])
# however this operation **create a new array** [2,3,4,5]
# and made x point to it instead of the first one
# so we have y --> [1,2,3,4] and x --> [2,3,4,5]

#-Second example--------------------------------------
x = np.array([1,2,3,4]) # create x --> [1,2,3,4]
y = x                   # made y point to x
# unril now the same x --> [1,2,3,4]
#                            |
#                            y
x += np.array([1,1,1,1])
# this operation **Modify the existing array**
# so the result will be
# unril now the same x --> [2,3,4,5]
#                            |
#                            y
</code>```

You can find out more about this behaviors (not only for this example) in this link In-place algorithm

My question is : Being aware of this behavior why should I use in-place algorithm in term of performance? (time of excution faster? less memory alocation?..)

EDIT : Clarification

The example of (+, =+) was just to explain simply the in-place algorithm to the one who don't know.. but the question was in general the use of in-place algorithm not only in this case..

As another more complex example: loading a CSV file (just 10 Million rows) in a variable then sorting the result, is the idea of in-place algorithm is to produce an output in the same memory space that contains the input by successively transforming that data until the output is produced? - This avoids the need to use twice the storage - one area for the input and an equal-sized area for the output ( Using the minimum amount of RAM, hard disk ... )

答:
x = x + 1 vs x += 1

Performance

It seems that you understand the semantical difference between x += 1 and x = x + 1.

For benchmarking, you can use timeit in IPython.

After defining those functions:

```<code>import numpy as np
def in_place(n):
    x = np.arange(n)
    x += 1

def not_in_place(n):
    x = np.arange(n)
    x = x + 1

def in_place_no_broadcast(n):
    x = np.arange(n)
    x += np.ones(n, dtype=np.int)
</code>```

You can simply use the %timeit syntax to compare performances:

```<code>%timeit in_place(10**7)
20.3 ms ± 81.4 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit not_in_place(10**7)
30.4 ms ± 253 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit in_place_no_broadcast(10**7)
35.4 ms ± 101 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
</code>```

not_in_place is 50% slower than in_place.

Note that broadcasting also makes a huge difference : numpy understands x += 1 as adding a 1 to every single element of x, without having to create yet another array.

Warning

in_place should be the preferred function: it's faster and uses less memory. You might run into bugs if you use and mutate this object at different places in your code, though. The typical example would be :

```<code>x = np.arange(5)
y = [x, x]
y[0][0] = 10
y
# [array([10,  1,  2,  3,  4]), array([10,  1,  2,  3,  4])]
</code>```

Sorting

Your understanding of the advantages of in-place sorting is correct. It can make a huge difference in memory requirements when sorting large data sets.

There are other desirable features for a sorting algorithm (stable, acceptable worst-case complexity, ...) and it looks like the standard Python algorithm (Timsort) has many of them.

Timsort is an hybrid algorithm. Some parts of it are in-place and some require extra memory. It will never use more than n/2 though.

Body:
Let's say I have this two snippet of code in python :

1 --------------------------
import numpy as np
x = np.array([1,2,3,4])
y = x
x = x + np.array([1,1,1,1])
print y

2 --------------------------
import numpy as np
x = np.array([1,2,3,4])
y = x
x += np.array([1,1,1,1])
print y

I thought the result of y will be the same in both examples since y point out to x and x become (2,3,4,5), BUT it wasn't

The results were (1,2,3,4) for 1 and (2,3,4,5) for 2.

After some research I find out that in first example

#-First example---------------------------------------
x = np.array([1,2,3,4]) # create x --> [1,2,3,4]
y = x                   # made y point to x
# unril now we have x --> [1,2,3,4]
#                          |
#                          y
x = x + np.array([1,1,1,1])
# however this operation **create a new array** [2,3,4,5]
# and made x point to it instead of the first one
# so we have y --> [1,2,3,4] and x --> [2,3,4,5]

#-Second example--------------------------------------
x = np.array([1,2,3,4]) # create x --> [1,2,3,4]
y = x                   # made y point to x
# unril now the same x --> [1,2,3,4]
#                            |
#                            y
x += np.array([1,1,1,1])
# this operation **Modify the existing array**
# so the result will be
# unril now the same x --> [2,3,4,5]
#                            |
#                            y

You can find out more about this behaviors (not only for this example) in this link In-place algorithm

My question is : Being aware of this behavior why should I use in-place algorithm in term of performance? (time of excution faster? less memory alocation?..)

EDIT : Clarification

The example of (+, =+) was just to explain simply the in-place algorithm to the one who don't know.. but the question was in general the use of in-place algorithm not only in this case..

As another more complex example: loading a CSV file (just 10 Million rows) in a variable then sorting the result, is the idea of in-place algorithm is to produce an output in the same memory space that contains the input by successively transforming that data until the output is produced? - This avoids the need to use twice the storage - one area for the input and an equal-sized area for the output ( Using the minimum amount of RAM, hard disk ... )

Body:
x = x + 1 vs x += 1

Performance

It seems that you understand the semantical difference between x += 1 and x = x + 1.

For benchmarking, you can use timeit in IPython.

After defining those functions:

import numpy as np
def in_place(n):
    x = np.arange(n)
    x += 1

def not_in_place(n):
    x = np.arange(n)
    x = x + 1

def in_place_no_broadcast(n):
    x = np.arange(n)
    x += np.ones(n, dtype=np.int)

You can simply use the %timeit syntax to compare performances:

%timeit in_place(10**7)
20.3 ms ± 81.4 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit not_in_place(10**7)
30.4 ms ± 253 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit in_place_no_broadcast(10**7)
35.4 ms ± 101 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

not_in_place is 50% slower than in_place.

Note that broadcasting also makes a huge difference : numpy understands x += 1 as adding a 1 to every single element of x, without having to create yet another array.

Warning

in_place should be the preferred function: it's faster and uses less memory. You might run into bugs if you use and mutate this object at different places in your code, though. The typical example would be :

x = np.arange(5)
y = [x, x]
y[0][0] = 10
y
# [array([10,  1,  2,  3,  4]), array([10,  1,  2,  3,  4])]

Sorting

Your understanding of the advantages of in-place sorting is correct. It can make a huge difference in memory requirements when sorting large data sets.

There are other desirable features for a sorting algorithm (stable, acceptable worst-case complexity, ...) and it looks like the standard Python algorithm (Timsort) has many of them.

Timsort is an hybrid algorithm. Some parts of it are in-place and some require extra memory. It will never use more than n/2 though.


问:
Material ui autocomplete issue with default value in React
I'm using redux-form with material ui autocomplete field.

What I need to do is:

when page load autocomplete value would be empty .

When user start to type and reach to 3 character I want to call API and the result of that API I want to show as autocomplete dataSource.

What I have tried:

I tried to not set dataSource and in seconde try I set dataSource={} in both the case I got same error message:

Failed prop type: The prop dataSource is marked as required in AutoComplete, but its value is undefined.**

Home.js class code

```<code>import React, {Component} from 'react';
import {Field, reduxForm} from 'redux-form';
import AutoComplete from 'material-ui/AutoComplete';
import {connect} from 'react-redux';

class Home extends Component {

renderAutoComplete = ({
                          input,
                          label,
                          meta: {touched, error},
                          children,
                          ...custom
                      }) => (
    <AutoComplete
        floatingLabelText={label}
        errorText={touched && error}
        {...input}
        onChange={(event, index, value) => input.onChange(value)}
        children={children}
        {...custom}
    />

)

render() {

    const startDate = new Date();

    const {handleSubmit} = this.props;

    return (

        <form onSubmit={handleSubmit(this.onSubmit.bind(this))}>

            <div>
                <Field name="Origin_1" label="FROM" component={this.renderAutoComplete} dataSource={}/>
            </div>

            <div>
                <button type="submit">
                    Submit
                </button>
            </div>

        </form>

    );

}

}

const LogInForm = reduxForm({
form: 'MaterialUiForm', // a unique identifier for this form
validate
})(Home);
export default connect(mapStateTOProps, {getCity})(LogInForm);
</code>```

答:
From the demo and source code comments, you can see that value for the dataSourse property need to be an array:

```<code>/**
 * Array of strings or nodes used to populate the list.
 */
 dataSource: PropTypes.array.isRequired,
</code>```

so you can do the following:

Set initial value of the dataSource as empty array

Do the API call when the length of inputed value will be more like 3 symbols

Update dataSource property on api responce callback

Also keep in mind that if you will use the array of objects for the value of dataSourse, each object need to have 'text' and 'value' keys:

```<code>const dataSource = [
  {text: 'Some Text', value: 'someFirstValue'},
  {text: 'Some Text', value: 'someSecondValue'},
];
</code>```

or additional dataSourceConfig for mapping:

```<code>const dataSourceCustomKeys = [
  {textKey: 'Some Text', valueKey: 'someFirstValue'},
  {textKey: 'Some Text', valueKey: 'someSecondValue'},
];
const dataSourceConfig = {
  text: 'textKey',
  value: 'valueKey',
};
</code>```

Body:
I'm using redux-form with material ui autocomplete field.

What I need to do is:

when page load autocomplete value would be empty .

When user start to type and reach to 3 character I want to call API and the result of that API I want to show as autocomplete dataSource.

What I have tried:

I tried to not set dataSource and in seconde try I set dataSource={} in both the case I got same error message:

Failed prop type: The prop dataSource is marked as required in AutoComplete, but its value is undefined.**

Home.js class code

import React, {Component} from 'react';
import {Field, reduxForm} from 'redux-form';
import AutoComplete from 'material-ui/AutoComplete';
import {connect} from 'react-redux';

class Home extends Component {

renderAutoComplete = ({
                          input,
                          label,
                          meta: {touched, error},
                          children,
                          ...custom
                      }) => (
    <AutoComplete
        floatingLabelText={label}
        errorText={touched && error}
        {...input}
        onChange={(event, index, value) => input.onChange(value)}
        children={children}
        {...custom}
    />

)

render() {

    const startDate = new Date();

    const {handleSubmit} = this.props;

    return (

        <form onSubmit={handleSubmit(this.onSubmit.bind(this))}>

                <Field name="Origin_1" label="FROM" component={this.renderAutoComplete} dataSource={}/>

                <button type="submit">
                    Submit
                </button>

        </form>

    );

}

}

const LogInForm = reduxForm({
form: 'MaterialUiForm', // a unique identifier for this form
validate
})(Home);
export default connect(mapStateTOProps, {getCity})(LogInForm);

Body:
From the demo and source code comments, you can see that value for the dataSourse property need to be an array:

/**
 * Array of strings or nodes used to populate the list.
 */
 dataSource: PropTypes.array.isRequired,

so you can do the following:

Set initial value of the dataSource as empty array

Do the API call when the length of inputed value will be more like 3 symbols

Update dataSource property on api responce callback

Also keep in mind that if you will use the array of objects for the value of dataSourse, each object need to have 'text' and 'value' keys:

const dataSource = [
  {text: 'Some Text', value: 'someFirstValue'},
  {text: 'Some Text', value: 'someSecondValue'},
];

or additional dataSourceConfig for mapping:

const dataSourceCustomKeys = [
  {textKey: 'Some Text', valueKey: 'someFirstValue'},
  {textKey: 'Some Text', valueKey: 'someSecondValue'},
];
const dataSourceConfig = {
  text: 'textKey',
  value: 'valueKey',
};


问:
Java Array/List with stable index on remove
I'm looking for a data structure like ArrayList which elements don't get reindexed after removing a single one from it.

As an example scenario, Consider having a list as following psoudocode:

```<code>A(0) = m
A(1) = n
A(2) = o
A(3) = p
A(4) = q
</code>```

Using ArrayAdapter, issuing a A.remove(2) results in:

```<code>A(0) = m
A(1) = n
A(2) = p      // index decremented
A(3) = q      // index decremented
</code>```

which is not my desired behaviour. I'm looking for a list/array/map/set/collection/whatever which gives a result like this:

```<code>A(0) = m
A(1) = n
A(3) = p      // index persisted
A(4) = q      // index persisted
</code>```

It "can" be done using a integer counter combined with a Map but i'm wondering if a cleaner solution is already available.

Dirty approach using Map and integer counter:

```<code>HashMap<Integer, Object> map = new HashMap<>();
int indexCounter = 0;

public void insertItem(Object o){
    map.put(indexCounter, o);
    indexCounter++;
}
</code>```

Any ideas?

Edit:
To clearify, by m, n, o, ... i mean different values. These are not necessarily string and can be any kind of objects. That's a pseudocode.

More than that, Using NULL or mock values would not be an option in my case. Although, i'm looking for a general solution, not a specific one for my case. Thanks for sharing btw.

Edit 2:
Actually, im looking for a data structure, not a hack or trick. Thus, if there is not such a thing provided in Java, the correct answer to this question would be a straight conclusive "No, there isn't such a thing".

答:
I would suggest to go with LinkedList which would solve your purpose and won’t impact performance on removal of element like ArrayList.

You can check this link to understand whether it satisfies your needs
https://dzone.com/articles/linked-list-journey-continues

Body:
I'm looking for a data structure like ArrayList which elements don't get reindexed after removing a single one from it.

As an example scenario, Consider having a list as following psoudocode:

A(0) = m
A(1) = n
A(2) = o
A(3) = p
A(4) = q

Using ArrayAdapter, issuing a A.remove(2) results in:

A(0) = m
A(1) = n
A(2) = p      // index decremented
A(3) = q      // index decremented

which is not my desired behaviour. I'm looking for a list/array/map/set/collection/whatever which gives a result like this:

A(0) = m
A(1) = n
A(3) = p      // index persisted
A(4) = q      // index persisted

It "can" be done using a integer counter combined with a Map but i'm wondering if a cleaner solution is already available.

Dirty approach using Map and integer counter:

HashMap<Integer, Object> map = new HashMap<>();
int indexCounter = 0;

public void insertItem(Object o){
    map.put(indexCounter, o);
    indexCounter++;
}

Any ideas?

Edit:
To clearify, by m, n, o, ... i mean different values. These are not necessarily string and can be any kind of objects. That's a pseudocode.

More than that, Using NULL or mock values would not be an option in my case. Although, i'm looking for a general solution, not a specific one for my case. Thanks for sharing btw.

Edit 2:
Actually, im looking for a data structure, not a hack or trick. Thus, if there is not such a thing provided in Java, the correct answer to this question would be a straight conclusive "No, there isn't such a thing".


问:
How to avoid use of Thread.Sleep
I never gave the use of Thread.Sleep much thought, until I downloaded the latest version of Netbeans.  Netbeans now warns you not to use Thread.Sleep.  So I did some research on the topic and found people stating that you only need to use Thread.Sleep for debugging/testing purposes and that if you use it at any other time you have poorly written code.

So my question is how can I keep from using Thread.Sleep in the following situation.

I have written a server application that interfaces with another application.  The server has two threads:

Handles the data coming over the socket and sends back other information or just plain acknoledgements.

This is the main thread.  After kicking off the socket thread it going into an indefinite while loop.  Within this while loop I check to make sure the socket thread is still active and that the user hasn't asked to exit the application via a TrayIcon interface.  Then I sleep and continue this while loop.

With this application, the TrayIcon is the only UI.

Here is the snippet I'm referencing:

```<code>// continues running as long as the exitth file is not present and
// the tray icon is not in a safe to exit status.

while(doNotExit())
{

    if (getPrimaryThread() == null || !getPrimaryThread().isAlive())
        resetsThreadAndSocket();

    try
    {
        // check to see if the socket threads are still active, if not create new ones.
        if ((getPrimaryThread() == null || !getPrimaryThread().isAlive()))
            createSocketThread();

        // check right before sleeping that the user does not want to exit.
        if(getTrayIcon().isExiting())
            break;

        // puts the main Thread to sleep for 3 seconds
           Thread.sleep(3000);
    }
    catch(SQLException ex)
    {
        _log.error(ex.getMessage(), ex);
        restartDatabase();
    }
}
</code>```

答:
You seem to be paranoid that some condition (maybe a RuntimeException or Error?) is going to cause your socket Thread to just die. Ideally, you would design your Socket Thread such that it protected itself from crashing. The following example creates a loop that can only be broken as a result of a JVM Error or Thread interrupt:

```<code>public void run() {
    while(!Thread.currentThread.isInterrupted()) {
        try {
            //you application logic
        } catch (RuntimeException e) {
           //log uncaught exception
        }
    }
}
</code>```

In order to shutdown the application, you would attach a listener to the TrayIcon which contained a reference to the SocketThread and could stop it by simply interrupting it.

```<code>socketThread.interrupt();
</code>```

I'll leave figuring how to add an ActionListener to a TrayIcon up to you.

Title: How to avoid use of Thread.Sleep

Body:
I never gave the use of Thread.Sleep much thought, until I downloaded the latest version of Netbeans.  Netbeans now warns you not to use Thread.Sleep.  So I did some research on the topic and found people stating that you only need to use Thread.Sleep for debugging/testing purposes and that if you use it at any other time you have poorly written code.

So my question is how can I keep from using Thread.Sleep in the following situation.

I have written a server application that interfaces with another application.  The server has two threads:

Handles the data coming over the socket and sends back other information or just plain acknoledgements.

This is the main thread.  After kicking off the socket thread it going into an indefinite while loop.  Within this while loop I check to make sure the socket thread is still active and that the user hasn't asked to exit the application via a TrayIcon interface.  Then I sleep and continue this while loop.

With this application, the TrayIcon is the only UI.

Here is the snippet I'm referencing:

// continues running as long as the exitth file is not present and
// the tray icon is not in a safe to exit status.

while(doNotExit())
{

    if (getPrimaryThread() == null || !getPrimaryThread().isAlive())
        resetsThreadAndSocket();

    try
    {
        // check to see if the socket threads are still active, if not create new ones.
        if ((getPrimaryThread() == null || !getPrimaryThread().isAlive()))
            createSocketThread();

        // check right before sleeping that the user does not want to exit.
        if(getTrayIcon().isExiting())
            break;

        // puts the main Thread to sleep for 3 seconds
           Thread.sleep(3000);
    }
    catch(SQLException ex)
    {
        _log.error(ex.getMessage(), ex);
        restartDatabase();
    }
}

Body:
You seem to be paranoid that some condition (maybe a RuntimeException or Error?) is going to cause your socket Thread to just die. Ideally, you would design your Socket Thread such that it protected itself from crashing. The following example creates a loop that can only be broken as a result of a JVM Error or Thread interrupt:

public void run() {
    while(!Thread.currentThread.isInterrupted()) {
        try {
            //you application logic
        } catch (RuntimeException e) {
           //log uncaught exception
        }
    }
}

In order to shutdown the application, you would attach a listener to the TrayIcon which contained a reference to the SocketThread and could stop it by simply interrupting it.

socketThread.interrupt();

I'll leave figuring how to add an ActionListener to a TrayIcon up to you.


问:
To which HTML element's event is an asp:RegularExpressionValidator client side validation bound?
This is a very specific question about how the client side (javascript) validation of a ASP.NET WebForms asp:RegularExpressionValidator works. Note: It is not about the actual regular expression!

My goal is to register an event on the client side that gets handeled BEFORE the regex validation.

Consider the following code (simplified, from the .aspx page)

```<code><asp:TextBox ID="TextBoxMultiId" runat="server" />
<asp:RegularExpressionValidator
ID="RegularExpressionValidatorMultiId" runat="server" Display="Dynamic"
ControlToValidate="TextBoxMultiId" ErrorMessage="Oops!"
SetFocusOnError="True" ValidationExpression="assigned_in_code">
</asp:RegularExpressionValidator>
</code>```

Then, I also load this jQuery snippet (in addons.js):

```<code>$(document).ready(function () {
    $("form input[type='text'], form textarea").on("change", function () {
        $(this).val(function (i, value) {
            alert('trim addon this:=' + this.id + ' trimmed:=' + value.trim());
            return value.trim();
        });
    });
});
</code>```

I would expect that, on any change of the text input's value, the onchange event would fire, causing the handler to alert and trim the value of the input. Then the validator should validate the trimmed input only.

However, this is what actually happens:

I make change to the input (by pasting a text with the keyboard and naviating away)

I get alerted immediately as expected

I press OK to dismiss the alert

The input's value gets trimmed and shows as such

The regular expression complains about a mismatch by showing it's red text "Oops!"

However, the moment after I dismiss the box, the value of the input should get trimmed, causing the validator to validate the trimmed text, which satisfies the regex.

It seems that the validator validates the pasted text, not the trimmed text. Why? How to trim so, that the trimmed variant gets validated?

Note: I am aware of https://forums.asp.net/t/1749522.aspx?Capturing+RegularExpressionValidator+event+client+side but I do not want to change existing code, plus, this actually should work on all validators in my code not just regex ones at a later time.

答:
The problem is not what event ASP.NET is using but the execution order. The ASP.NET validator is being attached to the change event before your code, that's why it's being executed first.

One possible solution is forcing the validation again from your javascript event.

```<code>$(document).ready(function () {
    $("form input[type='text'], form textarea").on("change", function (event) {
        $(this).val(function (i, value) {
            alert('trim addon this:=' + this.id + ' trimmed:=' + value.trim());
            return value.trim();
        });
        ValidatorOnChange(event);
    });
});
</code>```

Another possible solution, which I don't like much because it looks quite brittle, is moving your code above the form so you can be sure that it will be first in line in the execution list.

```<code><script src="jquery">
<script>
//your code
</script>
<form>
...
</code>```

Body:
This is a very specific question about how the client side (javascript) validation of a ASP.NET WebForms asp:RegularExpressionValidator works. Note: It is not about the actual regular expression!

My goal is to register an event on the client side that gets handeled BEFORE the regex validation.

Consider the following code (simplified, from the .aspx page)

<asp:TextBox ID="TextBoxMultiId" runat="server" />
<asp:RegularExpressionValidator
ID="RegularExpressionValidatorMultiId" runat="server" Display="Dynamic"
ControlToValidate="TextBoxMultiId" ErrorMessage="Oops!"
SetFocusOnError="True" ValidationExpression="assigned_in_code">
</asp:RegularExpressionValidator>

Then, I also load this jQuery snippet (in addons.js):

$(document).ready(function () {
    $("form input[type='text'], form textarea").on("change", function () {
        $(this).val(function (i, value) {
            alert('trim addon this:=' + this.id + ' trimmed:=' + value.trim());
            return value.trim();
        });
    });
});

I would expect that, on any change of the text input's value, the onchange event would fire, causing the handler to alert and trim the value of the input. Then the validator should validate the trimmed input only.

However, this is what actually happens:

I make change to the input (by pasting a text with the keyboard and naviating away)

I get alerted immediately as expected

I press OK to dismiss the alert

The input's value gets trimmed and shows as such

The regular expression complains about a mismatch by showing it's red text "Oops!"

However, the moment after I dismiss the box, the value of the input should get trimmed, causing the validator to validate the trimmed text, which satisfies the regex.

It seems that the validator validates the pasted text, not the trimmed text. Why? How to trim so, that the trimmed variant gets validated?

Note: I am aware of https://forums.asp.net/t/1749522.aspx?Capturing+RegularExpressionValidator+event+client+side but I do not want to change existing code, plus, this actually should work on all validators in my code not just regex ones at a later time.

Body:
The problem is not what event ASP.NET is using but the execution order. The ASP.NET validator is being attached to the change event before your code, that's why it's being executed first.

One possible solution is forcing the validation again from your javascript event.

$(document).ready(function () {
    $("form input[type='text'], form textarea").on("change", function (event) {
        $(this).val(function (i, value) {
            alert('trim addon this:=' + this.id + ' trimmed:=' + value.trim());
            return value.trim();
        });
        ValidatorOnChange(event);
    });
});

Another possible solution, which I don't like much because it looks quite brittle, is moving your code above the form so you can be sure that it will be first in line in the execution list.

<script src="jquery">
<script>
//your code
</script>
<form>
...


问:
How can I simplify this process of splitting/counting numpy subarrays?
I have a large dataset for which I would like to implement an efficient numpy solution. As a simpler example, consider a small array of numbers.

```<code>import numpy as np
arr = np.linspace(1, 10, 10)
</code>```

The code further below is very close to being my ideal solution, but I have hit a roadblock. First, I create a boolean mask to indicate the indices of the array at which array values are greater than a pre-defined lower bound and lesser than a pre-defined upper bound. I then split the boolean mask into subarrays, each of which consist of identical values by consecutive index. As an example, [0, 0, 0, 1, 1, 0, 0, 1, 1, 1] splits into [0, 0, 0], [1, 1], [0, 0], [1, 1, 1]. Lastly, I would like to take all subarrays consisting of only 1s and split them into individual subarrays. As an example, [1, 1, 1] should split into [1], [1], [1].

The code below does most of what I'd like, but in an inconvenient fashion. I would like all subarrays to be stored in a single array, from which I can count the number of subarrays and the number of elements in each subarray. Unfortunately, this is tricky for me as the function outputs are numpy arrays that are array(...) instead of just (...). I'm thinking there's a way to do this using np.ndarray.T that I get True/False values from and apply the axis kwarg to, though I have not had any success implementing this approach so far. How can I simplify this process?

```<code>def get_groups_by_difference(array, difference):
    """ This function splits arrays into subarrays in which every element is identical. """
    return np.split(array[:], np.where(abs(np.diff(array)) != difference)[0] + 1)

def check_consecutive_nested_arrays(array, repeated_value):
    """ This function returns a boolean array mask - True if all elements of a subarray contain the repeated value; False otherwise. """
    return np.array([np.all(subarray == repeated_value) for subarray in array])

def get_solution(array, lbound, ubound):
    # get boolean mask for array values within bounds
    bool_cnd = np.logical_and(array>lbound, array<ubound)
    # convert True/False into 1/0
    bool_cnd = bool_cnd * 1
    # split array into subarrays of identical values by consecutive index
    stay_idx = np.array(get_groups_by_difference(bool_cnd, 0))
    # find indices of subarrays of ones
    bool_chk = check_consecutive_nested_arrays(stay_idx, 1)
    # get full subarrays of ones
    ones_sub = stay_idx[bool_chk]
    return bool_cnd, stay_idx, bool_chk, ones_sub

bool_cnd, stay_idx, bool_chk, ones_sub = get_solution(arr, 3, 7)
print(bool_cnd)
>> [0 0 0 1 1 1 0 0 0 0]
print(stay_idx)
>> [array([0, 0, 0]) array([1, 1, 1]) array([0, 0, 0, 0])]
print(bool_chk)
>> [False  True False]
print(ones_sub)
>> [array([1, 1, 1])]
</code>```

My goal is to obtain an array result like the following:

```<code>[[0 0 0]
[1]
[1]
[1]
[0 0 0 0]]
</code>```

This way, I can find the number of elements per subarray and the number of subarrays (ie, 5 subarrays with lengths of [3, 1, 1, 1, 4].

答:
If I understand you correctly,

```<code>np.split(a, 1 + np.where(a[1:]|a[:-1])[0])
</code>```

should do what you want. Here a is the vector of ones and zeros.

This uses the fact that your final result can be obtained by splitting left and right of every 1.

Body:
I have a large dataset for which I would like to implement an efficient numpy solution. As a simpler example, consider a small array of numbers.

import numpy as np
arr = np.linspace(1, 10, 10)

The code further below is very close to being my ideal solution, but I have hit a roadblock. First, I create a boolean mask to indicate the indices of the array at which array values are greater than a pre-defined lower bound and lesser than a pre-defined upper bound. I then split the boolean mask into subarrays, each of which consist of identical values by consecutive index. As an example, [0, 0, 0, 1, 1, 0, 0, 1, 1, 1] splits into [0, 0, 0], [1, 1], [0, 0], [1, 1, 1]. Lastly, I would like to take all subarrays consisting of only 1s and split them into individual subarrays. As an example, [1, 1, 1] should split into [1], [1], [1].

The code below does most of what I'd like, but in an inconvenient fashion. I would like all subarrays to be stored in a single array, from which I can count the number of subarrays and the number of elements in each subarray. Unfortunately, this is tricky for me as the function outputs are numpy arrays that are array(...) instead of just (...). I'm thinking there's a way to do this using np.ndarray.T that I get True/False values from and apply the axis kwarg to, though I have not had any success implementing this approach so far. How can I simplify this process?

def get_groups_by_difference(array, difference):
    """ This function splits arrays into subarrays in which every element is identical. """
    return np.split(array[:], np.where(abs(np.diff(array)) != difference)[0] + 1)

def check_consecutive_nested_arrays(array, repeated_value):
    """ This function returns a boolean array mask - True if all elements of a subarray contain the repeated value; False otherwise. """
    return np.array([np.all(subarray == repeated_value) for subarray in array])

def get_solution(array, lbound, ubound):
    # get boolean mask for array values within bounds
    bool_cnd = np.logical_and(array>lbound, array<ubound)
    # convert True/False into 1/0
    bool_cnd = bool_cnd * 1
    # split array into subarrays of identical values by consecutive index
    stay_idx = np.array(get_groups_by_difference(bool_cnd, 0))
    # find indices of subarrays of ones
    bool_chk = check_consecutive_nested_arrays(stay_idx, 1)
    # get full subarrays of ones
    ones_sub = stay_idx[bool_chk]
    return bool_cnd, stay_idx, bool_chk, ones_sub

bool_cnd, stay_idx, bool_chk, ones_sub = get_solution(arr, 3, 7)
print(bool_cnd)
>> [0 0 0 1 1 1 0 0 0 0]
print(stay_idx)
>> [array([0, 0, 0]) array([1, 1, 1]) array([0, 0, 0, 0])]
print(bool_chk)
>> [False  True False]
print(ones_sub)
>> [array([1, 1, 1])]

My goal is to obtain an array result like the following:

[[0 0 0]
[1]
[1]
[1]
[0 0 0 0]]

This way, I can find the number of elements per subarray and the number of subarrays (ie, 5 subarrays with lengths of [3, 1, 1, 1, 4].

Body:
If I understand you correctly,

np.split(a, 1 + np.where(a[1:]|a[:-1])[0])

should do what you want. Here a is the vector of ones and zeros.

This uses the fact that your final result can be obtained by splitting left and right of every 1.


问:
How to maintain the scrolling state while orientation change in android
I have created one custom view that contains the horizontalscrollview. Now when i changes the orientation its scroll state change to 0 every time.

I got the previous scroll state by using onSaveInstanceState(Bundle savedInstanceState) and onRestoreInstanceState(Bundle savedInstanceState) . in onRestoreInstanceState i am using following method to get reposition the scroll,

```<code>hoz_scroll.scrollTo(hoz_x_pos, hoz_scroll.getScrollY());
</code>```

But there is not effect at all.
Help appreciated.  Thanks.

答:
Put this code in your Activity to not have it scroll when orientation changes.  You don't even need to code.</p>

```<code>@Override
public void onConfigurationChanged(Configuration config){
    super.onConfigurationChanged(config);
}
</code>```

Body:
I have created one custom view that contains the horizontalscrollview. Now when i changes the orientation its scroll state change to 0 every time.

I got the previous scroll state by using onSaveInstanceState(Bundle savedInstanceState) and onRestoreInstanceState(Bundle savedInstanceState) . in onRestoreInstanceState i am using following method to get reposition the scroll,

hoz_scroll.scrollTo(hoz_x_pos, hoz_scroll.getScrollY());

But there is not effect at all.
Help appreciated.  Thanks.

Body:
Put this code in your Activity to not have it scroll when orientation changes.  You don't even need to code.

@Override
public void onConfigurationChanged(Configuration config){
    super.onConfigurationChanged(config);
}